text
stringlengths
64
81.1k
meta
dict
Q: Qt set style for all objects but one I've currently got this style for all push buttons: this->setStyleSheet(".QPushButton { background-color: #416eb6; color: #ddd; }"); This is great because it allows me to keep a constant styling for all the QPushButton's without having to style them individually. An issue arises when I need to style a QPushButton representing a color chooser. The button should represent the color that was chosen from the color chooser, but instead it just keeps the initial style that I set. Things I have tried: Giving an empty style sheet for the item: this->setStyleSheet(#m_colorChooserButton { }); Setting the style to initial: this->setStyleSheet(#m_colorChooserButton { background-color: initial}); Using a similar css selector :not: this->setStyleSheet(".QPushButton:not(#m_colorChooserButton) { background-color: #416eb6; color: #ddd; }"); Is there any way to achieve this result? I'd like to mimic the :not selector if possible since that's the most straightforward, but at this point, I'd do anything that works. I'd like to avoid having to manually specify the style for each button I want it to show on, as there are well over 100 buttons and finding the object names of these buttons is very time consuming (large legacy code base). Thanks A: You have 2 choices: apply a stylesheet to just that button and invalidate/reapply it every time you change the selected colour or just subclass that button and reimplement the paintevent: class ColorButton : public QPushButton{ Q_OBJECT Q_DISABLE_COPY(ColorButton) public: ColorButton(QWidget* parent = Q_NULLPTR) :QPushButton(parent) ,m_color(Qt::red) {} const QColor& color() const {return m_color;} void setColor(const QColor& val){if(m_color==val) return; m_color=val; update();} protected: void paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionButton option; initStyleOption(&option); option.palette.setColor(m_color,QPalette::Background); p.drawControl(QStyle::CE_PushButton, option); } private: QColor m_color; }; P.S. The KDE API already has that widget: https://api.kde.org/frameworks-api/frameworks-apidocs/frameworks/kwidgetsaddons/html/classKColorButton.html
{ "pile_set_name": "StackExchange" }
Q: Grails - Spring Security UI Email for Username I'm using Grails 3.2.4 and am attempting to use the email property of my User class as the username for registration. So far, I've managed to get Spring Security Core to use the email as the username using the configuration setting below: grails.plugin.springsecurity.userLookup.usernamePropertyName='email' However, the registration functionality doesn't seem to take this into account and won't let me register a new user using only an email and password. I've made a few attempts at overriding the RegisterController but I continue to experience different errors regarding null usernames. It seems like I must be missing something very simple. Any help / direction is greatly appreciated. A: It appears that in version spring-security-ui-3.0.0.M2 the username property might not be override-able. String paramNameToPropertyName(String paramName, String controllerName) { // Properties in the ACL classes and RegistrationCode aren't currently // configurable, and the PersistentLogin class is generated but its // properties also aren't configurable. Since this method is only by // the controllers to be able to hard-code param names and lookup the // actual domain class property name we can short-circuit the logic here. // Additionally there's no need to support nested properties (e.g. // 'aclClass.className' for AclObjectIdentity search) since those are // not used in GSP for classes with configurable properties. if (!paramName) { return paramName } Class<?> clazz = domainClassesByControllerName[controllerName] String name if (clazz) { String key = paramName if (paramName.endsWith('.id')) { key = paramName[0..-4] } name = classMappings[clazz][key] } name ?: paramName } PS I'm getting around this now by doing something like this in my user domain class: static transients = ["migrating"]] String username = null public void setEmail(String email) { this.email = email this.username = email }
{ "pile_set_name": "StackExchange" }
Q: How can I insert formatted links in Google Sheet concatenations? I am using Google Sheets to run mail merges using the script editor; it references a cell with an email address and a cell with the body of the email. I am able to concatenate a number of other columns to generate the merge field values. I am only able to insert plain text URLs, and in most cases they render as links in browsers. However, I have recipient-specific URLs that are pretty long, and I'd like to alias them, in the body of the email. Basically, I want to get what would be the resulting links for the inputs below: <a href=https://www.recipient-site.com>Your Site</a> VIA =(concatenate("<a href=",G2,">",F2,"</a>")) or =HYPERLINK("https://www.recipient-site.com","Your Site") VIA =CONCATENATE("=hyperlink(",char(34),G2,char(34),",",char(34),F2,char(34),")") I have tried =hyperlink(G4,F4) where the values are from cells, and it renders correctly in the cell, but just shows the alias as plain text in the email. A: As the OP already realized, getValue() and getValues() return a string object for cells containing an hyperlink and the value returned when the object is concatenated is the link text that the OP referred as the alias. We could use getFormula() and getFormulas() to get the cells formulas and to parse the URL from the them. See Extract the link text and URL from a hyperlinked cell for answers showing how to do this.
{ "pile_set_name": "StackExchange" }
Q: Finding view of an icon in overflow menu I am trying to findview of an overflow icon. After clicking and opening the overflow icon, I tried using in onoptionsitemselected: View view = getActivity().findViewById(R.id.menu_tag); // null View view = getActivity().findViewById(R.id.mainMenu); // not null. <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/mainMenu" android:title="@string/text" android:orderInCategory="101" android:icon="@drawable/ic_more_vert_white_24dp" app:showAsAction="always"> <menu> <item android:id="@+id/menu_tag" android:icon="@drawable/tag_32" app:showAsAction="always|withText" android:title="@string/tags"/> <item android:id="@+id/menu_profile" android:icon="@drawable/user_32" app:showAsAction="always|withText" android:title="@string/profile"/> <item android:id="@+id/menu_debug" android:icon="@drawable/insect_32" app:showAsAction="always|withText" android:title="@string/debug"/> </menu> </item> </menu> It is giving me null but working fine for actionbar items. A: I found a solution by setting actionview to imagebutton and then finding the view.
{ "pile_set_name": "StackExchange" }
Q: Money Plant Branching and Watering I recently acquired a money plant and have placed it indoors at the top of a stairway in a non-draining pot. The plant seems to be growing very well. I have two specific questions: I have branched one part of it on the staircase in a downward direction. I heard from someone it will not grow in a downward direction but I'm not sure and would like to check whether it will work or not. How much should I water the plant? It would be super if someone can be specific in terms of quantity and timing. A: Thanks for confirming the plant name. This one likes well drained soil, so the first thing I'd say is that it shouldn't be in a non draining pot - being waterlogged will cause it problems. If you can transfer it to something which drains, with an outer container which doesn't, water with tepid water when the surface of the compost is dry to the touch, but not shrunken from the sides of the pot. Reduce watering in winter. Empty any water left in an outer pot after 30 minutes. Mist frequently, it likes high humidity, although where you are, high humidity might be the norm anyway, I'm not sure. As for the direction of growth, this one has fairly lax, drooping stems and leaves spilling out and down over the pot, which is its natural habit, but growth will always aim for where the light is brightest. You may find it becomes leggy and unattractive over time - cutting back hard in spring helps, but its advisable to root cuttings for replacement plants at the same time, in case the parent plant continues to look unattractive. Repot in Spring if necessary. Note that watering is not an exact science in home conditions - how much the plant needs is dependent on its local environment, how large the plant is, the ratio of compost to root within the pot, heat, and speed of growth, which varies according to the time of year.
{ "pile_set_name": "StackExchange" }
Q: How do I open Windows Explorer to a particular directory from a Windows command prompt? When I'm in a particular directory in a Windows command prompt, I sometimes want to open Windows Explorer so it already shows that same directory. How do I do that? (I'm looking for the equivalent to open . in a Mac OS X terminal.) A: Either one of these should do the trick: explorer . start .
{ "pile_set_name": "StackExchange" }
Q: How do I export a MySQL db structure to an Excel file? Is there any tool to export a MySQL db structure to an Excel file? For example: 1 ID int(10) not null pri 0 index comment Thanks for any help. A: Here is a much simpler way: From phpMyAdmin, select your database, then select the Structure tab. Scroll down to the bottom of the list of tables. Click on Data Dictionary. Select all, and then copy/paste into Excel. This method produces a report listing all tables, plus all fields within each table including the field type, if NULL is allowed, default value, links, comments, and MIME. It also lists all indexes including type, uniqueness, whether the index is packed, and index comments. A: You could query information_schema.columns to obtain the required data: SELECT * from information_schema.columns WHERE table_schema = 'db_2_66028' AND table_name = 'tbl'; table_schema is the name of your db table_name the name of the table. If you omit this, you will query column information for all your tables. See http://sqlfiddle.com/#!2/23f9b/1 for live demo. Here I used SELECT * for simplicity, but you will probably have to select only the require columns for your specific need. In addition, MySQL is able to export query result as CSV file, a text format that Excel, like any other spreadsheet, might easily read. Something like that might do the trick: SELECT * from information_schema.columns WHERE table_schema = 'db_2_66028' AND table_name = 'tbl' INTO OUTFILE '/tmp/result.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY ‘\\’ LINES TERMINATED BY '\n'
{ "pile_set_name": "StackExchange" }
Q: AngularJS: Uncaught Error: [$rootScope:infdig] I am trying to get all the courts for each game: The HTML looks like this: <div ng-repeat = "g in games"> {{g.gameName}} <ul> <li ng-repeat = "c in getCourts(g.id)" ng-bind = "c.courtName"></li> </ul> </div> The controller is : $scope.games = {}; $scope.courts = {}; //$scope.slots = {}; $http.get(URI+"booking/allGames").then(function success(res){ $scope.games = res.data; //console.log($scope.games); }, function error(res){ console.log(res.data.message); }); $scope.getCourts = function(gameId){ //courts = {}; $http.get(URI+"booking/courts/"+gameId).then(function success(res){ //console.log(gameId); console.log(res.data); return res.data; //return courts; }, function error(res){ console.log(res.data.message); });; } When I execute this, I getting this error: angular.min.js:6 Uncaught Error: [$rootScope:infdig] The angularJS documentaion says, This error occurs when the application's model becomes unstable and each $digest cycle triggers a state change and subsequent $digest cycle. One common mistake is binding to a function which generates a new array every time it is called. I saw this answer : AngularJS use a function in a controller to return data from a service to be used in ng-repeat But I am not sure how to fix this. A: I think your only option is to pre-fetch all the data like this... $http.get(URI+"booking/allGames").then(res => { $q.all(res.data.map(game => { return $http.get(URI+"booking/courts/"+game.id).then(res => { return angular.extend(game, {courts: res.data}); }); })).then(games => { $scope.games = games; }); }); Then you can just use a nested repeater <div ng-repeat="g in games"> {{g.gameName}} <ul> <li ng-repeat="c in g.courts" ng-bind="c.courtName"></li> </ul> </div>
{ "pile_set_name": "StackExchange" }
Q: Projections on Normed Spaces Let $\mathbb{E}$ be a (real or complex) Banach space (complete normed space). Let $P$ be a projection ($P^2=P$) from $\mathbb{E}$ into itself. Is it necessarily that the norm of $P$ equals to $1$? A: This is not true in general (e.g. with $P=0$). However, if the projection is orthogonal and nonzero, then the norm is certainly $1$. See, for instance, Operator norm of orthogonal projection.
{ "pile_set_name": "StackExchange" }
Q: Can I use @ngrx with vue? We have a desktop app in Angular and a mobile app in Vue, that do the same thing, share apis etc. We need a (shared) state management solution. From tutorials, I can see nothing particularly Angular-specific in Ngrx, but I'm completely new to state management and RxJS. Without recommending a product, does anyone know a reason why I can't point Vue at an @ngrx store ? A: No . Love to be wrong. The way you initialize a reducer is using StoreModule which is angular module, you cannot do in vue. The whole ngrx source code is built on angular ( using modules, services etc ). You can't run it without angular code.
{ "pile_set_name": "StackExchange" }
Q: Read an url HTTPS in a JSON file swift I try to read an URL request (in dictionary "vehicles")in a json but the array will empty This is the json and I need to read the dictionary and the url that are in vehicles { "count": 87, "next": "https://swapi.co/api/people/?page=2", "previous": null, "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "https://swapi.co/api/planets/1/", "films": [ "https://swapi.co/api/films/2/", "https://swapi.co/api/films/6/", "https://swapi.co/api/films/3/", "https://swapi.co/api/films/1/", "https://swapi.co/api/films/7/" ], "species": [ "https://swapi.co/api/species/1/" ], "vehicles": [ "https://swapi.co/api/vehicles/14/", "https://swapi.co/api/vehicles/30/" ], This is the code that I try if let results = json["results"] as? [[String : AnyObject]] { var finalArray2 : [String] = [] for result in results { if let dict = result as? [String: Any], let vehicles = dict["vehicles"] as? String{ self.URLveicoli = vehicles //print(self.nomepersonaggio) print(self.URLveicoli) //finalArray.append(name) finalArray2.append(vehicles) } } print(finalArray2) } A: In json vehicles is an array of strings (urls) not a string. Change this let vehicles = dict["vehicles"] as? String To let vehicles = dict["vehicles"] as? [String] And to append array of vechicles finalArray2.append(contentsOf: vehicles)
{ "pile_set_name": "StackExchange" }
Q: Prolog - SWI : How to create a Structure for computing values given to it I'm a first time user of prolog and I've been using it for about a week now, learning about the various basics from here, which has been helpful to a degree. I have been designing a database lookup for a fictional game title, where by the user will be able to consult the bestiary to obtain the statistics of a given character in the game. Sounds like an awesome project if you ask me :) I've been working on learning about "frames" to describe my nodes and how to use them so the format I'll use is going to be something along these lines. The latest item I've been learning about is "Numbers" in prolog and how they work, it seemed pretty simple enough in the tutorials until I wanted to use it in a more dynamic way. I have the following set up for my data nodes. (pseudo code) Frame: name(character), parent(none), base_stat(8.0). Frame: name(npc), parent(character). Frame: name(enemy), parent(npc). Frame: name(red_faction), parent(enemy), atk_bonus(1.5), spd_bonus(1.25), def_bonus(0.25). Frame: name(blue_faction), parent(enemy), atk_bonus(1), spd_bonus(1), def_bonus(1). Frame: name(fire_warrior), parent(red_faction), level(1.0), holding(nothing). Frame: name(water_consort), parent(blue_faction), level(1.0), holding(nothing). When consulted I want to return the following statistics to the user: attack(?), speed(?), defence(?). I was hoping to use an equation to work out the "?" areas of my program, to which the following equation would be used "(base_stat + level) * stat_bonus". So something like this:- compute(attribute) :- stat_bonus(stat bonus from parent node for required stat example:atk_bonus) base_stat(value from the character node's base_stat) level(value from the character we are looking up: eg water_consort lvl1) attribute is (level+base_stat) * stat_bonus I came up with this structure after a brief explanation from a tutor regarding algebraic approaches to numbers in prolog. There example went something like:- student(jack, 25). student(jill, 21). avg_Score(Z) :- student(jack, X), student(jill, Y), Z = (X + Y)/2. I understand that I need to extract the values for X and Y, and if I want to ever reconsult those values I'll have to repeat that extraction to use them. Now going back to my little project, I have a number of faction nodes (full diagram has 3, but there's no point going beyond two for this as I assume what ever process is needed can be applied N times), how do I get the information for my calculation? Assuming I were to request the data for the fire warrior, my system wants to calculate a stat (let's say attack) and it consults the equation I have. I'll need the following information: the attack bonus given by the parent node "red_faction" the base_stat given by the g.g.grandparent node "character" the instance node's level The example my tutor gave me will only work if I am to hard code in my request for everything and is very limited. Is there a method that I can use for "N" factions and "M" character instances for each faction? I would bother her again but she isn't free until after Easter, and I'm looking to finish this sometime over the weekend. From what I can tell Prolog does inheritance quite well, but I have no idea how to solve this. Thank you in advance for any constructive input you can give. A: Welcome to Prolog! I'm glad you're giving it a shot, and I hope you find it serves your imagination well, since you seem to have a lot! You're using a lot of strange terminology here for Prolog. I'm not clear on what you mean by "frame" or "node" or "extract" and I'm pretty sure you're using "consult" in an off way. I don't know if this is because the tutorial was written for SICStus or if it's just the usual confusion. I also wouldn't normally think of doing inheritance in Prolog, but that part of this I think I actually do understand. So I hope you'll play along and we'll see if I manage to answer your question anyway. First things first. It's not a big deal but average score should be implemented like this: avg_score(Z) :- student(jack, X), student(jill, Y), Z is (X + Y) / 2. % <-- note the use of 'is' instead of '=' This is a common beginner mistake. Prolog doesn't evaluate algebra by default, so when you say something like (X + Y) / 2 all you're really doing is building an expression, no different than div(plus(X, Y), 2). The one difference, really, is that is knows how to evaluate algebraic expressions like (X + Y) / 2 but not div(plus(X, Y), 2). (I'll pre-warn you that you'll find Prolog makes a lot more sense if you start using clpfd from the start, and use #= instead of is.) No, what's unhelpful about avg_score, of course, is that jack and jill are embedded within it. Someday you'll probably want to calculate the average scores of all your students. First let's calculate the average: average(L, Average) :- sum(L, Sum), length(L, Length), Average is Sum / Length. % this is overly complex because I wanted to show you % the tail recursive version sum(L, Sum) :- sum(L, 0, Sum). sum([], Sum, Sum). sum([X|Xs], Acc, Sum) :- Acc1 is X + Acc, sum(Xs, Acc1, Sum). Now we can get the average of all the students like this: avg_score(Z) :- findall(X, student(_, X), Scores), average(Scores, Z). I don't happen to know if this relates to what you're asking or not, but it seems like it might be helpful so there it is. Of course, another possibility is to parameterize things. We could take the original code and parameterize it by student: avg_score(Student1, Student2, Z) :- student(Student1, X), student(Student2, Y), Z is (X + Y) / 2. This seems like it might be more pertinent to querying the bestiary. Rather than asking attack(X) you would ask attack(fire_warrior, X). I hate to send you off to Logtalk when you're so new to Prolog, but I suspect it might hold some of the answers you're looking for. It's particularly good at handling inheritance in a way that vanilla Prolog probably isn't. But it can be a big diversion. For instance, you could handle the inheritance chain for querying the attack stat like this: % this is the inheritance tree parent_class(character, base). parent_class(npc, character). parent_class(enemy, npc). parent_class(red_faction, enemy). parent_class(blue_faction, enemy). parent_class(fire_warrior, red_faction). parent_class(water_consort, blue_faction). % these are the attack bonuses attack_bonus(base, 0). attack_bonus(red_faction, 1.5). attack_bonus(blue_faction, 1). calc_attack_bonus(X, Bonus) :- attack_bonus(X, Bonus), !. calc_attack_bonus(X, Bonus) :- \+ attack_bonus(X, Bonus), parent_class(X, Parent), calc_attack_bonus(Parent, Bonus). This appears to work for some basic queries: ?- calc_attack_bonus(fire_warrior, Bonus). Bonus = 1.5. ?- calc_attack_bonus(character, Bonus). Bonus = 0. I don't know if you want this behavior or not: ?- calc_attack_bonus(tree, Bonus). false. It's easy to fix if not (if parent_class fails, unify Bonus with 0, otherwise recur). This is not, however, all that extensible. A more extensible approach might be this: % these are the attack bonuses attribute(attack_bonus, base, 0). attribute(attack_bonus, red_faction, 1.5). attribute(attack_bonus, blue_faction, 1). % base stats attribute(base_stat, character, 8.0). attribute(level, fire_warrior, 1.0). Now we can write the rules we need without a lot of pain: calc_attribute(X, Attribute, Value) :- attribute(X, Attribute, Value), !. calc_attribute(X, Attribute, Value) :- \+ attribute(X, Attribute, Value), parent_class(X, Parent), calc_attribute(Parent, Attribute, Value). And now attack becomes easy: attack(X, Value) :- calc_attribute(X, attack_bonus, Bonus), calc_attribute(X, base_stat, Base), calc_attribute(X, level, Level), Value is (Level + Base) * Bonus. We need to generalize a bit more to get to where we can write compute though, because ideally, we want to say something like compute(fire_warrior, attack, Value). For that to happen, we need to know that attack_bonus is related to attack and we don't know that. Let's restructure attribute a little: % these are the attack bonuses attribute(base, bonus(attack), 0). attribute(red_faction, bonus(attack), 1.5). attribute(blue_faction, bonus(attack), 1). % base stats attribute(character, base_stat, 8.0). attribute(fire_warrior, level, 1.0). Now we're cooking: compute(X, Attribute, Value) :- calc_attribute(X, bonus(Attribute), Bonus), calc_attribute(X, base_stat, Base), calc_attribute(X, level, Level), Value is (Level + Base) * Bonus. And behold: ?- compute(fire_warrior, attack, Value). Value = 13.5. I hope that's what you wanted. :) Big Edit For fun I thought I'd see what this would be like with Logtalk, an object-oriented extension language for Prolog. I'm very new to Logtalk, so this may or may not be a good approach, but it did "do the trick" so let's see if it's more along the lines of what you're wanting. First, the base object: :- object(base). :- public(base_stat/1). :- public(attack/1). :- public(bonus/2). :- public(level/1). :- public(compute/2). bonus(attack, 0). base_stat(0). level(0). compute(Attribute, Value) :- ::bonus(Attribute, Bonus), ::base_stat(Base), ::level(Level), Value is (Level + Base) * Bonus. :- end_object. This is basically defining the facts we're going to store about each thing, and how to compute the property you're interested in. Next we establish the object hierarchy: :- object(character, extends(base)). base_stat(8.0). :- end_object. :- object(npc, extends(character)). :- end_object. :- object(enemy, extends(npc)). :- end_object. :- object(red_faction, extends(enemy)). bonus(attack, 1.5). bonus(speed, 1.25). bonus(defense, 0.25). :- end_object. :- object(blue_faction, extends(enemy)). bonus(attack, 1). bonus(speed, 1). bonus(defense, 1). :- end_object. :- object(fire_warrior, extends(red_faction)). level(1.0). holding(nothing). :- end_object. :- object(water_consort, extends(blue_faction)). level(1.0). holding(nothing). :- end_object. Now using this is pretty much a snap: ?- fire_warrior::compute(attack, X). X = 13.5. ?- water_consort::compute(attack, X). X = 9.0. I hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How to change background color and text color of clicked or auto-played video Problem: I have a HTML video playlist of Wistia videos and I'm trying to change the background-color and color of the videos as they are played, either by clicking on them or having the playlist autoplay. I'm currently using a:focus to accomplish the click part, but I'm looking for something more sophisticated? as a solution. If you click out of the video playlist or on the video itself, the colors go back to their defaults. Here is my code so far: https://codepen.io/atnd/pen/qzaVLX JavaScript is not my strong suit, so I don't really know where to begin. I'm using Embed Links to build a playlist, but I referenced Wistia's API and am unsure what is applicable: https://wistia.com/support/developers/player-api && https://wistia.com/support/developers/playlist-api Here's my pathetic JS: var vidcontainer = document.getElementById("vidcontainer"); var videos = video.getElementsByTagName("a"); for(i=0; i<videos.length; i++) { videos[i].addEventListener("click", function(event) { }); } Thank you in advance for any help you can provide! A: You could use something like this for toggling the backgroundColor when the menu item is clicked : var vidcontainer = document.getElementById("vidcontainer"); var videos = vidcontainer.getElementsByTagName("a"); function highlightMenuItemAndDisableOthers(element) { element.style.backgroundColor = 'red' for (let video of videos) { if (video !== element) video.style.backgroundColor = 'white' } } for (let video of videos) { video.addEventListener('click', event => { highlightMenuItemAndDisableOthers(video, videos) }) } For knowing which video is played automatically by the player, it will be more complex. You have to find an event in the API that tell when a new video is playing, then get the DOM element of the menu item and call the highlightMenuItemAndDisableOther method on it. Hope it helps!
{ "pile_set_name": "StackExchange" }
Q: create hyperlinks within VBscript array with variable output In effort to redeem this question: Updated edit below. <% doMenu dim products dim manu dim website products = Array("E-reader set: Kindle Paperwhite, $119","Leather tote, $160","Earrings, $88","Skin care duo: Moisturizer, $62","Throw pillow, $90","Vitamix 5200, $449","Tea set: Le Creuset kettle, $1oo","Spring nail polish collection, $51","Framed birthstone print, $48","Cotton robe, $25","Jewelry box, $49","Water bottle, $35","Polka-dot scarf, $38","Makeup set: Eye palette, $44","Sequin pouch, $88","Ceramic set: Jar, $22","Honeycomb perfume, $54","3-jar jam set, $24","Recipe box, $34","Hair dryer, $200","Epicurious 11-piece cookware set, $320","Cookbook collection: 100 Days of Real Food by Lisa Leake, $20","Threshold dining set: Placemats, $10","Sodastream genesis, $90","Alexia necklace, $49","Wild & wolf garden tool set, $33","Rattan floor basket, $59","Olivia burton watch, $105","Yoga set: Mat, $40","Hair-care system: Restore shampoo, $28","") manu = Array("leather case, $40","","","eye serum, $48","","","three organic tea blends, $50","","","","","","","lip palette, $40; brush set, $50","","mug, $18; tray, $15","","","","","","Twelve Recipes by Cal Peternell, $20; Better on Toast by Jill A. Donenfeld, $20","$10; napkins","","","","","","bag, $20; towel, $25","conditioner, $28; mask treatment, $4","") website = Array("www.amazon.com","www.baggu.com","www.sarahhealydesign.com ","www.kiehls.com","www.Laylagrayce.com","www.vitamix.com","www.williams-sonoma.com","www.essie.com","www.minted.com","www.worldmarket.com","www.westelm.com","www.swellbottle.com","www.echodesign.com","www.maccosmetics.com","www.bodenusa.com","www.rosannainc.com","www.libraryofowers.com","www.murrayscheese.com","www.rifepaperco.com","www.shopt3micro.com","www.jcpenney.com", "www.amazon.com", "www.target.com", "www.surlatable.com","www.stelladot.com","www.burkedecor.com","www.landofnod.com","www.modcloth.com","www.gaiam.com","www.livingproof.com","") %> The above code populates content sections, in a single dynamic one-page website. The problem is the website outputs just the copy / text URL. I need it to link, and preferably link out with a target="_blank" for new window. I have tried the below; via an answered suggestion -- and while i think this may be better practice it doesn't seem to run with the other arrays, and breaks the site to resolve to a white page only. I've tried including it within my other array structures within same include and separate and breaks the site. I have also toggled the name of arrUrls to website and declared dim arrUrls etc etc and everything just broke the page so still need a solution. dim arrUrls arrUrls = Array("www.amazon.com","www.baggu.com") For x=0 To UBound(arrUrls) currentUrl = arrUrls(x) Response.Write("<a href=""http://""" & currentUrl & """ target=""_blank"">" & currentUrl & "</a>") Next In the past I have done.. the below with jQuery arrays and would love a similar solution as something as inline and legible of this would be perfect. { value: "NYC", url: 'http://www.nyc.com' }, { value: "LA", url: 'http://www.la.com' }, { value: "Philly", url: 'http://www.philly.com' }, A: You don't create the hyperlinks in the array. You create them in the code iterating the array: <% Dim arrUrls, x, currentUrl arrUrls = Array("www.amazon.com","www.baggu.com") For x=0 To UBound(arrUrls) currentUrl = arrUrls(x) Response.Write("<a href=""http://" & currentUrl & """ target=""_blank"">" & currentUrl & "</a>") If x < UBound(arrUrls) Then Response.Write(" | ") Next %> Simple as that. A: <a href="http://<% response.write(website(day_part-1))%>" target="_blank" ><% response.write(website(day_part-1))%></a> Including this inline alone with only variable output was most optimal and functional. This code alone, inline; without altering the array.
{ "pile_set_name": "StackExchange" }
Q: Avoiding inheritance of submenu items in CSS superfish menu I need some more help on my superfish menu here: http://web288.merkur.ibone.ch/klingler/ I would like to modify the main buttons on hover and current. However this does also change the submenu entries what I do not want. I am not a CSS expert but somehow the submenu entries do inherit the properties. What I tried to add is the following .sf-menu a:hover, .sf-menu li.current a, .sf-menu li.sfHover a { background: #e24c4c url(../../images/bg-top-a-active.png) no-repeat center bottom; margin: 5px; padding: 0 10px; height: 35px; line-height: 35px; border-radius: 5px; } This does what I want for the main buttons but it does also change the submenu entries... What am I doing wrong? A: As I understand you only want to select the a elements which are direct children of li.current or li.sfHover. .sf-menu a:hover, .sf-menu li.current > a, .sf-menu li.sfHover > a {
{ "pile_set_name": "StackExchange" }
Q: How to replace more than one common sub string in a single string with another string? for(int i= 0 ;i<[urlsArrray count]; i++) { NSString *urlString = [urlsArrray objectAtIndex:i]; NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:escapedUrlString]; NSString *urlstring1 = [url absoluteString]; NSArray *parts = [urlstring1 componentsSeparatedByString:@"/"]; NSString *fileName = [parts objectAtIndex:[parts count]-1]; NSMutableString *tempString = [NSMutableString stringWithString:fileName]; // [tempString replaceCharactersInRange:[tempString rangeOfString:@"%20"] withString:@" "]; NSLog(@"file name in temp string: %@ word name: %@", tempString, wordNameDB); NSRange match = [tempString rangeOfString:wordNameDB]; if(match.location != NSNotFound) { NSLog(@"match found at %u", match.location); isAvailable = YES; break; } Hi friends, now my problem is i am getting file name from server..., if file name is having any spaces then it replace '%20' ( i.e ex: "hello world" is actual name but i am getting file name like: "hello%20world") . 1. I am not sure all file names having spaces. 2. And also i am not sure a file may have only one space so first i have to check the file is having spaces or not, if have then i want to replace all "%20" with @" " string. Please give me any suggestions or code snippets. OR " THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(@" ")..... thank you A: What you need is replacing the escape charcters, according to the encoding. Use this and all your spaces and other URL encoded characters will be converted to what you need. [@"yourString" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
{ "pile_set_name": "StackExchange" }
Q: Dismiss a modal ViewController after X seconds I have a login modal UIViewController open and what to show a second "Thank you" Viewcontroller modally for 60 seconds and then dismiss it, but I can figoure out how to do this in SWIFT. (It was easy in Objectiv C) Here is my code for opening the "Thank you viewcontroller" after closing the first one. weak var pvc = self.presentingViewController self.dismiss(animated: true, completion: { let thankYouExistingVC = self.storyboard?.instantiateViewController(identifier: "ThankYouExistingVC") as! ThankYouExistingVC pvc?.present(thankYouExistingVC, animated: true, completion: nil) }) A: You can do it using DisaptchQueue: DispatchQueue.main.asyncAfter(deadline: .now() + 60) { // Do whatever you want theViewControllerToDismiss.dismiss(animated:true, completion: nil) }
{ "pile_set_name": "StackExchange" }
Q: Does Spark incur the same amount of overhead as Hadoop for vnodes? I just read https://stackoverflow.com/a/19974621/260805. Does Spark (specifically Datastax's Cassandra Spark connector) incur the same amount of overhead as Hadoop when reading from a Cassandra cluster? I know Spark uses threads more heavily than Hadoop does. A: I'll give three separate answers. I apologize for the rather unstructured answer, but it's been building up over time: A previous answer: Here's one potential answer: Why not enable virtual node in an Hadoop node?. I quote: Does this also apply to Spark? No, if you're using the official DataStax spark-cassandra-connector. It can process multiple token ranges in a single Spark task. There is still some minor performance hit, but not as huge as with Hadoop. A production benchmark We ran a Spark job against a vnode-enabled Cassandra (Datastax Enterprise) datacenter with 3 nodes. The job took 9.7 hours. Running the same job on for slightly less data, using 5 non-vnode nodes, a couple of weeks back took 8.8 hours. A controlled benchmark To further test the overhead we ran a controlled benchmark on a Datastax Enterprise node in a single-node cluster. For both vnode enabled/disabled the node was 1) reset, 2) X number of rows were written and then 3) SELECT COUNT(*) FROM emp in Shark was executed a couple of times to get a cold vs. hot cache times. X tested were 10^{0-8}. Assuming that Shark is not dealing with vnodes in any way, the average (quite stable) overhead for vnodes were ~28 seconds for cold Shark query executions and 17 seconds for hot executions. The latency difference did generally not vary with data size. All the numbers for the benchmark can be found here. All scripts used to run the benchmark (see output.txt for usage) can be found here. My only guess why there was a difference between "Cold diff" and "Hot diff" (see spreadsheet) is that it took Shark some time to create metadata, but this is simply speculation. Conclusion Our conclusion is that the overhead of vnodes is a constant time between 13 and 30 seconds, independent of data size.
{ "pile_set_name": "StackExchange" }
Q: Getting child class type from parent class parameter I am going to have multiple "types" of an object and I am really not sure how best to retrieve/save those multiple types without having a separate save/retrieve for each type. My classes: public class Evaluation { public int Id public string Comment } public class EvaluationType_1 : Evaluation { public string field } public class EvaluationType_1 : Evaluation { public string field } What I would like to do in my repository: public interface IEvaluationRepository { public Evaluation getEvaluation(int id); public SaveEvaluation(Evaluation); } Inside the get/save methods: // Save/get common fields Id Comments // Get child type, perform switch Type childType = ??? switch(childType) { // Set child-specific fields } I'd rather not add a "type" column as I have this in another part of my database and I am not really liking it too much Update Here's more info for clarification, if necessary. I love the idea of using interfaces and generics, I'm really at a loss for how to incorporate them into my repository pattern. When I call getEvaluation, I want it to return an abstract Evaluation, but I'm struggling with this code. Same with Saving. Update 2 Daniel is helping me hone in on what exactly I am trying to ask. Database: Evaluations Id (PK) Comment EvaluationType1 Id (FK to Evaluations.Id) Field EvaluationType1 Id (FK to Evaluations.Id) Field So, in getEvaluation(int id), I need to figure out what type of Evaluation they want. Does this mean I should pass in a type? Same is true in saveEvaluation, But I can do a switch/function map to see what Type it is. A: Try this public interface ISaveable { void SaveFields(); } public abstract class Evaluation : ISaveable { public int Id public string Comment public virtual void SaveFields() { //Save ID and Comments } } public class EvaluationType_1 : Evaluation { public string field1 public override void SaveFields() { //Save field1 base.SaveFields(); } } public class EvaluationType_2 : Evaluation { public string field2 public override void SaveFields() { //Save field2 base.SaveFields(); } } Then you can have a collection of ISaveable such as List<ISaveable> and call SaveFields on each one, regardless of their type. You are now programming against the interface rather than against concrete types. The first step towards decoupling of code. Edited: In response to your comment In your repository, you would no longer program against the Evaluation class. Instead you would program agains t the methods in the interface that it implements: Instead of: public interface IEvaluationRepository { public Evaluation getEvaluation(int id); public SaveEvaluation(Evaluation); } You might have: public interface ISaveableRepository { public ISaveable getSavable(int id); public Save(ISaveable saveable); } And an implementation of the repository might be like: public class SaveableEvaluationRepository : ISaveableRepository { public ISaveable getSavable(int id) { //Add your logic here to retrieve your evaluations, although I think that //this logic would belong elsewhere, rather than the saveable interface. } public Save(ISaveable saveable) { saveable.SaveFields(); } }
{ "pile_set_name": "StackExchange" }
Q: How to avoid cumbersome if/else constructs? [Something more like an architecture approach, not just switch statement] I faced a task when I need to process a bunch of conditions and perform an action in the result. Are there any libraries or approaches that can help me building a structure like this? With replaceable/amendable conditions and results? A: There are several patterns here, you can use Chain Of Responsibility to extract out the logic into separate classes. If you want to fully extract it, there are rules engines that can help with that, making the if/else more data-driven. This has it's own concerns, namely around testing, promotion, etc... Feel free to peruse my rant against rules engines: Method or pattern to implement a Business Rules Engine in a solution?
{ "pile_set_name": "StackExchange" }
Q: Fast compare method of 2 columns EDIT: Instead for my solution, use something like For i = 1 To tmpRngSrcMax If rngSrc(i) <> rngDes(i) Then ... Next i It is about 100 times faster. I have to compare two columns containing string data using VBA. This is my approach: Set rngDes = wsDes.Range("A2:A" & wsDes.Cells(Rows.Count, 1).End(xlUp).Row) Set rngSrc = wsSrc.Range("I3:I" & wsSrc.Cells(Rows.Count, 1).End(xlUp).Row) tmpRngSrcMax = wsSrc.Cells(Rows.Count, 1).End(xlUp).Row cntNewItems = 0 For Each x In rngSrc tmpFound = Application.WorksheetFunction.CountIf(rngDes, x.Row) Application.StatusBar = "Processed: " & x.Row & " of " & tmpRngSrcMax & " / " & Format(x.Row / tmpRngSrcMax, "Percent") DoEvents ' keeps Excel away from the "Not responding" state If tmpFound = 0 Then ' new item cntNewItems = cntNewItems + 1 tmpLastRow = wsDes.Cells(Rows.Count, 1).End(xlUp).Row + 1 ' first empty row on target sheet wsDes.Cells(tmpLastRow, 1) = wsSrc.Cells(x.Row, 9) End If Next x So, I'm using a For Each loop to iterate trough the 1st (src) column, and the CountIf method to check if the item is already present in the 2nd (des) column. If not, copy to the end of the 1st (src) column. The code works, but on my machine it takes ~200s given columns with around 7000 rows. I noticed that CountIf works way faster when used directly as a formula. Does anyone has ideas for code optimization? A: Ok. Let's clarify a few things. So column A has 10,000 randomly generated values , column I has 5000 randomly generated values. It looks like this I have run 3 different codes against 10,000 cells. the for i = 1 to ... for j = 1 to ... approach, the one you are suggesting Sub ForLoop() Application.ScreenUpdating = False Dim stNow As Date stNow = Now Dim lastA As Long lastA = Range("A" & Rows.Count).End(xlUp).Row Dim lastB As Long lastB = Range("I" & Rows.Count).End(xlUp).Row Dim match As Boolean Dim i As Long, j As Long Dim r1 As Range, r2 As Range For i = 2 To lastA Set r1 = Range("A" & i) match = False For j = 3 To lastB Set r2 = Range("I" & j) If r1 = r2 Then match = True End If Next j If Not match Then Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = r1 End If Next i Debug.Print DateDiff("s", stNow, Now) Application.ScreenUpdating = True End Sub Sid's appraoch Sub Sample() Dim wsDes As Worksheet, wsSrc As Worksheet Dim rngDes As Range, rngSrc As Range Dim DesLRow As Long, SrcLRow As Long Dim i As Long, j As Long, n As Long Dim DesArray, SrcArray, TempAr() As String Dim boolFound As Boolean Set wsDes = ThisWorkbook.Sheets("Sheet1") Set wsSrc = ThisWorkbook.Sheets("Sheet2") DesLRow = wsDes.Cells(Rows.Count, 1).End(xlUp).Row SrcLRow = wsSrc.Cells(Rows.Count, 1).End(xlUp).Row Set rngDes = wsDes.Range("A2:A" & DesLRow) Set rngSrc = wsSrc.Range("I3:I" & SrcLRow) DesArray = rngDes.Value SrcArray = rngSrc.Value For i = LBound(SrcArray) To UBound(SrcArray) For j = LBound(DesArray) To UBound(DesArray) If SrcArray(i, 1) = DesArray(j, 1) Then boolFound = True Exit For End If Next j If boolFound = False Then ReDim Preserve TempAr(n) TempAr(n) = SrcArray(i, 1) n = n + 1 Else boolFound = False End If Next i wsDes.Cells(DesLRow + 1, 1).Resize(UBound(TempAr) + 1, 1).Value = _ Application.Transpose(TempAr) End Sub my (mehow) approach Sub Main() Application.ScreenUpdating = False Dim stNow As Date stNow = Now Dim arr As Variant arr = Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row).Value Dim varr As Variant varr = Range("I3:I" & Range("I" & Rows.Count).End(xlUp).Row).Value Dim x, y, match As Boolean For Each x In arr match = False For Each y In varr If x = y Then match = True Next y If Not match Then Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = x End If Next Debug.Print DateDiff("s", stNow, Now) Application.ScreenUpdating = True End Sub the results as follows now, you select the fast compare method :) filling in of the random values Sub FillRandom() Cells.ClearContents Range("A1") = "Column A" Range("I2") = "Column I" Dim i As Long For i = 2 To 10002 Range("A" & i) = Int((10002 - 2 + 1) * Rnd + 2) If i < 5000 Then Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = _ Int((10002 - 2 + 1) * Rnd + 2) End If Next i End Sub A: Here is non-looping code that executes almost instantly for the example given above from mehow. Sub HTH() Application.ScreenUpdating = False With Range("A2", Cells(Rows.Count, "A").End(xlUp)).Offset(, 1) .Formula = "=VLOOKUP(A2,I:I,1,FALSE)" .Value = .Value .SpecialCells(xlCellTypeConstants, 16).Offset(, -1).Copy Range("I" & Rows.Count).End(xlUp).Offset(1) .ClearContents End With Application.ScreenUpdating = True End Sub You can use whatever column you like as the dummy column. Info: Done get caught in the loop Some notes on speed testing: Compile vba project before running test. For Each Loops execute faster than For i = 1 To 10 loops. If possible exit the loop if the answer is found to prevent pointless loops with Exit For. Long executes faster than integer. Finally a faster loop method (if you must loop but its still not as fast as the above non-looping method): Sub Looping() Dim vLookup As Variant, vData As Variant, vOutput As Variant Dim x, y Dim nCount As Long Dim bMatch As Boolean Application.ScreenUpdating = False vData = Range("A2", Cells(Rows.Count, "A").End(xlUp)).Value vLookup = Range("I2", Cells(Rows.Count, "I").End(xlUp)).Value ReDim vOutput(UBound(vData, 1), 0) For Each x In vData bMatch = False For Each y In vLookup If x = y Then bMatch = True: Exit For End If Next y If Not bMatch Then nCount = nCount + 1: vOutput(nCount, 0) = x End If Next x Range("I" & Rows.Count).End(xlUp).Offset(1).Resize(nCount).Value = vOutput Application.ScreenUpdating = True End Sub As per @brettdj comments a For Next alternative: For x = 1 To UBound(vData, 1) bMatch = False For y = 1 To UBound(vLookup, 1) If vData(x, 1) = vLookup(y, 1) Then bMatch = True: Exit For End If Next y If Not bMatch Then nCount = nCount + 1: vOutput(nCount, 0) = vData(x, 1) End If Next x
{ "pile_set_name": "StackExchange" }
Q: what are the advantages of defining a foreign key What is the advantage of defining a foreign key when working with an MVC framework that handles the relation? I'm using a relational database with a framework that allows model definitions with relations. Because the foreign keys are defined through the models, it seems like foreign keys are redundant. When it comes to managing the database of an application in development, editing/deleting tables that are using foreign keys is a hassle. Is there any advantage to using foreign keys that I'm forgoing by dropping the use of them altogether? A: Foreign keys with constraints(in some DB engines) give you data integrity on the low level(level of database). It means you can't physically create a record that doesn't fulfill relation. It's just a way to be more safe. A: It gives you data integrity that's enforced at the database level. This helps guard against possibly error in application logic that might cause invalid data. If any data manipulation is ever done directly in SQL that bypasses your application logic, it also guards against bad data that breaks those constraints. An additional side-benefit is that it allows tools to automatically generating database diagrams with relationships inferred from the schema itself. Now in theory all the diagramming should be done before the database is created, but as the database evolves beyond its initial incarnation these diagrams often aren't kept up to date, and the ability to generate a diagram from an existing database is helpful both for reviewing, as well as for explaining the structure to new developers joining a project. It might be a helpful to disable FKs while the database structure is still in flux, but they're good safeguard to have when the schema is more stabilized. A: A foreign key guarantees a matching record exists in a foreign table. Imagine a table called Books that has a FK constraint on a table called Authors. Every book is guaranteed to have an Author. Now, you can do a query such as: SELECT B.Title, A.Name FROM Books B INNER JOIN Authors A ON B.AuthorId = A.AuthorId; Without the FK constraint, a missing Author row would cause the entire Book row to be dropped, resulting in missing books in your dataset. Also, with the FK constraint, attempting to delete an author that was referred to by at least one Book would result in an error, rather than corrupting your database.
{ "pile_set_name": "StackExchange" }
Q: Unity, errors when using Quaternion.Euler to copy rotations In the game I'm creating I have a square that rotates around a parent point, I want the square to always aim upright however (think of a rotating platform). What I've done is simply use child.transform.rotation = Quaternion.Euler(0.0f, 0.0f, -gameObject.transform.rotation.z) This rotates the child object in the opposite direction so that they're always aiming in the right direction. Except it doesn't, there is some error that piles up with bigger rotations. For example at 90º the child object will be rotated -90.77 instead which is very noticeable given that the game has a grid of sorts and when objects are not aligned to it they instantly pop out. So my question is, is there any way to avoid this error? A: transform.rotation is not an Euler angle triplet. It is a quaternion. So its z component is not a rotation angle that you can pipe through Quaternion.Euler meaningfully. If you want to apply only the roll of one object to another, you can do something like this: child.transform.rotation = Quaternion.LookRotation(Vector3.forward, transform.up); This forms a rotation whose forward direction maps to world forward (so 0 pitch / yaw), and whose up direction is as close as possible to parallel to your reference object's up vector when using roll alone. Or to roll it in the opposite direction, take the Quaternion.Inverse of the above.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between Application Program Interface and Uniform Resource Locator? What is the difference between Application Program Interface and Uniform Resource Locator? Please explain it in simple words, since I am still a beginner in web development. A: Let’s say that you have a friend you want to talk to. An application programming interface (API) is basically just a way for two different pieces of software to talk to each other. One API we have in real life is traditional postal mail. You can send a request to your friend by writing it on a piece of paper, putting it in the correct packaging/format, properly addressing the letter, and affixing the required payment. Your friend will receive the request if it follows all the requirements for sending mail. If it doesn’t follow those requirements, the letter will end up somewhere else or potentially nowhere at all. Once your friend gets the request, he has several options. If he doesn’t want to talk to you, he can just sit on the request and wait. If he really hates you, he can get a restraining order to make it forbidden. If he is in a mood to grant your request and if he is convinced the request is truly from you (usually using a token Or key in the case of an API) , he will send what you request back in reply. That letter is fundamentally a real life API. A uniform resource locator is where exactly your friend lives. Think of it as the address for his house. You can go there and visit him, but that’s time consuming and his parents may not like you, which is why you have the API/mail as your agreed upon way to communicate. The API is the postal system. The URL is where your friend lives.
{ "pile_set_name": "StackExchange" }
Q: install mysql proxy via ubuntu terminal How do i install MySql Proxy via ubuntu terminal http://dev.mysql.com/doc/refman/5.1/en/mysql-proxy-install-binary.html A: Go into the directory which contains mysql-proxy-0.8.2-platform.tar.gz from terminal. After that run the below command to extract the mysql-proxy-0.8.2-platform.tar.gz file inside the /usr/local. tar zxf mysql-proxy-0.8.2-platform.tar.gz -C /usr/local To set the environment path su root PATH=$PATH:/usr/local/mysql-proxy-0.8.2-platform/sbin
{ "pile_set_name": "StackExchange" }
Q: Remove duplicates in a PHP array I'm using the Google API to extract data from Analytics. But I can't remove the duplicates in my array. I have checked the forum and array_unique functionalities seems to do the trick but I can't make it working. Any ideas? Much appreciated! THE CODE: <?php $jsonurl = "URL"; $json = file_get_contents($jsonurl,0,null,null); $arrayJson = json_decode($json, true); $arrayTable = $arrayJson['rows']; ?> <table style="border 1px solid" width="700px"> <tr> <td>ID</td> <td>Source</td> <td>Medium</td> <td>Column 4</td> <td>Column 5</td> <td>Column 6</td> <td>Column 7</td> <td>Column 8</td> </tr> <?php for($i = 0; $i < count($arrayTable); $i++) { ?> <tr> <?php for($ii = 0; $ii < count($arrayTable[$i]); $ii++) { ?> <td> <?php print_r($arrayTable[$i][$ii]); ?></td> <?php } ?> </tr> <?php } ?> </table> A: You can use array_unique like below: $input = array("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique($input); print_r($result); Output: Array ( [a] => green [0] => red [1] => blue )
{ "pile_set_name": "StackExchange" }
Q: Is there a way to retain the order of variables in a Spark Dataset? I'm creating a Spark Dataset as Dataset<myBeanClass> myDataset = myDataFrame.as(Encoders.bean(myBeanClass.class)); At this point, its schema looks like, root |-- name: string (nullable = true) |-- age: string (nullable = true) |-- gender: string (nullable = true) After performing a map transformation, Dataset<myBeanClass> resultDataset = myDataset.map(new MapFunction<myBeanClass,myBeanClass>() { @Override public myBeanClass call(myBeanClass v1) throws Exception { // some code return v1; } }, Encoders.bean(myBeanClass.class)); the schema becomes root |-- age: string (nullable = true) |-- gender: string (nullable = true) |-- name: string (nullable = true) Noticed the same behavior in this example as well. Is there a way to retain the order? A: I couldn't figure out a way to stop the order of variables in the schema from changing. But I was able to convert it back to whatever order I wanted. Here is how I did it, DataFrame resultsDataFrame = myDataset.toDF().selectExpr(myDataFrame.schema().fieldNames()); The schema for resultsDataFrame is same as the schema of the DataFrame I created the Dataset from root |-- name: string (nullable = true) |-- age: string (nullable = true) |-- gender: string (nullable = true)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to have comments without blog post in Wordpress? I need to have page where people can send comments, but it is not blog post, so is it possible to make comments to that page without making a blog posting? A: Create a new page, "Comments" ? (Use a plugin to exclude this from your main navigation - if needed) on the page you dont really need to put any text, just scroll down to the "Discussion" section and make sure to tick the box "Allow Comments".. then when the page loads you can add comments to it..? if there is no comment area, then chances are the template file "Page.php" dosnt have the call for the comments file.. just open your page.php file and add <?php comments_template(); ?> were you would like your comment form to appear..
{ "pile_set_name": "StackExchange" }
Q: Can I recover from association (joinTable) with reference to missing data I've read through a lot of posts and docs and must be missing something. In my application (model below) I am having a data issue that seems to be out of my control where I have a categoryId in the join table JOBORDERCATEGORIES that has no corresponding row in the CATEGORY table. I am accessing the category data through getJobCategories() in the JobOrder. This is producing the following error when my Category table is missing a referenced row: 2012-03-07 08:02:10,223 [quartzScheduler_Worker-1] ERROR listeners.SessionBinderJobListener - Cannot flush Hibernate Sesssion, error will be ignored org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.matrixres.domain.Category#416191] and my code is halting. I have tried using ignoreNotFound but it is not helping me to get past the error above. If I missed a post on the solution to this problem please link me to it otherwise thoughts are welcome on how to move forward. Perhaps there is a more direct route I will have to hammer in to achieve my goal of getting a good category list, but I am not familiar enough with the framework to know what is next. As a note, I cannot write to any of these tables. thanks, rich A simplified Version of my Model: Job Order Object: class JobOrder { def getJobCategories() { def cats = [] try { def jocategories = this.categories if(!jocategories.isEmpty() && jocategories!=null){ println "we got categories for ${this.id}" jocategories.each { cat -> if(cat?.parentCategoryID == 0){ if(cat.occupation != null){ cats << cat.occupation } else { cats << cat.name } } } } } catch(e) { cats << "Other Area(s)" } cats } static mapping = { table 'dbo.JOBORDER' version false id generator: 'identity', column: 'JOBORDERID' /* * several other mapped columns deleted here */ categories joinTable:[name:'jobOrderCategories', column: 'categoryId', key:'jobOrderID'] } /* * several properties deleted here */ static hasMany = [categories: Category] //several other hasMany associations exist } Category Object: class Category { static mapping = { table 'CATEGORY' version false id generator: 'identity', column: 'categoryID' occupation column: 'OCCUPATION' name column: 'NAME' parentCategoryID column: 'PARENTCATEGORYID' /* * several other mapped columns deleted here */ jobOrders joinTable:[name:'jobOrderCategories', column: 'jobOrderID', key:'categoryId'] } String name String occupation int parentCategoryID /* * several properties deleted here */ static belongsTo = [JobOrder] static hasMany = [jobOrders:JobOrder] } Join Table: class JobOrderCategories { static mapping = { table 'JOBORDERCATEGORIES' version false isDeleted column: 'ISDELETED' jobOrderID column: 'JOBORDERID' categoryId column: 'CATEGORYID' } Boolean isDeleted Integer jobOrderID Integer categoryId } A: These kinds of situations aren't the most fun, but I have had to deal with this kind of Roll-Your-Own ORM problems before ;) Basically what you're going to want to do here is store the object properties not typed as Object references, but as ints, and while you'll lose some of the dynamic finder things GORM makes so nifty, you'll have a fairly straight-forward means of accessing the data that doesn't involve tangling yourself up with Hibernate's innards. Basically, this will involve ditching your hasMany and belongsTo properties on JobOrder and Category. Instead, you'll want to do things like def myJobOrder = JobOrder.get(yourId); def myCategoryIds = JobOrderCategories.findAllByJobOrderID(myJobOrder.id) def myCategories = Categories.withCriteria { in('id', myCategoryIds) } You can put variations of those traversals in helper methods on your classes, like for example, your getJobCategories method could become class JobOrder { //... def getJobCategories() { def myCategoryIds = JobOrderCategories.findAllByJobOrderID(this.id) def myCategories = Categories.withCriteria { in('id', myCategoryIds) } } } And so on. This is definitely not the prettiest thing in the world to deal with, and you lose your ability to traverse through things easily with GORM (ex a jobOrder.withCriteria { categories { eq('name', blah) } } becomes a executeQuery type of situation.) But overall, its not too bad to deal with :) Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: TreeTableView cells does not get updated when underlying data changes I am writing a Market Watch program which displays live quotes in a JFXTreeTableView, but when I update the data in the ObservableList, it doesn't get updated in the JFXTreeTableView. The changeDataDemo() method is actually tracking changes in the prices and is working fine (I'm using RethinkDB changefeeds to do it.) However I have removed the changefeed code here to increase readability. There is a method that adds rows to TreeTableView and is working perfectly but I have removed the code from here. This is my code: public class MainWindow implements Initializable { private ObservableList<MarketWatchEntry> marketWatchEntries = FXCollections.observableArrayList(); private JFXTreeTableColumn<MarketWatchEntry, String> instrument_token_col; private JFXTreeTableColumn<MarketWatchEntry, String> exchange_col; private JFXTreeTableColumn<MarketWatchEntry, String> instrument_type_col; private JFXTreeTableColumn<MarketWatchEntry, String> symbol_col; private JFXTreeTableColumn<MarketWatchEntry, String> expiry_col; private JFXTreeTableColumn<MarketWatchEntry, Number> buy_qty_col; private JFXTreeTableColumn<MarketWatchEntry, Number> buy_price_col; private JFXTreeTableColumn<MarketWatchEntry, Number> seller_price_col; private JFXTreeTableColumn<MarketWatchEntry, Number> sell_qty_col; @FXML private JFXTreeTableView<MarketWatchEntry> MarketWatch; @Override public void initialize(URL location, ResourceBundle resources) { populateMarketWatch(); } private void populateMarketWatch() { instrument_token_col = new JFXTreeTableColumn<>("Instrument Token"); instrument_token_col.setPrefWidth(80); instrument_token_col.setVisible(false); instrument_token_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().instrument_token); exchange_col = new JFXTreeTableColumn<>("Exchange"); exchange_col.setPrefWidth(80); exchange_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().exchange); instrument_type_col = new JFXTreeTableColumn<>("Instrument"); instrument_type_col.setPrefWidth(80); instrument_type_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().instrument_type); symbol_col = new JFXTreeTableColumn<>("Symbol"); symbol_col.setPrefWidth(80); symbol_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().trading_symbol); expiry_col = new JFXTreeTableColumn<>("Expiry"); expiry_col.setPrefWidth(80); expiry_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().expiry); buy_qty_col = new JFXTreeTableColumn<>("Buy Qty"); buy_qty_col.setPrefWidth(80); buy_qty_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().buy_qty); buy_price_col = new JFXTreeTableColumn<>("Buyer Price"); buy_price_col.setPrefWidth(80); buy_price_col.setCellValueFactory((JFXTreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().buyer_price); seller_price_col = new JFXTreeTableColumn<>("Seller Price"); seller_price_col.setPrefWidth(80); seller_price_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().seller_price); sell_qty_col = new JFXTreeTableColumn<>("Sell Qty"); sell_qty_col.setPrefWidth(80); sell_qty_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().sell_qty); final TreeItem<MarketWatchEntry> root = new RecursiveTreeItem<>(marketWatchEntries, RecursiveTreeObject::getChildren); MarketWatch.getColumns().setAll(instrument_token_col, exchange_col, instrument_type_col, symbol_col, expiry_col, buy_qty_col, buy_price_col, seller_price_col, sell_qty_col, ltp_col, ltq_col, open_price_col, high_price_col, low_price_col, close_price_col, average_price_col, change_col, net_change_col); MarketWatch.setRoot(root); MarketWatch.setShowRoot(false); } private void changeDataDemo() { marketWatchEntries.get(0).buyer_price = new SimpleDoubleProperty(100); } } I have removed irrelevant code blocks to increase readability. My question is how to get TreeTableView to update all the cells when the collection is updated with new data. MarketWatchEntry class class MarketWatchEntry extends RecursiveTreeObject<MarketWatchEntry> { StringProperty instrument_token; StringProperty exchange; StringProperty instrument_type; StringProperty trading_symbol; StringProperty expiry; DoubleProperty buy_qty; DoubleProperty buyer_price; DoubleProperty seller_price; DoubleProperty sell_qty; DoubleProperty last_price; DoubleProperty last_qty; DoubleProperty open_price; DoubleProperty high_price; DoubleProperty low_price; DoubleProperty close_price; DoubleProperty average_price; DoubleProperty change; DoubleProperty net_change; public MarketWatchEntry(String instrument_token, String exchange, String instrument_type, String trading_symbol, String expiry, double buy_qty, double buy_price, double sell_price, double sell_qty, double last_price, double last_qty, double open_price, double high_price, double low_price, double close_price, double average_price, double change, double net_change) { this.instrument_token = new SimpleStringProperty(instrument_token); this.exchange = new SimpleStringProperty(exchange); this.instrument_type = new SimpleStringProperty(instrument_type); this.trading_symbol = new SimpleStringProperty(trading_symbol); this.expiry = new SimpleStringProperty(expiry); this.buy_qty = new SimpleDoubleProperty(buy_qty); this.buyer_price = new SimpleDoubleProperty(buy_price); this.sell_qty = new SimpleDoubleProperty(sell_qty); this.seller_price = new SimpleDoubleProperty(sell_price); this.last_price = new SimpleDoubleProperty(last_price); this.last_qty = new SimpleDoubleProperty(last_qty); this.open_price = new SimpleDoubleProperty(open_price); this.high_price = new SimpleDoubleProperty(high_price); this.low_price = new SimpleDoubleProperty(low_price); this.close_price = new SimpleDoubleProperty(close_price); this.average_price = new SimpleDoubleProperty(average_price); this.change = new SimpleDoubleProperty(change); this.net_change = new SimpleDoubleProperty(net_change); } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return this.instrument_token.getValue().equals(((MarketWatchEntry) obj).instrument_token.getValue()); } @Override public int hashCode() { return 7 + 5 * Integer.valueOf(instrument_token.getValue()); } } A: The problem is in your changeDataDemo method: private void changeDataDemo() { marketWatchEntries.get(0).buyer_price = new SimpleDoubleProperty(100); } You are creating new instances of your properties instead of changing their values. Something like this works: private void changeDataDemo() { marketWatchEntries.get(0).buyer_price.set(100); } But it is recommended to provide setters/getters on your Entity class: class MarketWatchEntry extends RecursiveTreeObject<MarketWatchEntry> { private final DoubleProperty buyer_price; ... public MarketWatchEntry(String instrument_token, String exchange, String instrument_type, String trading_symbol, String expiry, double buy_qty, double buy_price, double sell_price, double sell_qty) { ... this.buyer_price = new SimpleDoubleProperty(buy_price); ... } public final DoubleProperty buyer_priceProperty() { return buyer_price; } public final double getBuyer_price() { return buyer_price.get(); } public final void setBuyer_price(double value) { buyer_price.set(value); } ... } so you can just call: private void changeDataDemo() { marketWatchEntries.get(0).setBuyer_price(100); }
{ "pile_set_name": "StackExchange" }
Q: IP Address Parameter in ASP.Net I have a stored procedure that inserts a few columns into a database, IP Address, Name, Comments. I am not sure how to get the ip address of the users machine. Perhaps I am to create a variable of the same type (INT) and then store the IP Address in there. I am kinda of lost on this one. static int IPAddress() { get { return Request.UserHostAddress; }; }//How do I pass from here into my stored procedure? cmdI.Parameters.Add(new SqlParameter("@IPAddress", cmdI)); cmdI.Parameters.Add(new SqlParameter("@Name", cmdI)); cmdI.Parameters.Add(new SqlParameter("@Comments", cmdI)); A: You need to convert the IP Address from a string to an int; see How to convert an IPv4 address into a integer in C#? However, I would change the DB to store IP address as a string. This way you will support IPv6.
{ "pile_set_name": "StackExchange" }
Q: how to access session variable in the file routes.php using cakephp 2.0? I'm needing to access a session variable in the routes file. (routes.php) Anyone know how I can do this? If not possible, is there any way to access a session variable in bootstrap.php? thank you A: You can start sessions this early as far as I know. App::uses('CakeSession', 'Model/Datasource'); $value = CakeSession::read('your-value');
{ "pile_set_name": "StackExchange" }
Q: Regular polygons meeting at a point $N$ regular polygons with $E$ edges each meet at a point with no intervening space. Show that $$N = \frac{2E}{E-2}\qquad E=\frac{2N}{N-2}$$ I did this part considering that the internal angles must add up to $2\pi$ , i.e $\left( 1 -\dfrac2E \right)\pi\times N =2\pi $. I am unable to explain the following: Using the result given above, show that the only possibilities are $E=3,4,6$ A: If $E\gt6$ then your second equation tells you something impossible about $N$. EDIT: Perhaps this was too subtle, so here are the details. Suppose $E\gt6$. Then by the second equation in the question, $2N/(N-2)\gt6$, $2N\gt6N-12$, $4N\lt12$, $N\lt3$. But if $N$ regular polygons meet at a point with no intervening space, then $N\ge3$, so we have a contradiction to our assumption that $E$ was greater than 6. So, $E\le6$. Also, there are no polygons with fewer than 3 edges, so $E\ge3$. Well, that doesn't leave very many values of $E$, does it? And $E=5$ leads to $N=10/3$, which is absurd. So, the only possibilities are $E=3,4,6$.
{ "pile_set_name": "StackExchange" }
Q: Upgrade error .net 1 winforms application I have an ld application written in .NET 1.1 which I try to upgrade to .NET 3.5. The VsStudio conversion is all fine, and after the upgrade I can run the application without any problems. However, since the fonts are another the text won't fit inside the controls. And that's where my trouble start, because as soon as I change anything, be it the size of a control or the size of any font, after a build the designer stops working with that form, hides it and display an error: at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value) at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object component, Object value) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement) Then, when I try to run the application, it won't load those forms at all, I only get an error. I'm not that comfortable with .NET so any hint on what might be the error would be helpful, thanks and regards! A: It seem to work when I set the "DesignerSerializationVisibility" attribute on some of the properties. This prevent the Designer from crashing and I was able to build and run my application
{ "pile_set_name": "StackExchange" }
Q: Microservice project structure using Spring boot and Spring Cloud I am trying to convert a normal monolithic web application into microservices structure using Spring Boot and Spring Cloud. I am actually trying to create Angular 2 front-end application and calls these my developed microservices in the cloud. And I am already started to break the modules into independent process's structure for microservice architecture. Here my doubt is that, when designing the flow of control and microservice structure architecture, can I use only one single Spring Boot project using different controller for this entire web application back end process? Somewhere I found that when I am reading develop all microservices using 2 different Spring Boot project. I am new to Spring and Spring Cloud. Is it possible to create all services in single project by using different modules? A: Actually, it doesn't matter to package all those services into ONE project. But in micro-service's opinion, you should separate them into many independent projects. There are several questions you can ask yourself before transforming original architecture. Is your application critical? Can user be tolerant of downtime while you must re-deploying whole package for updating only one service? If there is no any dependency between services, why you want to put them together? Isn't it hard to develop or maintain? Is the usage rate of each service the same? Maybe you can isolate those services and deploy them which are often to be invoked to a strong server. Try to read this article Adopting Microservices at Netflix: Lessons for Architectural Design to understand the best practices for designing a microservices architecture. And for developing with Spring Cloud, you can also read this post Spring Cloud Netflix to know which components you should use in your architecture.
{ "pile_set_name": "StackExchange" }
Q: SQL Sum of 2 rows when 4 rows are returned I'm trying to get a percent complete column in SQL for the following data. This is the results from my query. work_order_no status orderqty complete precentcomplete WO-000076 Approved 20.0000 9 5201725 WO-000076 Approved 20.0000 10 15605175 WO-000078 Approved 12000.0000 200 91258.3333333333 WO-000078 Approved 12000.0000 500 228145.833333333 What I need is a result with 2 rows. Row 1 will be WO-00076 and the percent complete. Row 2 will be WO-000078 and the percent complete. Below is the query that I am working with. Select distinct wo.work_order_no, wos.status_description, wo.order_qty as [ORDERQTY], p.good_tot_diff as [COMPLETE], (sum(p.good_tot_diff)/wo.order_qty) * 100 as [PERCENTCOMPLETE] from wo_master as wo, process as p, wo_statuses as wos, so_children as soc, so_sales_orders as sos, cs_customers as csc where wo.work_order_no = p.entry_18_data_txt and wo.work_order_no = soc.work_order_no and wo.wo_status_id = wos.wo_status_id and wo.mfg_building_id = @buildid and wos.wo_status_id = @statusid group by wo.work_order_no, wos.status_description, wo.order_qty, p.good_tot_diff So I would like the results to be like below work_order_no status orderqty complete precentcomplete WO-000076 Approved 20.0000 19 0.95 WO-000078 Approved 12000.0000 700 0.005 A: This should be what you want. The complete column should not be included in the GROUP BY, and should be summed. SELECT DISTINCT wo.work_order_no, wos.status_description, wo.order_qty AS [ORDERQTY], SUM(p.good_tot_diff) AS [COMPLETE], (sum(p.good_tot_diff)/wo.order_qty) * 100 AS [PERCENTCOMPLETE] FROM wo_master AS wo, process AS p, wo_statuses AS wos, so_children AS soc, so_sales_orders AS sos, cs_customers AS csc WHERE wo.work_order_no = p.entry_18_data_txt AND wo.work_order_no = soc.work_order_no AND wo.wo_status_id = wos.wo_status_id AND wo.mfg_building_id = @buildid AND wos.wo_status_id = @statusid GROUP BY wo.work_order_no, wos.status_description, wo.order_qty;
{ "pile_set_name": "StackExchange" }
Q: Windows batch string comparison in if statement wrong? i try to write a tiny batch file which shall react in different way dependent on a parameter. Unfortunately the "if" statement whch compares 2 strings seem not to work as expected. The code used is: @echo off if "%1"=="" goto Usage echo "Parameter: %1" IF /I "%1"=="START" { echo "Why the hell is %1 == Start?" SET Parameter=start goto :execute } else if /I "%1"=="STOP" { SET Parameter=stop goto :execute } echo "Parameter %1% invalid" :Usage echo "Synapsis:" echo " SwitchServices Start|Stop" goto :EOF :execute SET servicename=Dnscache SET filename=Dnscache.exe CALL :%parameter%_Service goto :EOF :stop_Service echo ... stopping service ... net stop %servicename% if (ERRORLEVEL GTR 0) call :kill_Service sc config %servicename% start= disabled Service stopped. exit /b :kill_Service taskkill /f /IM %filename% exit /b :start_Service echo ... starting service ... sc config %servicename% start= auto net start %servicename% exit /b :EOF The result is: c:\Users\kollenba\Documents\Temp>KapschServices.cmd xxx "Parameter: xxx" "Why the hell is xxx == Start?" ... starting service ... [SC] ChangeServiceConfig ERFOLG Der angeforderte Dienst wurde bereits gestartet. I do not understand why the condition if /I "%1"=="START" does not work as expected. Any hints? Precondition: the batch file must be executed with administrator permissions to allow the "net start" command. Used OS: Windows 7 A: In batch we don't use braces to enclose if statements, instead we use parenthesis. So replace this: IF /I "%1"=="START" { echo "Why the hell is %1 == Start?" SET Parameter=start goto :execute } else if /I "%1"=="STOP" { SET Parameter=stop goto :execute } By this one: IF /I "%1"=="START" ( echo "Why the hell is %1 == Start?" SET Parameter=start goto :execute ) else if /I "%1"=="STOP" ( SET Parameter=stop goto :execute ) You are also missing an echo before Service stopped. And a bonus tip: You actually don't need the :EOF label because goto :EOF will always take you to the End Of File
{ "pile_set_name": "StackExchange" }
Q: Magento - I deleted a website by accident I was going to delete a store view for a particular language in Magento. I deleted the website view by accident. Luckily I made a back-up just moments before. The tables 'core_config_data' and 'core_websites' have been restored and it seems the website is working properly. However I need to be 100% sure that no other data is missing. Magento does state: 'Removing a website does not lead to the removal of the information associated with (eg categories, products, etc.), but the removal can not be undone. We recommend that you back up your database before performing the removal.' I need to know in which tables data is removed when you deleted a website view? A: The safest is to restore your full database. If you delete a website all the stores associated to it are deleted and so all all the product values set for those specific store views. For example if you had a product named 'Something' but on a store view from the website you delete it had the name 'Something else' then you will lose this. If you restored only the store views the name of that product on the specific store view will be 'Something'.
{ "pile_set_name": "StackExchange" }
Q: QThread crashes the program? I implement QThread like this, but get program crashed when it runs. I've searched and seen posts saying it is not the correct way to use QThread. But I cannot find any reason for the crashes of my program, what I do is only triggering 'on_Create_triggered()' and I guarantee the mutex is locked and unlocked properly. I have tested the program for two days(testing only by 'std::cerr << ...;' prints results), but still cannot find reason. What I guess is that the thread may wait for the lock too long and cause program to crash. (not sounds reasonable...) :) My codes: Background.h class Background : public QThread { Q_OBJECT public: Background(int& val,DEVMAP& map, QQueue<LogInfoItem*>& queue, QList<DEV*>& devlist, QList<IconLabel*>& icllist,QMutex& m) :val_i(val),DevMap(map), LogInfoQueue(queue), DevInfoList(devlist), IconLabelList(icllist),mutex(m) {} ~Background(); protected: void run(void); private: DEVMAP& DevMap; QQueue<LogInfoItem*>&LogInfoQueue; QList<DEV*>& DevInfoList; QList<IconLabel*>& IconLabelList; int& val_i; QMutex& mutex; void rcv(); }; Background.cpp #include "background.h" Background::~Background() { LogFile->close(); } void Background::run(void) { initFile(); while(1) { msleep(5); rcv(); } } void Background::rcv() { mutex.lock(); ... ...//access DevMap, LogInfoQueue, DevInfoList, IconLabelList and val_i; ... mutex.unlock(); } MainWindow:(MainWindow has Background* back as property) void MainWindow::initThread() { back = new Background(val_i, dev_map, logDisplayQueue, devInfoList, iconLabelList, mutex); back->start(); } void MainWindow::on_Create_triggered() { mutex.lock(); ... ...//access DevMap, LogInfoQueue, DevInfoList, IconLabelList and val_i; ... mutex.unlock(); } A: I have found the reason, which is more subtle. (I use some codes written by others but believe it is not broken, what I got totally wrong! :) ) The broken codes: #define DATABUFLEN 96 typedef struct Para//totally 100bytes { UINT8 type; UINT8 len; UINT8 inType; UINT8 inLen; UINT8 value[DATABUFLEN];//96 bytes here }ERRORTLV; class BitState { public: UINT8 dataBuf[DATABUFLEN]; ...... }; And the function using it: bool BitState::rcvData() //the function crosses bound of array { UINT8 data[12] = { 0x72, 0x0A, 0x97, 0x08, 0x06, 0x0A, 0x0C, 0x0F, 0x1E, 0x2A, 0x50, 0x5F, }; //only 12 bytes UINT32 dataLen = 110; memcpy(this->dataBuf, data, dataLen); //copy 110 bytes to dataBuf //but no error or warning from compiler, and no runtime error indicates the cross } bool BitState::parseData(BitLog* bitLog)//pass pointer of dataBuf to para_tmp, but only use 0x08 + 4 = 12 bytes of dataBuf { Para* para_tmp; if(*(this->dataBuf) == 0x77) { para_tmp = (ERRORTLV*)this->dataBuf; } if(para_tmp->type != 0x72 || para_tmp->inType != 0x97 || (para_tmp->len - para_tmp->inLen) != 2) // inLen == 0x08 { return false; } else { //parse dataBuf according to Para's structure this->bitState.reset(); for(int i = 0; i < para_tmp->inLen; i++) // inLen == 0x08 only !!! { this->bitState[para_tmp->value[i]-6] = 1; } if(this->bitState.none()) this->setState(NORMAL); else this->setState(FAULT); QString currentTime = (QDateTime::currentDateTime()).toString("yyyy.MM.dd hh:mm:ss.zzz"); string sysTime = string((const char *)currentTime.toLocal8Bit()); this->setCurTime(sysTime); this->addLog(sysTime, bitLog); } return true; } bool BitState::addLog(std::string sysTime, BitLog* bitLog)// this function is right { bitLog->basicInfo = this->basicInfo;//not in data Buf, already allocated and initialized, (right) bitLog->bitState = this->bitState; //state is set by setState(..) bitLog->rcvTime = sysTime; //time return true; } Generally speaking, the program allocates 96 bytes to a byte array, but use 'memcpy(...)' to copy 110 bytes to the array, later uses only 12 bytes of the array. All kinds of crashes appear, which are confusing and frustrating...:( :( :(
{ "pile_set_name": "StackExchange" }
Q: 13.04 system UI fonts subbed with random serif font After upgrading to 13.04, the first thing I noticed was that the neat window title font (and all the other default system fonts I'd enjoyed) were replaced with other fonts. Also, the terminal font has really messed up spacing and is definitely not the font it's supposed to be. I checked the system settings, and even Tweak said the fonts weren't serif....why is this? (Tried uninstalling Tweak; now the "Appearance/Behavior" settings group isn't even available.) A: See if this applies to your case. It fixed the font spacing problems I was having in Gnome Terminal and Gvim. Fonts corrupted, all look the same I used Syanptic to determine the unidentified library. The following cleared it up for me. $ sudo apt-get purge libpango1.0-common pango-graphite
{ "pile_set_name": "StackExchange" }
Q: What is the difference between https://google.com and https://encrypted.google.com? Is it there any difference between the encrypted Google search (at https://encrypted.google.com) and the ordinary HTTPS Google search (at https://google.com)? In terms of security what were the benefits of browsing through encrypted Google search? Note that this is not a question about HTTP vs HTTPS. These are two Google services. A: According to Google, the difference is with handling referrer information when clicking on an ad. After a note from AviD and with the help of Xander we conducted some tests and here are the results 1. Clicking on an ad: https://google.com : Google will take you to an HTTP redirection page where they'd append your search query to the referrer information. https://encrypted.google.com : If the advertiser uses HTTP, Google will not let the advertiser know about your query. If the advertiser uses HTTPS, they will receive the referrer information normally (including your search query). 2. Clicking on a normal search result: https://google.com : If the website uses HTTP, Google will take you to an HTTP redirection page and will not append your search query to the referrer information. They'll only tell the website that you're coming from Google. If it uses HTTPS, it will receive referrer information normally. https://encrypted.google.com : If the website you click in the results uses HTTP, it will have no idea where you're coming from or what your search query is. If it uses HTTPS, it will receive referrer information normally. The same topic was covered in an EFF blog post. EDIT: Google dropped encrypted.google.com as of April 30 2018. According to Google, this domain was used to give users a way to securely search the internet. Now, all Google products and most newer browsers, like Chrome, automatically use HTTPS connections. A: At the time of writing (July 2013), the two sites have different preferences for key exchange algorithms. To inspect in Chrome, click the padlock icon and select the 'connection' tab. Against Chrome 28, vanilla google.com uses ECDHE_RSA, encrypted.google.com uses ECDHE_ECDSA. Both algorithms give forward secrecy. https://www.imperialviolet.org/2011/11/22/forwardsecret.html For details, compare the configurations using the SSL Labs server test https://www.ssllabs.com/ssltest/analyze.html?d=encrypted.google.com https://www.ssllabs.com/ssltest/analyze.html?d=google.com https://www.ssllabs.com/ssltest/analyze.html?d=www.google.com A: Today (March 2018), encrypted.google.com is deprecated, and as of 30 April 2018, encrypted.google.com will redirect to www.google.com. From the infrastructure point of view (servers, certificates, TLS parameters), there are no significant differences any more. Although the requests are handled by the same servers (see the end of this answer), there are still some differences between the two domains: Localized domain redirects encrypted.google.com does not redirect to other domains, whereas google.com attempts to redirect to a country-specific domain (ccTLD). To avoid this redirect, https://google.com/ncr is often proposed. However, that only works if cookies are enabled. To prevent the redirection from happening without requiring cookies, append the gws_rd=cr parameter to the URL. (for the points below, I won't differentiate between www.google.com and ccTLDs any more) Google Search branding Unlike google.com, encrypted.google.com's UI does not show links to other Google products/apps. E.g. compare the header at google.com (archived) with encrypted.google.com (archived). This is likely because encrypted.google.com was introduced specifically for encrypted search (these days, https support is a well-established default; back then https was introduced as an optional feature). Referrer leakage and user tracking In both cases, the HTTP referer for normal search results does not contain the original search terms in clear text (though there are many obscure URL parameters that can potentially be used to track the user, which is even more likely if the site uses Google services such as Google Analytics). This keyword hiding is often (depending on the browser, device, browser features as JavaScript) implemented by not directly linking to the final destination, but by using an intermediate redirection URL as the search result, e.g. [google domain]/url?q=[destination URL] (advertisements are routed through multiple redirection URLs and include the original search terms, regardless of the Google domain). Sometimes (again, depending on the browser, etc.) Google uses <meta content="origin" name="referrer"> to strip the HTTP referer, and alternative methods for tracking (e.g. beacons or hyperlink auditing). (At the time of writing, encrypted.google.com uses the former in Google Chrome, and www.google.com uses the latter method. But this does really not mean much. E.g. in Internet Explorer 11, the former method is used for both Google domains.) To keep the original destination URL without leaking the referrer, my "Don't Track Me Google" browser extension can be used: https://github.com/Rob--W/dont-track-me-google (Even without any intervention from websites such as Google, the HTTP referer can also be cleaned. For example, when the originator is HTTPS and the destination HTTP, or when Firefox's private browsing mode is used, or if the user is using flags or extensions that disable/strip the referer (example for Chrome, examples for Firefox)). In the past there was also a difference in information leakage through HTTP Referer, but that is not the case any more. Compare the help pages for SSL Search: Google Search Help - SSL Search (retrieved April 2013) (many paragraphs of text) Google Search Help - SSL Search (latest) (almost no text) The following test shows that the two different Google domains may resolve to different IP addresses, and that these IP addresses are able to handle search queries for any Google search domain. $ host encrypted.google.com encrypted.google.com is an alias for www3.l.google.com. www3.l.google.com has address 172.217.20.78 www3.l.google.com has IPv6 address 2a00:1450:400e:80a::200e $ host www.google.com www.google.com has address 172.217.20.68 www.google.com has IPv6 address 2a00:1450:400e:800::2004 $ curl -I https://encrypted.google.com/ --resolve encrypted.google.com:443:172.217.20.68 $ curl -I https://encrypted.google.com/ --resolve encrypted.google.com:443:172.217.20.78 $ curl -I https://www.google.com/?gws_rd=cr --resolve www.google.com:443:172.217.20.68 $ curl -I https://www.google.com/?gws_rd=cr --resolve www.google.com:443:172.217.20.78 $ curl -I https://www.google.nl/?gws_rd=cr --resolve www.google.nl:443:172.217.20.78 The last curl commands all receive the search results without further redirects (I haven't included their output in this answer). To see the SSL details, either replace -I with -vvv or use something like openssl s_client -connect google.com:443.
{ "pile_set_name": "StackExchange" }
Q: GWT DataGrid with SimplePager, Last Page Issue I'm using GWT DataGrid with SimplePager to show a my Data, The Component shows the first pages correctly, but the last page shows always 10 rows (10 = SimplePager.pagesize) even if we have less then 10 rows to display. AnyOne have an idea about yhis issue ? Thanx. A: I encountered a similar issue before. The small difference is that I was using Celltable instead of DataGrid. The problem is coming from a known bug of gwt which you can see the detail on its github page. Obviously it has been fixed yet. The workaround is to subclass the SimplePager and create your custom pager class. import com.google.gwt.user.cellview.client.SimplePager; import com.google.gwt.view.client.Range; public class CustomPager extends SimplePager { public CustomPager() { this.setRangeLimited(true); } @Override public void setPageStart(int index) { if (this.getDisplay() != null) { Range range = this.getDisplay().getVisibleRange(); int pageSize = range.getLength(); index = Math.max(0, index); if (index != range.getStart()) { this.getDisplay().setVisibleRange(index, pageSize); } } } }
{ "pile_set_name": "StackExchange" }
Q: with boxes/divs i created a box, and now i want to replicate it four times, make 4 boxes horizontally aligned but don't want to paste 4 times the code, any way to do this with <li> tag? The html: <div id="promos"> <div class="promoinside">promo</div> </div> the css: #promogrid{ width:auto; height: auto; background-color: #ffffff; } #promos{ position: relative; margin: 10px 5px 10px 5px; -moz-border-radius: 5px; border-radius: 5px; width:225px; height:160px; background-color: #fff; border-style:solid; border-width:1px; border-color: #cacaca; -moz-box-shadow: 0 0 4px #dadada; -webkit-box-shadow: 0 0 4px#dadada; box-shadow: 0 0 3px #dadada; } .promoinside{ position: absolute; margin: 3px 4px 4px 3px; width: 219px; height: 154px; background: #f5f5f5; background:-webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee)); background: -moz-linear-gradient(top, #fafafa, #eeeeee); } .promoinside:hover{ background: #fbfbfb; } A: You can definitely do that using li. Divs are valid inside li tags (see Is div inside list allowed?). You're much better off writing the code for each box manually, as it involves a minimal amount of code compared to creating them dynamically. (If the boxes change a lot however you would be better off making them dynamic.) <ul id="promos"> <li><div class="promoinside">promo</div></li> </ul> ul#promos { list-style: none; padding-left: 0; margin-left: 0; } ul#promos li { display: inline; }
{ "pile_set_name": "StackExchange" }
Q: What's the probability that at least one goldfish eats more than 1 pellet? I scatter 5 pellets in a tank of 5 goldfish. Assuming all pellets are eaten and each goldfish has equal probability of eating each pellet (and that goldfish don't eat less as they eat more), what is the probability that at least one goldfish eats more than 1 pellet? I had originally thought the answer was $\frac{1}{5^5}$, but then I realized that the denominator was wrong because the pellets are not replaceable. A: Think of it as rolling five $5$-sided dice: if pellet $1$ is eaten by fish $3$, die $1$ has come up $3$. In these terms you’re asking for the probability that the five dice all show different numbers. There are $5^5$ different ways they can come up; how many of those give the desired result? Added: Here’s another way to attack it. Imagine that no two pellets are eaten at exactly the same moment. Label them $P_1,\dots,P_5$ in the order in which they’re eaten. The probability that $P_1$ is eaten be a fish that hasn’t already swallowed a pellet is obviously $1$. The probability that $P_2$ is eaten by a different fish is $\frac45$. Keep going to find the probabilities that $P_3,P_4$, and $P_5$ are eaten by fish that haven’t already swallowed a pellet. What do you do with these probabilities to get the final result?
{ "pile_set_name": "StackExchange" }
Q: Send data from TableViewCell to Controller MVC-Principle I have got a UITableView with UITableViewCell inside UICollectionViewCell which is created in the ViewController. For both, the UITableView and the UITableViewCell I have a separate subclass file. In the UITableViewCell-Subclass I have a value changed delegate action linked to the TextField in it. Now whenever this value of the Textfield gets changed (the function is called) I need to pass the value down to my ViewController where it is processed. How is that done regarding the MVC-principle? A: You can use blocks or delegates or pass the value back to the ViewController. Inside the UITableViewCell subclass declare a delegate protocol TableViewCellDelegate { func new(value: Any) // your data type here } class MySubclass: UITableViewCell { weak var delegate: TableViewCellDelegate? } Now in the ViewController connect to this delegate. You can pass it to the UICollectionViewCell subclass and from there to the UITableViewCell Inside the value change delegate of the UITextField you call your method self.delegate?.new(value: "NewTextHere!") this way the data can be passed back to the ViewController
{ "pile_set_name": "StackExchange" }
Q: Javascript chained destructuring const someFunction = ({ a }) => { const { b } = a; return <div>{b}</div> } const obj = { a: { b: 1 } } someFunction(obj) Is there a way to chain object destructuring so that in someFunction, we can destructure obj to get b within the parameter instead of having to do a separate const { b } = a in the function body? A: You can do it like so: const someFunction = ({ a: { b } }) => { return b; } const obj = { a: { b: 1 } }; console.log(someFunction(obj));
{ "pile_set_name": "StackExchange" }
Q: Why mail() PHP function does not work with WAMP default installation? I have a default installation of WAMP Server 2.0. I'm trying to send email using this simple script: <?php if (mail('[email protected]', 'My Title', 'Some Text')) { echo "OK"; } else { echo "Why ??"; } ?> Unfortunately, I get the following warning: Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\My_Path\send_email.php on line 3 Why ?? What could be the reason for that ? I expected sending email to be a very simple task ... :( A: To be able to send email you need an outgoing email server (MTA). In most Linux systems there exists one by default, and PHP will use it by submitting mail to sendmail, a Linux app/alias for submitting mail to whichever MTA you have installed. Windows doesn't include an MTA by default. In Windows, to be able to send mail from PHP you need to have access to some outgoing email server and tell PHP the address and port of it. This is done in php.ini using the SMTP and smtp_port settings. It will default to localhost on port 25. Unless you have set up a mail server on that machine yourself, this will fail. If your ISP gives you an outgoing mail server, for example, you could use its address and port number. Or, if you're serious about sending mail, you'd set up your own mail server on the local machine or somewhere in your local network.
{ "pile_set_name": "StackExchange" }
Q: Make sure images get preloaded on an Ajax Call I have noticed that a jQuery Ajax call don't preload/load the images of the target page before it callbacks. So basically it just loads the html and then make the callback and after the callback it starts to load the image/images. So my question is if there's a way to make sure that the target page images also gets loaded/preloaded before the append function. Example Code: $.ajax({ url: ''+nextHref+'', success: function(data) { var $response = $(data); var oneval = $response.find('#ContainerWrapper').html(); // Then some kind of function that preloads the target images before it appends the ajax result. So basically the part below is where I don't know what o do. $response.find('#ContainerWrapper img').examplepreloadfunction(function(){ $("#ContainerWrapper").append(oneval); }); } }); Any answers, clues, ideas or experiments? A: To preload an image: $('<img/>')[0].src = '/path/to/image'; or: (new Image()).src = '/path/to/image'; You could try this for each image before injecting the HTML you received from the AJAX call into the DOM.
{ "pile_set_name": "StackExchange" }
Q: Validate Geolocation latitude and longitude I have a Ruby on Rails model Camping with #latitude and #longitude attributes. This should be validated. It must be validated so that: The values are correctly formatted. E.g. 48.8582 and 2.2945 but also 48.8 and 2.2. Any precision should be allowed. I store them as Float, any addtitional validation needed or advised? They are within valid ranges (0-90). Or should I allow negative numbers, or numbers above and below 90? I am not interested in whether on this point is an actual valid address (sea, northpole, whatever, as long as it is a valid point on earth). I am using geocoder gem, but for now, input is simply a pair of lat/lon textfields. Geocoder is merely of interest for this question because it may have utility-methods (which I cannot find) to validate a lat/long pair. A: I'm not aware of any methods in Geocoder to check that but you could just use rails validations validates :latitude , numericality: { greater_than_or_equal_to: -90, less_than_or_equal_to: 90 } validates :longitude, numericality: { greater_than_or_equal_to: -180, less_than_or_equal_to: 180 }
{ "pile_set_name": "StackExchange" }
Q: Man pages from custom location When I build some source in custom location, i.e.: configure --prefix=$HOME/.local and then, make install..., man pages are copied in ~/.local/share/man/ but inaccessible from man command How can I make man recognise pages in my custom location? A: For one-off manpage reading, just point man at the specific file: man ~/.local/share/man/manX/manpage.1.gz Otherwise, if you want to always check ~/.local/share, then set the MANPATH environment variable for your user session (typically in your .bashrc file). To check what the current MANPATH is, do: manpath you'll probably want to append :$HOME/local/.share/man to the end of that.
{ "pile_set_name": "StackExchange" }
Q: WHERE clause is not filtering on LESS THAN and GREATER THAN or BETWEEN I am trying to select MTR values that are between the values of 0 and 4. What am I doing wrong? SELECT DATEDIFF(M, TheDate, TheOtherDate) AS MTR FROM MyTable WHERE MyID = 2074163 AND MTR >= 0 OR MTR <= 4 Returns results that contain values inside and outside of the bounds of MTR being between 1 and 4. (from -3 to 75) Alternately SELECT DATEDIFF(M, TheDate, TheOtherDate) AS MTR FROM MyTable WHERE MyID = 2074163 and MTR BETWEEN 0 AND 4 Is also returning results that are 0, -2, -3, and -4 - but nothing higher than 0 and less than 4 (except for the entries that are 0) A: The correct syntax for this would be: SELECT DATEDIFF(M, TheDate, TheOtherDate) AS MTR FROM MyTable WHERE MyID = 2074163 AND ( DATEDIFF(M, TheDate, TheOtherDate) >= 0 AND DATEDIFF(M, TheDate, TheOtherDate) <= 4 ) A: Ypercube's comment is relevant. The reference to MTR in your WHERE clause should be flagged as invalid, according to the standard. But apart from that, which value of MTR do you think will ever make that OR evaluate to false ?
{ "pile_set_name": "StackExchange" }
Q: JavaScript push to array object is not working I have an html like below HTML: <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" /> <input type="hidden" id="project" value="" /> JS: function add(obj1 , obj2){ var jsonArray = []; var jsonObj = { product_id : obj1 , name : obj2 }; jsonArray.push(jsonObj); var field = document.getElementById('project'); field.setAttribute('value', JSON.stringify(jsonArray)); alert(field.getAttribute('value')); } I am trying to set first and retrieve again to check but nothing is happening..I can't understand where I am wrong...? A: I guess you missed to get the stringify result into stringData variable because of which you are getting a js error before it reaches the line where you are trying to alert the value. JSON or JSON.stringify is not provided by jQuery you have to include json2 library on the page if the browser natively do not support it. Try this function add(obj1 , obj2){ var jsonArray = []; var jsonObj = { product_id : obj1 , name : obj2 }; jsonArray.push(jsonObj); var stringData = JSON.stringify(jsonArray); var field = document.getElementById('project'); field.setAttribute('value', stringData); alert(field.getAttribute('value')); } Code to remove element from array based on your request in the comment. var newArray = [], productIdToRemove = "1234"; $.each(jsonArray, function(){ if(this.product_id != productIdToRemove){ newArray.push(this); } }); //Now newArray will not have '1234'
{ "pile_set_name": "StackExchange" }
Q: Diamond Syntax in C# Java 7 now has this "diamond syntax" where I can do things like ArrayList<int> = new ArrayList<>(); I'm wondering if C# has a similar syntax that I can take advantage of. For example, I have this part of a class: class MyClass { public List<double[][]> Prototypes; // each prototype is a array of array of doubles public MyClass() { Prototypes = new List<double[][]>; // I'd rather do List<>, in case I change the representation of a prototype later } } Does anyone know if this is possible, and if so, how I might go about using it? A: No, there's nothing quite like the diamond syntax in C#. The closest you could come would be to have something like this: public static class Lists { public static List<T> NewList<T>(List<T> ignored) { return new List<T>(); } } Then: public MyClass() { ProtoTypes = Lists.NewList(ProtoTypes); } That just uses normal generic type inference for methods to get T. Note that the value of the parameter is completely ignored - it's only the compile-time type which is important. Personally I think this is pretty ugly, and I'd just use the constructor directly. If you change the type of ProtoTypes the compiler will spot the difference, and it won't take long at all to fix it up... EDIT: Two alternatives to consider: A similar method, but with an out parameter: public static class Lists { public static void NewList<T>(out List<T> list) { list = new List<T>(); } } ... Lists.NewList(out ProtoTypes); The same method, but as an extension method, with the name New: public static class Lists { public static List<T> New<T>(this List<T> list) { return new List<T>(); } } ... ProtoTypes = ProtoTypes.New(); I prefer the first approach to either of these :) A: As Jon Skeet said and Eric Lippert backed up, constructors for generic classes in C# cannot infer their types from their parameters or the type of the variable to which the construction is assigned. The go-to pattern when this type of behavior is useful is usually a static generic factory method, which can infer its own generic type from those of its parameters. Tuple.Create() is an example; give it any list of parameters up to 8, and it will create a strongly-typed generic Tuple with those parameters as the data fields. This doesn't work out well for your case, however. When the variable will be local, consider doing it the other way around; use variable type inference, via the var keyword: var Prototypes = new List<double[][]>(); This is how the C# team decided to cut down on typing when instantiating variables. Locals are created - and change - much more often than instance variables, and this approach makes C# code look a little more like JavaScript. As Jon showed, it's possible to hide the mess, but you'll create more of a mess in the process. Here's another possibility using .NET 3.5/4.0's Expression features: public static string GetName(this Expression<Func<object>> expr) { if (expr.Body.NodeType == ExpressionType.MemberAccess) return ((MemberExpression) expr.Body).Member.Name; //most value type lambdas will need this because creating the Expression //from the lambda adds a conversion step. if (expr.Body.NodeType == ExpressionType.Convert && ((UnaryExpression)expr.Body).Operand.NodeType == ExpressionType.MemberAccess) return ((MemberExpression)((UnaryExpression)expr.Body).Operand) .Member.Name; throw new ArgumentException( "Argument 'expr' must be of the form ()=>variableName."); } public static void InitializeNew(this object me, params Expression<Func<T>>[] exprs) where T:new() { var myType = me.GetType(); foreach(var expr in exprs) { var memberName = expr.GetName() var myMember = myType.GetMember(memberName, BindingFlags.Instance|BindingFlags.Public |BindingFlags.NonPublic|BindingFlags.FlattenHierarchy, MemberTypes.Field|MemberTypes.Property); if(myMember == null) throw new InvalidOperationException( "Only property or field members are valid as expression parameters"); //it'd be nice to put these under some umbrella of "DataMembers", //abstracting the GetValue/SetValue methods if(myMember.MemberType == MemberTypes.Field) ((FieldInfo)myMember).SetValue(me, new T()); else ((PropertyInfo)myMember).SetValue(me, new T()); } } //usage class MyClass { public List<double[][]> list1; public List<double[][]> list2; public MyOtherObject object1; public MyClass() { this.Initialize(()=>list1, ()=>list2); this.Initialize(()=>object1); //each call can only have parameters of one type } } The implication is obvious here; it's more trouble than it's worth. To explain why I seemingly just had this laying around; the above is an adaptation of a method I use to throw ArgumentNullExceptions based on passed parameters, which requires the values to be encapsulated within Expressions in order to retain the names of the actual parameters from the calling method. In that situation, the complexity behind the scenes is reduced since all I need in the main helper is a check for null, and the added complexity saves me a lot more than I spend, by allowing me to one-line my null checks in every method and constructor of the codebase. I recommend ReSharper as a long-term solution to reducing this typing. When the type of an assignment target is known (as it is for instance fields and properties), and you type = new, ReSharper will pop up a suggestion for the type of the constructor, and auto-fill it for you if you want. If you change either the type or constructor afterward, R# will flag the assignment as inconsistent, and you can tell R# to change whichever one you want to match the other. A: If you just want to reduce code verbosity there is an opposite shortand syntax: the var operator Old: List<int> intList = new List<int>(); New: var intList = new List<int>(); At least you write List only once
{ "pile_set_name": "StackExchange" }
Q: Using an HTML drop-down menu with Google Apps Script on Google Sheets I am running a function on Google Sheets that requires a user to pick from a (rather lengthy) list of options. As UI service is deprecated, I thought I'd try with HTML, but I know nothing about this. I need the HTML User interface to pop up, have the user pick a name from the list, then go away, after passing the name back to the apps script function. I have tried to cobble together some code, but I can't seem to always get the drop-down menu to pop up, and I just can't seem to figure out how to send the choice back to the original function. Help? function genDiscRep(){ var ss=SpreadsheetApp.getActive(); var dontTouch=ss.getSheetByName("Do Not Touch"); var studentNamesArrayLength=dontTouch.getLastRow()-1000+1 var studentNames=dontTouch.getRange(1000,3,studentNamesArrayLength,1).getValues(); var test=HtmlService.createHtmlOutputFromFile('index') .setSandboxMode(HtmlService.SandboxMode.IFRAME); Browser.msgBox(test); } And then my html code (most choices removed for clarity) <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Select to Autocomplete</title> <script src="jquery-1.11.1.min.js"></script> <script src="jquery-ui.min.js"></script> <script src="jquery.select-to-autocomplete.js"></script> <script> (function($){ $(function(){ $('select').selectToAutocomplete(); $('form').submit(function(){ alert( $(this).serialize() ); return false; }); }); })(jQuery); </script> <link rel="stylesheet" href="jquery-ui.css"> <style> body { font-family: Arial, Verdana, sans-serif; font-size: 13px; } .ui-autocomplete { padding: 0; list-style: none; background-color: #fff; width: 218px; border: 1px solid #B0BECA; max-height: 350px; overflow-x: hidden; } .ui-autocomplete .ui-menu-item { border-top: 1px solid #B0BECA; display: block; padding: 4px 6px; color: #353D44; cursor: pointer; } .ui-autocomplete .ui-menu-item:first-child { border-top: none; } .ui-autocomplete .ui-menu-item.ui-state-focus { background-color: #D5E5F4; color: #161A1C; } </style> </head> <body> <form> <select name="Student" id="name-selector" autofocus="autofocus" autocorrect="off" autocomplete="off"> <option value="" selected="selected">Select Student</option> <option value="Abercrombie, Amber">Abercrombie, Amber(Gr 11)</option> <option value="Yupa, Jason">Yupa, Jason(Gr 9)</option> </select> <input type="submit" value="Submit" onclick="myFunction()"> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("name-selector").value; document.getElementById("demo").innerHTML = x; var ss=SpreadsheetApp.getActive(); Browser.msgBox(ss.getSheetName()); } </script> </body> </html> I apologize for the length of the html code. I wasn't sure what I could omit and still provide sufficient information. The beginning of the html is an attempt to utilize Jamie Appleseed's open-source code that allows auto-complete and auto-correction of a drop-down menu. (That part doesn't seem to be working either, but one thing at a time, I suppose). A: You can't use Browser.msgBox(test); Use SpreadsheetApp.getUi(). etc function genDiscRep() { var ss = SpreadsheetApp.getActive(); var dontTouch = ss.getSheetByName("Do Not Touch"); var studentNamesArrayLength=dontTouch.getLastRow()-1000+1; var studentNames=dontTouch.getRange(1000,3,studentNamesArrayLength,1).getValues(); var test = HtmlService.createHtmlOutputFromFile('index') .setSandboxMode(HtmlService.SandboxMode.IFRAME); SpreadsheetApp.getUi() .showModalDialog(test, 'User Input') }; You must use google.script.run.myFunction() to communicate back to the server side code: google.script.run .functionToRunOnFormSubmit(x); Use google.script.host.close() to close the dialog box. Index.html <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Select to Autocomplete</title> <script src="jquery-1.11.1.min.js"></script> <script src="jquery-ui.min.js"></script> <script src="jquery.select-to-autocomplete.js"></script> <script> (function($){ $(function(){ $('select').selectToAutocomplete(); $('form').submit(function(){ alert( $(this).serialize() ); return false; }); }); })(jQuery); </script> <link rel="stylesheet" href="jquery-ui.css"> <style> body { font-family: Arial, Verdana, sans-serif; font-size: 13px; } </style> </head> <body> <form> <select name="Student" id="name-selector" autofocus="autofocus" autocorrect="off" autocomplete="off"> <option value="" selected="selected">Select Student</option> <option value="Abercrombie, Amber">Abercrombie, Amber(Gr 11)</option> <option value="Yupa, Jason">Yupa, Jason(Gr 9)</option> </select> <input type="submit" value="Submit" onclick="myFunction()"> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("name-selector").value; document.getElementById("demo").innerHTML = x; google.script.run .functionToRunOnFormSubmit(x); google.script.host.close(); } </script> </body> </html> There needs to be a second function to handle the return from the user input: Code.gs function functionToRunOnFormSubmit(fromInputForm) { var ss = SpreadsheetApp.getActive(); ss.getSheetByName("Do Not Touch").getRange(2, 2, 1, 1).setValue(fromInputForm); };
{ "pile_set_name": "StackExchange" }
Q: Hallar índices de valores en una lista de python Supongamos que se tienen las listas: lst = [0.818362 0.115443 0 0 0.0507871 0.609459 0 0] values = [0.0596643 0.673551 0.712858 0.61972 0.818362 0.115443 0.539705 0.0507871 0.609459] y se desea hallar todos los índices de los valores en la lista values que hay en lst. El output resultante sería: idx = [4 5 7 8] ¿Es posible realizar esto de alguna forma a traves de values.index(lst)? A: Usar list.index como comentas, aunque posible (*) es ineficiente, además de tener que recorrer values por cada item de lst hay que manejar las excepciones ValueError que tendremos cuando el item no exista. lst = [0.818362, 0.115443, 0, 0, 0.0507871, 0.609459, 0, 0] values = [0.0596643, 0.673551, 0.712858, 0.61972, 0.818362, 0.115443, 0.539705, 0.0507871, 0.609459 ] indices = [] for item in lst: try: index = values.index(item) except ValueError: pass else: indices.append(index) (*) Esta aproximación tiene otro problema que hay que tener en cuenta, list.index retorna el primer índice que encuentra con ese valor, de tener valores repetidos en valores tendremos un problema: lst = [0, 2, 7] values = [5, 2, 8, 2, 7, 2, 7] for item in lst: #.... >>> indices [1, 4] Se puede solucionar pero complicamos todo aún más y hay mejores opciones. Otra aproximación es usar enumerate para obtener las parejas (indice, valor) de values y comprobar si el valor está en lst, añadiendo en tal caso el índice a la lista. Podemos usar una lista por compresión para mejorar la eficiencia. Además, dado que las búsquedas en listas son ineficientes por naturaleza, podemos pasar lst a un conjunto, dado que las búsquedas en tablas hash son mucho más eficientes: lst = [0.818362, 0.115443, 0, 0, 0.0507871, 0.609459, 0, 0] values = [0.0596643, 0.673551, 0.712858, 0.61972, 0.818362, 0.115443, 0.539705, 0.0507871, 0.609459 ] lst_set = set(lst) indices = [index for index, valor in enumerate(values) if valor in lst_set] >>> indices [4, 5, 7, 8] En este caso, ante repeticiones: lst = [0, 2, 7] values = [5, 2, 8, 2, 7, 2, 7] lst_set = set(lst) indices = [index for index, valor in enumerate(values) if valor in lst_set] >>> indices [1, 3, 4, 5, 6] Por último, en el caso de usar NumPy, podemos recurrir a numpy.isin que nos retorna un filtro boleano (array del tamaño de values en el que tenemos True si ese valor existe en lst y False en caso contrario). Podemos recuperar los índices aplicando numpy.where a dicho array simplemente: import numpy as np lst = np.array((0.818362, 0.115443, 0, 0, 0.0507871, 0.609459, 0, 0)) values = np.array( (0.0596643, 0.673551, 0.712858, 0.61972, 0.818362, 0.115443, 0.539705, 0.0507871, 0.609459) ) indices = np.where(np.isin(values, lst, assume_unique=True))[0] >>> indices array([4, 5, 7, 8])
{ "pile_set_name": "StackExchange" }
Q: MomentJS - convert datetime from UTC to different timezone I am trygin to convert utc time to local timezone with moment but without success.. Here is my code: var utc = moment.tz('2017-03-28 15:00:00','UTC'); var s = utc.format(); var pl = moment.tz(utc.format(), 'Europe/Warsaw').format(); console.info(s); console.info(pl); and the output is: VM4496:4 2017-03-28T15:00:00Z VM4496:5 2017-03-28T17:00:00+02:00 As you can see, moment adds 2 hours to UTC, but Europe/Warsaw is in UTC+1 time zone A: As you can see, moment adds 2 hours to UTC, but Europe/Warsaw is in UTC+1 time zone Not on March 28th. On March 28th, it's UTC+2, because of Daylight Savings Time, which starts on March 26th in Warsaw and runs through October 29th. OK, other question: how to make it to skip Daylight Savings time? Use the the Etc/GMT-1 timezone. Yes, really -1. It's horrible and wrong, but apparently, that's GMT+1 (!!!) in the tz database (which is used by [but not controlled by] Moment-Timezone) which uses that notation because of some POSIX convention. The Etc/GMT timezones have their sign reversed. Ugh. Details here and here. If that makes you uncomfortable, you could add your own timezone: moment.tz.add([ 'Own/UTC+1|+01|10|0|' ]); Example: moment.tz.add([ 'Own/UTC+1|+01|-10|0|' ]); var utc = moment.tz('2017-03-28 15:00:00','UTC'); var s = utc.format(); var plusOne = moment.tz(utc.format(), 'Etc/GMT-1').format(); var own = moment.tz(utc.format(), 'Own/UTC+1').format(); console.info(s); console.info(plusOne); console.info(own); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Console pause c# In this code Console.Write("Enter any number from 0 to 9:"); int k = Console.Read(); Console.Write("The ASCII code for it is:"); Console.WriteLine(k); Console.Read(); after I input a number my console close instantly. If I write this code Console.Write("Enter any string:"); string k = Console.ReadLine(); Console.Write("Your string is:"); Console.WriteLine(k); Console.Read(); my console stops so I can see what I wrote. Why is that happening? A: Try using the following instead of Console.ReadLine(); Console.ReadKey(); This will wait for your console to input any key before closing.
{ "pile_set_name": "StackExchange" }
Q: Python: One Try Multiple Except In Python, is it possible to have multiple except statements for one try statement? Such as : try: #something1 #something2 except ExceptionType1: #return xyz except ExceptionType2: #return abc A: Yes, it is possible. try: ... except FirstException: handle_first_one() except SecondException: handle_second_one() except (ThirdException, FourthException, FifthException) as e: handle_either_of_3rd_4th_or_5th() except Exception: handle_all_other_exceptions() See: http://docs.python.org/tutorial/errors.html The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
{ "pile_set_name": "StackExchange" }
Q: How does copy-paste work with xterm? Left-down-clicking in xterms starts the selection of something to be copy-pasted. Double-left clicking selects a word. Triple-left clicking selects a line. All this works under unity in 11.04. However, there is no way to copy-paste that selection to another place: The right-click menu shows paste disabled, and middle-clicking to copy-paste does not work. So how can I copy a selection from an xterm into another place? I am happy with any method to perform this. (I am using the default-installation no special configuration so far) Edit: Same problem with xedit A: Use middle click or shift+insert see X Window selection A: Xterm uses cut buffers, not the standard X11 clipboard selection used for standard copy-paste that gnome-terminal and most other Linux programs now use. But if you start xterm like this: xterm -ls -xrm 'XTerm*selectToClipboard: true'& then selections are available via the standard clipboard. Read more at Copying and Pasting in Xterm | StarNet Knowledge Database - PC X, X Windows, X 11 & More - StarNet The xcb program also provides command-line access to the cut buffers. E.g. in Trusty Tahr 12.04, running lxde window manager, I can triple click on a line of text in xterm, which highlights it and puts it in cut buffer 0. I can then run xcb -p 0 which prints the line out on stdout. For some reason it didn't work for me to click both buttons (simulating middle click) in an xterm, but shift-insert did work in an xterm. A: To copy between xterm and other programs/documents/... Add to the file ~/.Xresources (or create): XTerm*selectToClipboard: true Then run the command: xrdb -merge ~/.Xresources Restart xterm.
{ "pile_set_name": "StackExchange" }
Q: median from survfit object and textConnection I've used the methods of others to grab the median from a survfit object, namely using textConnecton, but I am running into a couple problems. # example library(survival) data(cancer) cox.ph <- coxph(Surv(time, status) ~ strata(I(age > 60)), data = cancer) coxph.fit <- survfit(cox.ph, conf.type = 'log-log') tmp <- tail(capture.output(print(coxph.fit)), length(unique(coxph.fit$strata)) + 1) tmp <- read.table(z <- textConnection(tmp), header = TRUE) Gives me this error: Error in read.table(z <- textConnection(tmp), header = TRUE) : more columns than column names and what tmp looks like > tmp [1] " records n.max n.start events median 0.95LCL 0.95UCL" [2] "I(age > 60)=FALSE 94 94 94 64 353 268 390" [3] "I(age > 60)=TRUE 134 134 134 101 301 239 353" So I'm thinking that the problem is with the spaces in the strata and how it is read by textConnection Another example: cox.ph <- coxph(Surv(time, status) ~ strata(sex), data = cancer) coxph.fit <- survfit(cox.ph, conf.type = 'log-log') tmp <- tail(capture.output(print(coxph.fit)), length(unique(coxph.fit$strata)) + 1) tmp <- read.table(z <- textConnection(tmp), header = TRUE) close(z) Here, tmp behaves as I want: > tmp records n.max n.start events median X0.95LCL X0.95UCL sex=1 138 138 138 112 270 210 306 sex=2 90 90 90 53 426 345 524 > tmp$median [1] 270 426 So basically, is there another method or a way that I can tell textConnection to use multiple spaces or tab as a delimiter (if that is indeed the issue)? I need to be able to use both methods, i.e. strata(sex) and strata(I(...)), because I am using this within a function, and the user supplies the survfit object. The second problem is that (I am using Rstudio (not the problem) ) if I narrow the console window so that tmp is split into several more rows of output, like so > tmp records n.max n.start sex=1 138 138 138 sex=2 90 90 90 events median X0.95LCL sex=1 112 270 210 sex=2 53 426 345 X0.95UCL sex=1 306 sex=2 524 So that my final data frame after read.table becomes > tmp X0.95UCL sex=1 306 sex=2 524 Which is obviously going to be a problem: > tmp$median NULL Here, the issue is probably that the output is captured as it will be printed in the console, and I want everything regardless of how it is printed or how large the console margins are. A: That is not actually using any of the objects, but is rather doing a screen scrape of side-effects printed to the console. The easy way: options(survfit.rmean = "individual") summary(coxph.fit)$table # returns the whole table from survmeans summary(coxph.fit)$table[ , "median"] #I(age > 60)=FALSE I(age > 60)=TRUE # 353 301 Hitting self in head: This is now the second time I've gone through the following process needlessly. The extraction of the desired printed table is describe in ?summary.survfit The hard way: If you want to get the "median"-as-object (and print it) you can high-jack the print.survfit function and modify it to print and return the median column of the matrix that the hidden function survmean creates: print.survfit.median <- function (x, scale = 1, digits = max(options()$digits - 4, 3), print.rmean = getOption("survfit.print.rmean"), rmean = getOption("survfit.rmean"), ...) { if (inherits(x, "survfitms")) { x$surv <- 1 - x$prev if (is.matrix(x$surv)) dimnames(x$surv) <- list(NULL, x$states) if (!is.null(x$lower)) { x$lower <- 1 - x$lower x$upper <- 1 - x$upper } } if (!is.null(cl <- x$call)) { cat("Call: ") dput(cl) cat("\n") } omit <- x$na.action if (length(omit)) cat(" ", naprint(omit), "\n") savedig <- options(digits = digits) on.exit(options(savedig)) if (!missing(print.rmean) && is.logical(print.rmean) && missing(rmean)) { if (print.rmean) rmean <- "common" else rmean <- "none" } else { if (is.null(rmean)) { if (is.logical(print.rmean)) { if (print.rmean) rmean <- "common" else rmean <- "none" } else rmean <- "none" } if (is.numeric(rmean)) { if (is.null(x$start.time)) { if (rmean < min(x$time)) stop("Truncation point for the mean is < smallest survival") } else if (rmean < x$start.time) stop("Truncation point for the mean is < smallest survival") } else { rmean <- match.arg(rmean, c("none", "common", "individual")) if (length(rmean) == 0) stop("Invalid value for rmean option") } } temp <- survival:::survmean(x, scale = scale, rmean) print(temp$matrix[ , "median"]) }s Then use it: > z <- print.survfit.median(coxph.fit) Call: survfit(formula = cox.ph, conf.type = "log-log") I(age > 60)=FALSE I(age > 60)=TRUE 353 301 > z I(age > 60)=FALSE I(age > 60)=TRUE 353 301
{ "pile_set_name": "StackExchange" }
Q: Profiling Doctrine 2.0 in Codeigniter What's a good way to profile doctrine queries when Doctrine 2.0 has been integrated into codeigniter? Using the usual CI profiler does not how the queries executed because it's using Doctrine and not the native, active record. e.g. when you add this code $this->output->enable_profiler(TRUE); it should also show the queries executed. http://codeigniter.com/user_guide/general/profiling.html A: You can add a profiler in the doctrine package namespace Doctrine\DBAL\Logging; class Profiler implements SQLLogger { public $start = null; private $ci; public function __construct() { $this->ci =& get_instance(); } /** * {@inheritdoc} */ public function startQuery($sql, array $params = null, array $types = null) { $this->start = microtime(true); $this->ci->db->queries[] = "/* doctrine */ \n".$sql; } /** * {@inheritdoc} */ public function stopQuery() { $this->ci->db->query_times[] = microtime(true) - $this->start; } } Then load the profiler as a logger in your main doctrine library (doctrine.php for me) $logger = new \Doctrine\DBAL\Logging\Profiler; $config->setSQLLogger($logger); And the normal profiling will work fine.
{ "pile_set_name": "StackExchange" }
Q: Is there a Dropped Call Listener Does the Android SDK have the ability to to trap a Dropped Call event? If so, what is it called? I've been prowling the documentation looking for it. Is there a difference between a hang up, and a dropped call? A: Does the Android SDK have the ability to to trap a Dropped Call event? No. Is there a difference between a hang up, and a dropped call? To humans, yes. To Android, no. A: Just a bit of additional information. The Android system does know when a call is dropped for what ever reason, i.e. Congestion, No Circuit Available etc. However none of this information is parsed through to the sdk. In the source at some point android basically mashes a whole bunch of telephony related information into a few, excruciatingly vague sdk calls. For example - the only indication we get of a call end is the changed in a PhoneStateListener from OffHook to Idle. Which literally encompasses every single reason for a call ending. Even different states of the call are mashed together. Where as we should be able to get information like whether the phone is alerting the b party or actually has an active connection, this is reduced to the three states available, offhook, idle and ringing - note ringing is only when your device is ringing, not when the person you are calling phone's ring. Sorry to be another bearer of bad new, but alas. all we can hope for is better support at a later stage
{ "pile_set_name": "StackExchange" }
Q: Use of nullable in onCreateView and onCreatedView I have two fragments classes say A and B and one mainactivity class.I looked some tutorials and have added recycler view(this is not the main concern though).Following up the tutorial on my both fragment classes i have this code @Nullable @Override public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){ View rootView = inflater.inflate(R.layout.absent, container, false); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } so what is the use of @Nullablehere?.i have searched this many times but i can't understand it's use and even that tutorial haven't mentioned anything about @nullabe.Can anyone make me understand about this? please don't bother in talking about recycler view because i have already added it. A: The @Nullable annotation indicates a variable, parameter, or return value that can be null You ever get a "NullPointerException"? That's because the value is null. Integer x; 'x' Will be null because you haven't assigned a value to it so there will be errors using it. But what if you have a variable that might actually be null in some use cases? Well, you'd use the @Nullable annotation meaning that it's okay to be null. @Nullable Bundle savedInstanceState Bundle in this case might have nothing stored in it. So it's okay to be null when the method is called. Same goes for the method onCreateView() meaning that the return can be null
{ "pile_set_name": "StackExchange" }
Q: Função de verificação só retorna vazia Fiz essas duas funções bem simples pra limitar os caracteres e pra ver se a coluna no banco ta vazia, por algum motivo só retorna vazia mesmo tendo resultados. public function limite_texto($texto, $limite, $complemento) { return mb_strimwidth(utf8_encode($texto), 0, $limite, $complemento); } public function vazio($texto, $limite, $complemento, $aviso) { if (empty($texto)) : return $aviso; else : return $this->limite_texto($texto, $limite, $complemento); endif; } $ctlr->vazio("oooooi", 3, "...", "O campo está vazio") Por algum motivo ta retornando apenas os "...", quando o esperado seria "ooo..." ou se a variavel $texto fosse vazia retornasse O campo está vazio, acho que errei na logica A: Você definiu que a função deve retornar 3 caracteres, você obteve 3 caracteres, mas achou estranho porque não vieram 6? Estranho. Talvez faltou mais atenção ao ler a documentação das funções que está utilizando: mb_strimwidth Valor retornado: The truncated string. If trimmarker is set, trimmarker replaces the last chars to match the width. É retornada a string truncada, mas se o valor de trimmarker for definido, trimmarker irá substituir os últimos caracteres da string até atingir o tamanho limite. Ou seja, você passa a string "oooooi", que truncada seria "ooo", mas como definiu o valor de trimmarker, ele substituirá os últimos caracteres até ter no máximo 3 caracteres (limite que você definiu). Portanto, a saída sempre será "...", pois apenas o valor de trimmarker já atinge o limite de caracteres que você definiu. Se o objetivo era obter "ooo...", você deveria ter definido o limite como 6, visto que você quer ter 6 caracteres na saída.
{ "pile_set_name": "StackExchange" }
Q: Handling a redirect from an old permalink to a new one I have a Page model in my rails 4 app. It has an :permalink attribute that is used so that when someone goes to "mysite.com/pages/page-name", the controller finds the Page with "page-name" as the permalink and then shows the view. pages_controller.rb: def show @page = Page.find_by_permalink!(params[:id]) end After a few months of the site being up, I want to change the permalink of a certain page, however I don't want to lose all the incoming links. I'm thinking I would do this. First I'd add_colum :new_permalink to the Page model. Then if this :new_permalink attribute was anything but nil or blank, it would pull up a new page in the controller like this: def show @page = Page.find_by_permalink!(params[:id]) if [email protected]_permalink.blank? @page = Page.find_by_permalink!(@page.new_permalink) end end This works, but the url in the browser still shows the old URL. I suppose this might not be so bad, but I think I'd like it to actually forward to the new page. Perhaps, instead of "new_permalink" it should be a new url and actually do a redirect? What would be your best solution for this? And could I make it a 301 redirect? A: Yes, you should use a 301 redirect so that both the user and search engines would send the browser to the correct location. def show @page = Page.find_by_permalink!(params[:id]) if @page.new_permalink.present? redirect_to page_path(@page.new_permalink), status: :moved_permanently return end end
{ "pile_set_name": "StackExchange" }
Q: What should I use instead of isinstance() I have to parse some object that is composed of lists. But it can have list within list within list : obj=[[smth1],[[smth2],[smth3]]] each smthX can be a list aswell. I'm looking for a value that I know is in a "second layer list". In my example, it could be in [[smth2],[smth3]] What i'm doing right now is iterarating on my object, and testing if what i'm iterating on is a list awell. if it is, I look for my value. for list in obj : if isinstance(list, obj) : for souslist in list : I LOOK FOR MY VALUE But I'm reading everywhere (http://canonical.org/~kragen/isinstance/ a lot of stackoverflow thread) that the use of isinstance() is only for special occasion (and my use doesn't look like a special occasion) Before using isinstance() I was testing what list[0] returned me in a try/except but it felt even wronger. Any alternate way to achieve this in a clean way ? (I don't have any power over the format of my obj I have to work on it) A: If you are looking for sub-lists with two item (which are lists) first off you need to check the length (if you are sure that all the items are list) then check if all the items in sub-list are list using isinstance() for sub in obj: if len(sub) == 2 and all(isinstance(i, list) for i in sub): # you can add " and isinstance(sub, list)" if you are not sure about the type of sub look_val(sub)
{ "pile_set_name": "StackExchange" }
Q: Bash Text Parsing I am getting confused with parameter substitution. Basically the file to be parsed is in the following structure: foo.txt: system.switch_cpus.commit.op_class_0::total 10000000 # Class of committed instruction system.switch_cpus.commit.bw_lim_events 10000000 # number cycles where commit BW limit reached system.switch_cpus.rob.rob_reads 80558432 # The number of ROB reads system.switch_cpus.rob.rob_writes 43430539 # The number of ROB writes system.switch_cpus.timesIdled 37218 # Number of times that the entire CPU went into an idle state and unscheduled itself system.switch_cpus.idleCycles 2755508 # Total number of cycles that the CPU has spent unscheduled due to idling system.switch_cpus.committedInsts 10000000 # Number of Instructions Simulated system.switch_cpus.committedOps 10000000 # Number of Ops (including micro ops) Simulated system.switch_cpus.cpi 8.369191 # CPI: Cycles Per Instruction system.switch_cpus.cpi_total 8.369191 # CPI: Total CPI of All Threads system.switch_cpus.ipc 0.119486 # IPC: Instructions Per Cycle system.switch_cpus.ipc_total 0.119486 # IPC: Total IPC of All Threads system.switch_cpus.int_regfile_reads 21773538 # number of integer regfile reads system.switch_cpus.int_regfile_writes 9447282 # number of integer regfile writes I want to find the following variables and print out the corresponding value: list=(IPC CPI) IPC="system.switch_cpus.ipc" CPI="system.switch_cpus.cpi" for i in $list: do awk -v a="$i" '{$1 == $a} {print}' $1 done Then I run the script with the following command: ./parser.sh foo.txt This is printing out the whole file. Output: system.switch_cpus.commit.op_class_0::total 10000000 # Class of committed instruction system.switch_cpus.commit.bw_lim_events 10000000 # number cycles where commit BW limit reached system.switch_cpus.rob.rob_reads 80558432 # The number of ROB reads system.switch_cpus.rob.rob_writes 43430539 # The number of ROB writes system.switch_cpus.timesIdled 37218 # Number of times that the entire CPU went into an idle state and unscheduled itself system.switch_cpus.idleCycles 2755508 # Total number of cycles that the CPU has spent unscheduled due to idling system.switch_cpus.committedInsts 10000000 # Number of Instructions Simulated system.switch_cpus.committedOps 10000000 # Number of Ops (including micro ops) Simulated system.switch_cpus.cpi 8.369191 # CPI: Cycles Per Instruction system.switch_cpus.cpi_total 8.369191 # CPI: Total CPI of All Threads system.switch_cpus.ipc 0.119486 # IPC: Instructions Per Cycle system.switch_cpus.ipc_total 0.119486 # IPC: Total IPC of All Threads system.switch_cpus.int_regfile_reads 21773538 # number of integer regfile reads system.switch_cpus.int_regfile_writes 9447282 # number of integer regfile writes How can create a list of variables in shell who have their own values and parse each of them from a file using awk or sed? A: you can do all in one awk script, if your list is not in a file you can use a here document and file substitution as below. $ awk 'NR==FNR{a[$1]; next} $1 in a' <(cat << EOF system.switch_cpus.ipc system.switch_cpus.cpi EOF ) file will give you system.switch_cpus.cpi 8.369191 # CPI: Cycles Per Instruction system.switch_cpus.ipc 0.119486 # IPC: Instructions Per Cycle If you want to search one at a time with a variable $ var='system.switch_cpus.ipc'; awk -v var="$var" '$1==var' file system.switch_cpus.ipc 0.119486 # IPC: Instructions Per Cycle However, in that case, using grep might be better off $ var='system.switch_cpus.ipc'; grep -wF "$var" file system.switch_cpus.ipc 0.119486 # IPC: Instructions Per Cycle UPDATE If your variable names are in a list, you can decode the values with this $ vars=(var1 var2) # define the list with variables, values even may not be assigned yet $ var1=value1; var2=value2 # assign values $ for v in ${vars[@]}; do echo ${!v}; done # extract values with indirect reference value1 value2
{ "pile_set_name": "StackExchange" }
Q: Why is there an "Invalid literal error"? I am getting the right answer in IDE but the online judge gives the following error: Traceback (most recent call last): File "/tmp/editor_trsource_1410281976_804149.py", line 10, in n=int(raw_input('')) ValueError: invalid literal for int() with base 10: '100 10' Problem Link: http://www.hackerearth.com/problem/golf/minimal-combinatorial/ def fact(x): f=1 while x>0: f=f*x x-=1 return f T=int(raw_input('')) while T>0: n=int(raw_input('')) r=int(raw_input('')) ans=fact(n)/(fact(r)*fact(n-r)) print str(ans) + "\n" T-=1 A: n and r are to be entered on the same line. 100 10 Your program expects them to be entered on two separate lines. 100 10
{ "pile_set_name": "StackExchange" }
Q: Free webapp to send a confirmation email to customer whenever a Paypal payment email arrives to my Gmail My final goal I have a website where people can order via Paypal. When someone pays, the only notification I receive is an email from Paypal. This email contains the email address of the customer as its first "mailto:" link. My goal is to quasi-immediately send the customer an email saying "We have received your payment and will process it within 72 hours". Paypal does not have this feature. My idea of a solution that would fit Usage scenario of the webapp ("TheWebapp.com" below): I register at TheWebapp.com with username "nicolas" I write the message I would like customers to receive. I set up my Gmail to forward Paypal notifications to [email protected] When TheWebapp.com receives such an email, it extracts the first "mailto:" address and send my message to it Any other solution to achieve the final goal is OK. A: Email confirmation would be too brittle, and susceptible to forged emails. Rather than email confirmation, use web confirmation: Paypal can redirect customers to an URL of your choice. The details for setting this up are here: https://www.paypal.com/ie/cgi-bin/webscr?cmd=p/mer/express_return_summary-outside This is a free feature, and doable even with a static HTML website.
{ "pile_set_name": "StackExchange" }
Q: How to change console code to 1252? I am trying to use PostgreSQL on Windows 8 using the command line provided by Git Bash so I can run Unix like commands. When accessing Postgres with the following command: psql -U postgres I get: Warning: Console code page (850) differs from Windows code page (1252) etc... in the Windows command tool, I just need to type chcp 1252 before accessing Postgres so the warning doesn't show up. What's the equivalent command in unix/git bash? I tried to do chcp 1252 or chcp from Git bash but it outputs: sh.exe": chcp: command not found Any ideas? A: Try "chcp.com 1252". Git bash doesn't suppose ".com" as a implicit executable postfix. It can't expand "chcp" to correct executable, so you should type fully "chcp.com".
{ "pile_set_name": "StackExchange" }
Q: Using mathpazo only for small caps? Really simple question... \usepackage{palatino} \usepackage{mathpazo} <-- How can I make it alter only small caps? A: I tried the following example: \documentclass{article} \usepackage{palatino} \begin{document} Text \textit{text \textbf{text}} \textbf{text} \end{document} After compiling, I ran pdffonts, getting this output name type encoding emb sub uni object ID ------------------------------------ ----------------- ---------------- --- --- --- --------- DTGJVU+URWPalladioL-Roma Type 1 Custom yes yes no 4 0 LAWSFM+URWPalladioL-Ital Type 1 Custom yes yes no 5 0 DCSYXP+URWPalladioL-BoldItal Type 1 Custom yes yes no 6 0 RLNCFA+URWPalladioL-Bold Type 1 Custom yes yes no 7 0 The same example file with mathpazo: \documentclass{article} \usepackage{mathpazo} \begin{document} Text \textit{text \textbf{text}} \textbf{text} \end{document} and the output of pdffonts is name type encoding emb sub uni object ID ------------------------------------ ----------------- ---------------- --- --- --- --------- DTGJVU+URWPalladioL-Roma Type 1 Custom yes yes no 4 0 LAWSFM+URWPalladioL-Ital Type 1 Custom yes yes no 5 0 DCSYXP+URWPalladioL-BoldItal Type 1 Custom yes yes no 6 0 RLNCFA+URWPalladioL-Bold Type 1 Custom yes yes no 7 0 As you can clearly see, the fonts are exactly the same. So just replace \usepackage{palatino} with \usepackage[sc]{mathpazo} If, for some reason, you don't trust the above, use substitutefont: \usepackage{palatino} \usepackage{substitutefont} \substitutefont{\encodingdefault}{\scdefault}{pplx} On the other hand, the documentation of psnfss has The part about mathpazo also tells you why you should prefer it to palatino: A: You need to add new font family (pplx) to the \scshape command: \documentclass{article} \usepackage{kantlipsum} \usepackage{palatino} \pagestyle{empty} \usepackage{etoolbox} \pretocmd{\scshape}{\fontfamily{pplx}\selectfont}{}{} \begin{document} \kant[1] \scshape\kant[2] \end{document} Compare to the output without this patch:
{ "pile_set_name": "StackExchange" }
Q: Call multiple services in background in android I have to call multiple services in background for a project in android app. In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database. But not able to call all services in a sequence. my code is as below: @Override public void onStart(Intent intent, int startid) { Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); Timer timer = new Timer(); final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this); final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this); final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this); final SyncTableTags syncTagObj = new SyncTableTags(this); final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this); final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this); final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this); final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this); final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this); final SyncEditUser syncEditUserObj = new SyncEditUser(this); final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this); TimerTask timerTask = new TimerTask() { @Override public void run() { syncUserObj.syncUserData(); syncVehicleObj.syncVehicleData(); syncLicenseObj.syncLicensesData(); syncTagObj.syncTagData(); syncTagMapObj.syncTagMappingData(); syncAddressObj.syncAddressData(); syncDispatchObj.syncDispatchData(); syncCompanyObj.syncCompanyData(); syncEditVehicleObj.syncVehicleData(); syncEditUserObj.syncUserData(); Log.i("TAG", "LogId After insert values "); } } }; timer.scheduleAtFixedRate(timerTask, 10000, 180000); call after every 3 minute super.onStart(intent, startid); syncUserData is a method, which call web service. A: I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask. It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests. private class YourTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { //call your methods from here //publish yor progress here.. publishProgress((int) ((i / (float) count) * 100)); } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { //action after execution success or not } }
{ "pile_set_name": "StackExchange" }
Q: How to rotate markups along with PDF on Autodesk Forge I have a PDF drawing already loaded into Forge Viewer and have some markups on it. When PDF be rotated by using camera the markups are not keep the initial position, angle... but it go away from the Viewer. Is it possible to keep markups rotate along with the PDF. Thank in advance. A: Try to keep track of the world coordinates between translation (movement of PDF) and convert them back to client/viewport coordinates to maintain their relative positions within the canvas - you can subscribe to the CAMERA_CHANGE_EVENT to react to user navigation and move the markups accordingly: //once the markups are created const originalWorldPos = viewer.clientToWorld(pos.x,pos.y) viewer.addEventListner(Autodesk.Viewing.CAMERA_CHANGE_EVENT, ()=>{ let newViewPortPos = viewer.worldToClient(originalWorldPos) //move markups to new position here ... })
{ "pile_set_name": "StackExchange" }
Q: Extracted float values are stored in a list of lists instead of a list of values I am doing an exercise for finding all the float point values in a text file and computing the average . I have managed to extract all the necessary values but they are being stored in a list of lists and I don't know how extract them as floats in order to do the calculations . Here is my code : import re fname = input("Enter file name: ") fhandle = open(fname) x = [] count = 0 for line in fhandle: if not line.startswith("X-DSPAM-Confidence:") : continue s = re.findall(r"[-+]?\d*\.\d+|\d+", line) x.append(s) count = count + 1 print(x) print("Done") and this is the output of x : [['0.8475'], ['0.6178'], ['0.6961'], ['0.7565'], ['0.7626'], ['0.7556'], ['0.7002'], ['0.7615'], ['0.7601'], ['0.7605'], ['0.6959'], ['0.7606'], ['0.7559'], ['0.7605'], ['0.6932'], ['0.7558'], ['0.6526'], ['0.6948'], ['0.6528'], ['0.7002'], ['0.7554'], ['0.6956'], ['0.6959'], ['0.7556'], ['0.9846'], ['0.8509'], ['0.9907']] Done A: You can make x a flat list of floats from the start: # ... for line in fhandle: # ... s = re.findall(r"[-+]?\d*\.\d+|\d+", line) x.extend(map(float, s)) Note that re.findall returns a list, so we extend x by it while applying float to all the strings in it.
{ "pile_set_name": "StackExchange" }
Q: When did Clara hold a sword? In The Girl Who Died when The Doctor asked who had held a sword in combat before only Clara and himself had their hands up. I remember that in The Christmas Invasion The Doctor held a sword when he challenged the Sycorax leader but i don't remember when, if ever, Clara held one in combat. So when did Clara hold a sword in combat before? A: Not exactly a sword, but she was holding a medieval weapon in battle during series 7 episode 12, Nightmare in Silver: And (as already mentioned by Slicey) another medieval weapon in this image from series 8 episode 4, Robot of Sherwood: A: It is possible she was battling with a sword in one of her many "fragments" during the doctor's life. But it is also possible she counted the one time she was (trying) to swing that huge axe in Robot of Sherwood.
{ "pile_set_name": "StackExchange" }
Q: be able to change disqus_identifier on some pages I'm using the wordpress plugin. I've found the code in the plugin file "comments.php" that defines the identifier for a page: var disqus_identifier = '<?php echo dsq_identifier_for_post($post); ?>'; What I've come up with so far is to replace it with: var disqus_identifier = '<?php echo get_post_meta($post->ID, 'dis_ident_field', true); ?>'; This means that it will get it's disqus_identifier from a custom field from Wordpress called dis_ident_field, but I'm worried about this method. For pages where I don't populate this field, I now have no identifier at all in the javascript in the page source. Can someone explain why having no id is bad, because the comments still work on all those pages properly, so it's getting an id from somewhere. A: You could use something like this to check if its set before using it or set it to the page id. <?php //Attempt to get identifier $disqus = get_post_meta($post->ID, 'dis_ident_field', true); //if isset & not blank else use $post->ID $disqus = (!empty($disqus)) ? $disqus : $post->ID; ?> var disqus_identifier = '<?=$disqus?>';
{ "pile_set_name": "StackExchange" }
Q: Tab completion freezes for Git commands only I have some strange behavior regarding my setup that I can't seem to narrow down. I am using tab completion in my shell without any issues (my shell is zsh). The issue I'm having is regarding tab completion after issuing a git command. Example 1 (works fine): I make a new directory, change into it and git init. I then touch hello.rb. If I do git add <tab> it will change it to git add hello.rb. Example 2 (doesn't work): I'm in a rails app that really isn't very big, and if I try to run git add G<tab> with the intent that it will pull up my Gemfile, it just hangs and hangs until I kill it with ctrl-c which outputs: Killed by signal in __git_complete_index_file after 159s In zsh I'm using: # completion autoload -U compinit compinit Has anyone else had this issue? I can work around it but I have to be doing something wrong and I'm unsure where else to look. Versions of things: git version 2.1.2 zsh 5.0.7 iTerm2 Build 2.0.0.20141103 Update: Git v 2.2.0 has fixed this issue so just upgrade if you're running into this issue. A: I'm assuming you are using RVM or some tool like that. There is a bug in the git-completion.bash shipped with the current git (2.1.3) and older versions, causing an endless loop when listing file completions in directories where RVM is used. The reason for this endless loop is a change of chpwd_functions, made by RVM and some other tools. I've found a patch for the git-comletion.bash affecting only the __git_ls_files_helper method which is used for listing files. The patch ignores the chpwd_functions and hence, these endless loops are omitted. In short: The __git_ls_files_helper function needs to be changed from: __git_ls_files_helper () { ( test -n "${CDPATH+set}" && unset CDPATH cd "$1" if [ "$2" == "--committable" ]; then git diff-index --name-only --relative HEAD else # NOTE: $2 is not quoted in order to support multiple options git ls-files --exclude-standard $2 fi ) 2>/dev/null } to: __git_ls_files_helper () { ( test -n "${CDPATH+set}" && unset CDPATH (( ${+functions[chpwd]} )) && unfunction chpwd (( ${#chpwd_functions} )) && chpwd_functions=() setopt chaselinks builtin cd "$1" 2>/dev/null if [ "$2" == "--committable" ]; then git diff-index --name-only --relative HEAD else # NOTE: $2 is not quoted in order to support multiple options git ls-files --exclude-standard $2 fi ) 2>/dev/null } Further information can be found in the RVM issue discussion on Github. The location of your git-completion.bash depends on how you have installed git. When using Homebrew, the location is something like /usr/local/Cellar/git/<git version>/etc/bash_completion.d/ on other systems, or when using other package managers, it usually should be something like /opt/local/etc/bash_completion.d For further information about the git-completion.bash, take a look at the Git Tips and Tricks, chapter 2.7 in the git-scm.com book. Update: Git v 2.2.0 has fixed this issue so just upgrade if you're running into this issue.
{ "pile_set_name": "StackExchange" }
Q: What policy implication would "non-whites-only space" generate? A group of students in Michigan is demanding a "non-whites-only" space so they can organize on social justice, specifically for people of color; (See here). The group's stated goal is to "fight against the oppression and hateful acts that try to destroy us and our community." Given the nationwide trend towards self-segregation, it would be interesting to see how governments / administrations at all levels form policies to accommodate such demands. Q1: what policy implications, if any, would "non-whites-only space" generate? Q2: what does that mean for people with mixed racial heritage? Like half-white / half-black (President Obama) or whites with 1/32nd indian (Senator Warren)? A: This is clear discrimination based on race, so I doubt it will stand if any white person tries to enter that facility. The government might need to send state troopers to enforce the right of anyone to enter the facility, though.
{ "pile_set_name": "StackExchange" }
Q: Allocating local variables in CPU registers Actually, I am familiar with memory model of .NET framework. I am interested in knowing if the JIT compiler could place local variables in CPU registers to improve the performance of the application, instead of allocating variables on the stack? If it can, what are the requirements for such an allocation and how does it decide whether or not to perform it? A: This is being done all the time by the JIT. It is a standard optimization for pretty much any JIT and native compiler. Don't confuse the logical IL stack with the physical x86 stack that the jitted code uses. They are very weakly related. IL stack contents and IL locals are being stored preferably in registers and spilled to the x86 stack only if needed. The only exception are structs which are usually stack-allocated in both the .NET 4.5 JIT and the vNext RyuJIT (as of VS2015 Preview). This is not documented but testing clearly shows that not even in the simplest cases structs are being enregistered. Maybe I missed some case where it happens but it is clearly a rare case. Primitive types and object references are consistently stored in registers (if available) according to my testing.
{ "pile_set_name": "StackExchange" }
Q: Is SharePoint Designer 2010 open source? I had an SharePoint interview today and was told that the company does not use SharePoint Designer 2010 because it is open source. This did not bother me because I have never been a great fan of it. However, I was not aware that I was open source. Therefore, my question - Is it actual open source? A: No. Open source means all the source code for SharePoint Designer is available for viewing and for possible extension. This is not the case much like most Microsoft products. SharePoint Designer is free to use though.
{ "pile_set_name": "StackExchange" }
Q: OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m; When I'mtrying to open Intellij IDE using command line in linux like this ./phpstorm.sh both android studio and PHPStorm I always got this message : OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m; support was removed in 8.0 and I was wondering if google find solution here but I was kinda lost here since I'm newbie in ubuntu 14.04. my question is what is the cause of this message to diplay? and how to resolve this? I've tried using this command export MAVEN_OPTS="-Xmx512m" but it's not resolve the issue. and I'm using java 1.8.0_73 downloaded from here. any useful help would be appreciated, thank you. A: This is only a warning saying the option has been ignored - so it should not cause any issues. The JVM options should be located in {IntelliJ folder}/bin/idea64.exe.vmoptions (on windows - probably something similar on linux). You can edit that file and delete the maxpermsize option.
{ "pile_set_name": "StackExchange" }
Q: Advice for checking integrity of serial char strings? I'm trying to create a flexible but reliable system for arduinos to interact using serial ascii strings. I'm using a message structure comprised of Command[10] + (optional) Params[20] + (optional) Header[30] + '\0' ( terminator). Each arduino node looks for incoming serial Commands (plus any appropriate optional Parameters) that it must respond to. During development and debugging it's sufficient to send Commands and Parameters using the IDE serial monitor without optional Header block or error-checking. But for interactive node-to-node communications, an optional 'Header' (technically a Footer) block is automatically added to the end of the message. If an incoming serial message includes a header block, it means that the message was sent automatically from another node (rather than manually from the IDE serial monitor), and consequently the message integrity should be checked against any relevent accompanying header contents, then an acknowledgement returned to the sender if the message was received ok. Header contents can optionally contain any of the following, and in any order:- s(source)=nnn, d(destination)=nnn, i(id)=nnn, l(msg length)=nnn, and non-critical mixtures of commas and/or spaces can be used as delimters. To test for message length, the transmitted l=nnn value (text representation) is padded to 3 digits with leading zeros, so the length stays the same whatever the value (eg:.anything from 000 to 999 still requires 3 digits). So far so good. But although a length test is better than nothing, it doesn't trap for corrupt characters, and the plan is for nodes to communicate via UDP broadcasts, so some form of error-checking and acknowledgement is essential. So the plan was to (also, or instead) use an optional c(checksum)=nnn in the header, whose value would be the mod sum of everything EXCEPT itself in the header entry. This is easily enough achieved for transmission by taking the mod sum of everything else when assembling the message, then adding the c=modsum on the end (or anywhere in the Header for that matter). In theory, the receiving end just needs to remove the c=nnn entry (plus any preceding delimter) from wherever it is in the Header, then compare the remaining message's calculated mod sum value against the transmitted c=nnn value. In practice, I don't know how to exclude the c=nnn entry from the header in order to calculate the remaining modsum, without being forced to accept and pander to unwelcome restrictive assumptions, such as the c=nnn value having to be the final entry, and having to use very strict delimiting. I'm trying to keep things as flexible and informal as possible, so that other x=nnn type instruction options may be added anywhere to the header if needed without risk of breaking existing rigidity. Perhaps I should add that this time a year ago I hadn't touched an arduino or C, and that this project has long ago changed from my original automation/security needs to become a goal for providing a simple-to-use interactive arduino distributed functionality cluster system suitable for anyone to use. The end finally seems to be in sight, which is thanks to the help and advice from you guys (a quick look through my questions shows how far you've brought me), so hopefully your greater experience and wisdom may also be able to offer a more satisfactory integrity-test solution if it is possible. I would also welcome any other comments that might help me improve on what I'm trying to do. ADDITIONAL INFO New incoming serial messages are received in char Buffer[64]. This gets split by delimiters into Command[10], Params[20] and Header[30], but these sizes are only arbitrary first guestimates which may change. Commands and Parameters can be whatever the node has been programmed to respond to. A trivial 'Blink' example might be a couple of nodes, one looking for incoming "PING" Commands and responding by returning "PONG" Commands, and the other node vice- versa. A more useful example could be an IR receiver node issuing instructions to a remote IR blaster node, so the "Command+Param+Header" string might be:- "IRSEND 'NEC 0xFFEEAB99, 32', s=1, d=2, l=044" The Command/Params parser accepts comma or space as delimiter except if they are contained within quotes. Quotes may be sent inside of quotes of the other type (single or double). Mr T's invaluable Header parser is slightly modified to also accept comma's or spaces as delimiters in the Header, therefore " , s=nnn,d=nnn, i=nnn l=nnn , " all extracts ok. All of the above is working ok in a very messy and disjointed proof-of-concept form. static char buffer[64]; int msgpos = 0; int msglength; int quotes=0; int parseMode=0; bool echo=false; bool ack=false; byte chksum=0; int modchk = 0; char command[10]; char param[20]; char header[30]; int snum=0, dnum=0, inum=0, lnum=0, cnum=0; void setup() { Serial.begin(9600); Serial.println("Ready"); } int readline(int readch, char *buffer, int len) { // If a CR terminated ascii string is received, returns string length, else returns -1 static int pos = 0; int rpos; if (readch >0) { // if a valid ascii character msgpos++; if (msgpos == 1) resetBuffer(); // First chr, so reset everything to make a new start if (!(pos < len-1)) Serial.println("Error: Msg too big for buffer"); else if ((readch !=10) && (readch != 13)) { buffer[pos++] = readch; modchk += readch; modchk %= 100; // Serial.print("modsum%='"); Serial.print(modchk); Serial.println("'"); buffer[pos] = 0; } // end if (pos < len-1) switch(readch) { case 10: break; // Ignore new-lines case 39: if (quotes==0) quotes=1; else if (quotes==1) quotes=0; else addChr(readch); break; // Turn on or off single-quotes case 34: if (quotes==0) quotes=2; else if (quotes==2) quotes=0; else addChr(readch); break; // Turn on or off double-quotes case 33: if (quotes==0) parseMode=-1; else addChr(readch); break; // ! Header info case 32: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break; // space delimiter case 44: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break; // comma delim case 13: // CR stop char if (parseMode==0) {Serial.println("Error: blank or corrupt message"); pos=0; return 0; } else if(quotes>0) {Serial.println("Error: open quotes not closed"); pos=0; return 0; } else {// new msg recvd ready for processing. TODO: check if msglength and/or checksum sent, if so and if correct, return ack to sender rpos = pos; pos = 0; // Reset position index ready for next time return rpos; } break; default: addChr(readch); break; } // end case } // end if (readch >0); return -1; // No end of line CR yet, so return -1. } void resetBuffer() { modchk=0; quotes=0; parseMode=0; command[0]='\0'; param[0]='\0'; header[0]='\0'; snum=0; dnum=0; inum=0; lnum=0; cnum=0; } bool parseModeBump() { switch (parseMode) { case 0: parseMode=1; break; case 1: parseMode=2; break; case 2: parseMode=-1; break; case -1: Serial.println("Error: too many delimited parameters"); return false; } return true; } bool addChr(char readch) { // char addch[2]; bool ret=true; addch[0]=readch; addch[1]='\0'; if (parseMode==0) parseMode=1; switch (parseMode) { case 1: strcat(command,addch); break; case 2: strcat(param,addch); break; case -1: strcat(header,addch); break; default: Serial.println("addChr Error: too many delimited parameters"); ret = false; } return ret; } void show() { Serial.print("SHOW: Command='"); Serial.print(command); Serial.print("'"); Serial.print(" Parameter='"); Serial.print(param); Serial.print("' "); Serial.print(" Header='"); Serial.print(header); Serial.println("'"); Serial.println(); Serial.print("Msg Length='"); Serial.print(msglength); Serial.println("'"); if (snum) { Serial.print("snum="); Serial.println(snum); } if (dnum) { Serial.print("dnum="); Serial.println(dnum); } if (inum) { Serial.print("inum="); Serial.println(inum); } if (lnum) { Serial.print("lnum="); Serial.println(lnum); } if (cnum) { Serial.print("cnum="); Serial.println(cnum); } } /* bool padzeros() { // Flawed - redo from scratch using 2 for loop passes char lengthstr[4]="7"; Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'"); int maxsize=sizeof(lengthstr); // size of lengthstr array int steps=strlen(leng)+1; // number of chars to be moved int hop=maxsize-steps; // number of steps to be jumped over each move if((steps>1)&&(maxsize>steps)) { for (int pos=steps-1; pos >= 0; pos--) { lengthstr[pos+hop] = lengthstr[pos]; lengthstr[pos]='0'; } } Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'"); } */ unsigned int calcmodsum(char* s){ unsigned int i = 0; int m=0; byte b; do { b = s[i]; m += s[i]; i++; } while (b != 0); //keep going until null terminator found at end of string m %= 100; // return m; } int getheader() { // extract values from header // char header[] = "s=123 d=789 c=463"; ack=false; echo=false; char * ptr = header; // header string pointer char * eq = NULL; // search char (=) int * num = NULL; // empty at start int c = 0; while (1){ eq = strchr(ptr, '='); ptr = eq; // update the pointer if (ptr == NULL) break; // found no '=' chars switch (*(ptr - 1)){ case 'd': num = &dnum; break; case 's': num = &snum; break; case 'i': num = &inum; break; case 'l': num = &lnum; break; case 'c': num = &cnum; c=3; break; default: num = NULL; } ptr++; if (num == NULL) //unrecognized var continue; // locate next = char *num = 0; while (*ptr && (*ptr != ' ') && (*ptr != ',') && isdigit(*ptr)) { // while valid digit and end of string not yet reached *num *= 10; // extract each int *num += *ptr - '0'; c++; ptr++; } } // Now Process any extracted header values if (lnum) { Serial.print("Msg length="); Serial.print(strlen(buffer)); Serial.println(); Serial.print("lnum="); Serial.print(lnum); Serial.println(); if (lnum==strlen(buffer)) Serial.println("* Msg length OK"); else Serial.println("* Incorrect msg length"); } if (cnum) { Serial.print("calcmodsum='"); Serial.println(calcmodsum(buffer)); Serial.print("cnum='"); Serial.print(cnum); Serial.println("'"); Serial.print("count='"); Serial.print(c); Serial.println("'"); if (modchk==cnum) Serial.println("* Checksum OK"); else Serial.println("* Incorrect checksum"); } } void loop() { // Check for new received serial string msglength = readline(Serial.read(), buffer, 64); // Returns length of new ascii string, or -1 while receiving, or 0 if received msg is corrupt if(msglength==0 ) { Serial.println("ERROR: received serial message was invalid and discarded");show(); resetBuffer();} else if(msglength > 0) { // New msg to deal with if (header) getheader(); show(); msgpos=0; // reset ready for new msg after finished with last msg } } Once I can finalise a satisfactory c=nnn validity test, I shall tidy up this working 'receiver' part and move on to doing the 'sender' part, which I'm hoping should be quite trival in comparison. I suppose it would be 'proper' to assemble the outgoing message into something like a char outmsg[64] string, but I'm trying to keep resources minimal to maximise the resources available for the arduino's 'real' functionality, so perhaps it may be better just to send the outgoing msg as consecutive serial chunks, ie:- Serial.print(Command); Serial.print(Params); Serial.println(Header); The header will be built up as required. If s=nnn (source) was received it will be assumed that an acknowledgement response is required by the source to prevent it repeating failed transmissions, so the received s=nnn would be used as the outgoing d=nnn destination to respond to - outgoing msgs need only include a source s=nnn if they requires a response back. The i=nnn (msg id) isn't yet used, but could eventually be for re-assembling individual chunks of larger msgs, or keeping track of msg order if multiple msgs are expected. The l=nnn is a zero-padded count of all transmitted characters (excluding the terminating ), so can be anywhere within the Header string. It would be preferable if the zero-padded c=nnn checksum could also be anywhere in the Header, but this will require a checksum() calculator function to be able to apply its calculation to all Header characters except the nnn data characters of c=nnn. As things are, I can jump straight to "c=" wearing blinkers, but that offers no relative position info, so leaves me oblivious of everthing before it. And I'd prefer not having to split Header[] into seperate Left[] and Right[] chunks which would unnecessarily wastes at least [30+30] chars of memory. So I think I must sequentially step through all Header characters looking for "=" while applying the mod sum calc to each, except for the 3 following chars when the preceeding char is "c", but I can't quite get my head around how to do that yet. If the C string functions could return relative string positions instead of absolute * pointers it could all be so much more straightforward. Does anyone know of any alternative string-relative functions that might be available? NEW INFO 2 * Most "Hello world" examples (eg: IRlib) demonstrate functionality using the IDE serial monitor for user interaction. Whatever the functionality, they can all be considered as just a black box capable of recognising a few incoming serial plain-text commands and actioning as appropriate, possibly by also issuing serial text command responses of their own. The aim of my project is for a user to easily turn that existing and already-proven serial user interaction into an automatic arduino to arduino serial interaction if wished. The headers are just an optional bolt-on for arduino to arduino reliability, but during dev and debugging the various optional header contents will still need to be read and written by users with the IDE serial monitor, which only allows ascii text interaction. Although this sort of system would not be the preferred solution for experts, it offers much advantage for non-experts. Un-skilled hackers could create effective working solutions without needing to aquire any rocket science first, and without needing to worry too much about resource limitations, or the problems and complexity of trying to consolidate incompatable or conflicting functionality onto any single device. If they have an arduino that can serially interact, they can use it as an interactive node. If two can interact over serial, then more can serially interact using RS485, or using serial Ethernet UDP slaves (ESP8266's are small and cheap). Only nodes that 'recognise' an incoming command would respond to it. A Triggers node could send ascii Alerts such as 'Mailbox Opened', 'Gate1 Visitor', Shed Door Opened' etc. A Responder node could parse such incoming Alerts to match against entries in a config file, then parse the corresponding config entry for appropriate Response commands to be issued to other cluster nodes, such as 'Mailbox: Announce Mailbox Delivery', or 'Zone2: Announce Zone 2 Activity, CCTV: Select Zone2'. This would allow new node functionality to be added easily just by updating the Responders appropriate config file entry to include any additional Response commands that become available from any new nodes. So adding an X10 node for instance might offer a new Response command such as 'X10, A12 ON', which only the newly added X10 node would be looking for and respond to. A cluster system could be evolved into whatever sophisticated functionality was required, with minimal software skills and knowledge. Commands and parameters could be any plain-text names that the user prefers, which when matched during input parsing would branch to any required local function. Despite any resulting complexity, all individual nodes could still just be considered as relatively simple black boxes capable of recognising a few incoming serial plain-text trigger commands and replying with plain-text responses. Cluster nodes aren't even limited to being arduinos, because they could include ANY devices capable of receiving and responding to simple ascii command strings. This offers easy gradual progression to other platforms if wished without needing to abandon all existing efforts and start over again from scratch. I knew I was biting off more than I could chew, but each time I play devils advocate trying to avoid wasting my time going up a dead-end, the more benefits become apparent to make the effort seem worthwhile. The forums are littered with questions and libraries aiming in a similar direction, but I haven't yet found anything which offers that simple black-box plain-text interaction capability, hence my continued struggle. I'm not a programmer so I'll never be able to offer an efficient library solution, but I must try to keep going until I've got something that is usable, and if others find it useful then maybe eventually it might offer incentive for someone to wish to optimise and improve on it. Hopefully the following should do what I want as far as ignoring "c=nnn" from the mod checksum wherever it finds it. unsigned int calcmodsum(char* passedstr){ // calculates the mod sum of passedstr excluding the 3 "c=nnn" value digits int pos = 0; int modsum=0; byte b; do { b = passedstr[pos]; if ((passedstr[pos]=='c')&&(passedstr[pos+1]=='=')&&(pos>2)) pos=pos+4; else modsum += passedstr[pos]; // skip next 3 digits after finding c= pos++; } while (b != 0); // keep going until null terminator found at end of string modsum %= 100; return modsum; } A: Hmm... the length of your question makes it difficult to focus an answer. I'll try by stating my interpretation, then I'll provide a longer answer ;-) Is there a way to wrap a text message between two Arduinos   (to increase reliability), but would still     allow me to do testing without the wrapper? If I assume that's what you're asking, then the above comments have touched on various aspects of an answer: "Yes." Let's progress through my interpretation: "Text" means ASCII values between 32 and 126 (SP and '~', the printable characters). "Wrapping a message" means sending some bytes before and possibly after the text. "Increasing reliability" means detecting and/or correcting characters that get corrupted. "Testing without the wrapper" means that you would like to use the Serial Monitor to send example commands while you're in a noise-free environment, testing the logic of the command execution, not the mechanism of communicating reliably. Wrapping You're on the right path by prefixing the text with a binary header, and Nick's library shows how to use a "special" start and end byte to delimit the messages. (This is also called message "framing".) If the START byte can appear inside the message elsewhere, you will need to either (1) "escape" the START byte when it appears inside the message, (2) provide a second method of verifying that the message is framed correctly (e.g., an END byte and/or a length), or (3) decrease the odds of a false start by using a multiple-byte START sequence. You appear to have chosen (2). You are free to chose the bytes that follow the START byte. Addressing, sequence number and message type are common. Of course, the message length is in there somewhere. Reliability. If you're happy to simply detect an error at the receiving end, a checksum is sufficient. I'd like to suggest the Fletcher checksum, as it is simple, quick and fairly robust. CRCs are more robust, but a little more expensive to compute. But because they are calculated over the rest of the message (the "payload"), they almost always appear at the end, before any END sequence. This also makes it easier for the receiver, because it can accumulate the checksum as the bytes are received, and reject the message if the received checksum does not match the calculated checksum. You can also use error detection to help with acknowledgements, if you decide to implement them. An alternative to ACK/NAK messages is to request the current state (a poll command), expecting that it should reflect the previous (unacknowledged) command. If the state doesn't match, send the command again. If you also want to perform error correction, there are numerous ways to add that. All of them will increase the size of the message, as well as the CPU time. (Sorry, Nick, but sending complemented nybbles is not a very robust detection scheme, and it doubles the message size without adding correction capability.) Testing without the wrapper You could use CR/LF as your message framing and assume that anything after CR/LF is the start of an unwrapped message. If it starts unwrapped, set a bool flag that skips the checksum part and END byte. Final notes Your current program is structured to hold the complete message in RAM for processing (sent or received). This is not always feasible in the Arduino environment. You don't put all the print chars in a buffer, then do one big Serial.print( buffer ), do you? Just like breaking a Serial.print into several smaller prints, reception can be performed the same way. You can watch for keywords, or accumulate parameter values without buffering the entire message. While it saves a lot of RAM, it also saves CPU time because each received character is handled once. With a buffered approach, each character is handled multiple times: read() into a buffer, then compared during a search, and maybe parsed. One of my recent posts has some general structure information, snipped a little for here: Reading data on the Arduino is different from most PC applications. Calling Serial.read() does not always return data. Well, it returns -1 (or 0xFF) if no characters are available. In a PC app, calling read will usually wait until a data has been received: the PC app is "blocked" until a character comes in. That's not very noticeable because the PC has a nice multitasking OS so your pointer keeps moving and other windows respond, even though the one app is waiting for a character. On the Arduino, you can make it block the same way, but there's no OS that will let you do something else while you're waiting for data (yes, there are multitasking solutions, but let's avoid that for now). So blocking on the Arduino can keep you from doing other things you may need to do, like blinking an LED or catching a button press. There are a few common ways to write an Arduino sketch that can cope with this speed disparity: 1) Force the Arduino to wait for each character (i.e., block), and write the sketch in a very linear, top-to-bottom fashion: while (Serial1.available() == 0) ; // wait inByte1 = Serial1.read(); if (inByte1 == 0x3E){ // START byte buffer[0] = inByte1; while (Serial1.available() == 0) ; // wait inByte1 = Serial1.read(); if (inByte1 == 0x03){ 2) Save each character in a buffer as it arrives until you have received an entire packet. Then parse the packet all at once with similar linear code: static uint8_t count = 0; // keeps its value across calls to loop if (Serial1.available()) { inByte1 = Serial1.read(); if (inByte1 == 0x3E) { // START character // Next packet starting, process the current one we've been saving, // if we have saved enough bytes (skips small/bad packets). if ((count > 6) && (buffer[0] == 0x3E)) { // SNIP: handle previous packet } // Reset the count to start a new packet with the 0x3E we just received. count = 0; } // Save the current byte if (count < sizeof(buffer)) buffer[ count ] = inByte1; count++; } 3) Parse each character as it arrives, picking up where you left off after doing other things. void loop() { // statics keep values across calls to loop static uint8_t count = 0; static bool skipping = true; static uint8_t messageLength = 0; if (Serial1.available()) { // or 'while' uint8_t inByte = Serial1.read(); if (inByte == 0x3E) { // START byte // Starting a new packet! buffer[0] = inByte; count = 1; skipping = false; } else if (!skipping) { // Saving a packet, store the current byte if (count < sizeof(buffer)) buffer[ count ] = inByte; // Use the current byte, depending on 'count' switch (count) { case 1: if (inByte != 0x03) skipping = true; // ignore other packet selector values break; case 2: messageLength = inByte; // Error check? if (messageLength != 40) skipping = true; break; case 3: // packetID = inByte; ? buffer[3] = inByte; break; case SNIPPED: other header information fields case SNIPPED: accumulate/parse payload case SNIPPED: verify checksum (ignore packet or execute packet) } count++; } } // Do other things, too? } Choice 1 is very linear. The disadvantage is that it blocks and does not recover from data errors very well. Choice 2 is pretty easy to understand and it doesn't block; other tasks can do things while waiting for a complete packet. The disadvantage is that all the packet processing happens when the last byte is received (actually, the first byte of the next packet in that code). Choice 3 is more difficult to understand, because the entire section is executed for each character, either starting a new packet or using the switch statement to handle each char. Different cases do a little work, depending on the count. The advantage is that the processing is spread out over each character, and you can decide to skip the rest of a packet at any point. This is actually a Finite-State machine approach, and Nick Gammon has a great description, too.
{ "pile_set_name": "StackExchange" }
Q: Printf and Scanf not working properly for second string input I'm trying to simply read input from the user and store a CD record into some variables. All the variables details are correctly printed out for all the variables except for the second array of char for artist which isn't printing anything. I've tried to deal with the extra character spacing by introducing the space at the front of each of my formatted strings in scanf(), but that hasn't fixed it. void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price); int main() { char title[61]; char artist[41]; short noOfTracks = 0; int isAlbum = 0; float price = 0.0; char albumOrSingleResponse; printf("Please enter the title: "); scanf(" %s", title); printf("Please enter the artist: "); scanf(" %s", artist); printf("Please enter the number of records: "); scanf(" %d", &noOfTracks); printf("Please enter whether or not the cd is an album/single (A or S): "); scanf(" %c", &albumOrSingleResponse); if(albumOrSingleResponse == 'A') { isAlbum = 1; } printf("Please enter the price of the CD: "); scanf(" %f", &price); displayCDInfo(title, artist, noOfTracks, isAlbum, price); return 0; } void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price) { printf("\nThe title of the CD is %s", title); printf("\nThe name of the artist is %s", artist); printf("\nThe number of tracks on this CD are %d", noOfTracks); printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single"); printf("\nThe price of the cd is $%.2f", price); } A: I figured out how to fix this now whilst keeping noOfTracks as a short. Since I was using "%d" for scanf on the Number of tracks variable I was overwriting the space allocated for the previous variable which was artist, hence why it wasn't being displayed. To solve this I had to change the "%d" to "%hu" for short int. void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price); int main() { char title[61]; char artist[41]; short noOfTracks = 0; int isAlbum = 0; float price = 0.0; char albumOrSingleResponse; printf("Please enter the title: "); scanf("%s", title); printf("Please enter the artist: "); scanf("%s", artist); printf("Please enter the number of records: "); scanf("%hu", &noOfTracks); printf("Please enter whether or not the cd is an album/single (A or S): "); scanf(" %c", &albumOrSingleResponse); if(albumOrSingleResponse == 'A') { isAlbum = 1; } printf("Please enter the price of the CD: "); scanf(" %f", &price); displayCDInfo(title, artist, noOfTracks, isAlbum, price); return 0; } void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price) { printf("\nThe title of the CD is %s", title); printf("\nThe name of the artist is %s", artist); printf("\nThe number of tracks on this CD are %hu", noOfTracks); printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single"); printf("\nThe price of the cd is $%.2f", price); }
{ "pile_set_name": "StackExchange" }
Q: What to do with an additional answer which IMHO explains only a small portion of the question, while another answer explains more For the apple.stackexchange question "...how do I set the PATH environment variable unified..." a 2nd answer was given, which relates to the question, but IMHO does not answer a majority portion of the question. Here some details: The question is about, how to set the PATH variable in a unified manner. The 2nd answer details how to change the file /etc/launch.conf. It is to note, that changing this file is needed for the overall answer. The author of the answer does make the valid point that, when he searched for, how to change /etc/launch.conf, the question came up. The 1st answer does not detail the change of /etc/launch.conf enough. So, the general problem is: What to do when an additional answer explains only a small (but unique portion) of the question, while an earlier answer explains more (but not what the additional question explains). Finally, I think I should note that I am the initial asker and poster of the 1st answer. A: If they are both useful, vote them both up. If one is only a little useful, don't vote on it. If one is actually wrong, downvote it. Feel free to comment on any of them. And if one of them actually solves your problem, accept it. In the special case where one of the answers is yours, if you realize it's not useful any more, delete it. If it has some value, leave it. You can always edit your answer to improve it, but don't just copy in what another answer said. A: I am the provider of the second, "minor" answer. Somehow along the way, even though my answer is factually accurate and provides (what I think is) vital information that the original answer is lacking, my answer was voted down. I don't care who did it, that's not the point. When you mouse over the vote down arrow, the tooltip "This answer is not useful" appears, which doesn't seem to be the case here, but again I'm biased. The reason I didn't try to "integrate" my information into the existing answer is that this type of editing is strictly frowned upon. I'm an edit reviewer on a few sites, including SO, and I frequently reject edits as "an attempt to reply to or comment on the existing post." I feel that one of the great things about the SE community is that if you feel that you can add to the conversation, that perhaps an existing answer doesn't quite cover all the bases, then you are encouraged to do so.
{ "pile_set_name": "StackExchange" }
Q: React-native component's componentDidMount() is not called under NavigatorIOS I create a component with ListView under the structure: TabBarIOS > NavigatorIOS > ListView. I try to fetch data in componentDidMount(). But it didn't work unless I fetch it in componentWillMount(). Why? I've put my work here https://github.com/chiakie/MyAwesomeProject In MotorcycleList.js, componentDidMount() seem to never be called. A: The componentWillMount() life cycle event is actually the correct place to call fetchData() because it is invoked once before the component mounts, this way you can setState do that the data is there when it mounts. Mounting: componentWillMount void componentWillMount() Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method,render() will see the updated state and will be executed only once despite the state change. Whereas componentDidMount() renders after the component had already mounted. Mounting: componentDidMount void componentDidMount() Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The componentDidMount() method of child components is invoked before that of parent components.
{ "pile_set_name": "StackExchange" }
Q: Best approach: Set/change password dialog I have a usercontrol which is responsible for presenting creation and change of users. The usercontrol is bound to an entity delivered by a RIA Service: [MetadataType(typeof(User.UserMetadata))] public partial class User { internal class UserMetadata { protected UserMetadata() {} [Required] public string Name { get; set; } [Exclude] public string PasswordHash { get; set; } [Exclude] public int PasswordSalt { get; set; } [Required] public string ShortName { get; set; } [Include] public IEnumerable<UserRole> UserRoles { get; set; } } [DataMember] [RegularExpression("^.*[^a-zA-Z0-9].*$", ErrorMessageResourceName = "BadPasswordStrength", ErrorMessageResourceType = typeof(ErrorResources))] [StringLength(25, MinimumLength = 6)] public string NewPassword { get; set; } } When creating a new user, the field "NewPassword" is required - but when changing properties of an existing user, it is not (it is used for password-changes). What is the best approach to solve this? I have several ideas, but they all feels a little bit crappy :-) Thanks A: It appears you are passing your current passwords back to the GUI. There is no need to ever do that. That would create a potential security hole Suggest you treat password changing as a separate service call, not just a simple record editing exercise. RIA services supports Invoke Operations which are basically arbitrary direct-calls to your RIA service. The only restriction on Invoke operations is that they cannot return complex types (not a problem for this example). Pass your current logged-in user identifier, the current password (encoded) and the new password (encoded) and do all the work server side. Return a simple success boolean value. Just some suggestions, I am happy to see other people's ideas on this one :)
{ "pile_set_name": "StackExchange" }
Q: How to initialize const size array in constructor without explicitly stating the size in class declaration? I need to do something like class foo { foo(); int a[]; } Further in cpp-file: foo::foo() : a{1,2,3,4} {} Peculiarities: C++98 standard array is not int, initializing list is much longer. Though its values are known at compile time, they can change from time to time EDIT: Another option is also suitable, when new[] is used for memory allocation, but, again, it is undesirable to state the array size explicitly: class foo { foo(); int * a; } Further in cpp-file: foo::foo() { a = new[]; // impossible // filling the array with values } A: You cannot do that: The size of the array is part of the type of the array, and hence of the class. The constructor is also part of the class. The class needs to exist first before you can call constructors, so the constructor call cannot influence the class definition.
{ "pile_set_name": "StackExchange" }
Q: Application output button in Xamarin I'm using Xamarin Studio to write C# and the Application Output button in the bottom right hand corner of the window has disappeared. I've had a look how to make it appear again but can't work out. Any help on turning it back on would be greatly appreciated. A: It's under View->Pads->Application Output
{ "pile_set_name": "StackExchange" }
Q: Should I use RouteParameter or UrlParameter for an Asp.NET web-api route? I've seen both being used and so I wonder, do they do the same thing or different things? If it's the latter, what's the difference? I tried answering it myself by having a look at the visual studio MVC 4 (rc) web api template, but sadly it uses both, so my confusion remains. Here's what the template contains: public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } A: Use RouteParameter for Web Api routes (.MapHttpRoute) and UrlParameter for standard MVC controller routes (.MapRoute). As you know standard MVC and Web API are 2 completely distinct APIs in terms of assemblies and namespaces even if both are pretty similar. You could for example self host your Web API in a console application, so you won't even have a reference to the System.Web.Mvc assembly and you would of course use RouteParameter in this case.
{ "pile_set_name": "StackExchange" }
Q: What manuscript is depicted in the HSM advertisement? The following advertisement recently appeared in the sidebar on math.se: Is the Greek script on the left actually from a mathematical manuscript? What is its source? A: User plannapus points out that the proposer of the ad links to the original source, which is the first page of Diophantus’s Arithmetica, specifically the 1621 translation by Claude Gaspard Bachet de Méziriac. The right-hand side is Greek, and the left-hand side a Latin translation; the bottom seems to be the translator's commentary. (Google Books has a scan of the British Museum copy of the 1621 version; it matches exactly.) A: This is an allusion to Fermat's comment in his copy of Diophantus's Arithmetica, whose page I assume is reproduced in the photo: "It is impossible to separate a cube into two cubes, or a biquadrate into two biquadrates, or in general any power higher than the second into powers of like degree: I have discovered a truly marvelous proof of it, but this margin is too small to contain it". The comment was next to the Problem II.8:"partition a given square into two squares", the problem of finding the Pythagorean triples, triples of integers that can serve as side lengths of a right angle triangle. Diophantus does not mention the geometric connection however, see more under Who discovered integer triangles with one angle trisecting another?
{ "pile_set_name": "StackExchange" }
Q: Storing and Displaying Videos on SharePoint 2016 I have a departmental request to store many videos ranging from 200 mb to 1gb in size. With SharePoint 2016 on-Premise, what is the most efficient way to go about this? A: I would use the assets library and upload the video on it. You have to adjust the file upload limit at web application level to accommodate the large file size. Asset Library: SharePoint's built-in Asset Library app is pre-configured to help you manage rich media assets, such as image, audio, and video files. Asset Libraries feature: Thumbnail–centric views Overlay callouts Digital asset content types Automatic metadata extraction for image files To add a asset library, please follow the below steps. Browse to the site where you want to create the library. In the Quick Launch, click Site Contents or click Settings Office 365 Settings button and then click Site Contents. Under Lists, Libraries, and other Apps, click Add an app. To create an Asset Library, you must have permission to create lists. If you don't have sufficient permissions, you won't see the Add an app link. Under Apps you can add, click Asset Library. In the Adding Asset Library dialog box, type a name for the library, and then click Create. Read more here: https://support.office.com/en-us/article/Set-up-an-Asset-Library-to-store-image-audio-or-video-files-96532BF6-DC72-4F82-BF0A-21EF945C4D04 Upload video, audio, or pictures to an Asset Library
{ "pile_set_name": "StackExchange" }
Q: C - shared memory cast to struct I've got to finish my C program, however I'm stuck on the Shared memory part of the task. Basically this is what I should do: MapViewOfFile returns a pointer to void which you can cast to anything you like. I suggest you create struct to represent the structure you would like the memory to have and cast the return pointer to this struct." I call the MapViewOffFile function, but I don't understand how I'm supposed to point the struct to it. Code: typedef struct { LARGE_INTEGER start; LARGE_INTEGER end; LARGE_INTEGER frq; } TimeOfSharing; TimeOfSharing timing; HANDLE fileView; fileView = MapViewOfFile(fileHandle, FILE_MAP_READ | FILE_MAP_WRITE,PAGE_READONLY, 0, 0); So how do I point the fileView to my struct? (I need to fetch the struct from another process) Hope I was clear enough! Thanks a lot! A: MapViewOfFile actually returns a pointer to void, not a HANDLE. You just need to cast that appropriately: TimeOfSharing *timing = (TimeOfSharing *)MapViewOfFile(...); // Then access as you see fit, e.g.: LARGE_INTEGER length; length.QuadPart = timing->end.QuadPart - timing->start.QuadPart; If you really need/want to actually copy the data, not just access it in place: TimeOfSharing my_copy = *(TimeOfSharing *)MapViewOfFile(...);
{ "pile_set_name": "StackExchange" }
Q: Usage of "aussetzen" I was making fun of someone's funny picture, and as response got a comment of Willst du was aussetzen? The two meanings of the verb are suspend, and expose. Am I right in interpreting the comment as do you want to remark on something (in specific)? Somehow I can not get the feeling of the usage of the verb in this case. A: The word has multiple meanings, two of which you have covered with your translations. to miss a turn Wer eine 1 würfelt, muss eine Runde aussetzen. to suspend, discontinue something Das Gericht setzte den Beschluss aus. to expose Der Einsiedler stieg aus seinem Erdloch und setzte sich dem Wetter aus. to set free Der Hund wurde an der Raststätte ausgesetzt – im Hotel war kein Platz für ihn. Seit wir Fische im Teich ausgesetzt haben, ist das Algenwachstum stark zurückgegangen. and finally: to (negatively) criticise something Ich habe an deinem Bild auszusetzen, dass es lächerlich wirkt. Most of the connotations this word implies are negative; in fact, only the fish-sentence can be understood in a positive way. I’m pretty sure that most of the meanings derived from somehow sitting something out or making something sit outside; it is now a rather widespread verb that can carry dozens of subtle meanings in context. Note that etwas an etwas aussetzen usually requires a complement with the particle an — not present in the OP’s quote. However, I have heard the occasional German omit that complement if both parties were absolutely sure about the object that was being criticised. Omitting daran is not formally correct, though.
{ "pile_set_name": "StackExchange" }
Q: IPhone Custom UIButton Cannot DismissModalViewController I have a custom UIButton class in my IPhone navigation application. When the user clicks the button I present a modal view which displays a tableview list of records that the user can select from. On click of the button I create my viewController and show it using the following code: -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ dropDownPickerViewController = [[DropDownListingViewController alloc] initWithNibName:@"DropDownListingView" bundle:[NSBundle mainBundle]]; ..... ..... [[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] presentModalViewController:dropDownPickerViewController animated:NO]; [dropDownPickerViewController release]; [super touchesEnded:touches withEvent:event]; } As you can see the button could be on any viewController so I grab the navigationController from the app delegate. Than in my DropDownPickerViewController code i have the following when a user selects a record: [[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] dismissModalViewControllerAnimated:NO]; But nothing occurs. It seems to freeze and hang and not allow any interaction with the form. Any ideas on why my ModalViewController wouldnt be dismissing? Im thinking it is the way I use the app delegate to present the viewController. Is there a way to go self.ParentViewController in a UIButton class so I can get the ViewController of the view that the button is in (if this is the problem)? Any ideas would be greatly appreciated. Thanks A: I did recall that I did have to do something similar once, and by looking at this post: Get to UIViewController from UIView? I was able to create some categories: // // UIKitCategories.h // #import <Foundation/Foundation.h> @interface UIView (FindUIViewController) - (UIViewController *) firstAvailableUIViewController; - (id) traverseResponderChainForUIViewController; @end @interface UIView (FindUINavigationController) - (UINavigationController *) firstAvailableUINavigationController; - (id) traverseResponderChainForUINavigationController; @end // // UIKitCategories.m // #import "UIKitCategories.h" @implementation UIView (FindUIViewController) - (UIViewController *) firstAvailableUIViewController { // convenience function for casting and to "mask" the recursive function return (UIViewController *)[self traverseResponderChainForUIViewController]; } - (id) traverseResponderChainForUIViewController { id nextResponder = [self nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]]) { return nextResponder; } else if ([nextResponder isKindOfClass:[UIView class]]) { return [nextResponder traverseResponderChainForUIViewController]; } else { return nil; } } @end @implementation UIView (FindUINavigationController) - (UINavigationController *) firstAvailableUINavigationController { // convenience function for casting and to "mask" the recursive function return (UINavigationController *)[self traverseResponderChainForUINavigationController]; } - (id) traverseResponderChainForUINavigationController { id nextResponder = [self nextResponder]; if ([nextResponder isKindOfClass:[UINavigationController class]]) { return nextResponder; } else { if ([nextResponder isKindOfClass:[UIViewController class]]) { //NSLog(@" this is a UIViewController "); return [nextResponder traverseResponderChainForUINavigationController]; } else { if ([nextResponder isKindOfClass:[UIView class]]) { return [nextResponder traverseResponderChainForUINavigationController]; } else { return nil; } } } } @end you can then call them like so: UINavigationController *myNavController = [self firstAvailableUINavigationController]; UIViewController *myViewController = [self firstAvailableUIViewController]; maybe they will help you, I hope so.
{ "pile_set_name": "StackExchange" }
Q: Dice Roller Change Sides and Amount of Dice in Set I am creating a dice roller that allows users to change the amount of sides on the dice as well as change the amount of dice in a set. I am able to get a console output, but not the right output within my HTML page. Ideally, when you click the button, it will change the amount of sides on the dice as well as the amount of dice. I would like to know what I am doing wrong, and how I would go about fixing it! Thanks!!! numbers = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50" ] $(function() { //var dice; // For creating a new Diceset dice = new DiceSet(); $("#rollButton").click(function() { //var dice, outcomeList, message; outcomeList = dice.roll(); console.log(outcomeList); // a good start, but you really don't want to reference //the array this way // use a for loop here instead of outcomeList message = "Rolled Dice! " + outcomeList + " <br>"; $("#outcome").append(message); }); // place click handler for reset here $("#diceResetButton").click(function() { dice.reset(); $("#outcome").html(""); console.log("Reset is Supposed to happen...") }); //click handler for changing the number of sides $("#setDiceSetSidesButton").click(function() { var select, chosen_number; dice.setNumSides(6); chosen_number = numbers[select]; $("DiceSize").html(chosen_number); console.log("Amount of Sides on Dice Should Change...") }); // click handler for setting the number of dice in the diceset $("#setDiceSetSizeButton").click(function() { var select, chosen_number; dice.setDiceSetSize(2); chosen_number = numbers[select]; $("DiceSides").html(chosen_number); console.log("Dice Set Amount Should change...") }); // click handler for getting the average number of rolls $("#RollAverageButton").click(function() { dice.getAverage(); console.log("Average is Supposed to Be Displayed...") }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <h1>Dice Roller Simulation</h1> <input type="number" id="setDiceSetSize" value="2" id="DiceSize" /> <input type="button" id="setDiceSetSizeButton" value="Set Dice Size" /> <br> <input type="number" id="setDiceSetSides" value="6" id="DiceSides"> <input type="button" id="setDiceSetSidesButton" value="Set Amount of Sides on Dice" /> <p> <input type="button" id="rollButton" value="Roll Dice" /> </p> <p> <input type="button" id="RollAverageButton" value="Get Average" /> </p> <p><input type="button" id="diceResetButton" value="Reset Dice Roll" /> </p> <p id="outcome"> </p> // // Example use: // dice = new DiceSet(); // // dice.roll() --> simulates roll and returns array of individual dice results // dice.numRolls() --> number of times the set of dice has been rolled // dice.getAverage() --> average totals from the sets // dice.history --> an array of totals from the set rolls // // dice.reset() --> resets history of dice rolls // // dice.setNumSides(8) --> configure for 8-sided DiceSet // dice.setDiceSetSize(4) --> roll 4 dice with each set class DiceSet { constructor() { this.sides = 6; this.quantity = 2; this.history = []; this.runningTotal = 0; } singleRoll() { return Math.floor(Math.random() * this.sides + 1); } setNumSides(numSides) { this.sides = numSides; this.reset(); } setDiceSetSize(numDice) { this.quantity = numDice; this.reset(); } reset() { this.history = []; this.runningTotal = 0; } numRolls() { return this.history.length; } getAverage() { return this.runningTotal / this.history.length; } roll() { var total, same, rollSet, i; same = true; rollSet = []; rollSet[0] = this.singleRoll(); total = rollSet[0]; for (i = 1; i < this.quantity; i++) { rollSet[i] = this.singleRoll(); total += rollSet[i]; if (rollSet[i] !== rollSet[i - 1]) { same = false; } } this.history.push(total); this.runningTotal += total; return rollSet; } } A: Is this what you want? https://jsfiddle.net/cCrul/8mof1hk4/ // // Example use: // dice = new DiceSet(); // // dice.roll() --> simulates roll and returns array of individual dice results // dice.numRolls() --> number of times the set of dice has been rolled // dice.getAverage() --> average totals from the sets // dice.history --> an array of totals from the set rolls // // dice.reset() --> resets history of dice rolls // // dice.setNumSides(8) --> configure for 8-sided DiceSet // dice.setDiceSetSize(4) --> roll 4 dice with each set class DiceSet { constructor() { this.sides = 6; this.quantity = 2; this.history = []; this.runningTotal = 0; } singleRoll() { return Math.floor(Math.random() * this.sides + 1); } setNumSides(numSides) { this.sides = numSides; this.reset(); } setDiceSetSize(numDice) { this.quantity = numDice; this.reset(); } reset() { this.history = []; this.runningTotal = 0; } numRolls() { return this.history.length; } getAverage() { return this.runningTotal / this.history.length; } roll() { var total, same, rollSet, i; same = true; rollSet = []; rollSet[0] = this.singleRoll(); total = rollSet[0]; for (i = 1; i < this.quantity; i++) { rollSet[i] = this.singleRoll(); total += rollSet[i]; if (rollSet[i] !== rollSet[i - 1]) { same = false; } } this.history.push(total); this.runningTotal += total; return rollSet; } } numbers = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50" ] $(function() { //var dice; // For creating a new Diceset dice = new DiceSet(); $("#rollButton").click(function() { //var dice, outcomeList, message; outcomeList = dice.roll(); console.log(outcomeList); // a good start, but you really don't want to reference //the array this way // use a for loop here instead of outcomeList message = "Rolled Dice! " + outcomeList + " <br>"; $("#outcome").append(message); }); // place click handler for reset here $("#diceResetButton").click(function() { dice.reset(); $("#outcome").html(""); console.log("Reset is Supposed to happen...") }); //click handler for changing the number of sides $("#setDiceSetSidesButton").click(function() { var chosen_number = $("#setDiceSetSides").val(); dice.setNumSides(chosen_number); $("DiceSize").html(chosen_number); console.log("Amount of Sides on Dice Should Change...") }); // click handler for setting the number of dice in the diceset $("#setDiceSetSizeButton").click(function() { var chosen_number = $("#setDiceSetSize").val(); dice.setDiceSetSize(chosen_number); $("DiceSides").html(chosen_number); console.log("Dice Set Amount Should change...") }); // click handler for getting the average number of rolls $("#RollAverageButton").click(function() { alert(dice.getAverage()); console.log("Average is Supposed to Be Displayed...") }); }); <!doctype html> <html> <head> <title>Dice Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src="dice.js"></script> <script src="diceLS.js"></script> </head> <body> <h1>Dice Roller Simulation</h1> <input type="number" id="setDiceSetSize" value="2" id="DiceSize"> <input type="button" id="setDiceSetSizeButton" value="Set Dice Size" /> <br> <input type="number" id="setDiceSetSides" value="6" id="DiceSides"> <input type="button" id="setDiceSetSidesButton" value="Set Amount of Sides on Dice" /> <p> <input type="button" id="rollButton" value="Roll Dice" /> </p> <p> <input type="button" id="RollAverageButton" value="Get Average" /> </p> <p><input type="button" id="diceResetButton" value="Reset Dice Roll" /> </p> <p id="outcome"> </p> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: ¿Puedo compartir un programa de Python (3.x) con alguien que no lo tenga instalado? Mi primer lenguaje fue c y como pueden imaginar las diferencias con python-3.x son notables. Python es orientado a objetos y una diferencia importante para un novato en Python como su servidor es que mientras C es compilado, Python es interpretado. Cuando aprendí C compartía mis programas sencillos (ya compilados) por diversión (algunos sí que les eran útiles), pero con Python quisiera saber si existe alguna manera de que alguien que no tiene instalado el intérprete pueda usar el programa de mi código python, pregunto porque además de la extensión .py noté que existen otras, no sé si esas ayuden. P.D. Uso windows OS. A: En el caso de las distribuciones Linux la mayoria trae instalado python 2.7x, para el caso de windows puedes usar una herramienta como PyInstaller que te crea un .exe de tu script y lo puedes compartir y lo pueden ejecutar sin tener python instalado. Uso básico de PyInstaller: pyinstaller.exe --onefile --windowed mi_script.py
{ "pile_set_name": "StackExchange" }
Q: 2 SQL Server queries throw an error I cannot take mssql_fetch_array I need to take logged users last 200 rows OrderId's from Orders table WHERE UserName = '$user' AND OrderState = '1' AND OrderId = OrderDetails My tables here Orders OrderId int UserName nvarchar(64) OrderState int OrderDetails OrderId int OrderDetailId int My sample code: $queryf = "SELECT TOP 200 * FROM Orders WHERE UserName='$user' AND OrderState='1' AND (SELECT * FROM OrderDetails WHERE OrderId='HERE PROBLEM') ORDER BY OrderId DESC"; $resultf = @mssql_query($queryf); $sayif = @mssql_num_rows($resultf); while($rowf = @mssql_fetch_array($resultf)) { $CustomerIds = $rowf["CustomerId"]; } Another sample codes added from @vkp SELECT TOP 200 o.* FROM Orders o JOIN OrderDetails d on o.OrderId = d.OrderId WHERE UserName='$user' AND OrderState='1' ORDER BY o.OrderId DESC Throws an error [FreeTDS][SQL Server]Ambiguous column name 'UserName'. I'm trying but I don't know how to resolve it. Thanks ! A: If I understand your question correctly, this should be all you need: Select Distinct Top 200 O.* From Orders O Join OrderDetails D On O.OrderId = D.OrderId Where O.UserName = '$user' And O.OrderState = 1 Order By O.OrderId Desc Another option is to use EXISTS: Select Top 200 O.* From Orders O Where Exists ( Select * From OrderDetails D Where D.OrderId = O.OrderId ) And O.UserName = '$user' And O.OrderState = 1 Order By O.OrderId Desc
{ "pile_set_name": "StackExchange" }
Q: Raspbian stuck in read-only after reboot I'm the new owner of a Raspberry Pi and I'm having trouble with my file-system getting stuck in read-only mode after rebooting the device. Here's the hardware I'm working with: Pi: model B PSU: Samsung GSIII charger 5A 1A SD: Kingston 8GB (brand new) input: basic USB keyboard and mouse video: HDMI I can install Raspbian using the NOOBS image just fine and once I'm in I can configure and install programs but after a reboot 90% of the time on boot up I get a warning about the file-system being read only and after I log into the shell I can't do any task that involves writing to a file. I can't even launch the desktop. I can run any shell programs I had installed before reboot. I'm rebooting only using the commands sudo reboot and sudo shutdown -h now. When shutting down I wait for the video to die and the light on the Pi to stop blinking before removing power. I've tried re-imaging the SD card many times and the first boot always works fine, sometimes it lets me reboot once or twice but it always has the same problem eventually. I have a moderate familiarity with Unix/Linux but this is my first attempt at using a Pi. Help! A: Have a look in /var/log/syslog and see if you can find some indication of why. If the filesystem is mounting read-only, the last thing in that file will be whatever happened when it was still read-write, since the system cannot log there otherwise. Which may or may not be helpful... The kernel's own log is in memory, however, and does not require a writable filesystem to access. You can view it with: dmesg | less Have a look at that right after you reboot. [Then based on that...] From the pictures it would appear you have either root filesystem corruption or a bad SD card. Let's hope it's the former. Re-flashing the whole image over and over is kind of a brute method and doesn't provide any clues about the problem. Instead, put the SD card into another linux system (you can use a liveCD), but don't mount it (or umount it if it automounts). Then, if the second partition on the card is /dev/sdb2: e2fsck -p -c /dev/sdb2 The -p means repair automatically, the -c is check for bad blocks. You should see some output about the things being fixed. This doesn't guarantee everything will be fine, but as long as the corruption is not too extensive, you should be okay. Do a second run e2fsck -f; -f forces the check since this time it may be marked "clean". If that goes okay, the fs is as repaired as it is going to get. Try booting that, and if it works, you are in luck. If not, try with another SD card to make sure yours is not defective. When shutting down, give it a good 15-20 seconds after all activity has stopped before you pull the power. Quite a few people come here with fs corruption problems, evidently the pi is very sensitive this way.
{ "pile_set_name": "StackExchange" }
Q: MySQL dump restore delta only At work we have a script that does a mysql data dump everynight. For development we usually need to work with data from the most recent dump. We kept doing a database restore every day for some time but now we are getting to a point where the restore is taking close to an hour everyday. Is there a way for us to do a delta restore in mysql or maybe just do a delta dump. Kind of like a patch file but for mysql. Any help on this topic would be greatly appreciated. -Hrithik A: An incremental backup will probably be your best option. Using a log file it creates something similar to a patch file. If both servers are running the same version of MySQL you can simply copy the MySQL files.
{ "pile_set_name": "StackExchange" }
Q: $postLink vs $OnInit and component life cycle order in angularjs Hey I have an exprience in building angularjs components and I just wonder why there is a $postlink cycle in every component life cycle. I know that $postLink cycle this hook is called after the controller's element and its children have been linked. When the component elements have been compiled and ready to go, this hook will be fired. But I have a couple of questions: 1.Does all DOM Manipulations has to be in $postlink cycle or attach event listeners? Why not building a directive for that purpose? 2.What prevent from me doing all DOM Manipluation in $OnInit and what is the difference between $OnInit cycle and $postlink cycle? Thanks again in advance A: 1. Directive or Component postLink? You can use both options. On my company we prefer use Directives for DOM manipulation. And keep components simple ;). 2. onInit() vs postLink() The answer is on diference between onInit and postLink. onInit() start when your bindings are ready, and component DOM are done. BUT DOM of their childs are not ready. postLink() runs when Component DOM and your DOM childs are ready. Then, if you only need use component elements use onInit(). But if you need use childrens too, use postLink(). Also, keep on mind my point 1.
{ "pile_set_name": "StackExchange" }