text
stringlengths
64
89.7k
meta
dict
Q: Longpress On UI Element (Or How To Determine Which Element Is Pressed?) I have an app that has a rather large help section in PDF form. It's getting to me that the PDF is so large and I can tell in instruments that it's putting a little too much strain on the processor, so I'm going to phase it out. I figured, a lighter implementation would be using a UILongPressGestureRecognizer that I could attach to every UI element that would display specified text in maybe a popover or a UIMenuController indicating the function of the selected element. So my question is this: How can I attach something like a tag to EVERY element in the view so it can be passed to a single method? When I tried tags, I found there was no way to access it through the (id)sender section of my method signature and thus there was no way to differentiate between the elements. EDIT: to the person below: While you have solved my facepalm of a question as to determining the tags of views, how might one go about attaching gesture recognizers to a UIBarButtonItem so as to ascertain it's tag? Your implementations allow for a very nasty unrecognized selector because UIGestureRecognizers dont have a tag property. A: You can derive the tag from an object passed in as the sender. Just have to check it's class and cast it appropriately. tag is a UIView property so we'll start there. - (void)someMethod:(id)sender { if (![sender isKindOfClass:[UIView class]]) return; UIView *senderView = (UIView *)sender; NSInteger tag = senderView.tag; }
{ "pile_set_name": "StackExchange" }
Q: C# nested if/else in a for loop I have a nested if/else statement in a for loop to determine whether or a a value is valid with an array value. It returns all values just fine, however if the IF is correct, it still does the else an additional three times. I thought once it was equal one time, it would stop, but I suppose I am missing something here. string sectionChoice; int ticketQuantity; double ticketPrice, totalCost; string[] section = { "orchestra", "mezzanine", "balcony", "general" }; double[] price = { 125.25, 62.00, 35.75, 55.50 }; bool isValidSection = false; sectionChoice = GetSection(); ticketQuantity = GetQuantity(); for (int x = 0; x < section.Length; ++x) { if (sectionChoice == section[x]) { isValidSection = true; ticketPrice = price[x]; totalCost = CalcTicketCost(ticketPrice, ticketQuantity); Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost); } else Console.Write("\n\nInvalid entry, {0} does not exist", sectionChoice); } When it is valid, it returns something like this: Your price is 32.50. Invalid entry, x does not exist Invalid entry, x does not exist Invalid entry, x does not exist A: What you're really trying to do is determine if section contains a particular value, and do something if it does. Just check that directly: if (section.Contains(sectionChoice)) You also shouldn't be using parallel arrays. Rather than having two arrays, sections an prices, in which the object at the index of each both "combine" to equal a value, it appears that what you're actually modeling is a means to lookup the price of a particular section. This is best modeled with a Dictionary that can easily look up the value for a particular key. Here your key is the section, and the value is its price. Dictionary<string, decimal> ticketsPrices = new Dictionary<string, decimal>() { {"orchestra", 125.25m}, //... }; bool isValidSection = false; string sectionChoice = GetSection(); int ticketQuantity = GetQuantity(); if (ticketsPrices.ContainsKey(sectionChoice)) { isValidSection = true; decimal ticketPrice = ticketsPrices[sectionChoice]; decimal totalCost = CalcTicketCost(ticketPrice, ticketQuantity); Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost); } else Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice); A: The keyword you are looking for is break; break will stop the execution of the loop it is inside. If you are inside nested loops it will only work on the innermost. The opposite of this is continue. Continue stops that iteration and moves onto the next. Here is an MSDN article explaining it more in depth for (int x = 0; x < section.Length; ++x) { if (sectionChoice == section[x]) { isValidSection = true; ticketPrice = price[x]; totalCost = CalcTicketCost(ticketPrice, ticketQuantity); Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost); break; } else Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice); }
{ "pile_set_name": "StackExchange" }
Q: Как реализовать метод, "убивающий" объекты? Допустим, есть класс Животные. От него наследуются 2 класса: Хищники и Травоядные. Можно ли реализовать метод в классе Хищники, вызов которого будет "убивать" объекты класса Травоядные. A: В принципе, на С++ можно реализовать что-то вроде #include <iostream> using namespace std; struct Food { Food() { cout << "Food constructor" << endl; } ~Food() { cout << "Food destructor" << endl; } }; struct Predator { void eat(Food& food) { food.~Food(); } void eat(Food* food) { delete food; } }; int main() { Predator p; Food *f1 = new Food; Food *f2 = new Food; p.eat(*f1); p.eat(f2); return 0; } Но, имхо, это плохо. Есть можно только динамически созданную еду). Хотя можно обезопасить себя от UB, запретив создание объектов Food на стеке: #include <iostream> using namespace std; struct Food { Food() { cout << "Food constructor" << endl; } void die() { delete this; } private: ~Food() { cout << "Food destructor" << endl; } }; struct Predator { void eat(Food& food) { food.die(); } void eat(Food* food) { food->die(); } }; int main() { Predator p; Food *f1 = new Food; Food *f2 = new Food; // Food f3; --> compile time error p.eat(*f1); // delete f2; --> compile time error p.eat(f2); // f2->die(); --> а это скомпилируется, но UB, если f2 уже съеден return 0; } А можно и целый ззопарк развести))). Причем в данном случае, и съедение животного, и его естественная смерть совершенно безопасны, животное никак не может умереть 2 раза, глобальная функция die оповещает и пастуха и хлев о смерти бедняги: #include <iostream> using namespace std; struct Animal { virtual void eat(Animal*&) = 0; friend void ::die(Animal*&); protected: virtual void die() = 0; virtual ~Animal() {} }; void die(Animal*& a); struct Sheep : public Animal { Sheep() { cout << "Sheep constructor" << endl; } void eat(Animal*&) {/* овечка не может съесть животное */ cout << "impossible" << endl;} protected: void die() { delete this; } private: ~Sheep() { cout << "Sheep destructor" << endl; } }; struct Wolf : public Animal { void eat(Animal*& food) { ::die(food); } protected: void die() { delete this; } private: ~Wolf() {} }; int main() { Animal *s1 = new Sheep, *s2 = new Sheep, *s3 = new Sheep; Animal *w1 = new Wolf, *w2 = new Wolf; w1->eat(s1); w2->eat(s2); s3->eat(w1); // Смело... die(s3); // От старости... Или со страху. die(w1); die(w2); // Отравленные овцы?! // w1->die(); --> ошибка компиляции die(w1); // --> ничего не происходит, т.к. w1==nullptr cout << static_cast<void*>(w1) << endl << static_cast<void*>(s1) << endl; return 0; } void die(Animal*& a) { if (a != nullptr) a->die(); else cout << "Dead animal can not die. RIP" << endl; a = nullptr; } Спасибо VladD за ссылки: Вот официальный FAQ насчёт delete this. А вот насчёт явного вызова деструктора (правда, только локальной переменной).
{ "pile_set_name": "StackExchange" }
Q: Pandas: evaluate two dataframes against each other Let's imagine a remember/recall game. There are rooms with a table full of chocolate and other stuff. You have 20seconds to look at each table. Later on you are asked what you've seen. This gives two datasets. One with the configuration of the tables and another one of what you can remember. The task is to evaluate which items you have recalled correctly and which one's you can not remember. In this task we don't care about the brand of the product. Just the type. Here's a sample configuration for two rooms. config = [ {'room': 'room1', 'kind': 'chocolate', 'brand': 'Mars'}, {'room': 'room1', 'kind': 'chocolate', 'brand': 'Mars'}, {'room': 'room1', 'kind': 'chocolate', 'brand': 'Milka'}, {'room': 'room1', 'kind': 'nuts', 'brand': 'Bahlsen'}, {'room': 'room2', 'kind': 'chocolate', 'brand': 'Mars'}, {'room': 'room2', 'kind': 'nuts', 'brand': 'Ültje'}, {'room': 'room2', 'kind': 'nuts', 'brand': 'Bahlsen'} ] import pandas as pd df_config = pd.DataFrame(config).sort_values(['room']) df_config Now you got 20second to memorize the times. Afterwards you are asked what you've seen. Here's what you remember: recall = [ {'room': 'room1', 'kind': 'chocolate'}, {'room': 'room1', 'kind': 'chocolate'}, {'room': 'room1', 'kind': 'nuts'}, {'room': 'room2', 'kind': 'nuts'} ] import pandas as pd df_recall = pd.DataFrame(recall).sort_values(['room']) df_recall Obviously you've seen two chocolate bars in room 1 thus you missed the third one. For room 2 you missed the second bag of nuts. So, the evaluation result would be somewhat like this: correct = [ {'room': 'room1', 'kind': 'chocolate', 'brand': 'Mars', 'eval': 'correct'}, # first chocolate room1 {'room': 'room1', 'kind': 'chocolate', 'brand': 'Mars', 'eval': 'correct'}, # second chocolate room1 {'room': 'room1', 'kind': 'nuts', 'brand': 'Bahlsen', 'eval': 'correct'}, # first nuts room1 {'room': 'room2', 'kind': 'nuts', 'brand': 'Ültje', 'eval': 'correct'}, # first nuts room2 ] incorrect = [ {'room': 'room1', 'kind': 'chocolate', 'brand': 'Milka', 'eval': 'incorrect'}, # third chocolate room1 not recalled {'room': 'room2', 'kind': 'chocolate', 'brand': 'Mars', 'eval': 'incorrect'}, # first chocolate room2 not recalled {'room': 'room2', 'kind': 'nuts', 'brand': 'Bahlsen', 'eval': 'incorrect'} # second nuts room2 not recalled ] I was thinking to merge both datasets based on the room and then group by the room and evaluate each group. Either by iterating over the group or using df.groupy(['room']).apply(my_function). The problem is, that the merge creates a quite huge group for each room and I'm not sure how to evaluate this. df = pd.merge(df_config, df_recall, on='room', suffixes=('', '_recall')) Any idea is welcome! Thanks A: I think you need helper columns for unique values per rooms and kind by cumcount. Then add column to parameter on and specify left join: df_config['g'] = df_config.groupby(['room','kind']).cumcount() df_recall['g'] = df_recall.groupby(['room','kind']).cumcount() df = pd.merge(df_config, df_recall, on=['room', 'g'], suffixes=('', '_recall'), how='left') print (df) brand kind room g kind_recall 0 Mars chocolate room1 0 chocolate 1 Mars chocolate room1 0 nuts 2 Mars chocolate room1 1 chocolate 3 Milka chocolate room1 2 NaN 4 Bahlsen nuts room1 0 chocolate 5 Bahlsen nuts room1 0 nuts 6 Mars chocolate room2 0 nuts 7 Ültje nuts room2 0 nuts 8 Bahlsen nuts room2 1 NaN
{ "pile_set_name": "StackExchange" }
Q: Pressing windows msdn dialog box buttons and changing the 'Edit' in ''Save as' dialog box in Delphi I got the following code from here and have changed it a little and I have changed the original question a little also. The timer interval is set to 5000. After the following 3 events occur the 'Events OnTimer' procedure will start to work. 1.WebBrowser1.Navigate('Any webpage'); 2.wait for it to load 3.programmatically press a download file button The problem now is I can't find the 'Edit'(Class Name) handle that belongs to(or is the child of) the 'Save as' dialog box. The handle for the 'Edit' comes to '0' in the code below, but if I use my mouse pointer and the following code: HND:= WindowFromPoint(PNT); Label1.Caption:= IntToStr(HND); the handle gives a result. Once I have the handle, I can use: SetWindowText(EditHandle, 'test text'); to change the text in 'Edit'(Class Name). procedure TForm1.Timer1Timer(Sender: TObject); Var WHandle : HWND ; ParentHandle : DWORD ; P : Array[0..256] Of Char ; ProcessIdActif : DWORD ; begin ProcessIdActif := 0 ; GetWindowThreadProcessId (handle,@ProcessIdActif); WHandle := FindWindow( Nil, Nil); While (WHandle <> 0) Do begin P[0] := #0; GetWindowText(WHandle, P, 255); if P[0] <> #0 then begin GetWindowThreadProcessId (WHandle,@ParentHandle); if ProcessIdActif = ParentHandle then begin if CompareText(p,'File Download') = 0 then begin ButtonHandle := FindWindowEx(WHandle, 0, 'Button', '&Save'); if (ButtonHandle > 0) then PostMessage(ButtonHandle, BM_CLICK, 0, 0); end else if CompareText(p,'Save As') = 0 then begin EditHandle := FindWindowEx(WHandle, 0, 'Edit',NIL); if (EditHandle > 0) then SetWindowText(EditHandle, 'test text'); end; end; end; WHandle := GetWindow(WHandle, GW_HWNDNEXT); end; end; I've been trying to understand everything here but I'm missing something. I'm able to press any windows dialog button by moving the mouse and pressing the mouse programatically, but I'd like to figure out how to press these buttons in a cleaner way. A: Disclaimer: the below code is not meant to be used in any way, it won't work correctly if the environment is different anyway (W7 here). Anyway, put the below in your timer handler and try to workout the differences (if it works hopefully..) with the code in the question: var WHandle, ButtonHandle, EditHandle: HWND; begin WHandle := FindWindow('#32770', 'File Download'); if WHandle <> 0 then begin SetForegroundWindow(WHandle); ButtonHandle := GetDlgItem(WHandle, $114B); if ButtonHandle <> 0 then begin // click the button // the dialog/button is kind of deaf.. while IsWindowEnabled(WHandle) do begin SendMessage(ButtonHandle, BM_CLICK, 0, 0); Sleep(100); end; WHandle := 0; while WHandle = 0 do begin // wait for the save as dialog WHandle := FindWindow('#32770', 'Save As'); Sleep(100); end; while not IsWindowVisible(WHandle) do Sleep(100); // get through the edit handle WHandle := FindWindowEx(WHandle, 0, 'DUIViewWndClassName', nil); EditHandle := GetWindow(GetWindow(GetWindow(GetWindow (WHandle, GW_CHILD), GW_CHILD), GW_CHILD), GW_CHILD); SetWindowText(EditHandle, 'test text'); end; end;
{ "pile_set_name": "StackExchange" }
Q: Equal height columns using Bootstrap and Jquery I am using Bootstrap in a current Web project but I don't know how to dynamically set the same height of column elements. I already know the .row-eq-height class but using that I loose the responsivity of Bootstrap elements. My HTML is : <div class="row" id="selection-wrapper"> <div class="col-lg-7 col-xs-12" id="map-container"> <!-- Zone for map display --> <div id="map"></div> </div> <div class="col-lg-5 col-xs-12"> <div class="text-container" id="selection"> // Content </div> </div> </div I would like the #selection column to be at least as high as #map-container (or higher because it has a border and I don't want it to cut the content). I already wrote few lines of Jquery : var map_height = $('#map-container').height(); var selection_height = $('#selection').height(); if (selection_height < map_height) { $('#selection').css('height',map_height); } Those lines work but I don't know how and when I should execute them as I would like to keep the equal height property all the time, even when the width of the container changes (which modifies the height of the #map-container). I'm not an expert in JS/Jquery and my English in not really good so I hope you still have understood what I want to do. Thanks a lot ! A: function equal_height() { var map_height = $('#map-container').height(); var selection_height = $('#selection').height(); if (selection_height < map_height) { $('#selection').css('min-height',map_height); } } $(document).ready(function(){ equal_height(); }); $(window).resize(function(){ equal_height(); });
{ "pile_set_name": "StackExchange" }
Q: Is spring default scope singleton or not? Could you please explain why Spring is creating two objects for the configuration of beans shown below, since by default spring default scope is singleton? The Spring configuration is here: <bean id="customer" class="jp.ne.goo.beans.Customer"> <property name="custno" value="100"></property> <property name="custName" value="rajasekhar"> </property> </bean> <bean id="customer2" class="jp.ne.goo.beans.Customer"> <property name="custno" value="200"></property> <property name="custName" value="siva"></property> </bean> A: Spring's default scope is singleton. It's just that your idea of what it means to be a singleton doesn't match how Spring defines singletons. If you tell Spring to make two separate beans with different ids and the same class, then you get two separate beans, each with singleton scope. All singleton scope means is that when you reference something with the same id, you get the same bean instance back. Here is how the Spring documentation defines singleton scope: Only one shared instance of a singleton bean is managed, and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container. Singleton scope means using the same id retrieves the same bean, that is all. Testing that no two ids referenced the same class would get in the way of using maps as beans, and would be complicated by proxying things with BeanFactories. For Spring to police this would involve a lot of work for little benefit, instead it trusts the users to know what they're doing. The way to define two names for the same bean is to use an alias: In a bean definition itself, you can supply more than one name for the bean, by using a combination of up to one name specified by the id attribute, and any number of other names in the name attribute. These names can be equivalent aliases to the same bean, and are useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself. Specifying all aliases where the bean is actually defined is not always adequate, however. It is sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the case in large systems where configuration is split amongst each subsystem, each subsystem having its own set of object definitions. In XML-based configuration metadata, you can use the element to accomplish this. So if you add a name in the bean configuration: <bean id="customer" name="customer2" class="jp.ne.goo.beans.Customer"> </bean> or create an alias for a bean defined elsewhere: <alias name="customer" alias="customer2"/> then "customer" and "customer2" will refer to the same bean instance. A: Spring default scope is singleton and it will create one object for all instances unless you explicitly specify the scope to be prototype. You have not posted spring configuration. Please post it, it will give a better idea. A: You're confusing two different concepts. The word singleton in spring is used for a bean scope, meaning that the bean will be created only once for the whole application. Singleton usual meaning refers to the GOF pattern. It is an object oriented pattern guarantying that only one instance of a class will exists (at least in the scope of the classLoader).
{ "pile_set_name": "StackExchange" }
Q: matlab engine data retrieval fails I have a problem reading out data from the matlab engine. I can create a variable in the engine, and saving the workspace and subsequently loading it into matlab shows that the variable exists and has the right value. However the C++ value that I retrieve is always zero, no matter what the real value is. The pointer to the variable that I receive (matM) is a valid pointer. If the 'engGetVariable' command fails, it should be NULL according to the Matlab documentation. Yet, trying the matlab command to retreive integer data from this pointer (mxGetData) yields zero, when the value of the variable should be 5. Also directly checking the value belonging to the pointer yields zero. Below is the code: int main() { Engine *ep; mxArray *matM = NULL; if (!(ep = engOpen(""))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } engEvalString(ep, "m = 5"); engEvalString(ep, "save 'MatlabTestsResult.mat'"); matM = engGetVariable(ep,"m"); if (matM==NULL){cout << "pointer is null..." << endl;} int* Cm = (int *)mxGetData(matM); cout << *Cm << endl; cout << "Pointer: " << matM << endl; int tst = *((int*) matM); cout << tst << endl; mxDestroyArray(matM); engClose(ep); return EXIT_SUCCESS; } and the output it creates: ./MatlabTests 0 Pointer: 0x7f25559b7f90 0 I can't find what I am doing different to the matlab examples ( http://www.mathworks.co.uk/help/matlab/apiref/mxgetdata.html , http://www.mathworks.co.uk/help/matlab/apiref/enggetvariable.html?searchHighlight=engGetVariable ) that causes the variable readout to fail. A: The return value from mxGetData should be cast to a double* I imagine, then you should be able to dereference it to get 5.0. By default Matlab numbers are doubles, so m = 5 does not assign an int to m.
{ "pile_set_name": "StackExchange" }
Q: How to make the data in month drop-down-list to be (Jan,Feb,......,Dec) in the sfWidgetFormDateTime a 2 options (date,time). and in my sfWidgetFormDateTime i add this option this->addOption('date', array('format'=>'%day%/%month%/%year%')). The data in the month DropDownList shows the month between (0-12), but i want the data in the month DropDownList to be show (Jan,....,Dec). So, what the way to do it?! A: Found the following information on http://fabien.potencier.org/chapter_10.html // Date $form->setWidget('dob', new sfWidgetFormI18nDate(array( 'culture' => $this->getUser()->getCulture(), 'month_format' => 'name', // Use any of 'name' (default), 'short_name', and 'number' 'label' => 'Date of birth', 'default' => '01/01/1950', 'years' => array(1950, 1951, .., 1990) ))); // For an English-speaking user, symfony renders the widget in HTML as <label for="dob">Date of birth</label> <select id="dob_month" name="dob[month]"> <option value=""/> <option selected="selected" value="1">January</option> <option value="2">February</option> ... <option value="12">December</option> </select> / <select id="dob_day" name="dob[day]">...</select> / <select id="dob_year" name="dob[year]">...</select> // For an French-speaking user, symfony renders the widget in HTML as <label for="dob">Date of birth</label> <select id="dob_day" name="dob[day]">...</select> / <select id="dob_month" name="dob[month]"> <option value=""/> <option selected="selected" value="1">Janvier</option> <option value="2">Février</option> ... <option value="12">Décembre</option> </select> / <select id="dob_year" name="dob[year]">...</select> Similar widgets exist for time (sfWidgetFormI18nTime), and datetime (sfWidgetFormI18nDateTime).
{ "pile_set_name": "StackExchange" }
Q: Heroku Node.js Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch I found a dozen solutions for Express powered apps with setting port to listen on. But I have an app that doesn't use Express and doesn't in fact listens anything. And after 60 seconds of it successfully running I get a Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch message. How I can get around it? Thanks. A: After lots of googling I decided to npm install express and add var express = require('express'); var app = express(); app.set('port', (process.env.PORT || 5000)); //For avoidong Heroku $PORT error app.get('/', function(request, response) { var result = 'App is running' response.send(result); }).listen(app.get('port'), function() { console.log('App is running, server is listening on port ', app.get('port')); }); This fixed the error, even though I don't like adding express just to avoid one error. If someone finds a better solution, please let me know. A: If your app doesn't listen any port then you should use another type of app in you Procfile, I mean in Procfile you have: web: node app.js replace it with: worker: node app.js "web" type of application means that your app MUST listen some port A: Another way would be changing the dynos from web (standard setting regardless of the settings in Procfile) to worker with these commands: heroku ps:scale web=0 heroku ps:scale worker=1 Sometimes Heroku ignores settings in the Procfile.
{ "pile_set_name": "StackExchange" }
Q: How to get the root url at startup in an OWIN asp.net Web API I have found many posts very similar to this, but I didn't find any that worked for me. I have an asp.net Web Api2 (not vnext) application, running under IIS, and using the Owin Startup class. When installed, the root url to this will be something like http://localhost/appvirtualdirectory where appvirtualdirectory is the name of the virtual directory it is configured to run under in IIS. IS there a way at startup where I have no Request property, ie in the Startup.Configure method, to get the root URL including the virtual directory being used? A: Try this HttpRuntime.AppDomainAppVirtualPath This is valid in both global and owin startup More details here https://msdn.microsoft.com/en-us/library/system.web.httpruntime(v=vs.110).aspx
{ "pile_set_name": "StackExchange" }
Q: How to get the message in a custom error page (Tomcat)? In JSPs, you may use response.sendError(int code, String message) to return a particular error code (eg 404 for not found) and a message as well. These messages display fine, as long as you use the default ugly Tomcat error pages. However, if you create a custom error page, how do you get that message? I've tried exception.getMessage() or pageContext.getErrorData() but no avail. I've been searching for this for like hours and nobody seems to even wonder about the same thing! :S I forgot to mention I've only tried it with 404s so far, since that's what I need most... The exception is null for some reason, so trying anything on it throws a NullPointerException. The error page is a 404 error page, set via web.xml (since I want it to be displayed for EVERY single 404 error) and for anyone wondering, yes it has the isErrorPage directive set to true... A: The error message is available via javax.servlet.error.message attribute of the request object in error page jsp. Here is the jsp syntax to access it: <c:out value="${requestScope['javax.servlet.error.message']}"/> You could look for other error related information available in the error page here under New Error Attributes. A: Hmm exception.getMessage() should work Try adding exception.getClass().getName() It could be a NullPointerException which has no message or the exception is not from Sun and the message isn't set properly Of course this only works, if I remember correctly, if the error is thrown by a jsp with <%@ page errorPage="/yourerrorpage.jsp" %> at the top. If the error comes from a servlet the exception details are passed as request attributes javax.servlet.error.status_code java.lang.Integer javax.servlet.error.exception_type java.lang.Class javax.servlet.error.message java.lang.String javax.servlet.error.exception java.lang.Throwable javax.servlet.error.request_uri java.lang.String javax.servlet.error.servlet_name java.lang.String Check the Servlet Specification (link is broken since ~2011) section 9.9 A: I'm sorry for answering so late, but I faced with this problem just a week ago, I've browsed a lot of different sites but nobody really aswered this problem the way I wanted to hear. In this post I found out a few interesting solutions and then came up to my own. Just include this source in your page: <% out.println(pageContext.getErrorData().getRequestURI()); out.println("<br/>"); out.println(pageContext.getErrorData().getStatusCode()); out.println("<br/>"); out.println(pageContext.getException()); out.println("<br/>"); %> It worked perfectly fine with me.
{ "pile_set_name": "StackExchange" }
Q: Title of Section in Center (thesis writing) For writing thesis, I am using \documentclass[a4paper,oneside, 12pt]{book} In it, sectioning was coming at left. I want them in center. This has been considered before (see this). But, I tried from its answer, the following. \section*{\centering\textcolor{blue}{Ukaaranta }} I was getting error. Also, instead of this, can I delete \textcolor{blue}? Since I color them in black only. Is it necessary to put * here? The error was showing this: [PDFLaTeX] Finished with exit code 1 Argument of \@sect has an extra } ...ion{\centering\textcolor{blue}{Ukaaranta }} Paragraph ended before \@sect was complete...ion{\centering\textcolor{blue}{Ukaaranta }} A: You could provide the following instructions in the preamble: \usepackage{sectsty} \allsectionsfont{\centering} This will center all section, subsection, and subsubsection headers. If you want to center only section-level headers, change the second command to \sectionfont{\centering}
{ "pile_set_name": "StackExchange" }
Q: Phoenix can't start - Missing AppName.Endpoint.start_link Pheonix changes so frequently that I'm not sure that what I'm doing is right. I'm trying to follow some tutorials, and all of them have the 'mix phoenix.start' command right after you finish compiling and that should start the server. (There is some talk on the issues page of Github that they are going to replace that with the mix phoenix.server command and you have to do something manually, not really following it. Anyways, that is in the development version v0.8.0-dev. I'm using the latest stable version 0.7.2) I'm getting an error trying to issue the 'mix phoenix.start' command trying to start the server (AppName: PhoenixCrud): > mix phoenix.start =INFO REPORT==== 13-Dec-2014::15:23:08 === application: logger exited: stopped type: temporary =INFO REPORT==== 13-Dec-2014::15:23:08 === application: cowboy exited: stopped type: temporary =INFO REPORT==== 13-Dec-2014::15:23:08 === application: cowlib exited: stopped type: temporary =INFO REPORT==== 13-Dec-2014::15:23:08 === application: ranch exited: stopped type: temporary ** (Mix) Could not start application phoenix_crud: PhoenixCrud.start(:normal, []) returned an error: shutdown: failed to start child: PhoenixCrud.Endpoint ** (EXIT) an exception was raised: ** (UndefinedFunctionError) undefined function: PhoenixCrud.Endpoint.start_link/0 (phoenix_crud) PhoenixCrud.Endpoint.start_link() (stdlib) supervisor.erl:314: :supervisor.do_start_child/2 (stdlib) supervisor.erl:297: :supervisor.start_children/3 (stdlib) supervisor.erl:263: :supervisor.init_children/2 (stdlib) gen_server.erl:306: :gen_server.init_it/6 (stdlib) proc_lib.erl:237: :proc_lib.init_p_do_apply/3 The docs have the updated phoenix.server command, but I tried that also, and that mix says that the task could not be found. Anyways, it looks as if the app_name/lib/app_name/endpoint.ex is missing a start_link function. Am I supposed to provide that? I have no idea right now what to put in because I'm just trying out the Phoenix web framework and don't know anything about it (hence the tutorials.) So, am I supposed to provide the start_link function, if so, can some give me some to stub in for now to try to follow some tutorials. Otherwise is it a bug? A: It is a Phoenix version thing. The endpoint is only available in master, but it seems you are not using master. You should either add {:phoenix, github: "phoenixframework/phoenix"} to your mix.exs or generate a Phoenix project from the 0.7.2 branch. A: My git knowledge is not that great, but here goes: To use 0.7.2 branch, you need to specifically checkout v0.7.2 tag. So this is how I did it: git clone https://github.com/phoenixframework/phoenix.git cd phoenix git checkout tags/v0.7.2 mix do deps.get, compile mix phoenix.new app_name ../app_name cd ../app_name #change the mix deps to: (I think you can just use default hex deps as well) {:phoenix, github: "phoenixframework/phoenix", tag: "v0.7.2"} mix do deps.get, compile mix phoenix.start Otherwise, the Phoenix code that you normally git clone is on the master branch is on 0.8.0-dev, which you will need to set the deps to the github master branch (as stated by @JoseValim) {:phoenix, github: "phoenixframework/phoenix"} Which means, you now need to use the mix phoenix.server command. Hope that helps others.
{ "pile_set_name": "StackExchange" }
Q: Open local file in pdf.js android webview ("file" is not supported error) I'm trying to follow the answer stated here. Based on the comments, loading a local file using pdf.js in android webview should work but I am getting the below error: I/chromium: [INFO:CONSOLE(18556)] "Fetch API cannot load file:///android_asset/www/pdfjs/web/tracemonkey.pdf. URL scheme "file" is not supported.", source: file:///android_asset/www/pdfjs/build/pdf.js (18556) I/chromium: [INFO:CONSOLE(13127)] "Uncaught (in promise) DataCloneError: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned.", source: file:///android_asset/www/pdfjs/build/pdf.js (13127) [INFO:CONSOLE(985)] "Uncaught (in promise) Error: An error occurred while loading the PDF.", source: file:///android_asset/www/pdfjs/web/viewer.js (985) Here is my code: class PDFViewerLocalActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.pdfviewer_layout) val webView = findViewById(R.id.pdfViewer) as WebView webView.settings.javaScriptEnabled = true webView.settings.allowFileAccessFromFileURLs = true webView.settings.allowUniversalAccessFromFileURLs = true webView.settings.builtInZoomControls = true webView.webChromeClient = WebChromeClient() webView.loadUrl("file:///android_asset/www/pdfjs/web/viewer.html?file=tracemonkey.pdf") } } A: Okay, this was a dumb question. I already put the following permissions in the manifest: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> But forgot that for API 23 and above you have to request permission at run time. So, just added the code to request permissions and it worked. @TargetApi(23) fun askPermissions() { val permissions = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE") val requestCode = 200 requestPermissions(permissions, requestCode) }
{ "pile_set_name": "StackExchange" }
Q: How to remove loaded script and add new script? I am creating a demo in which I have added a query string in the URL. When I load my HTML I get the value of my query. I want it so that if the query string has the value "simple", it removes the JS file that is loaded. If it finds a value other than "simple" it should load another JS file. I Google searched it for solution, but nothing works. Here is my HTML: <!DOCTYPE html> <html> <head> <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script> <script src="js/copynode.js" type="text/javascript" id="dynamic_files"></script> <script type="text/javascript"> $(window).load(function(){ // full load var query = decodeURIComponent(window.location.search.substring(1)); console.log("---------------------"); var index=query.indexOf("=") query=query.substr(index+1,query.length); console.log(query); if(query=="simple"){ alert('if--'); //$('#dynamic_files').remove(); }else{ alert('else--'); $('#dynamic_files').remove(); var script = document.createElement('script'); script.src = 'js/index.js'; document.getElementsByTagName('div')[0].appendChild(script); } }); </script> </head> <body > <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <button type="button" onclick="loadScript()">Load Script</button> </body> </html> A: you can check the value of the String first then write a function like : function checkString(){ if($('#ID_OF_ELEMENT_OF_THE_STRING').value == "simple"){ //load the script needed var head = document.getElementsByTagName('head').item(0); var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', 'http://mysite/my.js'); head.appendChild(script); }else{ //load the other part. } }
{ "pile_set_name": "StackExchange" }
Q: A Realization Problem for Character Tables Given an $n\times n$ table of complex numbers, are there known sufficient conditions for the table to be the character table of a finite group? Representation theory gives plenty of necessary conditions, but I can't imagine they'd be enough in general. A: You should look up an older article by Stephen Gagola, Jr., but read some of the arguments skeptically (as I did a long time ago when exploring this question in a graduate introduction to finite group representations): Gagola, Stephen M., Jr.(1-KNTS) Formal character tables. Michigan Math. J. 33 (1986), no. 1, 3–10. I'm not sure whether more interesting results are known by now, but it's a difficult problem which has been around for a long time. I think it's fair to describe the problem as essentially open, though inevitable in this subject.
{ "pile_set_name": "StackExchange" }
Q: Why don't products of Dirac deltas integrate correctly? Bug introduced in 10.0.0 and fixed in 10.0.1 The integral $\int \int \ \delta(x) \delta(y) \ dx dy=1$ evaluates to 0 in Mathematica Integrate[ DiracDelta[x]*DiracDelta[y], {x, -Infinity, Infinity}, {y, -Infinity, Infinity} ] returns 0 even though Integrate[ DiracDelta[x], {x, -Infinity, Infinity} ] correctly returns 1. What's going on? Edit: This concerns Version 10.0.0.0 installed on Ubuntu 14.04. The notebook contains no other commands. Clear[x,y] does not affect the outcome. A: Summarizing the comments, this was a bug in version 10.0.0. It has been fixed as of version 10.0.1. In[1]:= Integrate[ DiracDelta[x]*DiracDelta[y], {x, -Infinity, Infinity}, {y, -Infinity, Infinity}] Out[1]= 1
{ "pile_set_name": "StackExchange" }
Q: Перенос скрипта AHK в Python Есть скрипт на AHK, который нужно перенести на Python, потому что в AHK* нельзя проводить вычисления прямо в переменных, соответственно нужно сохранить функционал, при этом чтобы скрипт мог изменить переменную с помощью сложения\вычитания Вот сам скрипт: F1:: x = 1920 y = 1080 z = 0 MouseMove, x, y-y+z, 100 Send {LButton down} MouseMove, x, y, 100 MouseMove, x-x+z, y, 100 MouseMove, x-x+z, y-y+z, 100 MouseMove, x, y-y+z, 100 Send {LButton up} Loop, 135 { x = x - 8 y = y - 8 z = z + 8 MouseMove, x, y-y+z, 0 Send {LButton down} MouseMove, x, y, 0 MouseMove, x-x+z, y, 0 MouseMove, x-x+z, y-y+z, 0 MouseMove, x, y-y+z, 0 Send {LButton up} } Соответственно в Loop, там где вычисления в переменных AHK воспринимает это как строку а не как число, что нужно исправить, перенеся скрипт в Python. Примечание: AHK - AutoHotKey A: Есть модуль ahk. Это модуль обёртка, т.е. AutoHotkey должен быть установлен. Простейший пример использования: >>> from ahk import AHK # pip install ahk >>> >>> ahk = AHK() >>> >>> ahk.mouse_position (247, 292) >>> ahk.mouse_move (100, 100, speed=10, relative=True) # сдвинуть курсор >>> ahk.mouse_position (347, 392) >>> ahk.type ('# hello, world!') # напечатать в активном окне >>> # hello, world! >>> >>> win = ahk.active_window # сдвинуть активное окно >>> win.position (208, 433) >>> win.move (x=300, y=300) >>> win.position (300, 300)
{ "pile_set_name": "StackExchange" }
Q: How to create a simple GUI lib? I need to create a simple gui toolkit based on only a raw framebuffer. Are there any examples or papers describing such a thing? Obviously I could implement X but I think that's a little beyond the scope :) A: Is this for a Linux framebuffer? SDL is a graphics library worth looking at. It is a mature open source project, which makes it a good project to study and learn from. The documentation is also pretty good. Like many GUI toolkits it has a large API set, but you don't have to use all of it and can focus on just what you are interested. Developing a GUI toolkit can be a complex task.
{ "pile_set_name": "StackExchange" }
Q: Node-Red Dashboard. Ui template, update the url using msg.payload I need to change the url of ui_template in the dasboard of node-red. If I write something like: <iframe src="https://online.wonderware.eu/s/l5kctp/Explore/Analysis/loquesea/Embed"></iframe> I can see: If I try to send the url using the msg.payload y can see: I tried to get the payload with the next code: <iframe src={{msg.payload}}></iframe> And the payload is: msg.payload="https://online.wonderware.eu/s/l5kctp/Explore/Analysis/loquesea/Embed"; I tried a lot of sintaxis to read the payload but I can not read it correctly. Do you know How Can I read the payload and change the ui_template url? Thanks A: Try using template node in front of the ui_template. You want to use three curly brackets to escape the HTML. <iframe src={{{payload}}}></iframe> [{"id":"8fbf7029.588de","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"dc2dd6a.d014628","type":"inject","z":"8fbf7029.588de","name":"","topic":"","payload":"http://localhost:1880","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":"0.5","x":230,"y":220,"wires":[["35a71b83.0fda04"]]},{"id":"c1cf74f3.655238","type":"ui_template","z":"8fbf7029.588de","group":"d2702cb6.ab449","name":"","order":0,"width":"22","height":"12","format":"","storeOutMessages":true,"fwdInMessages":true,"templateScope":"local","x":600,"y":220,"wires":[[]]},{"id":"35a71b83.0fda04","type":"template","z":"8fbf7029.588de","name":"","field":"template","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<iframe src={{{payload}}}></iframe>","output":"str","x":420,"y":220,"wires":[["c1cf74f3.655238"]]},{"id":"d2702cb6.ab449","type":"ui_group","z":"","name":"G1","tab":"223c13e7.70f2cc","disp":true,"width":"22","collapse":false},{"id":"223c13e7.70f2cc","type":"ui_tab","z":"","name":"T1","icon":"dashboard","disabled":false,"hidden":false}]
{ "pile_set_name": "StackExchange" }
Q: Purpose of using binding source? I recieve some information about using binding source but I really don't understand explicitly why using binding source related to datagridview. My questions are: Advantage and disadvantage of using bindingsource instead of removing the third person that is between the datasource and data gridview? What context are you supposed to use binding source? A: Binding source can provide some additional logic that you want to protect your model. The most natural example is transaction logic or the ability to cancel changes. When you're binding a control to a datasource directly all changes take place immediately. With a binding source between these two you have the ability to cancel or save edit, to buffer changes etc.
{ "pile_set_name": "StackExchange" }
Q: NavigationView Как отоброзить иконку без заливки цвета? NavigationView Как отоброзить иконку без заливки цвета? есть xml иконка разноцветная. Вот пример = какой параметр нужно удалить из дефолт шаблона в а.с.? A: Согласно гугловому запросу navigation view icon color и ссылке на en-SO - Navigation drawer item icon not showing original colour надо так: mNavigationView.setItemIconTintList(null);
{ "pile_set_name": "StackExchange" }
Q: How can you stop MySQL slave from replicating changes to the 'mysql' database? I have my slave set to not replicate the 'mysql' database as described in this SHOW SLAVE STATUS\G; Slave_IO_State: Waiting for master to send event Master_Host: 127.0.0.1 Master_User: replication Master_Port: 3306 Connect_Retry: 60 Master_Log_File: master-bin.000001 Read_Master_Log_Pos: 1660 Relay_Log_File: mysql-relay-bin.000004 Relay_Log_Pos: 478 Relay_Master_Log_File: master-bin.000001 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_Do_DB: **Replicate_Ignore_DB: mysql** Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0 Last_Error: Skip_Counter: 0 Exec_Master_Log_Pos: 1660 Relay_Log_Space: 633 Until_Condition: None Until_Log_File: Until_Log_Pos: 0 Now, if I go to the MASTER server and issue a GRANT and FLUSH PRIVILEGES: GRANT SELECT ON *.* TO `foo`@`localhost` IDENTIFIED BY 'bar'; FLUSH PRIVILEGES; I then go back to the SLAVE server and issue: SHOW GRANTS FOR `foo`@`localhost`; and receive the response: +-------------------------------------------------------------------------------------------------------------+ | Grants for foo@localhost | +-------------------------------------------------------------------------------------------------------------+ | GRANT SELECT ON *.* TO 'foo'@'localhost' IDENTIFIED BY PASSWORD '*E8D46CE25265E545D225A8A6F1BAF642FEBEE5CB' | +-------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) How can I stop the slave from replicating changes the mysql database? I figured 'replicate_ignore_db' would have sufficed. A: Alright, after a few more hours of investigation, I think I figured it out. Adding my answer in case this is of use to others. According to the docs on replicate-ignore-db: Statement-based replication. Tells the slave SQL thread not to replicate any statement where the default database (that is, the one selected by USE) is db_name. Of course, statement-based replication is the default and what I was using. So I made the attempt to change the format by restarting the master with binlog_format=row to see what would happen. No dice. GRANTS and REVOKES still were replicated. Further investigation into the docs on replication changes on the mysql table revealed Statements that change the mysql database indirectly are logged as statements regardless of the value of binlog_format. This pertains to statements such as GRANT, REVOKE, SET PASSWORD, RENAME USER, CREATE (all forms except CREATE TABLE ... SELECT), ALTER (all forms), and DROP (all forms). Gah! Ok, so I checked the binlog using mysqlbinlog and my GRANT statement was not issueing a USE mysql database call (why should it?). So replicate-ignore-db could not in good conscience ignore the statement. My solution was to cut the changes to the mysql table out of the binary log completely by adding binlog-ignore-db=mysql to my.cnf and restart the server. Worked like a charm. A: The issue with Derek Downey's answer on this post is it will always work the same way (on or off). If you are in a situation where you'd like most grants to be replicated but not this one - or you don't want to bounce mysql (necessary to load the modified my.conf file) you can do it this way: SET session sql_log_bin = 0; GRANT SELECT ON *.* TO `foo`@`localhost` IDENTIFIED BY 'bar'; SET session sql_log_bin = 1; Please remember - that last line setting sql_log_bin = 1 is very important because without it you will not replicate anything.
{ "pile_set_name": "StackExchange" }
Q: How to Draw Circles in Playground with Xcode I'm working on a school project using Xcode and for part of it, I need to draw a circle on Xcode using Swift. How do I do that? A: The first thing you need to do is decide how large of a circle you want – this will determine the parameters you set. The first thing you do is make a constant named whatever you want and make it a square. Then, you can use variableName.layer.cornerRadius to make your circle. You have to use half of what you made the square as it is the radius of the circle. Here's an example of a circle with a 10 radius: let circle = UIView(frame: CGRect(x:0, y:0, width: 20, height: 20)) circle.backgroundColor = UIColor.blue //this is just so the circle is visible circle.layer.cornerRadius = 10 The really important thing to remember is that the square that you originally make must have the width and height be twice the size of the radius. Also, if you are having trouble seeing the circle then it might be because you didn't set a background color to it, so do something like the code above by setting the color to anything you want .
{ "pile_set_name": "StackExchange" }
Q: Boolean expressions for distinct graphs The question is to write two boolean expressions per set of graphs that differentiate between them. The domain for the expression should be all vertices in the given graph. Also, $E(x,y) =$ "there is an undirected edge between $x$ and $y$". Set 1 The only difference I found between 1.1 and 1.2 was that 1.2 has an additional vertex that has an edge with the last vertex. For 1.1: $\exists x,y,z (E(x,y) \land E(y,z) \land x \ne y \ne z)$ For 1.2, $\exists x,y,z,n (E(x,y) \land E(y,z) \land E(z,n) \land x \ne y \ne z \ne n)$ Set 2 The difference I found here was that in 2.1, if the first vertex is connected to a second vertex and the second vertex is connected to a third vertex, then the first vertex is not connected to the third vertex. However, in 2.2, all vertices are connected to each other. For 2.1: $\forall x,y,z (x \ne y \ne z \rightarrow E(x,y) \land E(y,z) \land \lnot E(x,z))$ For 2.2: $\forall x,y (x \ne y \rightarrow E(x,y))$ Am I interpreting these graphs correctly through my boolean expressions. If I am, then is there a more concise or logical way to represent these graphs? A: A few comments: $x \neq y \neq z$ is not really a good formula, but even if we would accept it, it would mean $x \neq y \land y \neq z$, in particular it may happen that $x = z$. What you want to say, is that $x,y,z$ are pairwise distinct, or formally $x \neq y \land x \neq z \land y \neq z$ (for 4 vertices you would have 6 pairs). Formula 1.1 doesn't distinguish between the two first graphs, because the second graph does have three vertices connected with edges. The difference is that there are only three vertices. Such condition are usually written as $\forall v\ (v = x \lor v = y \lor v = z)$ where $x,y,z$ are bound by some other quantifier. Formula 1.2 doesn't distingush between the two first graphs, because of the first bullet, for example $G = \{1,2\}$ and $E = \{(1,2),(2,1)\}$ would be a good model for it. The simplest formula that distinguishes between the two first graph checks if there exist 4 pairwise distinct vertices. Formula 2.1 doesn't distinguish the second pair of graphs because of the first bullet, that is we have $\neg E(x,x)$. Formula 2.2 works, good job ;-) I hope this helps $\ddot\smile$
{ "pile_set_name": "StackExchange" }
Q: handling a string as PHP Possible Duplicate: PHP: Calculate a math function f(x) in a string I have a little problem. I have a string, such that, $a = '(2+3+4)'; How can I handle $a such that the output, echo $a should be 9 instead of just giving (2+3+4). A: If your code is indeed $a = (2+3+4), then echo will output 9. It sounds like you have it a string. You could eval() that string to get the 9.
{ "pile_set_name": "StackExchange" }
Q: Get AWS Account ID using awscli How can I get the AWS Account ID using awscli? I look for something like $ aws <service> <options> 123456789012 Close, but not what I'm looking for: $ aws iam get-user. A: The following command returns the account number: aws sts get-caller-identity --query 'Account' --output text Command details can be found here (reformat the command as code session) A: Need to get an AWS Account ID from the aws cli tool? Here you go: aws sts get-caller-identity --output text --query 'Account'
{ "pile_set_name": "StackExchange" }
Q: Resolving dependencies using npm while installing Bootstrap 4 While installing Bootstrap 4 using npm it show me these errors: npm WARN [email protected] requires a peer of jquery@>=3.0.0 but none was installed. npm WARN [email protected] requires a peer of popper.js@^1.11.0 but none was installed. I'm using Git Bash, I also tried to install jQuery individually but it couldn't installed. Could you please help me to fix these issues? A: You'll need to install those dependencies and save them to you package.json npm install [email protected] --save npm install [email protected] --save The docs for npm install
{ "pile_set_name": "StackExchange" }
Q: CheckedChanged event not firing I have a person entering their address into a form. Then I have a second section on the form that may or may not use their same address they typed. I want a CheckBox that if checked, will fill in their already typed address. However I cannot get it to work. I am using VB.Net. I've tried .Text as well as .ToString() but either way isn't working. Protected Sub CheckBox_CheckedChanged(sender As Object, e As System.EventArgs) Handles CheckBox.CheckedChanged If CheckBox.Checked Then TextBoxAddressLine1Work.Text = TextBoxAddressLine1Local.Text End If End Sub A: There are two conditions for CheckedChanged event to work This event does not post the page back to the server unless the AutoPostBack property is set to true. A CheckBox control must persist some values between posts to the server for this event to work correctly. Be sure that view state is enabled for this control. The chances are that you may not have the AutoPostBack property set to true, if it is not then set it as in the following example <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" /> Additional recommendation: DO NOT use keywords as your identifiers such as variable name, control ID e.g. you have given assigned "CheckBox" as ID to a CheckBox control in your given example. Such naming convention can cause exceptions which may be hard to trace.
{ "pile_set_name": "StackExchange" }
Q: Parsing through XML in C# and searching for a "FAILED" I am trying to write a program in C# to parse through an XML file and look through the status of multiple elements to find one that failed. I don't have much experience working with XML but have done some research and am a little stuck. I'll post an example XML file below for reference. I figure I'll check the of each group first to see which group failed then search that group's individual elements. <Diagnostics ActionType="SPV" Ver="48"> <StartTimestamp>2014-04-18 13:36:44Z</StartTimestamp> - <Iteration> - <NODE1> <Device Name="A" Register="IDCODE" Status="PASSED"/> <Device Name="B" Register="IDCODE" Status="PASSED"/> <Device Name="C" Register="IDCODE" Status="PASSED"/> <Device Name="D" Register="IDCODE" Status="PASSED"/> <Device Name="E" Register="IDCODE" Status="PASSED"/> <Device Name="F" Register="IDCODE" Status="PASSED"/> <Device Name="G" Register="IDCODE" Status="PASSED"/> <Device Name="H" Register="IDCODE" Status="PASSED"/> <Device Name="I" Register="IDCODE" Status="PASSED"/> <Status>PASSED</Status> </NODE1> - <NODE2> <Status>PASSED</Status> </NODE2> - <NODE3> <Status>PASSED</Status> </NODE3> - <NODE4> <Device Name="A" Register="IDCODE" Status="PASSED"/> <Device Name="B" Register="IDCODE" Status="PASSED"/> <Device Name="C" Register="IDCODE" Status="PASSED"/> <Device Name="D" Register="IDCODE" Status="PASSED"/> <Device Name="E" Register="IDCODE" Status="PASSED"/> <Device Name="F" Register="IDCODE" Status="PASSED"/> <Device Name="G" Register="IDCODE" Status="PASSED"/> <Device Name="H" Register="IDCODE" Status="PASSED"/> <Device Name="I" Register="IDCODE" Status="PASSED"/> <Status>PASSED</Status> </NODE4> - <NODE5> <Device Name="E" Status="PASSED" /> <Device Name="F" Status="PASSED" /> <Device Name="H" Status="FAILED" /> <Device Name="I" Status="PASSED" /> <Status>FAILED</Status> </NODE5> <Passed>False</Passed> </Iteration> <EndTimestamp>2014-04-18 13:36:44Z</EndTimestamp> </Diagnostics> A: XmlNodeList nodes = xmlDoc.SelectNodes("//Device[@Status='FAILED']");
{ "pile_set_name": "StackExchange" }
Q: ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies I'm deploying my website on the server. My website is done using asp.net c# 4 and EF 4. I receive this error: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded Any idea how could I fix it? Thanks for your time on this A: It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc. A: check below link in which you can download suitable AjaxControlToolkit which suits your .NET version. http://ajaxcontroltoolkit.codeplex.com/releases/view/43475 AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0 AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5 A: Just Add AjaxControlToolkit.dll to your Reference folder. On your Project Solution Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll . Then build. Regards
{ "pile_set_name": "StackExchange" }
Q: PHP Explode Words I'm new in PHP programming. I need your help to finish my homework. I want to explode the following sentence: I love my band and my cat into arrays. But I need to use space and word and as delimiters. So it should become like this: $arr[0] -> I $arr[1] -> love $arr[2] -> my $arr[3] -> band $arr[4] -> my $arr[5] -> cat I have tried like this: $words = "I love my band and my cat" $stopwords = "/ |and/"; $arr = explode($stopwords, $words); But the problem is, it also removes characters and from word band so it becomes like this: $arr[0] -> I $arr[1] -> love $arr[2] -> my $arr[3] -> b $arr[4] -> my $arr[5] -> cat This is not what I want. I want to remove the word that exactly and, not word that contains and characters. Is there anyway to solve this? Can anybody help me? Thank you very much.. :-) A: If you want to avoid splitting out and in the middle of a word, you have to filter the result list (array_diff), or use a more complex regex. Then also consider preg_match_all instead of splitting: preg_match_all('/ (?! \b and \b) (\b \w+ \b) /x', $input, $words); This will only search for consecutive word-characters, instead of breaking up on spaces. And the assertion ?! will skip occurences of and.
{ "pile_set_name": "StackExchange" }
Q: Georeferencing a jpeg in QGIS but the scale is way off I've gone through the really helpful walk-through(s) of how to georeference a jpeg in order to make it a layer, but after inputting the coordinates (either by typing in actual coordinates or clicking "From map canvas" and aligning points) and loading the new layer, the scale is way off (and I think the jpeg isn't even remotely in the right place--hard to tell because of how off the scale is). Any ideas? A: You have to decide whether you want to enter coordinates in lat/lon, or from a background map with a projected CRS (e.g. in metres). For the first choice, you have to set the target CRS to WGS84 (EPSG:4326), and don't mix up lat and long values. For the second choice, the target CRS must be set to the same CRS as the project CRS. This can be different from the background map original CRS. If you load the georeferenced picture to QGIS canvas, check if the CRS is set correctly with Rightclick -> Set CRS for layer. Sometimes QGIS sets the CRS for new layers automatically to a CRS that you do not want in your case.
{ "pile_set_name": "StackExchange" }
Q: Converting a parallel program to a cluster program. From OpenMP to? I want to write a code converter that takes an OpenMP based parallel program and runs it on a cluster. How do I go about this problem? What libraries do I use? How do I set up a small cluster for this? I'm finding it extremely hard to find good material about cluster computing on the internet. EDIT: If it's impossible then how does Intel do it? The Intel compiler seems to do exactly what I want to. I don't have any specific application that I would like to run. I want to write the "converter/compiler", not the application. I understand that shared memory is different from distributed memory, but there has to be a way to sync memory, if not for all cases, then for some specific cases, even if it means that application is written with custom constructs. A: Intel has an implementation of OpenMP that works with their C++ and Fortran compilers for x86 64-bit clusters. You can get a 30-day eval version of these compilers for free. Other than that, Zifre is mostly right. If you are concerned with scalability, bite the bullet and write your parallel program in another programming model (MPI, CUDA, Cilk, ...) which is designed with distributed systems in mind. If you provide a little more information about your application, we may be able to provide more useful guidance on that front. A: It seems to me that this is not a good idea. The basic idea behind OpenMP is data-shared parallel execution. It works well, when accessing shared data costs you nothing. Every thread can access a variable in shared cache or RAM. The cluster computations exploit message-passing, because computers in cluster have distributed memory. When one process needs data from another one then you should manage data passing over the network. It is time-consuming operation. So, if you want to write such compiler, you should implement data broadcasting operations (e.g. MPI_Bcast from MPI) for each data access in OpenMP. This will kill parallel performance at all.
{ "pile_set_name": "StackExchange" }
Q: comparing two dynamic values in DataTrigger I want to compare two dynamic values User_id and user_id for equality and setting one property Cursor. Also, when the cursor is hand, I have to execute one function. How to do it? This is the code that I am using: <DataTrigger Binding="{Binding Path=User_id}" Value="{Binding Path=user_id}"> <Setter Property="Cursor" Value="Hand"/> </DataTrigger> A: There are a couple options to attack this. #1. Multibinding Converter You can use Multibindingto input the two values into a IMultiValueConverter. To use this type of binding in your DataTrigger, you would use follow the following syntax. <DataTrigger Value="True"> <DataTrigger.Binding> <MultiBinding> <MultiBinding.Converter> <local:EqualityConverter /> </MultiBinding.Converter> <Binding Path="User_id" /> <Binding Path="user_id" /> </MultiBinding> </DataTrigger.Binding> <Setter Property="Window.Cursor" Value="Hand"/> </DataTrigger> The MultiBinding.Converteris set to a new instance of EqualityConverter, which is a class I created that implements the IMultiValueConverter interface. This class will do the comparison for you. The DataTrigger triggers when this converter returns true. public class EqualityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values.Length < 2) return false; return values[0].Equals(values[1]); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #2. MVVM Pattern I'm not sure where your DataContext is coming from, but if possible, you may want to consider using a view model for your binding. The view model could expose a property that does the equality comparison for you. Something like this. public class UserViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int _User_id; private int _user_id; public int User_id { get { return _User_id; } set { if (_User_id != value) { _User_id = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("User_id")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsUserIdsEqual")); DoSomething(); } } } public int user_id { get { return _user_id; } set { if (_user_id != value) { _user_id = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("user_id")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsUserIdsEqual")); DoSomething(); } } } public bool IsUserIdsEqual { get { return _user_id == _User_id; } } private void DoSomething() { if (this.IsUserIdsEqual) { //Do something when they are equal. } } } If using a view model like this, your DataTrigger could simplify to.. <DataTrigger Binding="{Binding Path=IsUserIdsEqual}" Value="True"> <Setter Property="Window.Cursor" Value="Hand"/> </DataTrigger> Regarding executing a function on the trigger, I added a DoSomething method to highlight how the view model could be used to execute a function when the two IDs are equal. I'm not sure if that would work for your case because I'm not sure what the intent of the function call is, but it is a way to execute a function when a condition changes.
{ "pile_set_name": "StackExchange" }
Q: jquery cycle slideshow, with keycode navigation I'm using a slideshow on my website using jquery Cycle 1. I navigate into my slideshow with #next function. when clicking on my last slide of my slideshow it redirect me to another page (var random_next_url_enfant). I would like to add the spacebar and the right arrow key to navigation inside my slideshow. when I add this Js code it works, but on the last slide it starts the slideshow again instead of redirecting me to the next page. $(document.documentElement).keyup(function (e) { if (e.keyCode == 39) { $('#slider_projets').cycle('next'); } }); here is my full code using the mouse click. on the last slide, it redirects me to another page, it works perfectly. but I would like to get the same with the spacebar and the right arrow : $('#slider_projets').cycle({ speed: 600, //temps d'animation timeout: 0, //fréquence fx: 'scrollLeft', //compteur// pager: "#nav", after: function(currSlideElement, nextSlideElement, options, forwardFlag) { $('#counter_1').text((options.currSlide + 1) + ' / ' + (options.slideCount)); slideIndex = options.currSlide; nextIndex = slideIndex + 1; prevIndex = slideIndex - 1; if (slideIndex == options.slideCount - 1) { /*nextIndex = 0;*/ var random_next_url_enfant = $("#random_next_url_enfant").val(); $('#next').on("click", function(e){ e.preventDefault(); window.location = random_next_url_enfant; }); } if (slideIndex === 0) { prevIndex = options.slideCount - 1; } } }); I think i'm missing something but I can't find what ! here is a jsfiddle : http://jsfiddle.net/8HsdG/ thanks a lot for your help, A: @kkemple, I've resolved the problem... I just had to change : $(document.documentElement).keyup(function (e) { if (e.keyCode == 32) { $('#slider_projets').cycle('next'); } }); by $(document.documentElement).keyup(function (e) { if (e.keyCode == 32) { $("#next").trigger("click"); } }); and it works perfectly ! anyway thanks for your help !
{ "pile_set_name": "StackExchange" }
Q: Stack Overflow corrupt %ebp I'm trying to study for an exam, and looking over stack overflow stuff i was hoping someone could clear something up for me. (assume this is on a 32 bit system, so that all addresses are 4 bytes. Also I am studying it from a C function, so any code referenced is from C) Say our code wants to take in buf[4] from standard input, and so it creates a four byte buffer. If we use the version of gets() that does not check for out of bounds, and input the string "12345" we will corrupt the saved %ebp on the stack. This will not, however, change the return address. Does this mean that the program will continue executing the correct code, since the return address is correct, and it will still go back into the calling function? Or does the corrupted %ebp mean trouble further down the line. I understand that If we input something larger like "123456789" it would also corrupt the return address, thus rendering the program inoperable. A: EBP is the base pointer for the current stack frame. Once you overwrite that base pointer with a new value, subsequent references to items on the stack will reference not the actual address of the stack, but the address your overwrite just provided. Further behavior of the program depends on whether and how the stack is subsequently used in the code.
{ "pile_set_name": "StackExchange" }
Q: how to improve .collect() in pyspark? Is there any other way to tune pyspark so that .collect()'s performance can be improved? I'm using map(lambda row: row.asDict(), x.collect()) which is taking more that 5seconds for 10K records. A: I haven't tried it, but maybe the Apache Arrow project could help you
{ "pile_set_name": "StackExchange" }
Q: How can I keep Skype from telling me people's birthdays? I use Skype on my Windows phone as well as on my tablet and various other devices. Only the Windows Phone variant lights up with a notification when it is someone's birthday. This is just not information I need about most of the people on my Skype list. Either I know (my mother) or I don't care (a business contact I had one call with once and have left in my contacts list.) The handful of people I speak to regularly but don't already know their birthdays is not enough for me to want this feature. But I can't turn it off! I suspect I turned it off on my desktop and Metro versions of Skype, since they don't tell me. I don't see it as a setting on the phone though. Can it be turned off? A: If you send the message "/nobday" into any chat, it will disable birthday notifications for that entire client. Nothing will actually be sent to other party.
{ "pile_set_name": "StackExchange" }
Q: Introspection to Determine Originally Bound Variable of an Instance Is there anyway to determine the variable to which an instance was originally bound? With a function we can do this: def f(): pass print f.__name__ >> f g = f print g.__name__ >> f What I want is: class c: pass mything = c() print mything.__name__ >> mything The reason I want this is for more intuitive logging/error messages for an API I'm writing.. I.e. it would be nice to have print mything >> instance of c originally bound to 'mything' Instead of the usual: print mything >> <__main__.c instance at 0x7fb7994b25a8> And (I think?) would be nice to not make people explicitly supply a __name__ attribute in __init__ all the time.. Is this possible? advisable? A: You want for example something like this (the function example confuses me): class Foo(object): # something here pass a = Foo() b = Foo() c = Foo() print a.__name # a print b.__name # b print c.__name # c ? if so, no that is not possible. This information cannot be carried within the instance. Many Instance can point to the same instance like here: >>> class Foo(object): ... pass ... >>> >>> a = Foo() >>> b = a >>> c = b >>> >>> print a <__main__.Foo object at 0x01765B70> >>> print b <__main__.Foo object at 0x01765B70> >>> print c <__main__.Foo object at 0x01765B70> >>> They all the same, which instance name to carry, go the point? another issue is here: class Foo(object): pass a = [Foo(), Foo(), Foo()] The only possible solution I can think of is to tag the instance on initialization: >>> class Foo(object): ... def __init__(self, name): ... self.__name__ = name ... >>> a = Foo('a') >>> b = Foo('b') >>> c = Foo('c') >>> >>> a.__name__ 'a' >>> b.__name__ 'b' >>> c.__name__ 'c' >>>
{ "pile_set_name": "StackExchange" }
Q: Hide input if mouse not moved for 5 seconds I have a HTML img input for the page reqad.co.nf as a full screen function, how would I make this input hide if the mouse isn't moved for 5 seconds, and reappear if it moves again?<input type="image" src="fullscreenico.png" align="right" onclick="toggleFullScreen()"> A: Here's a snippet with a JQuery solution: jQuery(document).ready(function(){ var lastTimeMouseMoved; var alreadyPrompt = false; $(document).mousemove(function(e){ lastTimeMouseMoved = new Date().getTime(); alreadyPrompt = false; $(".theInputIdLikeToHide").show(); }); setInterval(function(){ if(!alreadyPrompt){ var currentTime = new Date().getTime(); if (currentTime - lastTimeMouseMoved > 5000) { $(".theInputIdLikeToHide").hide(); alreadyPrompt = true; } } }, 500); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="theInputIdLikeToHide">
{ "pile_set_name": "StackExchange" }
Q: Как получить то, что было задано с define в lua FFI? Многие функции системного программирования в linux работают с флагами (например, O_NONBLOCK). Но эти флаги же надо ещё и получить! Насколько я понимаю, флаги в заголовочных файлах определены при помощи #define. Традиционное нечто вроде ffi.C.O_NONBLOCK выдаёт ошибку, это не функция и не глобальная переменная! При этом файл заголовков подгружен при помощи библиотеки lcpp. И как же получить эти самые define'ы? A: Надо использовать не ffi.C. а ffi.lcpp_defs.. Пример 1 Файл test1.lua: local lcpp = require("lcpp") local ffi = require("ffi") ffi.cdef([[ #define MAX_SIZE 100 typedef struct { int data[MAX_SIZE]; } test_t; ]]) print("MAX_SIZE = " .. ffi.lcpp_defs.MAX_SIZE) Результат работы: MAX_SIZE = 100 Пример 2 Файл test2.lua: local lcpp = require("lcpp") local ffi = require("ffi") ffi.cdef("#include \"test.h\"") print("FREQUENCY_MHZ = " .. ffi.lcpp_defs.FREQUENCY_MHZ) print("FREQUENCY_KHZ = " .. ffi.lcpp_defs.FREQUENCY_KHZ) print("_PACKED_ = " .. ffi.lcpp_defs._PACKED_) Файл test.h: #ifndef TEST_H #define TEST_H #define FREQUENCY_MHZ 2 #define FREQUENCY_KHZ (FREQUENCY_MHZ * 1000) #define _PACKED_ __attribute__((packed)) #endif // TEST_H Результат работы: FREQUENCY_MHZ = 2 FREQUENCY_KHZ = (FREQUENCY_MHZ * 1000) _PACKED_ = __attribute__((packed)) Всё в общем-то работает, но из второго примера видно, что полного препроцессинга define'ов не происходит. На самом деле тут всё не так плохо. Пример 3 Файл test3.lua: local ffi = require("ffi") local lcpp = require("lcpp") local data, state = lcpp.compile([[ #define ROW_CNT 0x0F #define COL_CNT 0x0A #define DATA_CNT (ROW_CNT * COL_CNT) int data[DATA_CNT]; ]]) local data_type = ffi.typeof(data) print("data = " .. data) print("ROW_CNT = " .. state.defines.ROW_CNT) print("COL_CNT = " .. state.defines.COL_CNT) print("DATA_CNT = " .. state.defines.DATA_CNT) print("typeof(data) = " .. tostring(data_type)) Результат работы: data = int data[(15*10)]; ROW_CNT = 0x0F COL_CNT = 0x0A DATA_CNT = (ROW_CNT * COL_CNT) typeof(data) = ctype<int[150]> Как видно из этого примера, размерность массива вычислена правильно (150 элементов).
{ "pile_set_name": "StackExchange" }
Q: Adding resizable tables to a Richtextbox (.net or C#) Our Capstone group is designing a stripped-down text editor for designing syllabus templates, one of the requirements is being able to add and remove resizable tables that function similarily to Microsoft Word (rtf) tables, they must be resizable by "dragging" as well as customizable fonts etc. They must also be placed in the RichTextBox, or at least in a way that can transition easily between regular text and a cell with text. We have tried using different methods including tablelayoutpanel (doesn't work as it cannot be placed directly in the richtextbox), the closest we have found is using Stringbuilder, but this still does not work exactly as the cells cannot be resized, and the string itself is very difficult to manipulate. We also need the ability to "merge cells". We have tried designing in both .net and C#, however the results are similar. If anyone has any suggestions as how to work this program, I would appreciate it. This is the code for the table creation: Private Sub tsbTwoRows_Click(sender As Object, e As EventArgs) Handles tsbTwoRows.Click Dim rtbTemp As New RichTextBox Dim sbTaRtf As New System.Text.StringBuilder 'These strings are necessary so that it will be visible in MS Word sbTaRtf.Append("{\rtf1\fbidis\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Calibri;}{\f1\fnil\fcharset0 Microsoft Sans Serif;}}") sbTaRtf.Append("\viewkind4\uc1\trowd\trgaph108\trleft5\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 ") sbTaRtf.Append("\clbrdrt\brdrw15\brdrs\clbrdrl\brdrw15\brdrs\clbrdrb\brdrw15\brdrs\clbrdrr\brdrw15\brdrs") sbTaRtf.Append("\cellx4678") 'set the width of the first cell sbTaRtf.Append("\clbrdrt\brdrw15\brdrs\clbrdrl\brdrw15\brdrs\clbrdrb\brdrw15\brdrs\clbrdrr\brdrw15\brdrs") sbTaRtf.Append("\cellx9355") 'set the width of the second cell sbTaRtf.Append("\pard\intbl\ltrpar\sl252\slmult1\lang3082\f0\fs22\cell\cell\cell\row") sbTaRtf.Append("\pard\ltrpar\lang1033\f1\fs17\par") sbTaRtf.Append("}") rtbTemp.Rtf = sbTaRtf.ToString() 'This prevents the new table from deleting the text rtbContent.SelectedRtf = rtbTemp.Rtf rtbTemp.Undo() Me.rtbContent.Focus() Me.rtbContent.SelectionStart = Me.rtbContent.SelectionStart - 1 Me.rtbContent.SelectionLength = 0 End Sub A: Okay, after lots of trial and error we found that stringbuilder works rather erratically on .net, we tried the following code on c# and it worked much better: StringBuilder tableRtf = new StringBuilder(); tableRtf.Append(@"{\rtf1"); tableRtf.Append(@"\trowd"); tableRtf.Append(@"\clbrdrt\brdrw15\brdrs\clbrdrl\brdrw15\brdrs\clbrdrb\brdrw15\brdrs\clbrdrr\brdrw15\brdrs"); tableRtf.Append(@"\cellx1000"); tableRtf.Append(@"\trrh3000"); tableRtf.Append(@"\clbrdrt\brdrw15\brdrs\clbrdrl\brdrw15\brdrs\clbrdrb\brdrw15\brdrs\clbrdrr\brdrw15\brdrs"); tableRtf.Append(@"\cellx3000"); tableRtf.Append(@"\intbl \cell \row"); tableRtf.Append(@"\pard"); tableRtf.Append(@"}"); string combined2 = tableRtf.ToString(); string combined1 = this.TextEditor.Rtf.ToString(); tableRtf.AppendLine(tableRtf.ToString()); TextEditor.Select(TextEditor.TextLength, 0); TextEditor.SelectedRtf = tableRtf.ToString(); This creates a string in the form of a cell that surrounds text you enter in it, you can change the font inside it easily, program the cell's height using \trrh and it can be resized both in the windows form program as well as in Word when it is exported. Initially, it wasn't visible when exported to Word so I added the tableRtf.Append(@"\clbrdrt\brdrw15\brdrs\clbrdrl\brdrw15\brdrs\clbrdrb\brdrw15\brdrs\clbrdrr\brdrw15\brdrs"); line and it was given a font recognized by Word. Most importantly, when typing inside the table and pressing enter to create a new line, the cell automatically resizes itself to fit the contents.
{ "pile_set_name": "StackExchange" }
Q: How to always keep steam turbines running at maximum performance using nuclear power? In version 0.15.0, Steam Turbines were added to the game. They are significantly more powerful than steam engines (1 steam turbine is equal to ~10.5 steam engines), but I'm finding it difficult to keep them running at 100% power. To even reach the maximum available performance for steam turbines, you need to use nuclear power and heat exchangers. The heat exchangers use heat produced by the nuclear reactor to make steam at very high temperatures. From my observations, the exchangers need to be running at at least 500 °C to produce steam (the maximum is 1000 °C). Anything lower than 500 °C, and the turbines will not run. I've also noticed two things with nuclear power: The farther the heat exchanger is from the reactor, the cooler the temperatures will be. Tampering with the heat pipes will case the temperatures to change temporarily as the heat attempts to catch up. I'm able to get my turbines running at maximum efficiency when there is enough power on my grid already, but I am expanding my factory, and my expansion is starting to consume too much power. When this happens, the turbines fail to continue to run at maximum. They appear to consume their steam faster for some reason, and end up only being able to perform at about 60% their potential. My setup includes two nuclear reactors that are connected with heat pipes and are always running to produce enough heat. Right now, the exchangers are in the 600+ °C range so I should have enough heat to be making steam. How can I always keep them running at maximum power? Better yet, steam turbines can be linked together like steam engines, but doing this almost always ruins the performance of the turbines. How can I do this as well? A: It's hard to say where the bottleneck is because you haven't shown any of the mouseover info displays for the turbines, exchangers, and pipes, but here's some general advice: First of all, your setup is missing the bonus for multiple nuclear reactors. You must place them exactly adjacent to each other, with no intervening heat pipes. Once you do so, you will have exactly twice as much heat produced. Try to avoid cross-connecting heat pipes — each one should be a direct line from reactor to heat exchanger, and the only time three or more pipes should meet is if you're branching to feed more than one heat exchanger. (I'm not sure how much this will help, and it might change in the future, but my understanding is that in current versions heat pipes work pretty much like fluid pipes.) Simularly, make sure that the water pipelines are not cross-connected — for each offshore pump there should be a group of exchangers using its water with no overlap with other pumps. If there are cross-connections then water may flow in useless directions, reducing flow in the useful direction. In general, not enough offshore pumps can mean not enough water, but you don't have enough heat exchangers to need more than one, here. But you didn't show how many you have, so maybe adding a second one if you have only one might help if your water pipeline is not too efficient. steam turbines can be linked together like steam engines, but doing this almost always ruins the performance of the turbines. This just means that you don't have enough steam in that pipe to feed that many turbines. The total output will always be the same or better — there are no losses in a heat/steam system, only flow bottlenecks.
{ "pile_set_name": "StackExchange" }
Q: VBA Subroutine declaration issue stoping excel VBA from properly executing I am working on a simple subroutine to pull values from the Primary Worksheet and to move those values to the additional sheets. When I run the VBA macro it never gets past the subroutine declaration, any suggestions would greatly be appreciated. Option Explicit Sub Macro2() Dim rCell As Range, ws As Worksheet Application.DisplayAlerts = False With Sheets("Sheet1") Sheets.Add().Name = "Temp" .Range("D2", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True For Each rCell In Sheets("Temp").Range("D2", Sheets("Temp").Range("B" & Rows.Count).End(xlUp)) If Not IsEmpty(rCell) Then .Range("D2").AutoFilter field:=3, Criteria1:=rCell If SheetExists(rCell.Text) Then Set ws = Sheets(rCell.Text) Else Set ws = Worksheet.Add(After:=Worksheets(Worksheets.Count - 1)) ws.Name = rCell End If With .AutoFilter.Range .Offset(1).Resize(.Rows.Count - 1).Copy ws.Range("A" & Rows.Count).End(xlUp)(2) End With End If Next rCell Sheets("Temp").Delete .AutoFilterMode = False End With Application.DisplayAlerts = True End Sub added Function Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean Dim sht As Worksheet If wb Is Nothing Then Set wb = ThisWorkbook On Error Resume Next Set sht = wb.Sheets(shtName) On Error GoTo 0 SheetExists = Not sht Is Nothing End Function New error extract range has a illegal or missing field name @ .Range("D2", .Range("D"&Rows.Count).End(xlDown)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True A: When I run that code, it says: Compile Error: Sub or Function not defined and then highlights the SheetExists function. Either SheetExist is a function you forgot to include in your form, or it's a custom function that wasn't included in your example. EDIT: Wow, there's a lot going on here. If you step through the code after that, you'll also get a Run-time 1004 error ("Application-defined or object-defined error") here: .Range("D2", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True Try changing that to: .Range("D2", .Range("D" & Rows.Count).End(xlDown)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True From there, change this: Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count - 1)) ws.Name = rCell to this: Worksheets.Add(After:=Worksheets(Worksheets.Count - 1)).Name = rCell From there, though, I'm not sure what With .AutoFilter.Range is supposed to be doing, unless you meant With Sheets("Sheet1").AutoFilter.Range. From a debugging standpoint, you really want to add On Error Goto ErrRoutine at the beginning of your code, then add this to the end of your routine: Exit Sub ErrRoutine: MsgBox Err.Description Resume And put a breakpoint on MsgBox Err.Description to step back to the offending line.
{ "pile_set_name": "StackExchange" }
Q: How is geocoding from an address done? I was wondering how Google geocodes and address? Does it work like a DNS lookup, where they have a big table of addresses which is a hash to a geocode, or is there any fun geometery that goes into it? If it is a big hash table how did they go about gathering all that data? A: Busbina, I work for SmartyStreets where we verify and geocode street addresses -- so I'll tell you what I know, and link you to further sources for your own research. To answer your question: It is both. There are suppliers of massive databases (for example, those like TIGER Data) which contain relational, geo-political information including coordinates, streets, boundaries, and names. For US data, it is likely to obtain at least ZIP-level accuracy through tables like these simply by doing a lookup. For more accuracy, though, append the +4 code and you may narrow it down to a city block or floor of a high building. To attempt further accuracy (ie. knowing where precisely on the street a building is located), Google and others perform what is called interpolation, where they take the known boundaries from their datasets and and the known range of primary numbers from the start of that block or street to the end of it, and they solve a ratio. If the correct primary number is known, and for straight streets in an ideal setting, a simple ratio like this works: (primary number - starting primary number) / (ending primary number) = (x - starting boundary coordinate) / (ending boundary coordinate) Where x is a close guess to the actual location on the street - but only a guess. Accurate building-level data can be very expensive and I think is only available for some urban areas. The key is to get the right primary number and accurate, up-to-date data. Maintaining this can be time-consuming and expensive because of all the overhead involved with so much information. Note that Google and similar map services only perform address approximation, not address verification, and thus are liable to make mistakes (even if the geocoding algorithm is very precise) because the primary number may be wrong or may not even exist. So when that matters to you (or you aren't showing a Google Map and must honor the Terms of Service), something like LiveAddress, as a starting point, is certified by the USPS and won't return bad addresses. So there are some things to consider. More information: http://en.wikipedia.org/wiki/Geocoding#Address_interpolation http://www.ncgia.ucsb.edu/giscc/units/u016/u016.html ** I'll add a note, since I have had this question a lot: rooftop- or building-level accuracy is very expensive information. I know of very few providers who offer this, and they have mined and collected that data themselves. For example, Google has the Street View project, from which they've obtained accurate coordinates for approximate addresses, and they can provide such precision. But most geocoders use the same data from official sources, they just interpolate differently. If you want extremely precise coordinates like building-level, you can expect to pay mightily for it, or go collect the data yourself. (Yes, Google's is free to a point -- unless you intend to use the information for more than just showing a map, basically.)
{ "pile_set_name": "StackExchange" }
Q: upload multiple files with a single file_uploader rails 4 In sr_documents/form: <%= simple_form_for @service_request,:url=>upload_document_path(@service_request.id),:remote=>true,:html => { :multipart => true } do |f| %> <%= f.nested_fields_for :sr_documents do |q| %> <%= q.input :file,:required => true,:hint=>"(only .pdf,.docx,.doc,.txt)", multiple: true,:name=>'file[]' %> <%= f.button :submit ,:class=> "btn btn-go button",data: {"disable-with" => "Processing..."}%> <%= f.add_nested_fields_link :sr_documents,"Add new file" %> <%end%> I am using the gem nested_form_fields and paperclip in my app. Through the above code, I am able to upload multiple files. But my concern is how do I upload multiple files with a single file_uploader. I used name file[] and :multiple=>true, still its not working. Please help me out. A: I also needed same thing but didn't fine any solution. In my project I am using = file_field_tag :image_files, :multiple => true, name: 'image_files[]', style: 'display:none', :id => 'fileinput' User just have to select multiple files after selecting this field. And in controller I am able to get all those files with params[:image_files] I am then building images as : # This method builds images as per image_files params def build_images (params[:image_files] || []).each do |img| @product.images.build(file: img) end end
{ "pile_set_name": "StackExchange" }
Q: Weird behaviour in VS 2013 during debugging during debugging in Visual Studion 2013, for a C# project, the yellow arrow that appears next to the line number does not move to the next line. I have to press F10 twice on every line. When there is a method call and I press F11, it goes to that method and then jumps back to the calling part on pressing F10, I have to press F10 again a second time only then it goes back to the next line in the called method. What is going on? Did I accidentally turn on/off some setting in VS? Please help as this is causing a lot of frustration. Regards. A: It seems like you're debugging a MultiThreaded app, which is accessing the same method multiple times, as i said in the comments. Check your Threads window and you will see that more then 1 Thread is accessing the called method, and that's why you're experiencing having to press F10 more then once, and why F11 is returning back to the called method. Inside your Threads window, you can Freeze threads by right clicking them and pressing "Freeze".
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get the NAT Ip Address? is it possible to get my nat ip address across the Internet? I know I can see my ISP address but not my internal address. I remember seeing this done one time but I am thinking it was a java applet and not just a web page. can it be done with a regular web page? edit for clarification: I want to know if there is a way someone can get my local ip on my internal network from the Internet. A: Hi, is it possible to get my nat ip address across the Internet? By normal means no. Your internal address will be mapped to your router public address and the information lost to anyone outside. When they connect back to you (being an active connection or a response packet from a connection you established), your router will remap the public address back to your internal IP address (making also any necessary changes to the packets contents) without the outside knowledge. However, if someone from the outside somehow gains access to your router translation tables (where the mappings and connection states are kept), then indeed they can learn about your internal IP. They can also learn about your internal IP if you actively advertise it to those you connect to. This can be happen in numerous ways. An application may simply read your internal IP from your network device and forward it along when connecting. And this is how probably you've seen this happen. With Java enabled, for instance, a browser can unwillingly and without your knowledge send your internal IP by running a malicious webpage script. Note however that there are also legitimate uses for this, like recording internal and external IPs for purposes of abuse control and reporting. However, the internal IP is of no practical use to anyone outside. They can't use it to access your machine. So this shouldn't worry you in any way.
{ "pile_set_name": "StackExchange" }
Q: array.map needs index but doesn't need currentValue I have an empty array that I want to fill with strings. The strings will use an index value to count up. For instance: 'item 1' 'item 2' 'item 3' I have a working map function that will do this: let items = new Array(100).fill().map((item, index) => { return `item ${index + 1}` }) While this does fill the array with strings that iterate up through the index value, I am also passing in the item argument to the map function, which is the currentValue (as named in MDN). I'm not actually using this value, though. Seeing as how this value has to be passed in, I tried passing in null, but that gave me an error. I also tried to pass in an empty object, as in .map(( {}, index) => ...)}. honestly, I don't know what the rationale is to the empty object, but I figured I'd try it. Needless to say, that didn't work. My question is -- what do you do if you have no use for a required argument like this? Can I pass some kind of undefined or useless value in there? Should I be using another function other than map to do this? I could do this with a for loop: let items = new Array(100).fill() for (let index = 0; index < items.length; index++ { items[index] = `item ${index + 1}` } Would the for loop be the better choice in this case? A: fill + map is a waste when you can just use from - const result = Array.from(Array(10), (_,i) => `item ${i + 1}`) console.log(result) // [ "item 1" // , "item 2" // , "item 3" // , "item 4" // , "item 5" // , "item 6" // , "item 7" // , "item 8" // , "item 9" // , "item 10" // ]
{ "pile_set_name": "StackExchange" }
Q: Using Views in Doctrine 2 with Symfony 2 I have a database for orders (simplified): order: {id, shipment, discount, date} order_item: {id, order_id, name, amount, price} If I want to get the full price (SUM(item prices)+shipment-discount) I could of course ad a method to my Order class that does the query. On the other hand, it would be handy to have a view on order that includes the full price. Is it possible to integrate that into a Doctrine2 entity object? Is it even possible to generate such a view via annotations in the class, as I am maintaining my database layout with Symfony/Doctrine? A: You have Doctrine Entity and EntityRepository. Queries should go to Repository Classes as a method. A mysql-view is just a query. A Repository Class returns one or more Entity classes.. I.E Row in Database Table. Please provide some code and schema, to get better answers. This could go to Order Entity: public function getOrderTotal() { $sum = 0.0; foreach ($this->getOrderItems() as $item) { //Process } return $sum; } Native MySQL Views handling and generating is not supported by Doctrine2.
{ "pile_set_name": "StackExchange" }
Q: Installing MySQL 5.6 on Ubuntu I need to install mysql 5.6 on my ubuntu machine for development reasons (the newest version contains features that I need to incorporate into some web projects). But I am having some issues. I've been following this tutorial which is not specific for version 5.6 but I figured it would be about the same: http://www.ovaistariq.net/490/a-step-by-step-guide-to-upgrading-to-mysql-5-5/ I'm not sure if i'm setting up my /etc/my.cnf file properly. Here is what I have: # Example MySQL config file for large systems. # # This is for a large system with memory = 512M where the system runs mainly # MySQL. # # MySQL programs look for option files in a set of # locations which depend on the deployment platform. # You can copy this option file to one of those # locations. For information about these locations, see: # http://dev.mysql.com/doc/mysql/en/option-files.html # # In this file, you can use all long options that a program supports. # If you want to know which options a program supports, run the program # with the "--help" option. # The following options will be passed to all MySQL clients [client] #password = your_password port = 3306 socket = /var/run/mysqld/mysqld.sock # Here follows entries for some specific programs # The MySQL server [mysqld] port = 3306 socket = /var/run/mysqld/mysqld.sock skip-external-locking key_buffer_size = 256M max_allowed_packet = 1M table_open_cache = 256 sort_buffer_size = 1M read_buffer_size = 1M read_rnd_buffer_size = 4M myisam_sort_buffer_size = 64M thread_cache_size = 8 query_cache_size= 16M pid_file = /usr/local/mysql/data/dev.pid basedir = /usr/local/mysql datadir = /usr/local/mysql/data tmpdir = /tmp log_error = /var/log/mysql/error.log user = mysql # Try number of CPU's*2 for thread_concurrency thread_concurrency = 8 # Don't listen on a TCP/IP port at all. This can be a security enhancement, # if all processes that need to connect to mysqld run on the same host. # All interaction with mysqld must be made via Unix sockets or named pipes. # Note that using this option without enabling named pipes on Windows # (via the "enable-named-pipe" option) will render mysqld useless! # #skip-networking # Replication Master Server (default) # binary logging is required for replication log-bin=mysql-bin # binary logging format - mixed recommended binlog_format=mixed # required unique id between 1 and 2^32 - 1 # defaults to 1 if master-host is not set # but will not function as a master if omitted server-id = 1 # Replication Slave (comment out master section to use this) # # To configure this host as a replication slave, you can choose between # two methods : # # 1) Use the CHANGE MASTER TO command (fully described in our manual) - # the syntax is: # # CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>, # MASTER_USER=<user>, MASTER_PASSWORD=<password> ; # # where you replace <host>, <user>, <password> by quoted strings and # <port> by the master's port number (3306 by default). # # Example: # # CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306, # MASTER_USER='joe', MASTER_PASSWORD='secret'; # # OR # # 2) Set the variables below. However, in case you choose this method, then # start replication for the first time (even unsuccessfully, for example # if you mistyped the password in master-password and the slave fails to # connect), the slave will create a master.info file, and any later # change in this file to the variables' values below will be ignored and # overridden by the content of the master.info file, unless you shutdown # the slave server, delete master.info and restart the slaver server. # For that reason, you may want to leave the lines below untouched # (commented) and instead use CHANGE MASTER TO (see above) # # required unique id between 2 and 2^32 - 1 # (and different from the master) # defaults to 2 if master-host is set # but will not function as a slave if omitted #server-id = 2 # # The replication master for this slave - required #master-host = <hostname> # # The username the slave will use for authentication when connecting # to the master - required #master-user = <username> # # The password the slave will authenticate with when connecting to # the master - required #master-password = <password> # # The port the master is listening on. # optional - defaults to 3306 #master-port = <port> # # binary logging - not required for slaves, but recommended #log-bin=mysql-bin # Uncomment the following if you are using InnoDB tables #innodb_data_home_dir = /usr/local/mysql/data #innodb_data_file_path = ibdata1:10M:autoextend #innodb_log_group_home_dir = /usr/local/mysql/data # You can set .._buffer_pool_size up to 50 - 80 % # of RAM but beware of setting memory usage too high #innodb_buffer_pool_size = 256M #innodb_additional_mem_pool_size = 20M # Set .._log_file_size to 25 % of buffer pool size #innodb_log_file_size = 64M #innodb_log_buffer_size = 8M #innodb_flush_log_at_trx_commit = 1 #innodb_lock_wait_timeout = 50 [mysqldump] quick max_allowed_packet = 16M [mysql] no-auto-rehash # Remove the next comment character if you are not familiar with SQL #safe-updates [myisamchk] key_buffer_size = 128M sort_buffer_size = 128M read_buffer = 2M write_buffer = 2M [mysqlhotcopy] interactive-timeout When I try to run mysqld --skip-grant-tables --user=mysql I get this error: The program 'mysqld' can be found in the following packages: * mysql-server-core-5.1 * mysql-cluster-server-5.1 Try: sudo apt-get install <selected package> When i try to stop the server, I get this: * MySQL server PID file could not be found! When I try to start: Starting MySQL .. * The server quit without updating PID file (/usr/local/mysql/data/dev.pid). I am assuming I am not editing the my.cnf file properly, but i'm completely lost. Otherwise I have followed the instructions perfectly and I have made sure that the previous mysql 5.1 version was completely removed from the system. A: For the mysqld error, you may need to make sure that the binaries are in your $PATH. Try checking using which mysqld. If it is not on your path, you should add it to your profile (if you're using bash, this will probably be ~/.bash_profile): export PATH=/path/to/mysql/bin:$PATH As for the PID error, you might check /var/log/mysql/error.log to see if it gives you any hints as to what's wrong, but I have a feeling that it may be that the user the MySQL server is running under does not have permissions to write to the PID file, so make sure that it's owned by the mysql user (or the equivalent for your distro).
{ "pile_set_name": "StackExchange" }
Q: Comparing values within an array So, I asked a question 2 days ago, I'm going to try to rework it to make it simpler: I have a 2D array, which represents a Sudoku game. I'm trying to check the game for errors as with a typical Sudoku game: No number (1-9) is repeated within a row, column or 3x3 square. No empty cells. The user IS ALLOWED to enter a repeat value, but the game will not be considered "won" until they fix these errors. I want to allow them to enter wrong values, just not win. I'm very new to Java, so I had a limited knowledge to approach this with. I was going to try a long if, else statement comparing all the cells. That didn't work, because -1 was repeated. (-1 represents an empty square). I tried to get around this, but realized that this if statement was too messy and there had to be a better way. Then I thought to use boolean statements to test each number, setting to true if it had been seen before. That seems messy with so many boolean statements. So, I'm kind of at a wall. Any tips on what to try? Try not to use anything advance, only been doing Java 2 months. A: 1) You want to loop through the values, such as with a for loop. That will be much better than a long if-else-if chain. 2) To keep track of values seen, a simple way for you would probably be to use a list. I'll try to keep this example as simple as possible since you ask for "nothing advance." public boolean checkRow(int rowNumber) { ArrayList numbersSeen = new ArrayList(); for(int i = 0; i < 9; i += 1) { if(sudokuArray[i][rowNumber] != -1 && numbersSeen.contains(sudokuArray[i][rowNumber])) { return true; } } return false; } This will return true if row rowNumber has a number repeat in the 2D array specified by sudokuArray, and false otherwise. Notice the sudokuArray != -1, that takes into account the -1 placeholder for empty squares that you mentioned. When you compile something like this, if the compiler errors about trying to put an integer into the array list, you might have to make it generic by specifying ArrayList<Integer>. I do not recall if Java will auto-box a primitive for you when you specify a destination of type Object. This then leads into a small side-lesson which might be beneficial to you since you are new: Java has both primitive types (boolean, byte, short, int, long, float, double) and object versions of the primitive types (Boolean, Byte, Integer, etc.). If you do int i = 0; and Integer i2 = i;, Java will be nice enough to do the conversion for you. checkColumn would be very similar. check3X3area (or whatever you would want to call it) could be somewhat similar; perhaps you could use 2 for-loops, one nested inside the other, and loop 3 times each instead of 9. This will be left as an exercise for you. Also, you could make this generic to allow for sudoku boards that are not of size 9 with a few modifications.
{ "pile_set_name": "StackExchange" }
Q: Short-urls without index files? I'm wondering how urls like these are generated: http://www.example.com/Xj7hF This is a practice I have seen used by many url shorteners as well as other websites that supposedly don't want to display data in the url in a parameter format. Surely they can't be placing index files in the folder destination /Xj7hF etc with a redirect to the actual url, so I'm wondering how this is done. Any help would be very appreciated! (I'm running on a Linux server with Apache). A: Different web development frameworks and web servers do it in different ways, but, the most common is probably using mod_rewrite with apache. Basically, the web server sends the request to a dynamic scripting language (eg. PHP) rewritten in such a way that the script doesn't need to know what the original request URI looked like and the client browser doesn't need to know what script actually processed the request. For example, You will often see: http://something.com/123/ This is a request for /123 which Apache may rewrite as a request to /my_script.php?id=123 based on how the user configured mod_rewrite. (.htaccess example) # if the request is for a file or directory that # does not actually exist, serve index.php RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?url=$1
{ "pile_set_name": "StackExchange" }
Q: Mandrill "reject_reason":"unsigned" I'm trying to send emails using mandrill email service but I get the following error: [ { "email": "[email protected]", "status": "rejected", "_id": "daab0daa538a4fe9b161be709593be0b", "reject_reason": "unsigned" } ] I am trying to send email using ajax call in javascript like : $.ajax({ type: "POST", url: "https://mandrillapp.com/api/1.0/messages/send.json", data: { "key": "RemovedforSecurityitscorrect", "message": { "html": "<p>Example HTML content</p>", "text": $('#emailText').val(), "subject": $('#emailSubject').val(), "from_email": $('#fromEmail').val(), "from_name": $('#fromName').val(), "to": [{ "email": $('#toEmail').val(), "name": $('#recipientName').val(), "type": "to" }], "headers": { "Reply-To": $('#fromName').val() } }, success: function (data) { console.log("Email Sent"); }, error: function (xhr, status, error) { console.log("Error while sending mail"); } } }); all values are coming to ajax call & call is made to server evident from response. What can be issue? A: I got the reason, it was silly mistake. I was trying to send mail through my personal email id which is on different domain than to for which Mandrill is configured & verified. Searching for the reason of error, I found that this error is sent from Mandrill when Mail sent from unverified domains or domains without valid SPF and DKIM records will be rejected with the reject_reason, unsigned. For more information refer https://mandrillapp.com/api/docs/messages.html https://mandrill.zendesk.com/hc/en-us/articles/205582247-About-Domain-Verification https://mandrill.zendesk.com/hc/en-us/articles/205582267-About-SPF-and-DKIM For doing required setting related to SPF & DKIM for Mandrill please refer: https://mandrill.zendesk.com/hc/en-us/articles/205582277-How-do-I-add-DNS-records-for-my-sending-domains-
{ "pile_set_name": "StackExchange" }
Q: When using PresentationFramework.Aero, do I need to set "Copy Local" to true (and include it in my setup project)? My WPF project uses .NET 4 client profile. When I add <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml" /> to <Application.Resources> I get this exception when starting the program in debug mode (in release mode the program silently crashes): A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: 'Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '14' and line position '14'. When I set the property "Copy Local" of PresentationFramework.Aero to true, everything works and the exception is gone. "Copy Local" places a copy of PresentationFramework.Aero in my output directory and I therefore need to include it in my setup project. Why is that necessary? According to MSDN PresentationFramework.aero is included in the .NET framework 4.0 client profile and therefore in the GAC. I do not feel comfortable deploying a framework file with my application. Udate: As Hans Passant suggested I verified that the directory PresentationFramework.Aero exists in C:\windows\microsoft.net\assembly\gac_msil. Then I used fuslogvw.exe to generate the following log, created when starting my application "SetACL Studio.exe" without PresentationFramework.Aero.dll being present in the application directory. Interestingly, the loader does not even check the GAC. Why? *** Assembly Binder Log Entry (18.11.2011 @ 17:13:27) *** The operation failed. Bind result: hr = 0x80070002. The system cannot find the file specified. Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll Running under executable D:\Daten\Helge\Programmierung\SetACL Studio\Source\Bin\Debug\SetACL Studio.exe --- A detailed error log follows. === Pre-bind state information === LOG: User = HKT520\Helge LOG: DisplayName = PresentationFramework.Aero, Culture=neutral (Partial) WRN: Partial binding information was supplied for an assembly: WRN: Assembly Name: PresentationFramework.Aero, Culture=neutral | Domain ID: 1 WRN: A partial bind occurs when only part of the assembly display name is provided. WRN: This might result in the binder loading an incorrect assembly. WRN: It is recommended to provide a fully specified textual identity for the assembly, WRN: that consists of the simple name, version, culture, and public key token. WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. LOG: Appbase = file:///D:/Daten/Helge/Programmierung/SetACL Studio/Source/Bin/Debug/ LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache Base = NULL LOG: AppName = SetACL Studio.exe Calling assembly : PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. === LOG: This bind starts in default load context. LOG: Using application configuration file: D:\Daten\Helge\Programmierung\SetACL Studio\Source\Bin\Debug\SetACL Studio.exe.Config LOG: Using host configuration file: LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///D:/Daten/Helge/Programmierung/SetACL Studio/Source/Bin/Debug/PresentationFramework.Aero.DLL. LOG: Attempting download of new URL file:///D:/Daten/Helge/Programmierung/SetACL Studio/Source/Bin/Debug/PresentationFramework.Aero/PresentationFramework.Aero.DLL. LOG: Attempting download of new URL file:///D:/Daten/Helge/Programmierung/SetACL Studio/Source/Bin/Debug/PresentationFramework.Aero.EXE. LOG: Attempting download of new URL file:///D:/Daten/Helge/Programmierung/SetACL Studio/Source/Bin/Debug/PresentationFramework.Aero/PresentationFramework.Aero.EXE. LOG: All probing URLs attempted and failed. Update 2: This is the output from gacutil: C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin>gacutil.exe /l presentationframework.aero Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.30729.1 Copyright (c) Microsoft Corporation. All rights reserved. The Global Assembly Cache contains the following assemblies: presentationframework.aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL Number of items = 1 A: I just found the following on MSDN: You can also make a dynamic reference to an assembly by providing the calling method with only partial information about the assembly, such as specifying only the assembly name. In this case, only the application directory is searched for the assembly, and no other checking occurs. That explains the behavior I was seeing and why the GAC was not searched for PresentationFramework.aero.dll. I changed the dynamic reference to a full reference and removed "Copy Local" from PresentationFramework.aero. It now works without needing PresentationFramework.aero.dll in my application directory. For reference, here is the working resource dictionary code: <ResourceDictionary Source="/PresentationFramework.Aero,Version=3.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35,processorArchitecture=MSIL;component/themes/Aero.NormalColor.xaml" /> In short, delete the local copy of your themes(in case you have added in your solution), add the full reference in the App.xaml file under Application.Resources (Resource Dictionary) and this should do.
{ "pile_set_name": "StackExchange" }
Q: File-To-File using vectors - null result Why have I got null in the text file test3.txt after read the elements of vectors correctly? The problem is that the test1.txt consists of the string words, when I printed out the vector elements, it is OK, but when I print these elements vector to another file the other file is still null. import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Vector; public class VectorFile { public static void main (String args []) throws IOException { Vector vc = new Vector(); BufferedReader file = new BufferedReader(new FileReader("c://test1.txt")); FileWriter out = new FileWriter("c://test3.txt"); String s; while ((s = file.readLine()) != null) { vc.add(s); } file.close(); System.out.println(vc.size()); for(int i=0; i<vc.size(); i++){ out.write( (String) vc.get(i)); } } } A: Substitute this: for(int i=0; i<vc.size(); i++) { out.write( (String) vc.get(i)); } with this: for(int i=0; i<vc.size(); i++) { out.write((String)vc.get(i)+ System.getProperty("line.separator")); } out.flush();
{ "pile_set_name": "StackExchange" }
Q: How to supress Entry Point Not Found error on loading Delphi package? I maintain a program written in Delphi 6. It loads some bpl package files dynamically using SysUtils.LoadPackage. Often I change something in the program that causes a package to fail to load. When this happens a message box appears and then an exception is thrown. The message box and exception are separate. Here's an example of the message box: --------------------------- Connect Manager: ConnectManager.exe - Entry Point Not Found --------------------------- The procedure entry point @Connectmanagerplugin@TConnectManagerPluginClassList@UnRegister$qqrp17System@TMetaClass could not be located in the dynamic link library ConnectManagerPack.bpl. --------------------------- OK --------------------------- And here's the exception: --------------------------- Debugger Exception Notification --------------------------- Project ConnectManager.exe raised exception class EPackageError with message 'Can't load package Projects.bpl. The specified procedure could not be found'. Process stopped. Use Step or Run to continue. --------------------------- OK Help --------------------------- I can't see how to stop the message box from appearing. Any ideas accepted gratefully. A: Solved! I created a copy of SysUtils.LoadPackage in my application and edited this copy to pass a second param to SafeLoadLibrary. So the call to SafeLoadLibrary now looks like: Result := SafeLoadLibrary(Name, SEM_FAILCRITICALERRORS); This helped: http://msdn.microsoft.com/en-us/library/ms680621%28VS.85%29.aspx.
{ "pile_set_name": "StackExchange" }
Q: C# Exception when remotely connection to SQL Server 2005 instance Trying to connect to a SQL Server 2005 instance remotely but getting the following exception: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Have checked and the server is enabled to accept remote connections. Connection string I'm using in .NET looks like this: Data Source=SERVERIP\INSTANCE;Initial Catalog=DATABASENAME;User Id=USERNAME;Password=PASSWORD; Any ideas? Thank you :) A: Make sure the SQL Server Browser service is started on the remote machine, and that the firewall allows connections through port 1433 and 1434. And of course this is provided the instance you are trying to access does exist. A: You might want to try a quick telnet to TCP port 1433 of the server to see if you can establish a connection that way. telnet remote_name_or_ip 1433 If you can't, you know that it's at the network layer, and you can start checking things like the Windows Firewall or other network pieces that might get in your way. (You also need access via UDP to port 1434.)
{ "pile_set_name": "StackExchange" }
Q: Javascript object - using array value as key I have the following array const lastThreeYearsArr = [currYear, currYear-1, currYear-2 ] I need to define an object as: var obj = {lastThreeYearsArr[0]: 0, lastThreeYearsArr[1]: 0, lastThreeYearsArr[2]: 0}; But using the array as key doesn't seem to work in javascript. Is there a way to access the array value and put it as key in the object. A: You could create a new object by iterating the keys and use Object.assign with computed property names. var lastThreeYearsArr = ['currYear', 'currYear-1', 'currYear-2'], object = lastThreeYearsArr.reduce((o, k) => Object.assign(o, { [k]: 0 }), {}); console.log(object);
{ "pile_set_name": "StackExchange" }
Q: Indexing on Partition I deleted indexing on partioned table in Oracle.Is ther a way to recreate the index on the same?? A: By Deleting, do you mean "Dropped" an index on a partitioned table? You can always recreate them using one of the methods (based on your needs) shown here.. http://download.oracle.com/docs/cd/E11882_01/server.112/e16508/schemaob.htm#CNCPT1520 http://download.oracle.com/docs/cd/E11882_01/server.112/e16508/schemaob.htm#CNCPT1521
{ "pile_set_name": "StackExchange" }
Q: How do I set up nginx to serve data from a port? I have nginx serving a page on port 80. server { listen 80; server_name .example.com; root /var/www/docs; index index.html; } I also have a service running a server on port 9000. How do I set up a virtual directory in nginx (such as /service) to serve whatever is on port 9000? I am unable to open other ports, so I would like to serve this through some kind of virtual directory on port 80. A: Start with that (but you definetly will need more directives to make your server normally answering on this subdirectory): location /something { proxy_pass http://localhost:9000/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; }
{ "pile_set_name": "StackExchange" }
Q: Adding Text to SCNSphere Good afternoon, Firstly, please forgive my (probably) very basic question, I am fairly new to the world of AR... I am playing about with displaying 3D objects when the user taps the screen. I have successfully projected a bubble-like object into a set position when the user taps: override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let bubble = SCNSphere(radius: 0.1) bubble.firstMaterial?.transparency = 0.5 bubble.firstMaterial?.writesToDepthBuffer = false bubble.firstMaterial?.blendMode = .screen bubble.firstMaterial?.reflective.contents = #imageLiteral(resourceName: "bubble") let node = SCNNode(geometry: bubble) node.position = SCNVector3Make(0, 0.1, 0) let parentNode = SCNNode() parentNode.addChildNode(node) if let camera = sceneView.pointOfView { parentNode.position = camera.position // Animation like bubble let wait = SCNAction.wait(duration: 0.2) let speedsArray: [TimeInterval] = [0.5, 1.0, 1.5] let speed: TimeInterval = speedsArray[Int(arc4random_uniform(UInt32(speedsArray.count)))] let toPositionCamera = SCNVector3Make(0, 0, -2) let toPosition = camera.convertPosition(toPositionCamera, to: nil) let move = SCNAction.move(to: toPosition, duration: speed) move.timingMode = .easeOut let group = SCNAction.sequence([wait, move]) parentNode.runAction(group) { } } sceneView.scene.rootNode.addChildNode(parentNode) } What I would like to do now is display a number on the SCNSphere. Ideally so it looks like it is printed on the sphere's surface. I have tried the following code but found that, although the text is rendered, it is barely visible behind the sphere, and also a lot smaller than the sphere (I have attached a photograph to try and show this). I have tried playing about with the different values but I feel I am missing something vital with regards to positioning. let string = "25" let text = SCNText(string: string, extrusionDepth: 0.1) text.font = UIFont.systemFont(ofSize: 5) text.firstMaterial?.diffuse.contents = UIColor.black text.flatness = 0.005 let textNode = SCNNode(geometry: text) let fontScale: Float = 0.01 textNode.scale = SCNVector3(fontScale, fontScale, fontScale) parentNode.addChildNode(textNode) Any advice would be greatly appreciated. Thanks in advance! A: Not sure if it will give you what you exactly want. Its just a way where I put the number as a texture on sphere. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let bubble = SCNSphere(radius: 0.1) let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) view.backgroundColor = .black let label = UILabel(frame: CGRect(x: 0, y: 35, width: 200, height: 30)) label.font = UIFont.systemFont(ofSize: 30) view.addSubview(label) label.textAlignment = .center label.text = "25" label.textColor = .white bubble.firstMaterial?.diffuse.contents = view . . . }
{ "pile_set_name": "StackExchange" }
Q: oo program vs business rules changes I am maintaining a custom built and highly OO e-commerce application. The original designer made a few assumptions like: - there will never be more than 3 types of sales tax (state, national & hamonized) - each type of sales tax can have only one rate. - each state will be assigned one of the three tax types. He should have known better, but I guess it seemed reasonable at the time... All of a sudden each state is settings its own "harmonized" tax rate. Problem: 3 levels down the object stack, I have a tax calculation method that uses only amount and tax type. Now I am faced with the task of a pretty big restructure of a application that I have little understanding or little budget to learn I am inclined to stuff the state code into a session value and do a bit of hard-coded calculations on the other end. (1 day) instead of a re-structure (1-2 weeks??) Is it my imagination or do OO applications have a bigger learning curve and can be harder to maintain when the business rules take an unexpected turn? A: Is it my imagination or do OO applications have a bigger learning curve... Somewhat. I consider the curve to be steeper, but much shorter than an app built in functional code. An OO app is more likely to follow patterns, adhere to some kind of coding standard, and add structure or a framework to an application. While functional code is much more free to do as it pleases so long as the end-result is a working product. This produces an environment ripe for developer(s) to circum to the spaghetti-code mentality. ...and can be harder to maintain when the business rules take an unexpected turn? Depends. But this could be true regardless of the coding style used. In your case, this would appear true. However, OOP and patterns, historically, have made it easier for experienced programmers to maintain an application vs one written entirely of spaghetti, functional, code.
{ "pile_set_name": "StackExchange" }
Q: How to get face normals average in Maya? I generally program Unity3D related stuff, I'm still pretty new to Maya's python API. What I'm trying to do is to get the currently selected face normals average: What I achieved until now is an instance of a cube positioned according to the Move Manipulator. import maya.cmds as cmds import re #regular expression # get current position of the move manipulator pos = cmds.manipMoveContext('Move', q=True, p=True) # get the current selection selection = cmds.ls(sl=True) # trying to get the face normal angles of the current selection polyInfo = cmds.polyInfo(selection, fn=True) polyInfoArray = re.findall(r"[\w.-]+", polyInfo[0]) # convert the string to array with regular expression polyInfoX = float(polyInfoArray[2]) polyInfoY = float(polyInfoArray[3]) polyInfoZ = float(polyInfoArray[4]) print str(polyInfoX) + ', ' + str(polyInfoY) + ', ' + str(polyInfoZ) target = cmds.polyCube() cmds.move(pos[0], pos[1], pos[2], target) Now what I only need is to rotate the cube to the face average normals of the selection Please, any thoughts about this? Maya does have any method to give me those angles? I tried to rotate using polyInfo with face normals, but I think I'm missing something... EDIT: The final solution (thanks to @theodox) import maya.cmds as cmds # get current position of the move manipulator pos = cmds.manipMoveContext('Move', query=True, position=True) # get the current selection selection = cmds.ls(selection=True) target = cmds.polyCube() cmds.move(pos[0], pos[1], pos[2], target) constr = cmds.normalConstraint(selection, target, aimVector = (0,0,1), worldUpType= 0) cmds.delete(constr) A: You can achieve what you want without solving the issue in the question. The normalConstraint node will orient an object towards the closest available face normal. If you just want the face alignment, you can position your object and then create and immediately delete a normalConstraint. A minimal version would be: constr = cmds.normalConstraint('reference_object', 'object_to_align', aimVector = (0,0,1), worldUpType= 0) cmds.delete(constr) where the aim vector is the local axis that will be aligned to the surface. (There are a lot of options for how to do the alignment, you should check the docs in the normalConstraint command for more). To actually get the face normal, you can use the polyNormalPerVertex command to get the vertex-face normals for a face (they'll come back as numbers so you don't need to regex it. You will need to average them: def face_normal(face): vtxface = cmds.polyListComponentConversion(face, tvf = True) xes = cmds.polyNormalPerVertex(vtxface, q=True, x =True) yes = cmds.polyNormalPerVertex(vtxface, q=True, y =True) zes = cmds.polyNormalPerVertex(vtxface, q=True, z =True) divisor = 1.0 / len(xes) return sum(xes)* divisor, sum(yes) * divisor, sum(zes) * divisor However those are in local space. The only way to convert them to world space is to turn them into a vector (using Pymel or the Maya api) and then multiply them against the object matrix (also using the API). Once you have a world space vector you can construct a new matrix using that vector as the 'aim vector', the world up, and the cross vector of those as a new matrix for the object you want to align.. ... all of which is not super hard but it's a lot of work if you don't know the API well yet. Which is why I'd try the normalConstraint trick first.
{ "pile_set_name": "StackExchange" }
Q: Using cygwin and rsync -- "password file must not be other-accessible" I've finally got an old computer of mine running as a backup server with Ubuntu 11.10. I'm planning on using it to backup my Windows 7 machine weekly using rsync. I've got cygwin installed, and rsync works perfectly. I'm following this guide, though, to create it as a scheduled task: http://justinsomnia.org/2007/02/how-to-regularly-backup-windows-xp-to-ubuntu-using-rsync/ I have an rsync.bat script in C:\, and I can get the script to run correctly if I run it directly from the command line in Cygwin. However, when I try to run the rsync.bat script, I get this: ERROR: password file must not be other-accessible So it must be permissions issues on the secret file...I followed that guide and set the permissions to 600, and chowned it to Nate[the administrator]:SYSTEM. Any ideas on what might be causing the problem? EDIT: The file in question is actually on the Windows 7 machine. I figured I should ask here, since I'm dealing specifically with Cygwin and Rsync. After some googling, I found that there is a "strict modes" option that tells rsync not to check the permissions on the secret files, and that was added to accomodate Windows systems. However, after adding it and restarting the rsyn daemon, I still seem to be getting the same error. Here's my rysncd.conf file: [rsync] path = /home/nate/backups comment = My backups uid = nate gid = nate read only = false auth users = nate secrets file = /etc/rsyncd.secrets strict modes = false And the permissions on the secrets file, according to cygwin: -rw------- 1 Nate SYSTEM 11 Dec 9 18:48 secret I feel like I must be missing something really obvious. A: I was able to fix this issue by changing the password-file line to the following: –password-file=/cygdrive/c/cygwin/secret
{ "pile_set_name": "StackExchange" }
Q: Run the AlgoTrader in Eclipse I am trying to run the AlgoTrader in Eclipse but I get two errors The only problem now is when I run the SimulationStarter class I get the following error: 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl initialized service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module market-data on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module current-values on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module trades on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module portfolio on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module performance on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module algo on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module ib-market-data on service provider: BASE 1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module ib-trades on service provider: BASE Exception in thread "main" com.algoTrader.service.SimulationServiceException: Error performing 'SimulationService.simulateWithCurrentParams()' --> com.algoTrader.service.SimulationServiceException: Error performing 'SimulationService.runByUnderlayings()' --> com.algoTrader.service.RuleServiceException: Error performing 'RuleService.initServiceProvider(String strategyName)' --> com.espertech.esper.client.EPException: esper-mov.cfg.xml not found at com.algoTrader.service.SimulationServiceBase.simulateWithCurrentParams(SimulationServiceBase.java:246) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy12.simulateWithCurrentParams(Unknown Source) at com.algoTrader.starter.SimulationStarter.main(SimulationStarter.java:29) Caused by: com.espertech.esper.client.EPException: esper-mov.cfg.xml not found at com.espertech.esper.client.Configuration.getResourceAsStream(Configuration.java:928) at com.espertech.esper.client.Configuration.getConfigurationInputStream(Configuration.java:784) at com.espertech.esper.client.Configuration.configure(Configuration.java:767) at com.algoTrader.service.RuleServiceImpl.handleInitServiceProvider(RuleServiceImpl.java:81) at com.algoTrader.service.RuleServiceBase.initServiceProvider(RuleServiceBase.java:86) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy14.initServiceProvider(Unknown Source) at com.algoTrader.service.SimulationServiceImpl.handleRunByUnderlayings(SimulationServiceImpl.java:139) at com.algoTrader.service.SimulationServiceBase.runByUnderlayings(SimulationServiceBase.java:216) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy12.runByUnderlayings(Unknown Source) at com.algoTrader.service.SimulationServiceImpl.handleSimulateWithCurrentParams(SimulationServiceImpl.java:183) at com.algoTrader.service.SimulationServiceBase.simulateWithCurrentParams(SimulationServiceBase.java:242) ... 14 more I am able to run the MOV strategy in the cmd but I have been stuck here for a very long time! If anyone has any ideas or suggestions they would be much appreciated as this is very important for me and I have tried everything I could think of. A: For the first problem you can solve it when you add the after the build. <build> <pluginManagement> </pluginManagement> </build> The second one seems quite complex. Everyone that can solve it is machine
{ "pile_set_name": "StackExchange" }
Q: Why can not modify a map in foreach? I am new to Scala and use Spark to process data. Why does the following code fail to change the categoryMap? import scala.collection.mutable.LinkedHashMap val catFile=sc.textFile(inputFile); var categoryMap=LinkedHashMap[Int,Tuple2[String,Int]]() catFile.foreach(line => { val strs=line.split("\001"); categoryMap += (strs(0).toInt -> (strs(2),strs(3).toInt)); }) A: It's a good practice to try to stay away from both mutable data structures and vars. Sometimes they are needed, but mostly this kind of processing is easy to do by chaining transformation operations on collections. Also, .toMap is handy to convert a Seq containing Tuple2's to a Map. Here's one way (that I didn't test properly): val categoryMap = catFile map { _.split("\001") } map { array => (array(0).toInt, (array(2), array(3).toInt)) } toMap Note that if there are more than one record corresponding to a key then only the last one will be present in the resulting map. Edit: I didn't actually answer your original question - based on a quick test it results in a similar map to what my code above produces. Blind guess, you should make sure that your catFile actually contains data to process.
{ "pile_set_name": "StackExchange" }
Q: Modify the value of ${!i} All is in the title, this formula permit to show the value of {!i} but not to modify it, do you have any idea ? A: Use printf -v. $ x=foo $ foo=5 $ printf -v "$x" '%d' 9 $ echo "$foo" 9
{ "pile_set_name": "StackExchange" }
Q: shortcut "calc" meant to open calculator always open libreoffice ( first position in search ) When I search for an app with the windows keyboard key, I enter calc to open calculator, and I always have 2 results, LibreOffice, and Calculator. LibreOffice is always first, and I always open LibreOffice, which is not what I want. This is a many many times error, does anybody know how to prevent it ? Maybe changing the order of the 2 apps, or disabling LibreOffice for this search.... I don't know how to do none of them. A: You need to modify the related .desktop file for LibreOffice Calc and change the application's "name" to something else. Some hints on this process may be found here.
{ "pile_set_name": "StackExchange" }
Q: Fix point of function over disk Prove that there is a fix point of function $f:B(0,1) \to R^2$, where $B(0,1)$ is circle of radius 1, and $f(x,y)=\frac {1}{4}(ye^{x}-y,cosy)$. I tried to prove that f is contractive mapping (there is $0 < q < 1$ such that $d(f(a),f(b)) \leq qd(a,b)$), and than use Banach theorem. A: Maybe just without Banach's fixed-point theorem. At first we know that \begin{align} 0 - \frac{1}{4} \cos(0) = - \frac{1}{4} < 0 \,\,\, \text{ and } \,\,\,\frac{\pi}{4} - \frac{1}{4} \cos\left(\frac{\pi}{4}\right) = \frac{\pi}{4} - \frac{1}{4 \sqrt{2}} > 0. \end{align} The intermediate value theorem then yields existence of some element $y_0 \in (0, \frac{\pi}{4})$ such that \begin{align} y_0 = \frac{1}{4}\cos(y_0). \end{align} Simply choosing $x_0 = 0$ gives \begin{align} \frac{1}{4}\left( y_0 \text{e}^{x_0} - y_0 \right) = x_0. \end{align} Since $(x_0, y_0) \in B(0,1)$ for obvious reasons we have found a fixed point.
{ "pile_set_name": "StackExchange" }
Q: How to change the default rolling time in spdlog daily logger? Using spdlog, how can I change the default rolling time of the daily logger? In the following example, the rolling happens only at midnight: auto logger = spd::daily_logger_st("my_logger", "fl_log.txt"); A: Currently there is no direct way to change the rotation time in the daily logger - please open an issue here.. A quick workaround would be to modify the _calc_midnight_tp() function to return the desired rotation time instead of midnight in the daily_file_sink class.. For example to rotate in 1am instead of midnight: static std::chrono::system_clock::time_point _calc_midnight_tp() { using namespace std::chrono; auto now = system_clock::now(); time_t tnow = std::chrono::system_clock::to_time_t(now); tm date = spdlog::details::os::localtime(tnow); date.tm_min = date.tm_sec = 0; date.tm_hour = 1; auto rotate_time = std::chrono::system_clock::from_time_t(std::mktime(&date)); return system_clock::time_point(rotate_time + hours(24)); } Edit: I committed a fix to this issue. Now user can set HH:MM of the desired rolling time
{ "pile_set_name": "StackExchange" }
Q: File::copyDirectory return nothing I'm able to copy files using Storage::copy but when i tried to copy folder with File::copyDirectory, it doesn't change anything. Why is that? My Code: public function pasteDocument(Request $request) { if(Session::get('clipboard') == "copy"){ // copy to disk File::copyDirectory('public\img', 'public\js', true); } return redirect()->back(); } A: You need to pass full paths to copyDirectory(): File::copyDirectory(public_path('img'), public_path('js'), true);
{ "pile_set_name": "StackExchange" }
Q: NullReferenceException from DataVisualization.Charting.Axis.GetLinearPosition() I have created a form that displays a chart using Microsoft's DataVisualization.Charting.Chart control (I use version 4 of the .NET framework). I also draw some annotations on the chart, and to locate them I need to know about the chart axes. The code myChart.ChartAreas[0].AxisX.ValueToPixelPosition(location) gives me a NullReferenceException. The chart is definitely instantiated and I can set properties of the AxisX- for instance, myChart.ChartAreas[0].AxisX.Maximum = 1 works fine. Drilling into the exception message, it looks like the trouble is in the GetLinearPosition method, which is something internal to the Chart control: at System.Windows.Forms.DataVisualization.Charting.Axis.GetLinearPosition(Double axisValue) at System.Windows.Forms.DataVisualization.Charting.Axis.GetPosition(Double axisValue) at System.Windows.Forms.DataVisualization.Charting.Axis.ValueToPixelPosition(Double axisValue) Does anyone have any insight to get me started fixing this? Thanks in advance! A: This answer came in a comment to the question from Hans Passant: That rings a bell. I think the trouble is that this can't work until the control has figured out its data-to-display mapping. Which doesn't happen until it needs to paint itself, in typical lazy fashion. Call Update() first, something like that. Which got me far enough to make this discovery: You figured it out, Hans. The chart is on a TabControl tab, and I had to bring that tab to front (with the TabControl.SelectedTab property) before making the call to ValueToPixelPosition.
{ "pile_set_name": "StackExchange" }
Q: syntax error in SELECT statement With my limited SQL knowledge, I'm unable to figure this out. What's wrong with the following: DECLARE @Id int DECLARE @Name varchar(40) WHILE EXISTS ( SELECT TOP 1 @Name = Name, @Id=ID FROM MyTable c WHERE <CONDITION> ) BEGIN SOME MORE SQL using @Id and @Name END I get a syntax error near @Name = Name EDIT To add more context to the problem, I have two tables named Category (ID, Name, ParentID) and Account(ID, Name, CategoryID). There are 3 levels of Categories. Root Category SubCategory This is achieved using a recursive relation (ParentID > CategoryID). Problem to solve is that if there are any Accounts that belongs to a Category X (level 2), we must Create a SubCategory Y (level 3) with the same name as X Make Y a child of that X Move all Accounts from X to Y Here is the original script I have written: DECLARE @Id int DECLARE @Name varchar(40) WHILE EXISTS( SELECT TOP 1 @Name=Name, @Id=CategoryID FROM Category c WHERE ParentID = (SELECT TOP 1 CategoryID FROM Category WHERE Name = 'Root') AND (SELECT COUNT(*) FROM Account WHERE CategoryID = c.CategoryID) > 0 ) BEGIN INSERT INTO Category(Name, ParentID) VALUES(@Name, @Id) UPDATE Account SET CategoryID = @@IDENTITY WHERE CategoryID = @Id END A: You could use CURSOR loop: CREATE TABLE MyTable(ID INT, Name VARCHAR(100)); INSERT INTO Mytable(ID, Name) VALUES (1,10),(2,20); DECLARE @Id int; DECLARE @Name varchar(40); DECLARE cur CURSOR FAST_FORWARD FOR SELECT Name,ID FROM MyTable c WHERE 1=1; OPEN cur; FETCH NEXT FROM cur INTO @Id, @Name; WHILE @@FETCH_STATUS = 0 BEGIN SELECT @Id,@Name; FETCH NEXT FROM cur INTO @Id, @Name; END; CLOSE cur; DEALLOCATE cur; LiveDemo Please note that TOP 1 without explicit ORDER BY may produce different results between executions. EXISTS: EXISTS subquery Note that SELECT @ID = id, @Name = Name is not subquery but assignment. CREATE TABLE MyTable(ID INT, Name VARCHAR(100)); INSERT INTO Mytable(Id, Name) VALUES (1,10),(2,20); DECLARE @Id int; DECLARE @Name varchar(40); SELECT 1 WHERE EXISTS (SELECT @id = id FROM Mytable); -- assignment -- Incorrect syntax near '='. SELECT 1 WHERE EXISTS (SELECT id FROM Mytable); -- subquery LiveDemo 2
{ "pile_set_name": "StackExchange" }
Q: authClient.login returning error with "Unauthorized request origin" This just started happening within the past few days, and my code hasn't changed. Have I made a mistake, or is this new? It seems like it's implying there's a rule I should be adding to my security rules in firebase forge to allow access from the domain I'm working on (in this case localhost), but I don't know where to find that documentation. Can anyone help? How do I get past this error? A: With the release of Firebase Simple Login, which contains a number of OAuth-based authentication methods (Facebook, Twitter, GitHub, etc.), we included the idea of 'Authorized Origins'. Without this restriction, malicious sites could pretend to be your application and attempt to access your users' Facebook, Twitter, etc. data on your behalf. By restricting the domains for these requests to ones that you control and have verified, we can protect your users' data. To fix this error, log into Firebase Forge (by dropping your Firebase URL into your browser), and navigate to the 'Auth' panel on the left. You can configure multiple application domains here, comma-delimited. If you're interested in testing locally, set 127.0.0.1 in your application domain configuration, and ensure that you're accessing pages via http://127.0.0.1/..., rather than http://localhost/.... I hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Get Particular value from result string What I received XML response is : <?xml version="1.0" encoding="utf-8"?> <response status="200"> <invoice_id>829584</invoice_id> </response> I want "invoice_id" from above data. So anyone please help for the same. Thanks. A: try it with: $xml = '<?xml version="1.0" encoding="utf-8"?> <response status="200"> <invoice_id>829584</invoice_id> </response>'; $xmldom = simplexml_load_string($xml); echo $xmldom->invoice_id->__toString(); for more detail have a look at Php simple load xml
{ "pile_set_name": "StackExchange" }
Q: Shortcircuited motorcycle alternator leads to RPM proportional losses? I've had this puzzle for a couple of years but never been able to figure it out. Regulator manufacturers for typical 3-phase alternators provide the 14.4V by 'shorting' the phases. Obviously this comes with great losses but I cannot understand why this design is still in use. My electromagnetic theory is basic but I assume that somehow after a certain angular velocity back emf induces positive torque into the rotor which lessens the braking effect. I did intend to test that on a bench but I assume some of you at least have tried it or know the theory behind it. Is there a graph somewhere that will show braking torque vs RPMs? This could also apply to wind generators. Edit: The stator is on the bike, contains several wound inductors connected into a 3-phase delta configuration. The flywheel connected to the engine/crankshaft has permanent magnets. The configurations I've seen had magnets inside the flywheel, which would then spin outside of the wound stator. Three wires from the stator go into the 'black box', another (usually) two wires come out. The rectifier part is a standard 6-diode bridge. Regulator part is a zener-like part that triggers the shunt to all three (incoming) phases simultaneously to the ground after the bridge. Shorting is done via thyristor-like parts, so the zener triggers the gate for the SCRs. Typical generator power is about 400W@9000rpm, typical regulator/rectifier rating is about 20A. They get really hot, especially when no consumers are turned on. I suspect also consumers (headlights) also play a role in smoothing the resulting waveform. A: This is an old thread but I thought I would add something as there seems to be a widespread misunderstanding of this and there is not much information on the web. I think the designers and manufacturers of these devices want to keep the general population in the dark. I think what most people are missing is that these "fixed field" permanent magnet alternators have an inherently poor load regulation curve. With no load the output voltage can vary from 20V at idle to well over 100V at high revolutions per minute. However as the load current is increased a magnetic field is created in the stator which is in opposition to the field of the permanent magnets. Thus even short circuited it will not produce more than 40A or so. When the short is made by an SCR with a voltage drop of 1-2V this is only about 80W. The SCR is only turned on for part of the a.c cycle as it only turns on when the battery voltage exceeds 14.4V. Before it turns on the current is being delivered to the battery and all the other loads, the SCR only turns on when the other loads cannot absorb the current. When the SCR does short the windings the current is so high the the field in the stator almost cancels out the permanent magnet field so the torque load on the engine is reduced. This may seem inefficient but remember even if the field was produced by a wound rotor with slip-rings and brushes like in a car alternator that would also require power and there would also be power lost in the regulator so it isn't as bad as would first appear.
{ "pile_set_name": "StackExchange" }
Q: Email user when their name has been added to a list item I have a sales leads list that users add a sales leads into. Salespersons will come in and view these sales and can edit them and add a name of another salesperson to the item in a 'refer to' column. Is it possible to notify a person when they have been added to the 'refer to' column and email them? A: We can achieve it by creating workflow in SharePoint, I am sharing the basic steps to for creating the workflows. In the explanation below I'm using SharePoint 2013 but it is absolutely same in SP2010 or/and on premises, and even in SP2007 the process is very similar. 1) You will need SharePoint Designer installed on your computer. For Creating workflow: 2) Open SharePoint designer 3) Open your site 4) Go to Workflows 5) Click 'List Workflow' on ribbon and select your list 6) Add 'Send email' action 7) Configure 'Send email' action to use refer to field for determining recipients of email. Also define the body block for the message. You can also use different lookups here, for example inserting values from the item or item URL, etc. 8) Now go to 'Workflow Settings' 9) Setup workflow to start whenever item is created or changed. 10) Publish your workflow. This workflow will send Email to the user in refer to field whenever list item will change. If you want to track only the change in refer to field then you need to create one more hidden field in your list as "previous refer to". You can add user name to this field using workflow. Every time after sending email notifications check this previous refer to and refer to is different or not. If they are different then send email and set "previous refer to" field. How to make hidden field: Create new person or group field named "previous refer to". Go to List Settings > Advanced Settings. Select Yes on Allow management of content types? Click on the existing content type under the Content Type section. Next, click on the column you intend to hide, and choose the option Hidden. Click OK. How to check if the field is empty in workflow: Set workflow variable to your "previous refer to" field. Add IF condition in workflow and check if the newly created variable is empty or not. Source: How to check Person or group field is empty or not.
{ "pile_set_name": "StackExchange" }
Q: Is there any vs. Are there any "Is there any notebook on the desk?" "There isn't any notebook on the desk." I read these sentences in a worksheet made by someone whose native language isn't English. Are these sentences grammatically correct? Because I thought any is used with aren't and are "Are there any notebooks on the desk?" "There aren't any notebooks on the desk." A: The two sentences do go together, and are grammatical, but they would only occur in the particular circumstance of persistent enquiry. Get a couple of notebooks from the pile on desk. — There isn't a pile of books. OK, just grab two notebooks. — I can't see two notebooks. Is there any notebook on the desk? — No, there isn't any notebook. There are only sandwiches. To find a context where "Is there any notebook on the desk?" and "There isn't any notebook" both work is not easy and ends up being quite contrived. If the sentences are supposed to stand alone, as a spontaneous enquiry and its answer, then we wouldn't normally use any: Is there a notebook on the desk? Can you get it for me? — No, there's no notebook. Any as a determiner usually indicates more than one object: Are there any notebooks on the desk? I need one. — No, there aren't any.
{ "pile_set_name": "StackExchange" }
Q: PHP - Upload file reset I'm facing an upload issue using PHP. I upload the file using a form and the input type file provided from HTML, and I have to upload large files (max size 500MB). I have edited my php.ini file in this way: max_execution_time = 7200; max_input_time = 7200; memory_limit = 500M; post_max_size = 500M; upload_max_filesize = 500M. I made many tests during the last weeks using small files (20 MB) and the upload was working fine. Now I want to simulate the worst situation, when the user have to upload large files. I noticed that when the user tries to upload files larger than 100MB the upload "resets". The page receives 2048000 bytes, then it restart from 0 and again, it resets when it reach 2048000 bytes. This happens for a couple of times then the upload stops. I tried also to edit my httpd.conf adding the line: LimitRequestBody 524288000 The problem is still present. How can I solve this? A: I found what the problem was. I never checked the nginx.conf file. There is the an option called client_max_body_size that has to be edited. In my case it was set to 100m (100MB), I changed it to 500m and I solved the problem.
{ "pile_set_name": "StackExchange" }
Q: while calling method showing variable undefine in lightning component This page has an error. You might just need to refresh it. Action failed: c:SComponent$controller$arResult [str is not defined] Failing descriptor: {c:SComponent$controller$arResult} when click on the button whatever text i have entered is showing in alert box which is correct but after alert i am setting parameter from setParams it's throwing error str is not defined. i have use this in this way :--> action.setParams({str,sear}); and this way -->action.setParams({"str",sear}); and everytime i am getting same error which is mentioned above. Apex Controller Code is below public class SearchController { @AuraEnabled public static List<Contact> archCon(String str){ List<contact> conList = new List<contact>(); if(Str != null){ conList = [SELECT id FirstName, LastName, phone FROM CONTACT WHERE FirstName =: str]; } return conList; } } Component code below <lightning:input type="text" aura:id="input1" label="Enter a text" /> <lightning:button label="Search Record" title="Search" onclick="{!c.arResult }"/> Component controller code is below ({ arResult : function(component, event, helper) { var sear = component.find("input1").get("v.value"); alert(sear); var action = component.get("c.archCon"); **action.setParams({str,sear});** action.setCallback(this, function(response){ if(response.getState()==="SUCCESS" && component.isValid()){ alert("From server: " + response.getReturnValue()); } }); $A.enqueueAction(action); } }) A: You should actually need to use JSON syntax to pass params using action.setParams() method. So in your case you need to pass it either like this: action.setParams({str:sear}); Or like this: action.setParams({"str":sear});
{ "pile_set_name": "StackExchange" }
Q: An issue with Vlookup Example I want in B11 to sum up all 1s (from CLIENT A) and in C11 the amount of appearance of CLIENT A (in this example four times). Same for CLIENT B in B12 and C12. A: Enter formula for B11 as =SUMIF(A$2:A$8,"="&A11,B$2:B$8). Then drag down to fill B12. Enter formula for C11 as =COUNTIF(A$2:A$8,"="&A11). Then drag down to fill C12. System Counter All ~~~~~~~~ ~~~~~~~ ~~~ CLIENT A 2 4 CLIENT B 2 3 For some locales, use ; instead of , as the formula delimiter. Documentation: SUMIF and COUNTIF.
{ "pile_set_name": "StackExchange" }
Q: Jquery Update Not Working I have this script that I have copied to my html file. When I run it on fiddle combined with my html, it works. But on my site, it doesn't. Is this the correct way to include it?: <!-- SCRIPT TO UPDATE PRICE --> <script type="text/javascript>"> $('#quantity').change(function(ev){ var price = $('#quantity').val() * 0.1; $('#price').html((price).toFixed(2)); }); </script> This is how I have linked my jquery: <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> HTML <!DOCTYPE html> <html lang="sv-se"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ReClam Tryckeri i Uppsala</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default"> <!-- Start of navigation menu div --> <div class="container"><!-- 1-Start of container div --> <!-- Brand and toggle get grouped for better mobile display --> <a class="navbar-brand navbar-right" href="../index.php">ReClam Tryckeri</a> <div class="navbar-header"><!-- 2-Start of navbar header div --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div><!-- 2-End of navbar header div --> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><!-- 3-Start of navbar collapse div --> <ul class="nav navbar-nav"> <!-- CHECK IF START PAGE ACTIVE OR NOT AND CREATE LINK --> <li><a href='../index.php'>Erbjudanden<span class='sr-only'>(nuvarande)</span></a></li><!-- <li><a href="#">Trycksaker</a></li> --> <!-- GET TRYCKSAKER MENU --> <!-- CHECK IF DROPDOWN ACTIVE OR NOT --> <li class='dropdown active'><!-- BUILD THE PARENT MENU (STATIC) --> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Trycksaker<span class="caret"></span></a> <ul class="dropdown-menu"> <!-- BUILDING THE CHILD ITEMS FROM DATABASE (DYNAMIC) --> <li><a href="trycksaker.php?product_id=1">Flyers</a></li> <li><a href="trycksaker.php?product_id=2">Affischer</a></li> <li><a href="trycksaker.php?product_id=3">Foldrar</a></li> <li><a href="trycksaker.php?product_id=4">Broschyrer</a></li> <li><a href="trycksaker.php?product_id=5">Visitkort</a></li> <li><a href="trycksaker.php?product_id=6">Korrkort</a></li> <li><a href="trycksaker.php?product_id=7">Visitkort</a></li> </ul> <!-- GET SUPPORT MENU --> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Support<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Hur beställer jag?</a></li> <li><a href="#">Tryckfiler</a></li> <li><a href="#">Villkor</a></li> <li role="separator" class="divider"></li> <li><a href="#">Kontakta oss</a></li> <li role="separator" class="divider"></li> <li><a href="#">Om oss</a></li> </ul> </div><!-- 3-End of navbar collapse div --> </nav><!-- End of navigation menu div --><!-- BUILD COLUMN SYSTEM FOR CROSSDEVICE USABILITY --> <div class="container"> <div class="row"> <div class="col-md-1 col-sm-0 col-xs-0"> </div> <div class="col-md-6 col-sm-0 col-xs-0"> <!-- BUILD PRODUCT INFO FROM DATABASE --> <article> <h3>Flyers</h3> <hr><h4 class='text-justify'>Flyers är vår benämning på trycksaker som består av ett plant ark.</h4> <!-- SCRIPT TO UPDATE PRICE --> <script type="text/javascript>"> $('#quantity').change(function(ev){ var price = $('#quantity').val() * 0.1; $('#price').html((price).toFixed(2)); }); </script> <!-- BUILDING THE ATTRIBUTE FORM FOR THE OPTIONS --> <hr> <form> <div class="form-group"> <!-- BUILDING THE FIRST OPTION STATIC--> <select class="form-control"> <option disabled selected value>Välj Format</option> <!-- OPTION 1 BUILDING THE CHILD ITEMS FOR THE ATTRIBUTES (DYNAMIC) --> <option>A4&nbsp;&nbsp;&nbsp;&nbsp;210x279mm</option> <option>A5&nbsp;&nbsp;&nbsp;&nbsp;148x210mm</option> <option>A6&nbsp;&nbsp;&nbsp;&nbsp;105x148mm</option> <option>A7&nbsp;&nbsp;&nbsp;&nbsp;74x105mm</option> <option>A8&nbsp;&nbsp;&nbsp;&nbsp;52x74mm</option> <option>Card&nbsp;&nbsp;&nbsp;&nbsp;85x55mm</option> <option>High&nbsp;&nbsp;&nbsp;&nbsp;75x210mm</option> <option>Stand&nbsp;&nbsp;&nbsp;&nbsp;100x210mm</option> <option>Square&nbsp;&nbsp;&nbsp;&nbsp;105x105mm</option> <option>Half&nbsp;&nbsp;&nbsp;&nbsp;105x210mm</option> <option>Long&nbsp;&nbsp;&nbsp;&nbsp;105x297mm</option> <option>Cd&nbsp;&nbsp;&nbsp;&nbsp;120x120mm</option> <option>Box&nbsp;&nbsp;&nbsp;&nbsp;148x148mm</option> <option>Frame&nbsp;&nbsp;&nbsp;&nbsp;160x160mm</option> <option>Dvd&nbsp;&nbsp;&nbsp;&nbsp;183x273mm</option> <option>Full&nbsp;&nbsp;&nbsp;&nbsp;210x210mm</option> </select> <br> <!-- BUILDING THE PRINT OPTION STATIC--> <select class="form-control"> <option disabled selected value>Välj Tryck</option> <!-- PRINT OPTION 1 BUILDING THE CHILD ITEMS FOR THE ATTRIBUTES (DYNAMIC) --> <option>4+0&nbsp;&nbsp;&nbsp;&nbsp;Ensidigt Färgtryck</option> <option>4+4&nbsp;&nbsp;&nbsp;&nbsp;Dubbelsidigt Färgtryck</option> </select> <br> <!-- BUILDING THE SECOND OPTION STATIC--> <select class="form-control"> <option disabled selected value>Välj Pappersvikt</option> <!-- BUILDING THE CHILD ITEMS FOR THE ATTRIBUTES (DYNAMIC) --> <option>90g/m²</option> <option>115g/m²</option> <option>135g/m²</option> <option>170g/m²</option> <option>250g/m²</option> <option>350g/m²</option> </select> <br> <!-- BUILDING THE THIRD OPTION STATIC--> <select class="form-control"> <option disabled selected value>Välj Papperstyp</option> <!-- BUILDING THE CHILD ITEMS FOR THE ATTRIBUTES (DYNAMIC) --> <option>Silk</option> <option>Gloss</option> </select> <br> <!-- BUILDING THE QUANTITY OPTION STATIC--> <select class="form-control" id="quantity" name="quantity" > <option disabled selected value>Välj Antal</option> <!-- BUILDING THE QUANTITY ATTRIBUTES (DYNAMIC) --> <option>250</option> <option>500</option> <option>750</option> <option>1000</option> <option>1500</option> <option>2000</option> <option>2500</option> <option>5000</option> <option>7500</option> <option>10000</option> <option>15000</option> <option>20000</option> <option>25000</option> </select> <br> <!-- CREATE THE INPUT FIELD FOR MARKING --> <input type="text" class="form-control" placeholder='Märk din order med ett arbetsnamn. Exempelvis "Inbjudan Fredde"'> <br> <!-- CREATE THE UPLOAD AND ORDER BUTTON --> <label class="btn btn-info btn-file"> Bifoga Tryckfiler <input type="file" style="display: none;"><span class="glyphicon glyphicon-upload"></span> </label> <div style="float: right;"> <button class="btn btn-primary">Lägg i varukorgen <span class="glyphicon glyphicon-shopping-cart"></span></button> </div> <!-- FINISHING THE OPTION FORM --> </div> <!-- CREATING THE CHOICE ALERT AREA --> <hr> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span>×</span></button> Priset uppdateras automatiskt när du gjort dina val ovan. </div> <div class="alert alert-info" role="alert" id="price" name="price"></div> <!-- CREATING THE PRICE AND IMAGE AREA --> </div> <div class="col-md-5 col-sm-12 col-xs-12"> <!-- CREATING THE LINK FOR IMAGE --> <img src='../images/Flyers.jpg' alt="Flyers"></div> <!-- ADD AN EMPTY DIV RIGHT FOR EMPTY WHITE SPACE ON DESKTOP --> <div class="col-md-1 col-sm-0 col-xs-0"> </div> </div> </article> </div><!-- End Container Div) --> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html> A: Move the script code inside document.ready(function(){..}) <script type="text/javascript>"> $(document).ready(function() { $('#quantity').change(function(ev){ var price = $('#quantity').val() * 0.1; $('#price').html((price).toFixed(2)); }); }) </script
{ "pile_set_name": "StackExchange" }
Q: Functions: Detirmining values a & b The problem $f(x)$ and $g(x)$ are defined over the real number set $\mathbb{R}$ as follows: $$ \begin{split} g(x) &= 1-x+x^2\\ f(x) &= ax+b \end{split} $$ If $g(f(x)) = 9x^2 - 9x + 3$, determine all the possible values of $a$ and $b$. Basically i'm completely thrown by this. How would you begin to work out the values of $a$ & $b$? What sort of tests? I get functions, but have just never been asked something like this, any help simplifying this would be much appreciated. I'm not looking for all the possible values of $a$ & $b$. Just someone to tell me what direction to go to find that out. Many thanks A: HINT: $g(x)= 1-x+x^2$ and $ f(x)=ax+b$ $\implies g(f(x))=g(ax+b)$ $=1-(ax+b)+(ax+b)^2=a^2x^2+x(2ab-a)+1-b+b^2$ Again, $g(f(x)) = 9x^2 - 9x + 3$ Equate the coefficients of the different powers of $x$
{ "pile_set_name": "StackExchange" }
Q: Adding JQuery or Javascript (not coffee.script) code to a Rails 3.2 app? I just finished Code School's intro course on JQuery, jQuery Air: First Flight. It was a great way to learn the basics of jQuery and when I was done I was all excited about adding some jQuery to my new little rails 3.2 app. How to make that happen isn't obvious, though. By default, rails 3.2 comes with the jquery-rails and coffee-rails gems. New 3.2 apps are all set up accept javascript and jquery in the form of coffee-script. While I'll learn coffee-script soon, right now all I've got is jquery. More specifically, should I add something like: <script type="text/javasript" src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> into the head of my app/views/layouts/application.html.erb file or is all that taken care of jquery-rails gem and the <%= javascript_include_tag "application" %> already there? Where in my app do I put the jQuery code? With every new controller I generate, rails 3.2 creates a nice [new_controller].js.coffee file in the app/assets/javascripts/ directory. Javascript doesn't work if I put it in that .coffee file. Anyone have any thoughts? A: Having experimented around and corresponded with the good folks at Code School, I've come up with the following answer with others may find useful: Rails 3.2 apps are ready made to accept coffeescript. Indeed, every new controller automatically generates a [new_controller].js.coffee file ready to accept one's new coffeescript. While I'll get to coffeescript soon enough, having just finished JQuery Air: First Flight, all I know is jQuery. Here's what one needs to do to add jQuery to one's Rails 3.2 app with default, asset pipeline settings: 1) Place javascript_include_tag(:application) in the app/views/layouts/application.html.erb file. Code School's Adam Fortuna notes that it is typical to put that line in the footer which sounds like good advice. That probably allows the rest of the page to load before the javascript. 2) In the 'app/assets/javascripts/' directory create a new file with the suffix .js which in my case was user.js. Note: Do not name your jQuery file the same as the automatically created .js.coffee file or it will not be read, probably because the coffeescript file alone will be. 3) Add your jQuery javascript to that file to your heart's content! It's already part of your 3.2 app, included with the jquery-rails gem. If others have insight into using jquery and javascript instead of coffee-script in a rails 3.2 app, please add. That said, my next step is to learn coffee-script!
{ "pile_set_name": "StackExchange" }
Q: Why is my While loop not working? I'm trying to make a game that gives you the chance to critical hit , normal hit or hit something. Now I think it has to do with the variable within the if/else. This is my code: var chance = parseInt(Math.random() * 10); var hpDummy = 10; while ( hpDummy >=1) { if(chance >= 5 && chance <7) { alert("You throw a punch at the dummy! You graze it's nose dealing 1 damage"); var hpDummy = hpDummy -1; } else if (chance >=7) { alert("You throw a punch at the dummy! You directly hit its jaw dealing 2 damage ! AMAZING shot ! "); var hpDummy = hpDummy -2; } else { alert("You completely miss the dummy almost hitting Welt !"); var hpDummy = hpDummy -0; } } A: Just put chance variable inside the function. If your chance variable has value less than 5 then it will become infinite loop. So try something like this var hpDummy = 10; while (hpDummy >= 1) { var chance = parseInt(Math.random() * 10); if (chance >= 5 && chance < 7) { alert("You throw a punch at the dummy! You graze it's nose dealing 1 damage"); var hpDummy = hpDummy - 1; } else if (chance >= 7) { alert("You throw a punch at the dummy! You directly hit its jaw dealing 2 damage ! AMAZING shot ! "); var hpDummy = hpDummy - 2; } else { alert("You completely miss the dummy almost hitting Welt !"); } } JS Fiddle Demo
{ "pile_set_name": "StackExchange" }
Q: Implementing Facebook FQL in Python It will probably be obvious soon enough, but I am new to coding and StackOverflow -- apologies if I come off as a bit oblivious. I have been trying to query Facebook with FQL out of a function on my views.py page in a Django app. I did have a working solution utilizing the Facebook Graph API, but it was ultimately a poor solution since I am aiming to retrieve the user’s newsfeed. While there are a number of answers relating to Facebook FQL in PHP, there are no explicit examples in Python. Instead, most of the questions are just related to the syntax of the query, and not how to actually integrate it into an actual function. The query I am looking to make is: SELECT post_id, app_id, source_id, updated_time, filter_key, attribution, message, action_links, likes, permalink FROM stream WHERE filter_key IN (SELECT filter_key FROM stream_filter WHERE uid = me() AND type = 'newsfeed’) As I understand, the best way to make this request is using Requests but frankly, I am just looking for a working solution. I considered posting some of my non-working code up here, but it has pretty much spiraled into a mess. Any help or direction is greatly appreciated! UPDATE Just wanted to document where I am at, with Sohan Jain's help, I've gotten to this point: def get_fb_post(request): user_id = UserSocialAuth.objects.get(user=request.user) api = facebook.GraphAPI(user_id.tokens) # response gets deserialized into a python object response = api.fql('''SELECT post_id, app_id, source_id, updated_time, filter_key, attribution, message, action_links, likes, permalink FROM stream WHERE filter_key IN (SELECT filter_key FROM stream_filter WHERE uid = me() AND type = 'newsfeed')''') print(response) data = {'profile': '...something...' } # what should be going in here? return HttpResponse(json.dumps(data), mimetype='application/json') In PyCharm I am getting the following (link to image if you prefer: http://i.stack.imgur.com/8sZDF.png): /Library/Python/2.7/site-packages/facebook.py:52: DeprecationWarning: django.utils.simplejson is deprecated; use json instead. from django.utils import simplejson as json In my browser I am getting this(image link again: http://i.stack.imgur.com/njXo8.png): GraphAPIError at /fbpost/ I am not sure how to fix the DeprecationWarning. I tried at the top of the file putting "from django.utils import simplejson as json" but that didn't work (I thought it was probably a bit too simplistic, but worth a shot). If I replace the query with this: response = api.fql("SELECT name, type, value, filter_key FROM stream_filter WHERE uid = me()") I do get a very long response that looks like this: [{u'filter_key': u'nf', u'type': u'newsfeed', u'name': u'News Feed', u'value': None}, {u'filter_key'... ...}] It goes on and on and does appear to be returning valid information. A: I have figured out how to get a response, the code looks something like this: from facepy import GraphAPI def get_fb_post(request): user_id = UserSocialAuth.objects.get(user=request.user) access_token = user_id.tokens graph = GraphAPI(access_token) data = graph.fql('''SELECT post_id, app_id, source_id, updated_time, filter_key, attribution, message, action_links, likes, permalink FROM stream WHERE filter_key IN (SELECT filter_key FROM stream_filter WHERE uid = me() AND type = 'newsfeed')''') return HttpResponse(json.dumps(data), mimetype='application/json') This is returning the information that I was looking for, which looks something like this: {u'data': [{u'filter_key': u'nf', u'permalink': u'facebook-link', u'attribution': None, u'app_id': u'123456789', u'updated_time': 1398182407, u'post_id': u'1482173147_104536679665087666', u'likes': ...etc, etc, etc.... Now, I am just going to try and randomize the displayed post by randomly iterating through the JSON -- granted, this is outside of the scope of my question here. Thanks to those who helped.
{ "pile_set_name": "StackExchange" }
Q: What does "hull weight" include? I am looking to purchase a small sailboat, and want to know if my girlfriend and I could lift the bare hull minus rigging to cartop it. Specs variously list the displacement or the "hull weight". I'm not sure if the "hull weight" includes the rigging, mast, sail(s), etc. All that stuff will probably weigh 20-30lbs, and lifting a 90lb hull vs lifting a 120lb hull will make a world of difference. A: As Rory states in his answer, hull weight is just the hull. But you need not worry, the mast, rudder, center board, sail, etc. Are usually loaded separately from the hull of the boat. For small two person sail boats, around 100 pound. All the parts except for a couple pieces of hardware come off. The mast slides in and out of a mounting well. The sail and spars either come loose, or fold up with the mast The center board (keel) slides in and out through a hole in the top (centreboard trunk) The rudder clips on and off (it should also fold up, but not all do) The rigging is some rope (line) that generally winds around the sail and spars for travel/storage. If they don't come off, keep looking. The added weight would be the least of your issues. Generally the bare boat is carried to shore, the mast and sail are mounted at the waters edge, the rudder is mounted and folded up. Once you have pushed off from shore the center board and rudder are lowered. Anything else would be a huge headache to try and maneuver. You may also want to consider a community sailing class. Local clubs often offer them for a vary reasonable price. A: The original meaning was the weight of the water displaced by the hull, but typically the hull weight is used to mean just the weight of the hull - minus fittings etc. Hopefully that helps solve your problem.
{ "pile_set_name": "StackExchange" }
Q: Can you use the Android Trace class from multiple threads? Are you able to use the Android Trace class (http://developer.android.com/reference/android/os/Trace.html) from multiple threads and have it log time doing operations on each of those threads appropriately? In particular, I have 2 threads that are each doing things and I'd like to visualize what each thread is doing at a given point in time using systrace. The docs for Trace only say that you should call #endSection from the same thread that called #beginSection, but it doesn't say whether multiple threads can be making their own calls to beginSection and endSection at the same time. Does anyone know if this is safe? A: It's safe. It writes a marker to the systrace device, which is shared across multiple processes and threads.
{ "pile_set_name": "StackExchange" }
Q: Computability of infinite-dimensional vector space So there is a talk about infinite-dimensional vector space being computable. But then I find it hard to understand. Apparently, dimension is infinite, so how would the operations of the space be computable? Is it something like $\pi$ being computable, although it has infinite number of digits? A: Short answer The general answer is that computability is easy for locally compact spaces, doable for separable spaces, and hard for non-separable spaces. The short anwer for a particular example, namely $\ell^2$ is: in order to get computability on $\ell^2$ working, represent an element $x$ of $\ell^2$ by a program which accepts $n$ and gives (the list of coefficients of) a finite rational linear combination of the standard basis vectors which is within $2^{-n}$ of $x$ in the $\ell^2$ norm. Long answer One general way of equipping a space $X$ with computability is to choose a datatype $\mathtt{T}$ in your favorite programming language (it can be Turing machines and tapes if you're into 1950's memorabilia, otherwise I would recommend a reasonable programming language such as Haskell), and a realizability relation $\vdash_X$ on $\mathtt{T} \times X$, where $\mathtt{d} \Vdash_X x$ means "datum $\mathtt{d}$ represents (implements, realizes) the point $x \in X$". For instance, if $X$ is the space of all finite graphs, then $\mathtt{T}$ could be the datatype of adjancency matrices. If $Y$ is another space with a computability structure, then a map $f: X \to Y$ is said to be computable or realized if there is a program $\mathtt{p}$ such that $\mathtt{d} \Vdash_X x$ implies $\mathtt{p}(\mathtt{d}) \Vdash_Y f(x)$, i.e., $\mathtt{p}$ does to the representing data what $f$ does to points. The most important principle to always keep in mind is that computability is about computability of structure, not computability of a bare set. For instance, it makes no sense to ask "Is $\pi$ computable?" or even "Which elements of $\mathbb{R}$ are computable?" You must first make up your mind about what structure of $\mathbb{R}$ you want to consider, and then see if you can make it computable. The correct computability structure on $\mathbb{R}$ turns out to be: arithmetical operations must be computable (including the constants $0$ and $1$) the order relation $<$ must be semidecidable, there is a program which, given $d \vdash_{\mathbb{R}} x$ and $k \in \mathbb{N}$, computes a rational approximation of $x$ with precision $2^{-k}$, the limit operator $\lim$ which assigns to every rapid Cauchy sequence of reals its limit, is computable. (A sequence $(x_n)$ is rapid if $|x_n - x_m| \leq 2^{-\min(n,m)}$ for all $m, n$. The point is that we need to have a known rate of convergence, any other rate would do just as well.) If you leave out anything, or try to add more, you will get into trouble by either having many non-equivalent computability structures on $\mathbb{R}$, or none. A datatype for representing reals for which all of the above can be implemented is $$\mathtt{nat} \to \mathtt{rational}$$ where a function $\mathtt{p}$ represents a real $x$ when, for every $n \in \mathbb{N}$, $\mathtt{p}(n)$ returns (a representatve of) a rational number $q$ such that $|x - q| \leq 2^{-n}$. (Such a function $\mathtt{p}$ may be represented by a Turing machine, or a piece of source code, or an expression in $\lambda$-calculus.) Let us now look at an infinite dimensional space $\ell^2$. It is a real Hilbert space with a countable orthonormal basis, so the relevant structure is: vector space structure: $0$, $+$, $-$ and scalar multiplication, the scalar product: $\langle {-}, {-} \rangle$ completeness: given a rapid Cauchy sequence $(x_n)$ in $\ell^2$, we can compute $\lim_n x_n$ basis: for every $x \in \ell^2$ we can compute a sequence $(\lambda_n)$ of real numbers such that $x = \sum_n \lambda_n \cdot e_n$ where $$e_n = (\underbrace{0, \ldots, 0}_n, 1, 0, 0, \ldots)$$ is the canonical orthonormal basis. Now the question is what datatype we should choose to represent $\ell^2$ so that all of the structure is computable. A simple one that works is $$\mathtt{nat} \to \mathtt{list}(\mathtt{rational}),$$ i.e, we can represent an element $x \in \ell^2$ with a function $\mathtt{p}$ that accepts a natural number and returns a finite list of rational numbers. The realizability relation is $$\mathtt{p} \Vdash_{\ell^2} x$$ is defined as follows: for every $n \in \mathbb{N}$, $p(n)$ is a list of rationals $[q_0, \ldots, q_m]$ such that $\|x - \sum_{i=0}^m q_i e_i\|_2 \leq 2^{-n}$. I leave it as an exercise to verify that with this representation we can indeed implement all of the structure of $\ell^2$, as stated above. Further reading (sorry for blowing my own horn): A. Bauer, J. Blanck: Canonical Effective Subalgebras of Classical Algebras as Constructive Metric Completions", J. UCS 16(18): 2496-2522 (2010)
{ "pile_set_name": "StackExchange" }
Q: Paso y recepcion de variables por GET [PHP] No puedo recoger mi variable $_GET correctamente. Tengo un boton que a traves de javascript me redirige a una url $(".btnSeeGlossary").click(function() { let idGlossary = $(this).attr("idGlossary"); window.location = "glossary?id=" + idGlossary; }) Una vez redirigido, digamos que la url quedo http://localhost/translateapp/glossary?id=6, estoy en el sitio maquetado, quiero obtener el id de la siguiente manera: $value = $_GET["id"]; var_dump($value); Var dump me retorna NULL =( Si cambio por $value = $_GET; var_dump($value); Value retorna "glossary" Edit: Dejo el htaccess por si esto pueda estar afectando. Options All -Indexes RewriteEngine On RewriteRule ^([-a-zA-Z0-9]+)$ index.php?route=$1 A: Finalmente, era el htaccess. Si reescribo las url debo agregar la bandera [QSA] RewriteRule ^([-a-zA-Z0-9]+)$ index.php?route=$1 [QSA] solucionó el problema.
{ "pile_set_name": "StackExchange" }
Q: Unpermitted parameters when uploading image with tinymce I'm using tinymce-rails-image-upload to upload images with paperclip (following this demo-app). When I try to upload an image I'm getting an 'umpermitted parameters' reminder and the image doesn't upload. The upload modal shows 'Got a bad response from server': Processing by TinymceAssetsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"auth token", "hint"=>"", "file"=>#<ActionDispatch::Http::UploadedFile:0x000001025a2780 @tempfile=# <File:/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207- 12522-9rj6xq>, @original_filename="applecash.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"applecash.jpg\"\r\nContent-Type: image/jpeg\r\n">, "alt"=>""} Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207-12522-9rj6xq[0]' 2>/dev/null Unpermitted parameters: utf8, authenticity_token (0.1ms) begin transaction Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE (questions.position IS NOT NULL) AND (1 = 1) ORDER BY questions.position DESC LIMIT 1 Binary data inserted for `string` type on column `file_content_type` SQL (0.8ms) INSERT INTO "questions" ("created_at", "file_content_type", "file_file_name", "file_file_size", "file_updated_at", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["file_content_type", "image/jpeg"], ["file_file_name", "timcook.jpg"], ["file_file_size", 120040], ["file_updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["position", 9], ["updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00]] (7.3ms) commit transaction Completed 200 OK in 68ms (Views: 0.6ms | ActiveRecord: 8.7ms) Here's the controller: class TinymceAssetsController < ApplicationController respond_to :json def create geometry = Paperclip::Geometry.from_file params[:file] question = Question.create params.permit(:file, :alt, :hint) render json: { question: { url: question.file.url, height: geometry.height.to_i, width: geometry.width.to_i } }, layout: false, content_type: "text/html" end end and the question model: class Question < ActiveRecord::Base has_attached_file :file end and the view: <%= simple_form_for [@comment, Question.new] do |f| %> <%= f.text_area :body, :class => "tinymce", :rows => 10, :cols => 60 %> <% end %> <%= tinymce plugins: ["uploadimage"] %> A: It's ok to not permit some of the parameters, so Unpermitted parameters: utf8, authenticity_token is a reminder, not an exception. I suggest you log what are question model instance errors: question = Question.create params.permit(:file, :alt, :hint) logger.debug question.errors.full_messages
{ "pile_set_name": "StackExchange" }
Q: How to access each channel of a pixel using cuda tex2D I'm learning cuda texture memory. Now, I got a opencv Iplimage, and I get its imagedata. Then I bind a texture to this uchar array, like below: Iplimage *image = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3); unsigned char* imageDataArray = (unsigned char*)image->imagedata; texture<unsigned char,2,cudaReadModeElementType> tex; cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(8, 8, 8, 0, cudaChannelFormatKindUnsigned); cudaArray *cuArray = NULL; CudaSafeCall(cudaMallocArray(&cuArray,&channelDesc,width,height)); cudaMemcpy2DToArray(cuArray,0,0,imageDataArray,image->widthstep, width * sizeof(unsigned char), height, cudaMemcpyHostToDevice); cudaBindTextureToArray(texC1_cf,cuArray_currentFrame, channelDesc); Now I lanch my kernel, and I want to access each pixel, every channel of that image. This is where I get confused. I use this code to get the pixel coordinate (X,Y): int X = (blockIdx.x*blockDim.x+threadIdx.x); int Y = (blockIdx.y*blockDim.y+threadIdx.y); And how can I access each channel of this (X,Y)? what's the code below return? tex2D(tex, X, Y); Besides this, Can you tell me how texture memory using texture to access an array, and how this transform looks like? A: To bind a 3 channel OpenCV image to cudaArray texture, you have to create a cudaArray of width equal to image->width * image->nChannels, because the channels are stored interleaved by OpenCV. cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<unsigned char>(); cudaArray *cuArray = NULL; CudaSafeCall(cudaMallocArray(&cuArray,&channelDesc,width * image->nChannels,height)); cudaMemcpy2DToArray(cuArray,0,0,imageDataArray,image->widthstep, width * image->nChannels * sizeof(unsigned char), height, cudaMemcpyHostToDevice); cudaBindTextureToArray(texC1_cf,cuArray_currentFrame, channelDesc); Now, to access each channel separately in the kernel, you just have to multiply the x index with number of channels and add the offset of desired channel like this: unsigned char blue = tex2D(tex, (3 * X) , Y); unsigned char green = tex2D(tex, (3 * X) + 1, Y); unsigned char red = tex2D(tex, (3 * X) + 2, Y); First one is blue because OpenCV stores images with channel sequence BGR. As for the error you get when you try to access texture<uchar3,..> using tex2D; CUDA only supports creating 2D textures of 1,2 and 4 element vector types. Unfortunately, ONLY 3 is not supported which is very good for binding RGB images and is a really desirable feature.
{ "pile_set_name": "StackExchange" }
Q: Extract matrix from batch, represented as Tensor I'm using Tensorflow in C++. I'm using a trained model to extract patches from an input image. My output tensor (after session Run) is outputs and has in outputs[0] a batch of N patches, MxMxD. auto patches = outputs[0].tensor<float, 4>(); Now, I want to display this images using OpenCV, in particular, I want to use the cv::eigen2cv function, that given an Eigen::Matrix gives me a cv::Mat. The problem is that I need to loop over this output tensor and for each element, extract an Eigen::Matrix. I've tried the proposed solution, here: https://stackoverflow.com/a/39475756/2891324 but I can't even compile the code because of Eigen error: EIGEN_STATIC_ASSERT_VECTOR_ONLY: const auto patch_side = 256; int batch_id = 0; using Matrix = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; for (auto i = 0; i < grid_shape.second; ++i) { for (auto j = 0; j < grid_shape.first; ++j) { auto size = patch_side * patch_side * depth; auto map = Eigen::Map<Matrix>(patches.data() + batch_id * size, size); // Eigen::Matrix4f m = map; Matrix m = map; cv::Mat p; cv::eigen2cv(m, p); cv::imshow("p", p); cv::waitKey(); /* ml(cv::Rect(i * patch_side, j * patch_side, patch_side, patch_side)) = cv::Mat(cv::Size(patch_side, patch_side), CV_32F, patches.slice patches.data() + (i + j) * patch_side * patch_side); */ std::cout << "i,j" << i << "," << j << "\n"; batch_id++; } } So, how can I get a Matrix from a Eigen::Tensor (or tf::Tensor) that I'll be able to use into cv::eigen2cv? A: Looking a bit around the documenation of OpenCV, and considering TensorFlow tensors are always row-major, you should be able to just do something like: const auto patch_side = 256; int batch_id = 0; for (auto i = 0; i < grid_shape.second; ++i) { for (auto j = 0; j < grid_shape.first; ++j) { auto size = patch_side * patch_side * depth; cv::Mat p(patch_side, patch_side, CV_32FC(depth), patches.data() + batch_id * size); cv::imshow("p", p); cv::waitKey(); /* ml(cv::Rect(i * patch_side, j * patch_side, patch_side, patch_side)) = cv::Mat(cv::Size(patch_side, patch_side), CV_32F, patches.slice patches.data() + (i + j) * patch_side * patch_side); */ std::cout << "i,j" << i << "," << j << "\n"; batch_id++; } } Note this does not copy the tensor data but rather creates a cv::Mat that points to it.
{ "pile_set_name": "StackExchange" }
Q: How can I use collections with the excel com interface from visual works Using the Excel COM automation interface I can set value in a cell by doing: excel := COMDispatchDriver createObject: 'Excel.Application'. excel getWorkbooks Add. excel setVisible: true. (excel getRange: 'A1') setValue: 100 Is there a way I can do this with a collection, something like: excel := COMDispatchDriver createObject: 'Excel.Application'. excel getWorkbooks Add. excel setVisible: true. (excel getRange: 'A1:A4') setValue: #(1 2 3 4) A: ExcelApplicationController | cont | cont := (Examples.Excel97ApplicationController new). [ cont addWorkbook. cont isVisible: true. "Insert the title of our report." cont caption: 'First Quarter Results'. cont setRange: 'B5:E9' to: #( #( 10 20 30 40 ) #( 1 2 3 4 ) #( 101 201 301 401) #( 102 203 305 407 ) ). ] ensure:[ cont notNil ifTrue: [ cont release. cont := nil ] ]
{ "pile_set_name": "StackExchange" }
Q: How to indicate the last indice in a PHP array? I have a simple mail() script that sends to multiple emails dynamically by seperating the emails with commas. <?php $sendto = array("[email protected]", "[email protected]", "[email protected]"); foreach ($sendto as $email) { if ($email is the last indice in the array..) // <-- here $to = $email; else $to = $email . ', '; } $subject = "test message"; $msg = "this is a test"; if (mail($to, $subject, $msg)) echo "message sent"; else echo "uh oh"; ?> How do I identify if (this is the last piece of data in my array) ? A: No need. $to = implode(', ', $sendto); A: php includes implode or join which will work much better here: $to = implode(', ', $sendto);
{ "pile_set_name": "StackExchange" }
Q: Phonegap Consuming Web Service PHP The next problem is try to consume a web service. I try with plugins and pure xml but the result still be "NULL". The code is this. function soap(imei,clave) { var divToBeWorkedOn = "#res"; var webServiceURL = ''; var parameters = '<?xml version="1.0" encoding="utf-8"?> \ <soap:Envelope xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:xsd=" http://www.w3.org/2001/XMLSchema " xmlns:soap=" http://schemas.xmlsoap.org/soap/envelope/"> \ <soap:Body> \ <registra_imei> \ <request> \ <imei>'+imei+'</imei> \ <clave>'+clave+'</clave> \ </request> \ </registra_imei> \ </soap:Body> \ </soap:Envelope>'; $.ajax({ type: "Post", url: webServiceURL, data: parameters, contentType: "text/xml; charset=\"utf-8\"", dataType: "xml", success: function(msg) { alert("funciono "+msg); }, error: function(e){ alert("error"); } }); } The Web services is a simple SOAP PHP. Just I need send the variables and then get a response that will be a code (1, 2 or 3). The requeriment from the event "registra_imei" are this: Name: registra_imei Binding: SOAPBinding Endpoint: SoapAction: urn:soapwsdl#registra_imei Style: rpc Input: use: encoded namespace: urn:soapwsdl encodingStyle: http://schemas.xmlsoap.org/soap/encoding/ message: registra_imeiRequest parts: imei: xsd:string clave: xsd:string Output: use: encoded namespace: urn:soapwsdl encodingStyle: http://schemas.xmlsoap.org/soap/encoding/ message: registra_imeiResponse parts: return: xsd:int Namespace: urn:soapwsdl Transport: http://schemas.xmlsoap.org/soap/http Documentation: Registra imei A: My comment is too long to post it into the comment area. So, using SoapUI i simulated a call to your WSDL and i got this as a RAW response: HTTP/1.1 200 OK Date: Tue, 14 Apr 2015 19:44:24 GMT Server: LiteSpeed X-Powered-By: PHP/5.4.39 Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept Set-Cookie: PHPSESSID=870fgce5tm1ep8get75066i491; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: text/html; charset=utf-8 Content-Length: 0 This is the SOAP request: <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:soapwsdl"> <soapenv:Header/> <soapenv:Body> <urn:registra_imei soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <imei xsi:type="xsd:string">65656565</imei> <clave xsi:type="xsd:string">123</clave> </urn:registra_imei> </soapenv:Body> </soapenv:Envelope> RAW request: POST http://soap.movilaccesscloud.cl/serversoap.php/ HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "urn:soapwsdl#registra_imei" Content-Length: 508 Host: soap.movilaccesscloud.cl Proxy-Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) Apparently, the error is in the back-end of your webservice. Check your PHP code, if possible please share part of the code. I repeat, my intention was to put the comment in the proper area, but as you can see it´s too long. :)
{ "pile_set_name": "StackExchange" }
Q: Retrieve a select element options list that has been re-ordered with JavaScript I have a Dictionary of names/numbers that are passed through to my View from my Controller. This becomes: Model.arrayPositions[x] These are then added to a select list: <form> <div class="col-xs-12"> <select id="ListIn" class="select-width" name="SelectionIn" multiple="multiple" size="@Model.arrayPositions.Count"> @foreach (var item in Model.arrayPositions) { if (item.Value != null) { <option class="active" value="@item.Value">@Html.DisplayFor(modelItem => @item.Key)</option> } } </select> </div> </form> Array items with no value are ignored, the rest is added to the list. Items can then be added/removed or moved up/down the list using JavaScript: function AddSelected() { $('#ListOut option:selected').each(function (i, selected) { $('#ListIn').append('<option class="active" value="1">' + selected.innerText + '</option>'); selected.remove(); }); } function RemoveSelected() { $('#ListIn option:selected').each(function (i, selected) { $('#ListOut').append('<option class="inactive" value="-1">' + selected.innerText + '</option>'); selected.remove(); }); function MoveUp() { var select1 = document.getElementById("ListIn"); for (var i = 0; i < select1.length; i++) { if (select1.options[i].selected && i > 0 && !select1.options[i - 1].selected) { var text = select1.options[i].innerText; select1.options[i].innerText = select1.options[i - 1].innerText; select1.options[i - 1].innerText = text; select1.options[i - 1].selected = true; select1.options[i].selected = false; } } } (Moving down is pretty much just the opposite of Moving up) (#ListOut is simply a second list that has the array items with a value of null added to it) (The final value is not too important right now, so I'm not specifically retaining it. The order of the list is more important) I'm changing the order using Javascript to avoid having the page refresh constantly for such a simple action. However, once I press an update button I'll have a call to my Controller (ASP.NET Core in C#). What I am wondering is how I could retrieve the final values of the list in the new order. i.e. If Model.arrayPositions = {a=1,b=2,c=null,d=3}, it would add them to the list as: [a,b,d] I then use javascript to remove 'a' and move 'd' up, resulting in [d,b] When I press the update button I would like the retrieve the current list of [d,b] from the View. What would be the best way to achieve this? Or, alternatively, what other methods might be used to achieve the same goal (note that I wouldn't want page refreshes or partial refreshes if possible). A: You can use ajax method to hit your controller on the click of your update button syntax of jquery ajax is:- <script> $.ajax({ type:'POST', url : 'controllerNAME/ActionNAME', datatype: 'json', data : {'parameterOne': parameterone, 'parameterTwo' : parametertwo,...}, success : function(response) { alert(response.d) //put your logic here for further advancements } }); </script>
{ "pile_set_name": "StackExchange" }