text
stringlengths
15
59.8k
meta
dict
Q: Jquery Keypres function not working FireFox I have the following JQuery function which validates a text field for numbers and one decimal only. It works fine in Crome but its not working in Firefox. Anyone know how i achieve the same in Firefox? $('#amount').keypress(function(event) { checkAmount(event, $(this)); }); function checkAmount(event, inputBox){ if((event.which != 46 || $(inputBox).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } }; A: Documentation says: Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms. You may want to use $.keydown.
{ "language": "en", "url": "https://stackoverflow.com/questions/22639195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make my program work when not in focused (background)? I made a small application for myself that is running how it should, but I cant for the life of me figure out how to allow/force it to accept input when not the window in focus. The program counts the presses of one of the buttons on my gamepad and updates the count on the window, but both the game and my application need to be in focus to recieve input. I made this in pygame as it allowed me to map the gamepad button easily, but if anyone knows a way to make it functionally the same while allowing the game and the application to record at the same time, it would be appreciated import pygame from sys import exit pygame.init() j = pygame.joystick.Joystick(0) j.init() count = 0 #Making the Window display_surface = pygame.display.set_mode((350, 200)) pygame.display.set_caption('Reset Counter') font = pygame.font.Font('freesansbold.ttf', 32) text = font.render(("Reset Count: "+str(count)), True, (255, 0, 0)) textRect = text.get_rect() textRect.center = (350 // 2, 200 // 2) display_surface.fill((255, 255, 255)) display_surface.blit(text, textRect) pygame.display.update() while True: events = pygame.event.get() pygame.event.set_grab(False) for event in events: #Looking for button 15 on my Gamepad if event.type == pygame.JOYBUTTONDOWN: if j.get_button(15): count = count + 1 #Updating Text text = font.render(("Reset Count: "+str(count)), True, (255, 0, 0)) display_surface.fill((255, 255, 255)) display_surface.blit(text, textRect) pygame.display.update() #Functional Close Button elif event.type == pygame.QUIT: pygame.quit() exit() A: You have to set to set SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS before Pygame and the joystick module is initialized: import os os.environ["SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"] = "1" import pygame pygame.init()
{ "language": "en", "url": "https://stackoverflow.com/questions/75142202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Docker DNS server on other nodes The new version of Docker (version 1.10) includes a DNS server to pass alias information from other hosts on the same network. There used to be hosts file entries for resolving linked containers (or containers on the same network). I am wondering if it is possible to use this embedded DNS server on an overlay network? I have looked in the documentation (and in issues) and cannot find information about this. A: So the way the new embedded DNS "server" works is that it isn't a formal server. It's just an embedded listener for traffic to 127.0.0.11:53 (udp of course). When docker sees that query traffic on the container's network interface, it steps in with its embedded DNS server and replies with any answers it might have to the query. The documentation has some options you can set to affect how this DNS server behaves, but since it only listens for query traffic on that localhost address, there is no way to expose this to an overlay network in the way that you are thinking. However this seems to be a moving target, and I have seen this question before in IRC, so it may one day be the case that this embedded DNS server at least becomes pluggable, or possibly exposable in the way you would like.
{ "language": "en", "url": "https://stackoverflow.com/questions/35885780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel selecting last value in range for a updated list macro I'd appreciate help with the following.... I'm using a validation list function, but I will need people to add to the list easily. So I recorded a macro and will link it from a button, so they just need to add a new value and click the button. The problem is I need it to find the last populated cell in that column. I've looked online and on here, but because I'm completely new to VBA I can't figure out how to edit it. Here is the code, I need it to select D4 to the last populated value in column D. Range("F5").Select ActiveCell.SpecialCells(xlCellTypeSameValidation).Select With Selection.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=Filters!$D$4:$D$21" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With Range("G15").Select Thanks!! A: Not sure if this it what you want but here is code for finding the last (bottom) filled in cell in a column. Call it as lastRow = findLastRow(yoursheetname, yourcolumnname (like "F:F" or a named column) ): Option Explicit Function findLastRow(Sheetname As String, ColumnName As String) Dim lastRow As Integer Dim r As Range Dim WS As Worksheet Set WS = Worksheets(Sheetname) lastRow = WS.UsedRange.Rows.Count '* '* Search backwards till we find a cell that is not empty '* Set r = WS.Range(ColumnName).Rows(lastRow) While r.Value = "" Set r = r.Offset(-1, 0) Wend lastRow = r.Row Set WS = Nothing findLastRow = lastRow End Function A: There are 2 easy ways to deal with this. * *Formatted Tables *Named Range using an Offset() Just put you list(s) on another admin/config/list sheet to get it out of the way. Here are a few good sites explaining how to do it, if you search Excel dynamic validation list http://excelsemipro.com/2011/05/a-dynamic-dependent-drop-down-list-in-excel/ http://www.contextures.com/xlDataVal02.html https://www.extendoffice.com/documents/excel/4021-excel-data-validation-dynamic-range.html https://chandoo.org/wp/2010/09/13/dynamic-data-validation-excel/ http://www.techrepublic.com/article/pro-tip-create-a-dynamic-validation-control-in-excel/
{ "language": "en", "url": "https://stackoverflow.com/questions/46472334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make EF6 Include() subclass navigation properties for a List of items I am trying to select a list of Invoices and their subclassed items. Here are the models: public class SalesContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Invoice> Invoices { get; set; } public DbSet<InvoiceItem> InvoiceItems { get; set; } public SalesContext() : base ("DefaultConnection") { } } public class Invoice { public int Id { get; set; } public List<InvoiceItem> Items { get; set; } public Invoice() { Items = new List<InvoiceItem>(); } } public abstract class InvoiceItem { public int Id { get; set; } public int Qty { get; set; } } public class ProductInvoiceItem : InvoiceItem { public int ProductId { get; set; } public Product Product { get; set; } } public class Product { public int Id { get; set; } public string Name { get; set; } } Here's the seed data: internal sealed class Configuration : DbMigrationsConfiguration<SalesContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(SalesContext context) { context.Products.AddOrUpdate(p => p.Name, new Product {Name = "Bible - New Living Translation"}, new Product {Name = "Bible - King James Version"} ); context.SaveChanges(); context.Invoices.AddOrUpdate(new Invoice { Items = new List<InvoiceItem>() { new ProductInvoiceItem {ProductId = 1}, new ProductInvoiceItem {ProductId = 2} } } , new Invoice { Items = new List<InvoiceItem>() { new ProductInvoiceItem {ProductId = 1} } } ); context.SaveChanges(); } } Here, I'm trying to select the data out with its associated subclass properties. public class SalesController : Controller { private SalesContext db = new SalesContext(); // GET: Sales public ActionResult Index() { var query = db.Invoices.Include(i => i.Items); var query2 = query.Include(i => i.Items.OfType<ProductInvoiceItem>().Select(pi => pi.Product)); var list = query2.ToList(); return View(list); } } In the above code sample, query2 is broken. It throws a runtime exception. System.ArgumentException was unhandled by user code HResult=-2147024809 Message=The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path ParamName=path Source=EntityFramework StackTrace: at System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable1 source, Expression1 path) at ParentChildEntityFrameworkStuff.Web.Controllers.SalesController.Index() in c:\users\brandon.miller\documents\visual studio 2015\Projects\ParentChildEntityFrameworkStuff\ParentChildEntityFrameworkStuff.Web\Controllers\SalesController.cs:line 20 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f() InnerException: If I use query and get rid of the query2 stuff, it returns data, but of course leaves out the Product on the ProductInvoiceItems. The ProductId field is set, so I know it is getting at least the value types for the ProductInvoiceItems. I've tried and tried and searched and searched and have been unable to find a solution for this, arguably, common use-case. What can I do in order to eagerly load the Product navigation property?
{ "language": "en", "url": "https://stackoverflow.com/questions/34932835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: serving common html without facelets/jsf-tags I have the folder containing a client-side-html-template ("template.xhtml"). The folder resides in public folder (not in WEB_INF). When saved the file with suffix "xhtml" and wrap the content with "<ui:composition", then client side (ajax) request can access. However, when I save it to "template.html" and delete the "<ui:composition", then client ajax cannnot access this page (401). My web.xml has this mapping: <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <mime-mapping> <extension>xhtml</extension> <mime-type>text/html</mime-type> </mime-mapping> <security-constraint> <display-name>Restrict raw XHTML Documents</display-name> <web-resource-collection> <web-resource-name>XHTML</web-resource-name> <url-pattern>*.xhtml</url-pattern> </web-resource-collection> <auth-constraint /> </security-constraint> How can I serve common "html-files" by client side ajax request without intercepting these files by jsf/facelets? A: Found a simple way without the need to change web.xml: I changed the static "html" files to "htm".
{ "language": "en", "url": "https://stackoverflow.com/questions/48215705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I only have to escape the last backslash in a string literal? I have the following Python code: localExtractpath = "D:\Python\From 0 to 1\Excel\" if os.path.exists(localZipPath): print("Cool! '" + localZipPath + "' exists...proceeding...") This gives me the error: File "", line 2 localExtractpath = "D:\Python\From 0 to 1\Excel\" ^ SyntaxError: EOL while scanning string literal When I escape the last \ in the string, the code works. Why do I only have to escape the last \? A: Why do I only have to escape the last \? Because only after the last \ there is a symbol (") which together with \ forms an escape sequence — \" (escaping the role of the quote symbol " as a string terminator). If \ with subsequent symbol(s) don't form an escape sequence, it's kept as is, i.e. as the backslash symbol itself. (In your case neither \P, nor \F and nor \E form an allowed escape sequence, so the symbol \ itself is interpreted literally — as is.) An (unsolicited) solution: Use forward slashes (/) instead of backslashes (\) (all Windows system calls accept them, too): localExtractpath = "D:/Python/From 0 to 1/Excel/" A: The last backslash in "D:\Python\From 0 to 1\Excel\" is escaping your ending quotation mark, so in the eyes of the interpreter, your string is unterminated. In fact, you have to escape all your backslashes if you want to use the literal backslash in your string: "D:\\Python\\From 0 to 1\\Excel\\" A: Other answers are right: you should escape all your backslashes and, even better, you should use forward slash for path elements (you can even take a look at the pathlib library). But to answer specifically your question on why the issue lies only in the last one and not in the previous backslashes, you should take a look at the definition of string literals. You will see that there is a (short) list of characters for which the backslash makes something particular. For the rest, the backslash is taken as itself. For instance "\n" is interpreted not as a string with two characters (\ and n) but as a string with only a single line-feed character. That is not the case with "\P", "\F" or "\E" which are two characters each since they don't have a specific meaning. \" and \' are particular in that they allow to respectively insert a " or ' character in a string literal delimited by this same character. For example, 'single: \', double "' and "single: ', double: \"" are two ways to define the single: ', double " string literal.
{ "language": "en", "url": "https://stackoverflow.com/questions/61306105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to protect columns in hibernate from being read Lets say I have models Configuration and User. In Configuration I specify relation to User like this: @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name= "user") private User author; And then when I want all configuration per specific user I get something like this: {"id":1,"key":"Layout","value":"boxed","author":{"id":1,"name":"Roy","login":"roy","password":"spring"}} How can I protect A: I am not sure if this solves your problem. But it looks like typical need of View instead of direct table fetch. In View you can control which all columns to be read or not to be read. A: There's no way of Hibernate-read protection. You can protect fileds from beeing updated or inserted using declarations (insertable = false, updatable = false). If you want not to give some fields to the user you should use high-level logic, like filtering fields in your Json. A: I have found solution. In entity class, if I join column I can simply put annotation @JsonIgnoreProperties({"prop1", "prop2"}), or if it is standard type property @JsonIgnore is enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/31378267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find big enough gaps in booking table A rental system uses a booking table to store all bookings and reservations: booking | item | startdate | enddate 1 | 42 | 2013-10-25 16:00 | 2013-10-27 12:00 2 | 42 | 2013-10-27 14:00 | 2013-10-28 18:00 3 | 42 | 2013-10-30 09:00 | 2013-11-01 09:00 … Let’s say a user wants to rent item 42 from 2013-10-27 12:00 until 2013-10-28 12:00 which is a period of one day. The system will tell him, that the item is not available in the given time frame, since booking no. 2 collides. Now I want to suggest the earliest rental date and time when the selected item is available again. Of course considering the user’s requested period (1 day) beginning with the user’s desired date and time. So in the case above, I’m looking for an SQL query that returns 2013-10-28 18:00, since the earliest date since 2013-10-27 12:00 at which item 42 will be available for 1 day, is from 2013-10-28 18:00 until 2013-10-29 18:00. So I need to to find a gap between bookings, that is big enough to hold the user’s reservation and that is as close a possible to the desired start date. Or in other words: I need to find the first booking for a given item, after which there’s enough free time to place the user’s booking. Is this possible in plain SQL without having to iterate over every booking and its successor? A: If you can't redesign your database to use something more efficient, this will get the answer. You'll obviously want to parameterize it. It says find either the desired date, or the earliest end date where the hire interval doesn't overlap an existing booking: Select min(startdate) From ( select cast('2013-10-27 12:00' as datetime) startdate from dual union all select enddate from booking where enddate > cast('2013-10-27 12:00' as datetime) and item = 42 ) b1 Where not exists ( select 'x' from booking b2 where item = 42 and b1.startdate < b2.enddate and b2.startdate < date_add(b1.startdate, interval 24 hour) ); Example Fiddle A: SELECT startfree,secondsfree FROM ( SELECT @lastenddate AS startfree, UNIX_TIMESTAMP(startdate)-UNIX_TIMESTAMP(@lastenddate) AS secondsfree, @lastenddate:=enddate AS ignoreme FROM (SELECT startdate,enddate FROM bookings WHERE item=42) AS schedule, (SELECT @lastenddate:=NOW()) AS init ORDER BY startdate ) AS baseview WHERE startfree>='2013-10-27 12:00:00' AND secondsfree>=86400 ORDER BY startfree LIMIT 1 ; Some explanation: The inner query uses a variable to move the iteration into SQL, the outer query finds the needed row. That said, I would not do this in SQL, if the DB structure is like the given. You could reduce the iteration count by using some smort WHERE in the inner query to a sane timespan, but chances are, this won't perform well. EDIT A caveat: I did not check, but I assume, this won't work, if there are no prior reservations in the list - this should not be a problem, as in this case your first reservation attempt (original time) will work. EDIT SQLfiddle A: Searching for overlapping date ranges generally yields poor performance in SQL. For that reason having a "Calendar" of available slots often makes things a lot more efficient. For example, the booking 2013-10-25 16:00 => 2013-10-27 12:00 would actually be represented by 44 records, each one hour long. The "gap" until the next booking at 2013-10-27 14:00 would then be represented by 2 records, each one hours long. Then, each record could also have the duration (in time, or number of slots) until the next change. slot_start_time | booking | item | remaining_duration ------------------+---------+------+-------------------- 2013-10-27 10:00 | 1 | 42 | 2 2013-10-27 11:00 | 1 | 42 | 1 2013-10-27 12:00 | NULL | 42 | 2 2013-10-27 13:00 | NULL | 42 | 1 2013-10-27 14:00 | 2 | 42 | 28 2013-10-27 15:00 | 2 | 42 | 27 ... | ... | ... | ... 2013-10-28 17:00 | 2 | 42 | 1 2013-10-28 18:00 | NULL | 42 | 39 2013-10-28 19:00 | NULL | 42 | 38 Then your query just becomes: SELECT * FROM slots WHERE slot_start_time >= '2013-10-27 12:00' AND remaining_duration >= 24 AND booking IS NULL ORDER BY slot_start_time ASC LIMIT 1 A: OK this isn't pretty in MySQL. That's because we have to fake rownum values in subqueries. The basic approach is to join the appropriate subset of the booking table to itself offset by one. Here's the basic list of reservations for item 42, ordered by reservation time. We can't order by booking_id, because those aren't guaranteed to be in order of reservation time. (You're trying to insert a new reservation between two existing ones, eh?) http://sqlfiddle.com/#!2/62383/9/0 SELECT @aserial := @aserial+1 AS rownum, booking.* FROM booking, (SELECT @aserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate Here is that subset joined to itself. The trick is the a.rownum+1 = b.rownum, which joins each row to the one that comes right after it in the booking table subset. http://sqlfiddle.com/#!2/62383/8/0 SELECT a.booking_id, a.startdate asta, a.enddate aend, b.startdate bsta, b.enddate bend FROM ( SELECT @aserial := @aserial+1 AS rownum, booking.* FROM booking, (SELECT @aserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS a JOIN ( SELECT @bserial := @bserial+1 AS rownum, booking.* FROM booking, (SELECT @bserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS b ON a.rownum+1 = b.rownum Here it is again, showing each reservation (except the last one) and the number of hours following it. http://sqlfiddle.com/#!2/62383/15/0 SELECT a.booking_id, a.startdate, a.enddate, TIMESTAMPDIFF(HOUR, a.enddate, b.startdate) gaphours FROM ( SELECT @aserial := @aserial+1 AS rownum, booking.* FROM booking, (SELECT @aserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS a JOIN ( SELECT @bserial := @bserial+1 AS rownum, booking.* FROM booking, (SELECT @bserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS b ON a.rownum+1 = b.rownum So, if you're looking for the starting time and ending time of the earliest twelve-hour slot you can use that result set to do this: http://sqlfiddle.com/#!2/62383/18/0 SELECT MIN(enddate) startdate, MIN(enddate) + INTERVAL 12 HOUR as enddate FROM ( SELECT a.booking_id, a.startdate, a.enddate, TIMESTAMPDIFF(HOUR, a.enddate, b.startdate) gaphours FROM ( SELECT @aserial := @aserial+1 AS rownum, booking.* FROM booking, (SELECT @aserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS a JOIN ( SELECT @bserial := @bserial+1 AS rownum, booking.* FROM booking, (SELECT @bserial:= 0) AS q WHERE item = 42 ORDER BY startdate, enddate ) AS b ON a.rownum+1 = b.rownum ) AS gaps WHERE gaphours >= 12 A: here is the query, it will return needed date, obvious condition - there should be some bookings in table, but as I see from question - you do this check: SELECT min(enddate) FROM ( select a.enddate from table4 as a where a.item=42 and DATE_ADD(a.enddate, INTERVAL 1 day) <= ifnull( (select min(b.startdate) from table4 as b where b.startdate>=a.enddate and a.item=b.item), a.enddate) and a.enddate>=now() union all select greatest(ifnull(max(enddate), now()),now()) from table4 ) as q you change change INTERVAL 1 day to INTERVAL ### hour A: If I have understood your requirements correctly, you could try self-JOINing book with itself, to get the "empty" spaces, and then fit. This is MySQL only (I believe it can be adapted to others - certainly PostgreSQL): SELECT book.*, TIMESTAMPDIFF(MINUTE, book.enddate, book.best) AS width FROM ( SELECT book.*, MIN(book1.startdate) AS best FROM book JOIN book AS book1 USING (item) WHERE item = 42 AND book1.startdate >= book.enddate GROUP BY book.booking ) AS book HAVING width > 110 ORDER BY startdate LIMIT 1; In the above example, "110" is the looked-for minimum width in minutes. Same thing, a bit less readable (for me), a SELECT removed (very fast SELECT, so little advantage): SELECT book.*, MIN(book1.startdate) AS best FROM book JOIN book AS book1 ON (book.item = book1.item AND book.item = 42) WHERE book1.startdate >= book.enddate GROUP BY book.booking HAVING TIMESTAMPDIFF(MINUTE, book.enddate, best) > 110 ORDER BY startdate LIMIT 1; In your case, one day is 1440 minutes and SELECT book.*, MIN(book1.startdate) AS best FROM book JOIN book AS book1 ON (book.item = book1.item AND book.item = 42) WHERE book1.startdate >= book.enddate GROUP BY book.booking HAVING TIMESTAMPDIFF(MINUTE, book.enddate, best) >= 1440 ORDER BY startdate LIMIT 1; +---------+------+---------------------+---------------------+---------------------+ | booking | item | startdate | enddate | best | +---------+------+---------------------+---------------------+---------------------+ | 2 | 42 | 2013-10-27 14:00:00 | 2013-10-28 18:00:00 | 2013-10-30 09:00:00 | +---------+------+---------------------+---------------------+---------------------+ 1 row in set (0.00 sec) ...the period returned is 2, i.e., at the end of booking 2, and until "best" which is booking 3, a period of at least 1440 minutes is available. An issue could be that if no periods are available, the query returns nothing -- then you need another query to fetch the farthest enddate. You can do this with an UNION and LIMIT 1 of course, but I think it would be best to only run the 'recovery' query on demand, programmatically (i.e. if empty(query) then new_query...). Also, in the inner WHERE you should add a check for NOW() to avoid dates in the past. If expired bookings are moved to inactive storage, this could be unnecessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/19529276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send real time data variable between function and variable? I'd like to assign to double variable (param1) result of one function. { //we are inside one function double param1 = function(); } captured_values() must capture in real time double variable. This variable I would like to assign by function() to my param1 program1::program1(QWidget *parent): QMainWindow(parent) { captured_values(){ //here function() should be used - to send captured value to param1} } Should I use signal and slots mechanism or maybe other one? Could someone please give complete code example? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/21921241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs data-binding not working properly Here is my code link: I am facing two problems here: * *when drop down item for example text is clicked, the Question type section list does not go to the proper format, *when selected another drop down item again, the last Question type is changed as well, but actually could not be changed. Could someone help me on that? Thanks in advance! A: This doesn´t seem to be an error in your script. You wrote in line 147 of index.html: <script src="Form Builder.js"></script>enter code here But ist should be: <script src="script.js"></script> Here is a Plunker
{ "language": "en", "url": "https://stackoverflow.com/questions/22523881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AutoCompleteTextView list - Not displaying single word string first followed by two words string I am new to Android application development and I am currently working on an existing Android application I have an alphabetically sorted list of strings for the AutoCompleteTextView and some of the strings have 2 words. when I start typing a letter then I would like to have the autocomplete list appeared such that it shows the strings sorted by the letter which i have typed for example: I have the list alphabetically sorted: free love, love, love letter, loveless Now, if I type 'L' then first string shown in the autocomplete list is free love, the second string shown is Love but I would like to have Love as the first string because it start with 'L' . Thereafter it should show loveless, free love and love letter but it doesn't show in the order i have typed Can you suggest on how to implement this in Android?
{ "language": "en", "url": "https://stackoverflow.com/questions/58520445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set minimum number of lines on uilabel can this be done? I have good reason for to use this somewhere. Adding text to meet quality standards....AND heres more, and more, and more and more, quality standards met.... some fake code var=nothing A: You could take the lineHeight of the UIFont that the label's using and make its frame's height that times three. A: I had a similar case where I needed to have a cell with a constant height, but the contents of a label could be shorter than what was needed to have it always have three lines. I duplicated the label, set the contents to "1\n2\n3" to give it the three lines required, set it to hidden, and then gave it the top and bottom constraints of the label I wanted to have a consistent height. Then I set the visible label top constraint to my placeholder and removed its bottom constraint. Now the placeholder fixes the height at the required amount and the visible label will grow down (to the maximum of three lines) as needed while staying fixed to the top (and not centering verticaly if it doesn't have content for three lines).
{ "language": "en", "url": "https://stackoverflow.com/questions/29910556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How to pass Object or array with Query string in PHP I am learning PHP and wondering How do i pass an array or object with query string using php ? I do google it but could not find a good answer about it. Here what i wondering ? http://www.example.com/abc?array('a','b','c') http://www.example.com/abc?object("a":"a","b":"b") A: That is my prefer ..you can try it <?php $link = "http://www.example.com/abc?"; //try with object // $a = new stdClass(); // $a->a = "a"; // $a->b = "b"; //try with array $a = ["a","b","c"]; header("location:{$link}param=".json_encode($a)); www.example.com/abc <?php $data = json_decode($_GET["param"]); var_dump($data);
{ "language": "en", "url": "https://stackoverflow.com/questions/40500517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Type 'string' is not assignable to type 'Position' I'm modifying React js to ts now. It is Class Componenet. I want to get css settings by props and apply it to Element. How should I fix this? render(){return( <span style={{ position: this.props.position , left: this.props.left, top: this.props.top, height: this.props.height, width: this.props.width }} /> </span>)} A: Typescript expects the string to be literally one of the options of the position property - absolute, relative etc One way to solve it is to tell him that you know the type will be ok, like so : <span style={{ position: this.props.position, left: this.props.left, top: this.props.top, height: this.props.height, width: this.props.width }: as React.CSSProperties} /> </span>)} Another option is to go where the position property is originally defined (parent element) and let Typescript enforce type, for example: const styles: ('absolute' | 'relative' | 'fixed') = 'absolute'; A: There is no need to cast the object but declare the type React.CSSProperties when initializing. function MyComponent(props) { const styles: React.CSSProperties = { position: this.props.position, left: this.props.left, top: this.props.top, height: this.props.height, width: this.props.width }; return ( <span style={styles}></span> ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/69161276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mysql Natural sorting in varchar field Is there anyway to sort the string with number field by its number only I have a value like this subject_code DE 312 DE 313 DE 315 Eng 311 COMP 314 can it be sort like this subject_code Eng 311 DE 312 DE 313 COMP 314 DE 315 I tried order by SOUNDEX(subject_code),LENGTH(subject_code),subject_code but it does not work as expected. Thank you for your any help and suggestions. A: One workaround to your situation uses string operations to obtain the numerical subject code and use it for sorting. SELECT subject_code FROM yourTable ORDER BY CAST(SUBSTR(subject_code, INSTR(subject_code, ' ') + 1) AS UNSIGNED) However, you should really be storing the text and numerical code in separate columns. Output: Demo here: Rextester
{ "language": "en", "url": "https://stackoverflow.com/questions/44227641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ClassCastException when reading OUT parameters from EclipseLink PLSQLStoredProcedureCall I need to call an Oracle Stored Procedure using EclipseLink (2.3.1.v20111018-r10243). The procedure have IN and OUT parameters, and I need to read the OUT parameter. I found this example and my code is pretty much a copy of the example, but instead of receiving a List from the API, it is throwing an Exception because the value is an Integer of value "1", and I can't figure out why. The procedure is being called properly, the IN parameter is ok, but the code fails to read the response which "should" be a List according to the example. import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.eclipse.persistence.jpa.JpaEntityManager; import org.eclipse.persistence.platform.database.jdbc.JDBCTypes; import org.eclipse.persistence.platform.database.oracle.plsql.OraclePLSQLTypes; import org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall; import org.eclipse.persistence.queries.DataModifyQuery; import org.eclipse.persistence.sessions.DatabaseRecord; import org.eclipse.persistence.sessions.Session; public class ProcedureCall { @PersistenceContext private EntityManager em; public String execute(Long parameter) throws Exception { PLSQLStoredProcedureCall call = new PLSQLStoredProcedureCall(); call.setProcedureName("two_arg_in_out"); call.addNamedOutputArgument("X", OraclePLSQLTypes.BinaryInteger); call.addNamedArgument("Y", JDBCTypes.VARCHAR_TYPE, 40); DataModifyQuery query = new DataModifyQuery(); query.setCall(call); query.addArgument("Y"); List queryArgs = new ArrayList(); queryArgs.add(parameter); Session session = ((JpaEntityManager) em.getDelegate()).getActiveSession(); Object obj = session.executeQuery(query, queryArgs); // The system prints "Return: 1" System.out.println("Return: " + obj); List results = (List) obj; // Here is where exception happens DatabaseRecord record = (DatabaseRecord) results.get(0); String y = (String) record.get("X"); return "done"; } } The system throws the following exception: Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.List This is the procedure from the example I am using: PROCEDURE two_arg_in_out(x OUT BINARY_INTEGER, y IN VARCHAR) AS BEGIN x := 33; END; A: This looks similar to the example shown here: https://wiki.eclipse.org/EclipseLink/Examples/JPA/nonJDBCArgsToStoredProcedures#Handling_IN_and_OUT_arguments The difference is you are using a DataModifyQuery which is designed around JDBC's executeUpdate to execute the query, and so returns an int instead of a resultset. You will want to use a DataReadQuery to obtain results.
{ "language": "en", "url": "https://stackoverflow.com/questions/32853944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql trigger set variable from php $query=" CREATE TRIGGER history_trigger BEFORE UPDATE ON config FOR EACH ROW Begin DECLARE oid int(11); DECLARE oname varchar(10); DECLARE ipadd varchar(16); SET oid='$operatorId'; SET oname='$operatorname'; if new.description!=old.description then insert into log (operatorId, operatorname, columnname, rowid, newdata, olddata) values (oid, oname, 'description', old.id, new.description, old.description); end if; end; "; mysql_query($query); I need php variable insert into log table while trigger start. I try edit '$operatorId','$operatorname' in $query string, but I see '$operatorId' the string in the new row not the correct Id. How to make the php variable in to mysql trigger query? Please help, thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/40308559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Connect to database fail from wordpress in wampserver I changed the wp-config to the following setting define('DB_Name', 'wp'); define('DB_User', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost:3306'); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', ''); I got the following error message Warning: mysqli_real_connect(): (HY000/1045): Access denied for user 'DB_USER'@'localhost' (using password: NO) in C:...\wp-includes\wp-db.php on line 1489 when I changed to 'localhost' to 'myipaddress' I got the following error message Warning: mysqli_real_connect(): (HY000/1130): Host 'xxx' is not allowed to connect to this MySQL server in C:...\wp-includes\wp-db.php on line 1489 However, I can login to phpAdmin to create a new database using just the username 'root' without password. I can also go in to mysql without password through MYSQL console What can I do to solve this problem? How to grant permission? Thank you, A: If in doubt check the manual That will tell you that define('DB_Name', 'wp'); define('DB_User', 'root'); Should be define('DB_NAME', 'wp'); define('DB_USER', 'root');
{ "language": "en", "url": "https://stackoverflow.com/questions/36821904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get data from this "list" looking thing in python 2.7 I'm working on a project that implements stock data, (it's in python 2.7). The module i'm using (yahoo finance https://pypi.python.org/pypi/yahoo-finance) will return historical data in this format: print yahoo.get_historical('2014-04-25', '2014-04-29') [{u'Volume': u'28720000', u'Symbol': u'YHOO', u'Adj_Close': u'35.83', u'High': u'35.89', u'Low': u'34.12', u'Date': u'2014-04-29', u'Close': u'35.83', u'Open': u'34.37'}, {u'Volume': u'30422000', u'Symbol': u'YHOO', u'Adj_Close': u'33.99', u'High': u'35.00', u'Low': u'33.65', u'Date': u'2014-04-28', u'Close': u'33.99', u'Open': u'34.67'}, {u'Volume': u'19391100', u'Symbol': u'YHOO', u'Adj_Close': u'34.48', u'High': u'35.10', u'Low': u'34.29', u'Date': u'2014-04-25', u'Close': u'34.48', u'Open': u'35.03'}] Is there any way to parse this data like a list? I don't recognize the formatting it's in. Is there any simple way i could separate the high for the day? I thought about just making it a string and using something like string = yahoo.get_historical('2014-04-25', '2014-04-29') string[13] + string[14] + string[15] ... + string[21] = Volume but I know there must be a better way to do this. Hopefully it's something simple that I'm missing. A: It's a list of dictionaries, three items in a list. Easier to see if using the pprint.pprint() module function: [{u'Adj_Close': u'35.83', u'Close': u'35.83', u'Date': u'2014-04-29', u'High': u'35.89', u'Low': u'34.12', u'Open': u'34.37', u'Symbol': u'YHOO', u'Volume': u'28720000'}, {u'Adj_Close': u'33.99', u'Close': u'33.99', u'Date': u'2014-04-28', u'High': u'35.00', u'Low': u'33.65', u'Open': u'34.67', u'Symbol': u'YHOO', u'Volume': u'30422000'}, {u'Adj_Close': u'34.48', u'Close': u'34.48', u'Date': u'2014-04-25', u'High': u'35.10', u'Low': u'34.29', u'Open': u'35.03', u'Symbol': u'YHOO', u'Volume': u'19391100'}] You can read them like: readings = yahoo.get_historical('2014-04-25', '2014-04-29') for reading in readings: print reading['Volume'] The high for the day could be: high_reading = max(readings, key=lambda reading: float(reading['High'])) (which is the max() function which returns the biggest thing in a sequence, provided with a custom function to say what it should look at when comparing the items). A: Why don't you use a syntax like: for dayData in dict to separate the values for each day and do the processing in the for loop with something like dayDict['Volume']. Then you can just add any details to a master array outside the loop for further processing or analytics later in the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/30960625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8? Why the following example shows the image in Firefox 4, but not in Chrome 10 and Internet Explorer 8? HTML: <div style="background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div> CSS: div { width: 60px; height: 60px; border: 1px solid black; } Any ideas for workarounds? A: u must specify the width and height also <section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" > A: Chrome 11 spits out the following in its debugger: [Error] GET http://www.mypicx.com/images/logo.jpg undefined (undefined) It looks like that hosting service is using some funky dynamic system that is preventing these browsers from fetching it correctly. (Instead it tries to fetch the default base image, which is problematically a jpeg.) Could you just upload another copy of the image elsewhere? I would expect it to be the easiest solution by a long mile. Edit: See what happens in Chrome when you place the image using normal <img> tags ;) A: it is working in my google chrome browser version 11.0.696.60 I created a simple page with no other items just basic tags and no separate CSS file and got an image this is what i setup: <div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div> I put an id just in case there was a hidden id tag and it works A: As c-smile mentioned: Just need to remove the apostrophes in the url(): <div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div> Demo here A: I would like to add (in case someone came here looking for it) that it's not possible for url() to point a local image if you are trying to send an styled email. You have to deploy that image somewhere else.
{ "language": "en", "url": "https://stackoverflow.com/questions/5846637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: Drawing on canvas ANDROID I have the following scenario: I have a switch with 24 ports. I want to draw them on the canvas. I managed to do that but the problem is that when I change the state of a port I have to draw them again but it is not happening. Here are my classes: PortTemplate: public class PortTemplate{ private Rect port = new Rect(); private PointerCoords insertPoint=new PointerCoords(); private float xCoord; private float yCoord; private float gap; ... //DRAWING PORT public Rect drawPort(){ port.set((int)insertPoint.x, (int)insertPoint.y, (int)insertPoint.x+portWidth, (int)insertPoint.y+portHeight); return port; } //********** ... //setters and getters MainActivity public class MainActivity extends Activity implements OnClickListener{ Rect rec = new Rect(); int numberPorts=24; PortTemplate[] recs=new PortTemplate[numberPorts]; PortTemplate[] newRecs=new PortTemplate[numberPorts]; Canvas canvas; ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); port = (TextView) findViewById(R.id.port); mSelect = (Button) findViewById(R.id.select); mOptions = (Button) findViewById(R.id.option); mSelect.setOnClickListener(this); mOptions.setOnClickListener(this); surface= (SurfaceView) findViewById(R.id.surface); surface.setBackgroundColor(Color.TRANSPARENT); surface.getHolder().addCallback(new Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { // Do some drawing when surface is ready PointerCoords insertRec=new PointerCoords(); float x = insertRec.x=36; float y = insertRec.y=22; for(int i=0; i<numberPorts; i++) { recs[i]=new PortTemplate(); recs[i].setInsertPoint(x,y); recs[i].setPortHeight(21); recs[i].setPortWidth(23); recs[i].setPortNumber(i+1); newRecs[i]=new PortTemplate(); newRecs[i].setInsertPoint(x,y); newRecs[i].setPortHeight(21); newRecs[i].setPortWidth(23); newRecs[i].setPortNumber(i+1); x+=26.3; } Bitmap eqImage = BitmapFactory.decodeResource(getResources(), R.drawable.ports); Bitmap newImage = Bitmap.createScaledBitmap(eqImage, 700, 60, true); canvas = holder.lockCanvas(); canvas.drawBitmap(newImage, new Matrix(), null); EquipmentTemplate newEqup = new EquipmentTemplate(); newEqup.setHeight(200); newEqup.setWidth(650); newEqup.setxCoord(0); newEqup.setyCoord(0); for(int i=0; i<numberPorts; i++) { canvas.drawRect(recs[i].drawPort(), recs[i].getPaint()); } canvas.drawColor(Color.TRANSPARENT); holder.unlockCanvasAndPost(canvas); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); } ... And inside the MainActivity I have methods that will allow the user to change the state of a selected port and change its state: private void selectPortDialog() { String[] portsWithNumbers = new String[numberPorts]; for(int i=0; i<numberPorts; i++) { portsWithNumbers[i]="Port: "+recs[i].getPortNumber(); } AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle("Select Port"); dialogBuilder.setSingleChoiceItems(portsWithNumbers, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { selected = recs[which].getPortNumber(); } }); dialogBuilder.setPositiveButton("Select", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Selected port: "+selected, Toast.LENGTH_LONG).show(); port.setText("Port "+selected); } }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); } private void selectOptions() { final String[] options = new String[3]; if(recs[selected-1].isConnected()==false && recs[selected-1].getReserved()==false && recs[selected-1].getDefect()==false) { options[0]="Connect"; options[1]="Reserve"; options[2]="Defect"; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle("Action"); dialogBuilder.setSingleChoiceItems(options, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which==0) { newRecs[selected-1].setConnected(true); refresh(); } } }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); } } public void refresh() { surface.getHolder().addCallback(new Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { // Do some drawing when surface is ready canvas = holder.lockCanvas(); for(int i=0; i<numberPorts; i++) { canvas.drawRect(newRecs[i].drawPort(), newRecs[i].getPaint()); } canvas.drawColor(Color.TRANSPARENT); holder.unlockCanvasAndPost(canvas); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); } The problem is that when they chose the state they wnat the canvas is not drawing the ports(refresh method). Any ideas how can I make the canvas draw the port on the existing port? Thank you in advance! A: A couple things... * *You're doing your drawing in surfaceCreated which is only called when the surface is first created, so there will not be any subsequent calls to this method. *You should really be creating a custom View in your case. Simply extend View and do your drawing in onDraw. You'll also be given access to methods such as invalidate() which will re-draw your View.
{ "language": "en", "url": "https://stackoverflow.com/questions/19359996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contentful get richtext field content I'm building a blog for my personal website and I choose Contentful as a headless CMS. However, I succeeded at accessing the fields with this query : const query = ` { blogCollection { items{ title slug cover{ url title } } } } ` But I don't know how to get my rich text's content as well and render it in my website. My blog type looks like this : JSON preview: { "name": "Blog", "description": "", "displayField": "title", "fields": [ { "id": "title", "name": "Title", "type": "Symbol", "localized": false, "required": true, "validations": [], "disabled": false, "omitted": false }, { "id": "slug", "name": "slug", "type": "Symbol", "localized": false, "required": true, "validations": [ { "unique": true } ], "disabled": false, "omitted": false }, { "id": "cover", "name": "Cover", "type": "Link", "localized": false, "required": false, "validations": [], "disabled": false, "omitted": false, "linkType": "Asset" }, { "id": "content", "name": "content", "type": "RichText", "localized": false, "required": true, "validations": [ { "enabledMarks": [ "bold", "italic", "underline", "code" ], "message": "Only bold, italic, underline, and code marks are allowed" }, { "enabledNodeTypes": [ "heading-3", "heading-4", "heading-5", "heading-6", "ordered-list", "unordered-list", "hr", "blockquote", "embedded-entry-block", "embedded-asset-block", "table", "hyperlink", "entry-hyperlink", "asset-hyperlink", "embedded-entry-inline", "heading-1", "heading-2" ], "message": "Only heading 3, heading 4, heading 5, heading 6, ordered list, unordered list, horizontal rule, quote, block entry, asset, table, link to Url, link to entry, link to asset, inline entry, heading 1, and heading 2 nodes are allowed" }, { "nodes": {} } ], "disabled": false, "omitted": false } ], "sys": { "space": { "sys": { "type": "Link", "linkType": "Space", "id": "3oa8py5argun" } }, "id": "blog", "type": "ContentType", "createdAt": "2022-10-17T15:18:25.241Z", "updatedAt": "2022-10-17T15:18:25.744Z", "environment": { "sys": { "id": "master", "type": "Link", "linkType": "Environment" } }, "publishedVersion": 1, "publishedAt": "2022-10-17T15:18:25.744Z", "firstPublishedAt": "2022-10-17T15:18:25.744Z", "createdBy": { "sys": { "type": "Link", "linkType": "User", "id": "5TAfaCaLZgOEcEh6haDIYA" } }, "updatedBy": { "sys": { "type": "Link", "linkType": "User", "id": "5TAfaCaLZgOEcEh6haDIYA" } }, "publishedCounter": 1, "version": 2, "publishedBy": { "sys": { "type": "Link", "linkType": "User", "id": "5TAfaCaLZgOEcEh6haDIYA" } } } } How can I adjust my Query so I can get my rich text and how can I render it correctly in my page ? I'm using NextJS A: Since you're using Rich Text, to fetch the content your GraphQL query should look as follow: { blogCollection { items { title slug cover { title description url } content { json } } } } json in content will return the Rich Text as a JSON object. You can then use the Rich Text Render to render the content on your site. Here's the Next.js and Contentful starter guide that might be useful: https://www.contentful.com/nextjs-starter-guide/
{ "language": "en", "url": "https://stackoverflow.com/questions/74100430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Blazor Wasm Authorization state logged multiple times I'm currently working on a Blazor Webassembly application consuming data from an API. Both applications are secured by an IdentityProvider (IdentityServer4): * *Blazor Wasm App (Oidc) *API *IdentityServer4 It works fine, I can login, logout and retrieve the correct data. I'm running into 1 issue though: info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1] Authorization was successful. This message is logged multiple times from blazor.webassembly.js:1, basically any time I do a page transition or load data on a grid or actually any other possible activity. It looks to me like a permanent roundtrip from the Blazor app back to the IdentityServer4. Do you know why this log message appears multiple times? How can I solve this issue? A: How can I solve this issue? By ignoring it. No issue here. It looks to me like a permanent roundtrip from the Blazor app back to the IdentityServer4 Not at all. A message such as this: info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1] Authorization was successful. is issued by the authorization service when you try to access a protected resource ( annotated by the Authorize attribute), and it is called to check if you are authorized to access the protected resource. In your Blazor client, annotate the Counter page with the Authorize attribute, run your app, and alternately navigate from the Index page to the Counter page (after being authenticated), you'll notice that each time you try to navigate to the Counter page the above message will increase by one (to left of the message). Once again, this is because the authorization service is being called to check if you are authorized to access the protected resource... This is by design. You authenticate only once, but being spied on again and again, not without reason of course, and even that not always succeed.
{ "language": "en", "url": "https://stackoverflow.com/questions/66029743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: copying date with milliseconds in excel vba I would like to copy the exact date contained in one cell to another cell. I use this command: Range("E" & ii).Value = Range("C" & ii).Value but the date format is missing the milliseconds despite having the column formatted using: Columns("E:E").Select Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss.0" I get "0" millisecond always in E column despite having a millisecond value in C column. thanks and regards A: Use this format: "dd/mm/yyyy hh:mm:ss.000"
{ "language": "en", "url": "https://stackoverflow.com/questions/22219646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Services and the HTTP protocol: 404 I am implementing some REST based web services - which is working wonderfully so far. I have been following the advice of Vinay Sahni (http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api). I've realised a potential problem with the idea of using a "404" to indicate when an entity in a service is not found. This is based on the idea to Hijack the HTTP protocol's 404 error response - since it's already there and available. In the case that there is a problem with the web service - ie. A Tomcat redeploy fails... calling a web service will result in a 404 regardless of if the entity actually exists, or the URL is actually not available. Is it not ideal to use a 404 for this reason? I feel that someone out there has run in to the same potential problem. A: When a requested entity is not found you should use 404 Not Found. Period. If your server deploy failed, clients should get a 5xx error, not a 4xx error. You shouldn't design your application around your infrastructure shortcomings. If you need circumvent those shortcomings, you should do it in ways that are decoupled from your application, like middlewares, proxies, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/23796008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mysqli.reconnect = ON changed connection encoding? how to prevent switching the connection encoding by reconnect? Everything of my settings are utf-8, but since I have enabled this function in php.ini of the cli ... I have tested anything ... and when I have a long working script then in any point of the script the connection is switched and I have wrong data. After I have disabled it again, then everything is fine. But why is it so? What kind of settings should I set in my.cfg to prevent this switching of the connection encoding? Cheers Nik A: From the MySQL Docs: If you are using the mysql client with auto-reconnect enabled (which is not recommended), it is preferable to use the charset command rather than SET NAMES. For example: mysql> charset utf8 Charset changed The charset command issues a SET NAMES statement, and also changes the default character set that mysql uses when it reconnects after the connection has dropped. Therefore, issue this: mysqli_query('charset utf8'); Or whatever charset you're using (if other than UTF8). This should fix the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/4422630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pub Sub Cloud Function - Async Await Trying to accomplish the following via a scheduled Firebase Function: * *Fetch Firestore Collection *Delete Collection *Make Get Request to External API *Write Get Request results to Firestore Collection. The function is failing to deploy. Error logs only say {"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. When I run the emulator suite locally, I get no errors, but the DB does not update. I'm getting a linting error on the "=>" that's attached to the "onRun" method. Not sure if this is a code problem or an ESLint problem for ES6 in Firebase Functions. const functions = require('firebase-functions'); const admin = require('firebase-admin'); const axios = require('axios'); admin.initializeApp(); const db = admin.firestore(); exports.scheduledFunction = functions.pubsub .schedule("every 2 minutes") .timeZone("America/New_York") .onRun(async (context) => { try { const querySnapshot = await db.collection("my_collection").get(); console.log(querySnapshot.docs) const promises = querySnapshot.docs.map(doc => db.collection("my_collection").doc(doc.id).delete()); await Promise.all(promises); const options = { "method": "get", "url": "www.myUrl.com", "headers": { "Cookie": "...", }, }; const axiosResponse = await axios(options); const apiResponse = JSON.parse(axiosResponse.data); const parsedResponse = apiResponse["news_results"]; const docCreationPromises = parsedResponse.map(response => db.collection("my_collection").add(parsedResponse)) await Promise.all(docCreationPromises); return null; } catch (error) { console.log(error); return null; } }); A: For the ESLint issue with =>, try setting the ecmaVersion to 8 in your ESLint config. module.exports = { root: true, env: { es6: true, node: true, }, extends: [ "eslint:recommended", "google", ], parserOptions: { ecmaVersion: 8 } }; When I run the emulator suite locally, I get no errors, but the DB does not update. Are you using Firestore emulator? If yes, then data will be added there and not in production so you can see the data in emulator only.
{ "language": "en", "url": "https://stackoverflow.com/questions/68582466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Context Menu vs Popup What is the difference between a ContextMenu class and the Popup class? A: The MSDN docs do a nice job of displaying the distinction: The Popup Class: Represents a pop-up window that has content. The ContextMenu Class: Represents a pop-up menu that enables a control to expose functionality that is specific to the context of the control. So the ContextMenu is a more-specific version of a Popup - it's meant to be bound to a specific control, providing ways to interact with that control. Read further on the MSDN page: the ContextMenu has built-in facilities for displaying itself when you right-click on the associated control, and it is automatically displayed within a Popup. The Popup class is much more general: it simply defines a barebones window (no default borders or decoration) that can display any arbitrary UIElement on top of other controls (notice that the Popup class is part of the Primitives namespace, meaning it's meant to be part of the composition of other controls, such as the ContextMenu).
{ "language": "en", "url": "https://stackoverflow.com/questions/4404731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: syntax error unexpected token bash scripting I am getting a few of these errors in my bash script. I am new to the language. Any pointers? #!/bin/bash echo "Calculating the value V for all given values" inflation=(0 0.03 0.05) tax_rate=(0 0.28 0.35) for I in inflation do for R in tax_rate do V=(4000*((1+0.07*(1-R))/(1+I))^10) echo -n "$V " done done This is my output: Calculating the value V for all given values ./investment.sh: line 9: syntax error near unexpected token (' ./investment.sh: line 9: V=(4000*((1+0.07*(1-R))/(1+I))^10)' ./investment.sh: line 12: syntax error near unexpected token done' ./investment.sh: line 12: done' A: * *always test your code to https://shellcheck.net on errors (you have too much do statements) *bash can't compute floating numbers itself, use bc [1] instead *to do arithmetic substitution, use $(( )) *to do arithmetic, without arithmetic substitution, use (( )) form *UPPER CASE variables are reserved for system, better use lower case *inflation=(0 0.03 0.05) is an array, you can access it via "${inflation[@]}" *quote variables ! [2] [1] bc bc <<< "scale=2; (4000*((1+0.07*(1-$r))/(1+$i))^10)" [2] Learn how to quote properly in shell, it's very important : "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes http://mywiki.wooledge.org/Arguments http://wiki.bash-hackers.org/syntax/words Command Substitution: "$(cmd "foo bar")" causes the command 'cmd' to be executed with the argument 'foo bar' and "$(..)" will be replaced by the output. See http://mywiki.wooledge.org/BashFAQ/002 and http://mywiki.wooledge.org/CommandSubstitution $((...)) is an arithmetic substitution. After doing the arithmetic, the whole thing is replaced by the value of the expression. See http://mywiki.wooledge.org/ArithmeticExpression ((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. Finally #!/bin/bash echo "Calculating the value v for all given values" inflation=(0 0.03 0.05) tax_rate=(0 0.28 0.35) for i in "${inflation[@]}"; do for r in "${tax_rate[@]}"; do v="$(bc <<< "scale=2; (4000*((1+0.07*(1-$r))/(1+$i))^10)")" echo -n "$v " done done echo Output Calculating the value v for all given values 7840.00 6480.00 5920.00 5360.00 4400.00 4000.00 4400.00 4000.00 3600.00
{ "language": "en", "url": "https://stackoverflow.com/questions/62379433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: drone-kit Python is not connecting with Iris+ I'm trying to build my first dronekit python program, and I'm doing some tests with some examples but I couldn't connect to my UAV(Iris+). I plugged the usb radio(3DR 915 MHz) and I put vehicle = connect('/dev/ttyUSB0', wait_ready=True). Actually I have no idea which string I should put in. Thanks in advance guys, I need some help! My code: print "Start simulator (SITL)" from dronekit_sitl import SITL sitl = SITL() sitl.download('copter', '3.3', verbose=True) sitl_args = ['-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,353'] sitl.launch(sitl_args, await_ready=True, restart=True) # Import DroneKit-Python from dronekit import connect, VehicleMode import time # Connect to the Vehicle. print "Connecting to vehicle on: '/dev/ttyUSB0'" vehicle = connect('/dev/ttyUSB0', wait_ready=True) # Get some vehicle attributes (state) print "Get some vehicle attribute values:" print " GPS: %s" % vehicle.gps_0 print " Battery: %s" % vehicle.battery print " Last Heartbeat: %s" % vehicle.last_heartbeat print " Is Armable?: %s" % vehicle.is_armable print " System status: %s" % vehicle.system_status.state print " Mode: %s" % vehicle.mode.name # settable # Close vehicle object before exiting script vehicle.close() # Shut down simulator sitl.stop() print("Completed") A: Best place for getting dk support now is probably here: https://discuss.dronekit.io/c/python In answer, I have not tried this on Linux. I suspect the connection string is correct, but you may have to also set the baud rate using baud=57600
{ "language": "en", "url": "https://stackoverflow.com/questions/35469440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java AWT Robot - how to read item text / label? I need to select appropriate option from the popup window. Unfortunately, it is not the popup displayed by the web page, so I cannot use Selenium framework for that purpose. As I checked, it is possible to navigate to different option by pressing arrow keys. Thus keyPress and keyRelease​ from Java AWT Robot should work for me perfectly to select option and confirm the selection by pressing Enter key. Unfortunately, I do not see a method to read currently selected item text. Without that I cannot find appropriate option. Is it possible to read item label using Java AWT Robot? A: If the target application is another java application, then you should be able to get a reference to the component hierarchy and traverse it until you find the text field & label in question. Assuming it's not a java application, then I don't believe it's possible to do this - at least directly. Robot just provides mouse / keyboard input, but you could use it combined with other classes in the toolkit to at least partially solve your problem. Use the Robot methods keyPress & keyRelease to input CTRL-A. Then CTRL-C. Once the text is in the clipboard, you could read it using Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor) You might be able to use the same approach for a text label, assuming it is selectable. This question is talking about using java.awt.Robot to alter text in another program (MS excel), but it might provide you some additional ideas for tackling the problem: How can I select text in another application with java.awt.robot (example: shift+home)
{ "language": "en", "url": "https://stackoverflow.com/questions/64102733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the color of the Mask View? I am not sure if I understand the concept of Masking correctly but I am trying to recreate the Twitter logo expansion animation in their app: Twitter Logo expansion I have this code so far: class LaunchScreenViewController: UIViewController { var mask: CALayer! override func viewDidLoad() { setUpViewMask() } func setUpViewMask() { mask = CALayer() mask.contents = UIImage(named: "logo_mask")?.cgImage mask.contentsGravity = kCAGravityResizeAspect mask!.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) mask!.anchorPoint = CGPoint(x: 0.5, y: 0.5) mask!.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2) view.layer.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1).cgColor view.layer.mask = mask } } The output of this is: How would I change the black background to be blue? I tried doing but it didn't seem to work: view.layer.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1).cgColor A: Create an intermediate layer where you apply mask. Set the background of your view to the desired background, and set background color of the intermediate layer to the color that you wish your mask to appear in. Something like this, view.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1) // set background of the view portion that do not include mask let parentLayer = CALayer() parentLayer.frame = view.bounds parentLayer.backgroundColor = UIColor.white.cgColor // sets background of mask view.layer.addSublayer(parentLayer) let mask = CALayer() mask.contents = UIImage(named: "twitter.png")?.cgImage mask.contentsGravity = kCAGravityResizeAspect mask.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) mask.anchorPoint = CGPoint(x: 0.5, y: 0.5) mask.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2) parentLayer.mask = mask A: This can be achieved by changing the background color of appDelegate's window... let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window!.backgroundColor = UIColor.blue
{ "language": "en", "url": "https://stackoverflow.com/questions/48570301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android mount unmount sd card I am working on an application that scans the sd card. At this time, I am using the emulator of eclipse to test my android application. I have created a virtual sd-card for testing purposes on eclipse. I want to know if there is any way of un-mounting and then mounting the sd card on the emulator (eclipse) so that I can test my application that when the sd-card is unmounted, it should generate a message etc.. Can anyone help me here.. A: It is possible to boot the device without the external storage, which allows you to test what happens when you do not get the Environment.MEDIA_MOUNTED state. Just create an AVD with an existing SD card .iso file. Then, rename the file. When you load this AVD, it will work just fine but it won't have the external storage loaded. This allows you to test your logic for when the external media isn't mounted. I created a separate AVD for testing the no-external-storage scenario, but you could rename the .iso file and restart the emulator if you want to run both tests on the same one. I did try the umount method above, and while it's useful (as Torp mentions, it's a harsher test), the system still thinks the SD card is mounted and my alternate logic isn't run. A: Hmm i just started an emulator, got a root shell with adb shell and started unmounting things. It seemed to work just fine. Had to do umount /mnt/sdcard/.android_secure and then umount /mnt/sdcard on a 2.3.3 VM but it seemed to work. Check what's on your VM with mount before umounting. Of course this is a much "harsher" solution than umounting from the Android UI - kind of simulates an user that removes the sd card without umounting it first - but it may help with your testing. A: You can't mount/unmound virtual SD card while the emulator is running as explained here (re)mounting the SD card on android emulator If you want to test your app, I suggest you to find a real device. A: Sorry for my ignorance but why can't you go to Android Setting menu then select Storage and unmount SD card? You can mount it back in same way. It works under emulator called using Eclipse. My version ADT adt-bundle-windows-x86_64-20140702
{ "language": "en", "url": "https://stackoverflow.com/questions/6968264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Input and fonts are mutually exclusive on EGLFS QPA I build Qt-5.9.2 on Ubuntu 16.04.3 LTS with EGLFS QPA enabled. I switch to terminal on Ctrl+Alt+F1 screen. Then I run my Qt application app (Qt Quick based, if matters): # to debug input export QT_LOGGING_RULES=qt.qpa.input=true # to be able to close by Ctrl+C my application export QT_QPA_ENABLE_TERMINAL_KEYBOARD=1 ~/app -platform eglfs So far so good: it starts normally and all looks fine. But touchscreen and mouse input are not handled by Qt. Debug output: debug: libinput: opening input device '/dev/input/event1' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event1'. debug: libinput: opening input device '/dev/input/event2' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event2'. debug: libinput: opening input device '/dev/input/event0' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event0'. debug: libinput: opening input device '/dev/input/event8' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event8'. debug: libinput: opening input device '/dev/input/event3' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event3'. debug: libinput: opening input device '/dev/input/event4' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event4'. debug: libinput: opening input device '/dev/input/event7' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event7'. debug: libinput: opening input device '/dev/input/event5' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event5'. debug: libinput: opening input device '/dev/input/event6' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event6'. debug: libinput: opening input device '/dev/input/event9' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event9'. debug: libinput: opening input device '/dev/input/event10' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event10'. debug: libinput: opening input device '/dev/input/event11' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event11'. debug: libinput: opening input device '/dev/input/event12' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event12'. debug: libinput: opening input device '/dev/input/event13' failed (Operation not permitted). debug: libinput: failed to create input device '/dev/input/event13'. debug: Using xkbcommon for key mapping Then I press Ctrl+C. The next step is to check file permissions for device files: $ ll /dev/input/event* crw-rw---- 1 root input 13, 64 ноя 8 17:53 /dev/input/event0 crw-rw---- 1 root input 13, 65 ноя 8 17:53 /dev/input/event1 crw-rw---- 1 root input 13, 74 ноя 8 17:53 /dev/input/event10 crw-rw---- 1 root input 13, 75 ноя 8 17:53 /dev/input/event11 crw-rw---- 1 root input 13, 76 ноя 8 17:53 /dev/input/event12 crw-rw---- 1 root input 13, 77 ноя 8 17:53 /dev/input/event13 crw-rw---- 1 root input 13, 66 ноя 8 17:53 /dev/input/event2 crw-rw---- 1 root input 13, 67 ноя 8 17:53 /dev/input/event3 crw-rw---- 1 root input 13, 68 ноя 8 18:38 /dev/input/event4 crw-rw---- 1 root input 13, 69 ноя 8 17:53 /dev/input/event5 crw-rw---- 1 root input 13, 70 ноя 8 17:53 /dev/input/event6 crw-rw---- 1 root input 13, 71 ноя 8 18:38 /dev/input/event7 crw-rw---- 1 root input 13, 72 ноя 8 17:53 /dev/input/event8 crw-rw---- 1 root input 13, 73 ноя 8 17:53 /dev/input/event9 Okay. I decided to add current user to group input: sudo usermod -a -G input $USER Then I relogin on Ctrl+Alt+F1 screen. Now output of groups command contains input group. I try again to run my application: ~/app -platform eglfs Now it correctly react on mouse and touchscreen input events, but fonts are not rendered - there are even no correctly sized rectangles as placeholders instead of corresponding letters. I remove the user from group input: sudo deluser $USER input Then (after relogin) I try to just change file permissions for input devices: sudo chmod o=g /dev/input/event* Effect is the same. Rollback: sudo chmod o= /dev/input/event* What is the cause of such a behaviour? Why can't I use both libinput and fonts simultaneously? The workaround is to run the application with root privileges, but it may lead to critical security vulnerability. Are there specific settings for libinput to solve the problem? Providing ad-hoc fonts also has no effect: wget https://github.com/dejavu-fonts/dejavu-fonts/releases/download/version_2_37/dejavu-fonts-ttf-2.37.tar.bz2 sudo mkdir -p /usr/local/Qt-5.9.2/lib/fonts sudo tar --extract --verbose --strip-components=2 -C /usr/local/Qt-5.9.2/lib/fonts --file dejavu-fonts-ttf-2.37.tar.bz2 dejavu-fonts-ttf-2.37/ttf/ export QT_QPA_FONTDIR=/usr/local/Qt-5.9.2/lib/fonts A: Submitted as a bug. Solved by adding to input group and by removing QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/47182068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I, in Microsoft Lync automatically accept a desktop sharing request from WPF How can I, in Microsoft Lync client automatically accept a desktop sharing request programmatically in WPF, and also How can I put it in fullscreen mode? A: Not at all? Sorry. You know, there are serious security implications allowing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/8492767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ant build in Eclipse I am trying to use custom build file in order to display the current git version in my Android application. I haven't used ant before and I have not really an idea how to use it. I read plenty of topics in SO and searched quite a lot in Google but I cannot figure it out. I don't really have the time to learn everything about ant but I need this thing running. At the bottom, you can find the code. Current status The file custom_rules.xml is imported in the build.xml created by Eclipse. The macrodef part is invoked but the targets not. I tried to change the External Tools Configurations, tab Targets but whenever I check a target (no matter in which ant file), I get a message: Unknown argument: -pre-build for example (when I put checkmark on -pre-build). I tried adding this line: <import file="${sdk.dir}/tools/ant/build.xml" /> and defining sdk.dir but that doesn't change anything. What am I missing? As I said, I have no idea about ant and the only tutorial that helped me was this one. Current code (custom_rules.xml) <?xml version="1.0" encoding="UTF-8"?> <?eclipse.ant.import ?> <project name="Custom build"> <macrodef name="git" taskname="@{taskname}"> <attribute name="command" /> <attribute name="dir" default="" /> <attribute name="property" default="" /> <attribute name="taskname" default="" /> <attribute name="failonerror" default="on" /> <element name="args" optional="true" /> <sequential> <exec executable="git" dir="@{dir}" outputproperty="@{property}" failifexecutionfails="@{failonerror}" failonerror="@{failonerror}"> <arg value="@{command}" /> <args/> </exec> </sequential> </macrodef> <target name="-pre-build"> <git command="rev-list" property="versioning.code" taskname="versioning"> <args> <arg value="master" /> <arg value="--first-parent" /> <arg value="--count" /> </args> </git> <git command="describe" property="versioning.name" taskname="versioning"> <args> <arg value="--always" /> </args> </git> <echo level="info" taskname="versioning">${versioning.code}, ${versioning.name}</echo> <replaceregexp file="AndroidManifest.xml" match='android:versionCode=".*"' replace='android:versionCode="${versioning.code}"' /> <replaceregexp file="AndroidManifest.xml" match='android:versionName=".*"' replace='android:versionName="${versioning.name}"' /> </target> <target name="-post-build" > <replaceregexp file="AndroidManifest.xml" match='android:versionCode=".*"' replace='android:versionCode="0"' /> <replaceregexp file="AndroidManifest.xml" match='android:versionName=".*"' replace='android:versionName="0"' /> </target> </project> A: I just figured it out. * *I renamed the targets to pre-build and post-build without -. *I went to External Tools Configurations and selected build.xml to the left. On the right, I went to the tab Targets, checked my two targets (in addition to the build target which already had a checkmark) and set the order to be pre-build, build, post-build. *I went to the project properties and I selected Builders on the left. I created a new builder using the build.xml file and having the three targets from the previous bullet point, in the same order. I placed this builder before the Java builder. *I removed the post-build target as it puts the version back to 0 and seems to do that earlier than I would like. I am still not sure that this is the optimal solution. Also, the solution fails when there is no git versioning. I tried using this code for solving the issue but it didn't worked. Nevertheless, it is the best I could do and it helps me getting the info I need in the app. A: Use Git executable with Argument --version and catch the output in a property for further usage, f.e. : <project> <exec executable="git" outputproperty="gitversion"> <arg value="--version"/> </exec> <echo>$${gitversion} => ${gitversion}</echo> </project> output : [echo] ${gitversion} => git version 1.8.3.msysgit.0
{ "language": "en", "url": "https://stackoverflow.com/questions/24017230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Get Meta Tags I have this code: <?php $LF = 'links.txt'; $Rfp = fopen($LF, 'r'); while(!feof($Rfp)) { $links = fgets($Rfp); $tags = get_meta_tags($links); if ($tags['description'] == "") echo "No META Description Found"; else echo $tags['description']; } fclose($Rfp); ?> My links.txt has a list of 5000 URLS one per line. I get this error for every URL in my file, when I execute this script Warning: get_meta_tags(http://www.1saleaday.com ) [function.get-meta-tags]: failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known. in F:\xampp\htdocs\mte.php on line 10 No META Description Foundhttp://www.1stopflorists.com Warning: get_meta_tags() [function.get-meta-tags]: php_network_getaddresses: getaddrinfo failed: No such host is known. in F:\xampp\htdocs\mte.php on line 10 I am sure that the links I have in my links.txt file, all have META description. So, where am I failing? Please guide. A: Here are my example which is working: links.txt is looking like in this example http://www.site1.com http://www.site2.com http://www.site2.com/page1 no space after each line and no break at the end of file <?php $LF = 'links.txt'; $Rfp = fopen($LF, 'r'); while(!feof($Rfp)) { $links = fgets($Rfp); echo "<br>"; echo "<font color=\"red\">Load URL: $links </font>"; $tags = get_meta_tags($links); echo "<br>"; if ($tags['description'] == "") echo "No META Description Found"; else echo "<br>"; echo "<b>Description</b> - "; echo $tags['description']; echo "<br>"; if ($tags['keywords'] == "") echo "No META Keywords Found"; else echo "<br>"; echo "<b>Keywords</b> - "; echo $tags['keywords']; echo "<br>"; } fclose($Rfp); ?> the result look well and no errors A: The answer you need is right in the warning output you included...note the space after the URL: Warning: get_meta_tags(http://www.example.com ) [function.get-meta-tags] If you add: $links = trim($links); Your code will start working. A: php_network_getaddresses: getaddrinfo failed: No such host is known Apparently, PHP is unable to load the page. Perhaps the links don't have the proper format? A quick test shows that this happens when I try get_meta_tags('http://domain.com http://another-domain.com');, perhaps there is something wrong with the newlines? (Windows vs Unix line-endings?)
{ "language": "en", "url": "https://stackoverflow.com/questions/8656442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React-native Determining whether the code is being debugged remotely or not Is there a reliable way to determine if react-native code is running on the device, or in chrome (remote-debugging) from within the code? I have some console logs, that are mostly useful in the chrome console, and want to disable them when on the device (they are already disabled for prod builds), as they have a major performance impact outside of remote debug mode. A: I'm not sure is this what you mean, but I'll give it a shot: I found this hack some time ago const isDebuggingEnabled = (typeof atob !== 'undefined'); A: This seems to work for now: const debuggingEnabled = !!window.navigator.userAgent; As window.navigator.userAgent is undefined on android and ios
{ "language": "en", "url": "https://stackoverflow.com/questions/43895125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joomla 3 Guests Redirect So I have few articles in my menu which are for registered users only. I want them to be visible for everyone but if the user is not logged-in once he clicks on the menu I want him get redirected to the login page.. I saw this tutorial: Auto redirect guests to login but it seems outdated, in joomla 3.3 I can't find any "alias" menu item type. Is there any alternative for that? Iam using Joomla 3.3.1 with Community Builder. -Thank you. A: There are two ways you could do this really. One is through code and the other is through the administrators panel. I'm assuming based on the question you are interested in the back end solution. This involves creating two unique menu items with the same name (alias' would need to be different). One which is only visible to logged in users, which points to the component view desired. The second menu is only visible to guests, and will point to the user log in component view with a redirect url set to component view you wish them to be redirected to. I attached a link below to an article explaining how to only show menu items to guests and have them hide when users are logged in. http://docs.joomla.org/How_do_you_hide_something_from_logged_in_users%3F
{ "language": "en", "url": "https://stackoverflow.com/questions/24805311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I programmatically suspend/resume process and its children on Mac OS X? I am trying to control a spawned task that in my case is a bash script that then runs another program. I wish to be able to suspend and resume those processes. My program is meant to be able to spawn any task so I cannot presume to know if the spawned process will spawn another process or processes. I launched the process using NSTask and can control the original process but it does not affect the child processes. Any help would be appreciated. A: The SIGSTOP signal does this. With a negative PID, the kill command will send it to the entire process group. kill -s SIGSTOP -$pid Send a SIGCONT to resume.
{ "language": "en", "url": "https://stackoverflow.com/questions/32288349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to randomly fill in 10% 2 dimensional array with int = 1? I have little problem , im starting learn java . I need to create 2dimensional array , and i need fill this array in 10% only int 1 of course my code need fill this array randomly . Need some hints how to fill in 10% . public static void main(String[] args) { int maxX = 10; int maxY = 10; int[][] Arr = new int[maxX][maxY]; Random r = new Random(); // random ints for (int x = 0; x < maxX; x++) { for (int y = 0; y < maxY; y++) { Arr[x][y] = r.nextInt(2); } } // printing Arr for (int i = 0; i < Arr.length; i++) { for (int j = 0; j < Arr[i].length; j++) { System.out.print(Arr[i][j] + " "); } System.out.println(); } } A: You can take the following steps: Suppose you need to fill an N * N array. * *Create a List and add to it (N * N) / 10 1s and (N * N * 9) / 10 0s. list.addAll(Collections.nCopies(count,1 or 0)) can help you here. *Run Collections.shuffle on that List to obtain random order. *Iterate over the elements of the List. The first N elements will become the first row the the 2D array, the next N elements will become the second row of the array, and so on... A: An alternative to shuffling is to pick 10% x N random positions and put a 1 (if a 0 was in the position, otherwise pick another position). In pseudo code: int[][] array = new int[N][N] apply N * N / 10 times { index = random(0 .. N * N) if array(index) = 0 then array(index) = 1 else retry with another index } You will need to convert the index from 0 to N*N into a pair of i,j in the 2D array. A: I would use "double random = Math.random();" And then an if to check if the variable random is less or equal to 0.1 A: Make the array, take a random row and column, while the percentage is not exceeded, check if the position has 0, if yes fill it with 1. int[][] array = new int[N][N]; int percentage = N*N/10; int filled = 0; while(filled <= percentage) { Random rand = new Random(); int i = rand.nextInt(N+1); int j = rand.nextInt(N+1); if(array[i][j] == 0) { filled++; array[i][j] = 1; } } for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { System.out.print(array[i][j] + " "); } System.out.println(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/55721895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: QX11EmbedContainer and QProcess problem I've been trying to put a QX11EmbedContainer in my app, and I need to start a terminal within it (because with konsolepart I can practically do nothing). QX11EmbedContainer* container = new QX11EmbedContainer(this); // with or without "this" I got the same result container->show(); QProcess process(container); QString executable("xterm -into "); QStringList arguments; arguments << QString::number(container->winId()); process.start(executable, arguments); compilation goes fine,but I got this message: QProcess: Destroyed while process is still running. and I'm not able to see the container, suggestions?????? Thanks A: The QProcess is allocated on the stack and will deleted as soon as it goes out of scope. This is likely to happen before the the "xterm" child process quits (hence the output). Try allocating the QProcess in the heap instead: QProcess * process = new QProcess(container); ... process->start(executable, arguments); You can delete the QProcess in three ways: * *Do nothing. Let the QX11EmbedContainer delete it. It is a child of the QX11EmbedContainer and will be deleted when the QX11EmbedContainer is deleted. *Hook up the finished() signal to its own deleteLater() slot. connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), process, SLOT(deleteLater()) ); *Delete it yourself by retaining a pointer to it and delete that pointer later. As an extra note, I'm suspicious of the first parameter to QProcess::start(). It should be the path to your executable and further arguments should be added to the QStringlist. QProcess * process = new QProcess(container); QString executable("xterm"); // perhaps try "/usr/X11/bin/xterm" QStringList arguments; arguments << "-into"; arguments << QString::number(container->winId()); proces->start(executable, arguments);
{ "language": "en", "url": "https://stackoverflow.com/questions/383173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sqlite-net in universal app - where is my db? Previously I have used LocalDb in Silverlight apps for Windows Phone 8 which worked great on 8.1 also. If I wanted to inspect my db, I used the ISETOOL to download the file and attached it in vs. Management switched me to building a 'universal' app for RT. I am adopting SQLite-net. In my app, I call: var db = new SQLiteConnection("Example.db"); db.CreateTable<SampleModel>(); I can see that data is preserved since if I do an insert and then commit and then retrieve in another method it all works. However, when I use ISETOOL nothing is copied from the emulator to my local folder. Where is my SQLite db? A: To answer this, you have to pass the full path to the SqlConnection constructor, like so: var dbFile = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "//Sample.db"; var sql = new SqlConnection(dbFile); Also note that if you're trying to work with SQLite from a portable library, you wouldn't be able to call ApplicationData.Current (very inconvenient). I had to supply this parameter from within executing app.
{ "language": "en", "url": "https://stackoverflow.com/questions/24595542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: copy file into another file in prolog Good morning/evening how can I write something in a file and then copy its content into the current file? for example I consult file1.pro then I have rule write something in file2.pro , after this rule finish its job I want append the content of the file2.pro int file1.pro . when I tried to append into file1.pro directly , the data appear like undefined symbols ,I don't know why please hellp me thank you. A: Specifics of the solution might depend on the Prolog dialect. Here I am using SWI-Prolog. SWI-Prolog allows you to open a file with open(SrcDest, Mode, Stream), where SrcDest will be your file name, Mode is read/write/append/update, and Stream is the "file descriptor" the system will return. The manual clarifies difference between appending and updating as follows: "Mode append opens the file for writing, positioning the file-pointer at the end. Mode update opens the file for writing, positioning the file-pointer at the beginning of the file without truncating the file." To copy from one stream to another you should use copy_stream_data(Stream1,Stream2). Finally, you should close the streams, otherwise the output file will be empty. Putting everything together gives copy(File1,File2) :- open(File1,read,Stream1), open(File2,write,Stream2),copy_stream_data(File1,File2),close(File1),close(File2). If you need to rewrite the second file, just use update/append mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/2900505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programmatic file upload to AWS S3 bucket I want to provision an AWS S3 bucket and an IAM user (with programmatic access only) so I can facilitate file upload privilege for that user only. The user will receive the AWS access key ID and secret access key, to use in a simple Node.js or Python console application. What are the minimal steps required to achieve this? * *Create an IAM user (with programmatic access), with no permissions - DONE *Create a S3 bucket and block all public access - DONE *Add a bucket policy that looks like this: { "Version": "2012-10-17", "Id": "Policy1234567", "Statement": [ { "Sid": "Stmt1234567", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::1234567890:user/someuser" }, "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::some-bucket-name/*" } ] } I have a simple node.js application that will upload a given file to the bucket: const fs = require('fs'); const zlib = require('zlib'); const AWS = require('aws-sdk'); const s3 = new AWS.S3({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY }); const bucketName = 'some-bucket-name'; const fileName = 'alargefile.iso'; var body = fs.createReadStream(fileName) .pipe(zlib.createGzip()); // Upload the stream var s3obj = new AWS.S3({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, params: { Bucket: bucketName, Key: fileName } }); s3obj.upload({ Body: body }, function(err, data) { if (err) { console.log("An error occurred", err); } else { console.log("Uploaded the file at", data.Location); } }); *Since the user does not have any permissions, do I still need to create a custom policy to apply as a permission for the user? The OOTB policies are either too generous (AmazonS3FullAccess) or too restrictive (AmazonS3ReadOnlyAccess). Another bit of confusion is that I have set a bucket policy that regulates access to the bucket for a specific user, so would that not be sufficient? A: You can create custom policy for IAM user as well, where you only allow PUTObject to specific bucket. example: { "Version": "2012-10-17", "Id": "Policy1234567", "Statement": [ { "Sid": "Stmt1234567", "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::some-bucket-name/*" } ] } If the bucket and IAM user are in the same account, you don't need bucket policy if IAM user has the above policy. You definitely need Identity policy based on below link: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html
{ "language": "en", "url": "https://stackoverflow.com/questions/56717536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List element value returns wrong values when accessing attribute I have a React component that I am trying to implement so that it can pass the particular value of the list item that a user clicks to a handle method. var React = require('react'); var {connect} = require('react-redux'); export var Keyboard = React.createClass({ handleKeyClick: function(keyClicked) { console.log(keyClicked.target.value); }, render: function () { return ( <ul onClick={(e) => this.handleKeyClick(e)}> <li value="1">1</li> <li value="2">2</li> <li value="3">3</li> <li value="4">4</li> <li value="5">5</li> <li value="6">6</li> <li value="7">7</li> <li value="8">8</li> <li value="9">9</li> <li value="0">0</li> <li value="B">B</li> </ul> ); } }); export default connect()(Keyboard); This works properly for all of the integer valued list items, but when I click the list item with the value of B, I receive 0 as my value, rather than B. Am I unaware of a restriction that only allows integers to be passed through onClick methods? Or perhaps I configured the onClick method incorrectly. Other examples of this situation: * *value="3f" returns 3 *value="H5" returns 0 *value="35" returns 35 It seems apparent this is an issue with the String, but I don't know why. I'm using React version "^0.14.7" A: Explanation This isn't React's fault. This is defined in the HTML5 Specification to behave this way. Per the link: 4.4.7 The li element [...] Content attributes:  Global attributes  If the element is a child of an ol element: value - Ordinal value of the list item Where value is defined as such: The value attribute, if present, must be a valid integer giving the ordinal value of the list item. And a "valid integer" is defined as such: A string is a valid integer if it consists of one or more ASCII digits, optionally prefixed with a "-" (U+002D) character [...] The rules for parsing integers are as given in the following algorithm. When invoked, the steps must be followed in the order given, aborting at the first step that returns a value. This algorithm will return either an integer or an error. * *Let input be the string being parsed. *Let position be a pointer into input, initially pointing at the start of the string. *Let sign have the value "positive". *Skip whitespace. *If position is past the end of input, return an error. *If the character indicated by position (the first character) is a "-" (U+002D) character: a. Let sign be "negative". b. Advance position to the next character. c. If position is past the end of input, return an error. *Otherwise, if the character indicated by position (the first character) is a "+" (U+002B) character: a. Advance position to the next character. (The "+" is ignored, but it is not conforming.) b. If position is past the end of input, return an error. *If the character indicated by position is not an ASCII digit, then return an error. *Collect a sequence of characters that are ASCII digits, and interpret the resulting sequence as a base-ten integer. Let value be that integer. *If sign is "positive", return value, otherwise return the result of subtracting value from zero. In steps 8 and 9, it describes the behavior you see. The following examples: * *"3f" returns 3 *"H5" returns 0 *"35" returns 35 The first returns 3 because of step 9. It collects all the ASCII digits present if the first character is an integer, which is just 3, and interprets as an integer. In the second example, it returns 0 because of this: If the value attribute is present, user agents must parse it as an integer, in order to determine the attribute's value. If the attribute's value cannot be converted to a number, the attribute must be treated as if it was absent. The attribute has no default value. Parsing fails on H5 because the first character is not +, -, or an ASCII digit. Since the attribute is treated as absent as it's invalid, it's just 0, because value still needs to be a valid integer. If you pass an invalid integer that can't be parsed, the result of access attribute value is just 0, which is per the HTML Living Standard, in the applicable paragraph: If a reflecting IDL attribute has a signed integer type (long) then, on getting, the content attribute must be parsed according to the rules for parsing signed integers, and if that is successful, and the value is in the range of the IDL attribute's type, the resulting value must be returned. If, on the other hand, it fails or returns an out of range value, or if the attribute is absent, then the default value must be returned instead, or 0 if there is no default value. On setting, the given value must be converted to the shortest possible string representing the number as a valid integer and then that string must be used as the new content attribute value. Here, the value attribute is not defined to have a default value, and in this case H5 isn't a valid integer so parsing fails and 0 is returned by specification. The last example returns 35 because it's a completely valid integer for value. Solution So instead, you can use Element.getAttribute. Per the link: getAttribute() returns the value of a specified attribute on the element No conversion happens in the method. It just gets the value as it does not need to convert to integer to figure out ordering as HTML does to determine where to place the lis. The HTML Living Standard outlines the internal workings of this method. It just accesses a NamedNodeMap containing attributes and does not to any conversion. Thus: console.log(document.getElementById("test").getAttribute("value")); <ul> <li value="Foobar" id="test">Test</li> </ul> This can be applied to your situation by doing this: keyClicked.target.getAttribute("value"); A: It appears that value when used with an li must be a number. I'd try this instead: <li data-value="123abc">123abc</li> keyHandler.target.getAttribute('data-value'); A: The HTMLLIElement.value property gets or sets the ordinal of the list element, and is always a number. If you want to get the string value, you have to read the value attribute instead. keyHandler.target.getAttribute('value')
{ "language": "en", "url": "https://stackoverflow.com/questions/42497875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: couldn't host on EC2, django/nginx/gunicorn I am trying to deploy django web app on EC2, but I was not able to access the site at domain name and also I am not able to access the gunicorn. I tried the same on DigitalOcean and everything seemed fine and working well. I am trying to learn to deploy on EC2, but stuck. I have tried many tutorials but unable to access. Thanks A: You have to allow inbound traffic for your instance. Security groups enable you to control traffic to your instance, including the kind of traffic that can reach your instance. For example, you can allow computers from only your home network to access your instance using SSH. If your instance is a web server, you can allow all IP addresses to access your instance via HTTP, so that external users can browse the content on your web server. To enable network access to your instance, you must allow inbound traffic to your instance. To open a port for inbound traffic, add a rule to a security group that you associated with your instance when you launched it. Source: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html
{ "language": "en", "url": "https://stackoverflow.com/questions/32000750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: wrong number of arguments - in initialize method I am not able to figure out this extremely simple error: xyz_controller.rb: @isbn = params[:q] @search_type = params[:search_type] ... @prices = Generalsearch.new(:search_term => @isbn, :search_type => @search_type) generalsearch.rb attr_accessor :search_term , :search_type def initialize(search_term , search_type) self.search_term= search_term self.search_type= search_type end ... I keep getting wrong number of arguments (1 for 2) app/models/generalsearch.rb:11:in `initialize' app/controllers/book_controller.rb:47:in `new' app/controllers/book_controller.rb:47:in `view' A: you are passing only one argument ie hash :search_term => @isbn, :search_type => @search_type in Generalsearch.new() use Generalsearch.new( @isbn, @search_type) A: You have to use, as you're accepting 2 params on the initialize function, not a hash of of params. @prices = Generalsearch.new(@isbn, @search_type) A: If you want to use Generalsearch.new(:search_term => @isbn, :search_type => @search_type) Then you can have in the initialize method def initialize(options) # You can also use options[:search_term], # but fetch lets you know if the key doesn't exist self.search_term= options.fetch(:search_term) self.search_type= options.fetch(:search_type) end
{ "language": "en", "url": "https://stackoverflow.com/questions/5805409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get protocol and domain name on localhost and remote server on localhost my site has this address - localhost/example.com on remote server it is - https://example.com is there a php $_SERVER variable - or another way - to get exactly: * *localhost/example.com - when I'm on localhost *https://example.com - when I'm on remote server thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/66737163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using event handler for manually created component I'v been working on a project & decided to work in a unit file i have imported a few components & successfully used them, Only when trying to use the event handlers of the components i got lost. I have researched & know it is possible i just don't know how & what i have to-do for example: unit Unit1; interface uses Component; var Component: TComponent; implementation procedure Example1; begin Component:=TComponent.Create(nil); //do something... end; procedure OnComponentChangeEvent(Sender: TObject); <<<< [Use event onchange of component] begin //do something... end; end.
{ "language": "en", "url": "https://stackoverflow.com/questions/58898790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What method to Login Customer Without Password in Magento 1.9? I want customers login with their email id only. Is any way to skip password in magento 1.9. Thanks A: Try this below code : $email = 'example@email.com'; $customer = Mage::getModel('customer/customer'); $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); $customer->loadByEmail(trim($email)); Mage::getSingleton('customer/session')->loginById($customer->getId());
{ "language": "en", "url": "https://stackoverflow.com/questions/68189303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: select text in textbox: extract word from caret position without selection I have a problem and I want to see if you can help me. What I look for is that when I right click on a word inside a TexBox tell me about which word I am posed, and then I can add that word to the dictionary that I already have created. My code: If textbox1.SelectedText <> "" Then Dim agr As String = textbox1.SelectedText.Remove(textbox1.SelectedText.Length - 1) MsgBox(agr) Else MsgBox("Select a word by double click to add it to the dictionary") End If A: There is a property which is called SelectionStart, representing the position of the caret in the textbox. Its value will be valid also when there is nothing selected. Loop left from there, until you encounter a word boundary or zero. Then loop right until you encounter a word boundary or Len-1. Use the two offsets you got this way, to extract the word around the caret with the SubString function. A: Using this code will solve your problem. If it works for you then please mark it as Solved so that future readers get the confirmation. And ask me any query about it if you got any in the comment section below. Private Sub Textbox1_MouseDown(sender As Object, e As MouseEventArgs) Handles Textbox1.MouseDown If MouseButtons.Right Then If Textbox1.TextLength - Textbox1.Text.IndexOf(" ", 0) > Textbox1.SelectionStart Then Textbox1.Select((Textbox1.Text.LastIndexOf(" ", Textbox1.SelectionStart) + 1), (Textbox1.Text.IndexOf(" ", Textbox1.SelectionStart) - (Textbox1.Text.LastIndexOf(" ", Textbox1.SelectionStart) + 1))) Else Textbox1.Select(Textbox1.Text.LastIndexOf(" ", Textbox1.TextLength) + 1, Textbox1.TextLength - Textbox1.Text.LastIndexOf(" ", Textbox1.TextLength)) End If End If End Sub Best of luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/42864797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are the hearts in turtle appearing slanted? import turtle t = turtle.Turtle() def heart(x): t.penup() t.goto(x, -100) t.pendown() t.color('black','red') t.begin_fill() t.left(45) t.forward(100) t.circle(50, 180) t.right(90) t.circle(50, 180) t.forward(100) t.end_fill() for i in range(3): if i==1: x=-250 heart(x) elif i==2: #continue x=0 heart(x) else: #continue x=250 heart(x) t.hideturtle() turtle.done() This program is supposed to draw three hearts in a straight line I've made a loop that sets the initial position of the heart. It's supposed to draw the heart in one position and move to the next position. While the pointer is moving over the next position, the hearts are appearing slanted. A: Your heart function assumes the turtle's heading is 0, but in the course of drawing a heart, heading changes due to left/right calls. One solution is to reset heading with t.setheading(0) at the start of the function. Also, your loop/if combo is overcomplicated. I suggest either removing the ifs or removing both the loop and the ifs and using 3 separate heart calls. Here's a simplified version: import turtle def heart(x): t.penup() t.goto(x, -100) t.pendown() t.color("black", "red") t.setheading(0) t.begin_fill() t.left(45) t.forward(100) t.circle(50, 180) t.right(90) t.circle(50, 180) t.forward(100) t.end_fill() t = turtle.Turtle() t.hideturtle() for x in range(-250, 251, 250): heart(x) turtle.exitonclick() Consider making size and y values parameters for heart, and optionally t. As is, it's a bit on the hardcoded side.
{ "language": "en", "url": "https://stackoverflow.com/questions/75624207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error jshint validation es5 error throwing on jshint validation over terminal, I have empty js file still it throws error. f.js: line 0, col 0, ES5 option is now set per defaul 1 error A: Create .jshintrc file in your home directory and set es5 to FALSE. { "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) }
{ "language": "en", "url": "https://stackoverflow.com/questions/28336708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display only newest post from category on page wordpress I'm not very familiar with PHP so I'm really struggling with this. I have a category called students-of-the-month with an id of 5. I'd like to have one page on my wordpress site that displays only the most recent post from that category. How can I do this? A: Edit the template for showing categories to only list one post per page. By default it shows the x most recent posts; if x is one, it only shows that one most recent post. A: I ended up doing it differently. I found this page: http://codex.wordpress.org/Template_Hierarchy On the page it said this: category-{slug}.php - If the category's slug were news, WordPress would look for category-news.php This would let me use that page to display any posts in the student of the month category. I'd just program that page to only display the most recent. As for the nav problem, I ended using the "Page Links To" plugin. Thanks for the tips though, they sent me in the correct direction!
{ "language": "en", "url": "https://stackoverflow.com/questions/14299980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome doesn’t show un-minified code in spite of source map present I’m using Grunt and UglifyJS to generate source maps for my AngularJS app. It produces a file customDomain.js and customDomain.js.map. JS file Last line of customDomain.js looks like this: //# sourceMappingURL=customDomain.js.map Map file I find two references to customDomain.js inside of customDomain.js.map, one at the beginning: "sources":["../../../.tmp/concat/scripts/customDomain.js"] I think this looks weird so I trim it to: "sources":["customDomain.js"] The second reference is at the end: "file":"customDomain.js" ...which I leave as it is. Testing When I run my app in Chrome I expect to see my development code when I click on customDomain.js, but I do not: I can see on the console output from my web server that customDomain.js.map is indeed requested from the browser: 200 /js/customDomain.js.map (gzip) What is missing? A: "sources":["customDomain.js"] should be relative to the customDomain.map.js file. Make sure they are in the same directory on your server if this is the case for you. "file":"customDomain.js" should be changed to the name of the map file, in your case this would be "file":"customDomain.map.js". Here's a map file example taken from treehouse (sourceRoot may be unnecessary in your case): { version: 3, file: "script.js.map", sources: [ "app.js", "content.js", "widget.js" ], sourceRoot: "/", names: ["slideUp", "slideDown", "save"], mappings: "AAA0B,kBAAhBA,QAAOC,SACjBD,OAAOC,OAAO..." }
{ "language": "en", "url": "https://stackoverflow.com/questions/40397244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'VNCEnv' object has no attribute 'remote_manager' when running OpenAI universe example When I try to run the following example code from here, Python is unable to find the remote_manager attribute. I have all required packages installed and the OpenAI gym examples appear to work as they should. I run Python 3.5 under Linux Mint 18, and I got OpenAI gym and universe from the pip repositories. import gym import universe # register Universe environments into Gym env = gym.make('flashgames.DuskDrive-v0') # any Universe environment ID here observation_n = env.reset() while True: # agent which presses the Up arrow 60 times per second action_n = [[('KeyEvent', 'ArrowUp', True)] for _ in observation_n] observation_n, reward_n, done_n, info = env.step(action_n) env.render() The full stacktrace is [2017-01-25 14:04:05,416] Making new env: flashgames.DuskDrive-v0 Traceback (most recent call last): File "/home/mark/projects/development-playground/src/utils/openai_experiments.py", line 5, in <module> observation_n = env.reset() File "/usr/local/lib/python3.5/dist-packages/gym/core.py", line 123, in reset observation = self._reset() File "/usr/local/lib/python3.5/dist-packages/universe/wrappers/timer.py", line 15, in _reset return self.env.reset() File "/usr/local/lib/python3.5/dist-packages/gym/core.py", line 123, in reset observation = self._reset() File "/usr/local/lib/python3.5/dist-packages/universe/wrappers/render.py", line 25, in _reset observation_n = self.env.reset() File "/usr/local/lib/python3.5/dist-packages/gym/core.py", line 123, in reset observation = self._reset() File "/usr/local/lib/python3.5/dist-packages/universe/wrappers/throttle.py", line 42, in _reset observation = self.env.reset() File "/usr/local/lib/python3.5/dist-packages/gym/core.py", line 123, in reset observation = self._reset() File "/usr/local/lib/python3.5/dist-packages/universe/envs/vnc_env.py", line 331, in _reset self._handle_connect() File "/usr/local/lib/python3.5/dist-packages/universe/envs/vnc_env.py", line 498, in _handle_connect for remote in self.remote_manager.pop(n=n): AttributeError: 'VNCEnv' object has no attribute 'remote_manager' A: You forgot to call env.configure() env = gym.make('flashgames.DuskDrive-v0') env.configure(remotes=1) observation_n = env.reset()
{ "language": "en", "url": "https://stackoverflow.com/questions/41852625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date range in mongodb atlas search using queryString is not working I tried this but with no success (I got an empty result): { queryString: { defaultPath: 'anyfield', query: 'createdAt:["2000-01-30T20:19:53.123Z" TO *]' } } I tried with no quotes too. And I tried the range operator directly and it works, but my query comes as queryString, so I need it working in queryString. A: if you have a date object handy great. If not, something like this (pseudocode/JS): date = new Date; date = date.toISOString(); then, here is the query from the docs: { "$search": { "index": "default", "range": { "path": "anyField", "gte": "2000-01-30T20:19:53.123Z", "lte": date, } } } A: According to mongodb engineers, the queryString operators only accept AND and OR. It doesn't accept any other operator like TO, used in range filters.
{ "language": "en", "url": "https://stackoverflow.com/questions/69826668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connect to UDP server I'm try to create an application for iOS, where I can connect to a UDP Server and receive data from it. My situation: * *I have a UDP server on Windows machine (IP = 192.168.1.6). *I have iPad (IP = 192.168.1.5); *UDP server sends to virtual address (IP = 239.254.1.2) and port (7125) messages, something like "HELLO!!!!! I'm here!!!!" I need add some logic for the iOS app, where I can connect to virtual IP address (IP = 239.254.1.2) and port (7125) and receive messages "HELLO!!!!! I'm here!!!!" from UDP server. Does anyone have any suggestions? UPDATE1: For UDP connection I'm use GCDAsyncUdpSocket Here my code: @interface ViewController () { GCDAsyncUdpSocket *udpSocket; } - (void)viewDidLoad { [super viewDidLoad]; udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; } - (IBAction)startStop:(id)sender { if (isRunning) { // STOP udp echo server [udpSocket close]; [self logInfo:@"Stopped Udp Echo server"]; isRunning = false; [portField setEnabled:YES]; [startStopButton setTitle:@"Start" forState:UIControlStateNormal]; } else { // START udp echo server int port = [portField.text intValue]; if (port < 0 || port > 65535) { portField.text = @""; port = 0; } NSError *error = nil; if (![udpSocket bindToPort:7125 error:&error]) { [self logError:FORMAT(@"Error starting server (bind): %@", error)]; return; } if (![udpSocket joinMulticastGroup:@"239.254.1.2" error:&error]) { [self logError:FORMAT(@"Error join Multicast Group: %@", error)]; return; } if (![udpSocket beginReceiving:&error]) { [udpSocket close]; [self logError:FORMAT(@"Error starting server (recv): %@", error)]; return; } [self logInfo:FORMAT(@"Udp Echo server started on port %hu", [udpSocket localPort])]; isRunning = YES; [portField setEnabled:NO]; [startStopButton setTitle:@"Stop" forState:UIControlStateNormal]; } } - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext { if (!isRunning) return; NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (msg) { /* If you want to get a display friendly version of the IPv4 or IPv6 address, you could do this: NSString *host = nil; uint16_t port = 0; [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address]; */ [self logMessage:msg]; } else { [self logError:@"Error converting received data into UTF-8 String"]; } [udpSocket sendData:data toAddress:address withTimeout:-1 tag:0]; } When I press "Start" button in the log I see message "Udp Echo server started on port 7125", but delegate method - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext never fired and application dont receive any messages from virtual IP address. Can you help me with this issue? Thank you. A: 239.254.1.2 is a multicast address that the UDP server is sending packets to. Anyone listening on that address will receive the packets. So: * *create a UDP socket *bind your socket to port 7125 *join the multicast group 239.254.1.2 *your app will start receiving the udp packets Probably should just mention that UDP is connectionless protocol, i.e. you cannot connect to a UDP server. A: RichardBrock was right and sample code from UPDATE1 works perfectly. Problem was with my home Network, and when I tryed this code in the work Network everything works fine!!! Thanks you
{ "language": "en", "url": "https://stackoverflow.com/questions/15422135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Problem with apples push notification services Hello I am using Apple's push notification . My web services are in c sharp .I used Push notification code. Every thing is going fine. With out error. but why My messages are not delivered to iphone application, I am using development certificate. same thing is working properly from php script. I am getting log that message is delivered but not getting on iphone.. Also checked sandbox. Url for testing
{ "language": "en", "url": "https://stackoverflow.com/questions/7319667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AS3 array to Object I have this array var ar:Array = [234*256,558*698,256*784...]; and i want to convert it to 2 arrays where first element (before *) goes in var ar_x:Array; and second element (after *) goes in other array var ar_y:Array; How to do that? Thanks. A: If you know the values at compile time just place them in the two separate arrays. You can't separate them at runtime since when you place them like this : var ar:Array = [234*256,558*698,256*784]; The multiplication will be calculated and stored in the array and you will have this at runtime : var ar:Array = [59904,389484,200704]; On the other hand if the values are coming from an external source as strings "234*256" You can split that from the * symbol and store the two parts in separate arrays. var multiply:String = "234*256"; var parts:Array = multiply.split("*"); ar_x.push(parts[0]); ar_y.push(parts[1]); A: I've got it! Code looks like this: var def_poss:Array = [def_pos[i][1],def_pos[i][2],def_pos[i][3],def_pos[i] [4],def_pos[i][5],def_pos[i][6],def_pos[i][7],def_pos[i][8],def_pos[i][9],def_pos[i][10],def_pos[i][11]]; } for (var m:int=0;m<def_poss.length;m++) { var temp_def:Array = def_poss.toString().split("*"); } for (var n:int=0;n<temp_def.length;n++) { var parts:Array = temp_def.toString().split(","); def_x.push(parts[0]); def_y.push(parts[1]); def_x.push(parts[2]); def_y.push(parts[3]); def_x.push(parts[4]); def_y.push(parts[5]); def_x.push(parts[6]); def_y.push(parts[7]); def_x.push(parts[8]); def_y.push(parts[9]); def_x.push(parts[10]); } First I have to split ("*") to get strange array ["255","255,586".....], then iterate thru that array and split(",") then push parts to separate arrays Thanks for help!
{ "language": "en", "url": "https://stackoverflow.com/questions/11139409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular JS dynamically set tabindex attribute I'm fairly new to Angular, and I'm working on a simple flashcard website. Here's my current relevant HTML: <div id="flashcards" class="row"> <div class="flashcard col-sm-6 col-md-4 col-lg-3" ng-repeat="card in cards"> <div class="flashcard-inside" ng-class="{'flipped' : card.flipped}"> <div class="flashcard-btns"> <button ng-click="flip(card)" class="btn btn-secondary"> <i class="fas fa-sync-alt"></i> </button> <button ng-click="remove(card)" class="btn btn-danger"> <i class="fas fa-trash"></i> </button> </div> <div class="flashcard-front"> <textarea ng-model="card.front" class="form-control flashcard-content" ng-tabindex="{-1 : card.flipped}"> </textarea> </div> <div class="flashcard-back"> <textarea ng-model="card.back" class="form-control flashcard-content" tabindex="card.flipped ? 0 : -1"> </textarea> </div> </div> </div> </div> I'm making a flashcard for each card in cards. My remove and flip functions are fairly simple: $scope.flip = (card) => card.flipped = !card.flipped; $scope.remove = (card)=> $scope.cards = $scope.cards.filter(obj=> obj.front!=card.front || obj.back!=card.back); As you can see above, I've tried ng-tabindex="{-1 : card.flipped}" and I've tried tabindex="card.flipped ? 0 : -1" and several other combinations with no luck. I was hoping someone more experienced in Angular could point me in the right direction. It seems my problems would be solved if I could get a hold of the DOM element from the card variable in my flip scrips, and set its tabindex attribute with jQuery, however I can't seem to access the element for the textarea (which would be nice because I'd also like to focus it later). A: There is no need to use ng-attr-tabindex, it can simply be done with interpolation: <div class="flashcard-front"> <textarea ng-model="card.front" class="form-control flashcard-content" tabindex="{{card.flipped ? -1 : 0}}"></textarea> </div> <div class="flashcard-back"> <textarea ng-model="card.back" class="form-control flashcard-content" tabindex="{{!card.flipped ? -1 : 0}}"></textarea> </div> The problem with the code in the question is that the interpolation needs double curly brackets ({{ }}). The ng-attr-* syntax is only necessary in exotic situations. For more information, see * *AngularJS Developer Guide - Interpolation *AngularJS Developer Guide - ngAttr for binding to arbitrary attributes A: Credit to @Phix for the suggestion to use ng-attr. The relevant part is ng-attr-tabindex="{{card.flipped ? -1 : 0}}" and the same but with !card.flipped instead of card.flipped. My full code is: <div class="flashcard-front"> <textarea ng-model="card.front" class="form-control flashcard-content" ng-attr-tabindex="{{card.flipped ? -1 : 0}}"></textarea> </div> <div class="flashcard-back"> <textarea ng-model="card.back" class="form-control flashcard-content" ng-attr-tabindex="{{!card.flipped ? -1 : 0}}"></textarea> </div> Angular Docs
{ "language": "en", "url": "https://stackoverflow.com/questions/60659886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: new line in one row bootsrap i try to add 6 elements to one row with the following definition: <div class="row container"> <div class="col-sm-4 col-md-4"> <div class="ih-item circle effect1"><a href="#"> <div class="spinner"></div> <div class="img"><img class="img-responsive" src="http://news.uwlax.edu/wp-content/uploads/2013/09/FMF.jpg" alt="img"></div> </a></div> </div>... </div> each line should contain 3 elements and the rest have to start new line. actualy the new line stand and cover part of the first line. see the attached screenshot. any advice? thanks. A: First of all, do not use 'row' and 'container' on the same <div>. 'row' should always be a child of 'container'. Second, define 3 <div>'s with 'col-md-4 col-sm-4' inside a <div class="row">. Repeat. A: maybe i was not clear enough. i inserted 6 columns into one row. each one of them has the class "col-md-4" so i accepted 2 lines with 3 columns. my problem was that the the bottom line rose slightly on top line. i succeeded to solve it by giving the attribute margin-bottom:30px; thank you for answering me.
{ "language": "en", "url": "https://stackoverflow.com/questions/30613528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I make a constant variable next to random generated characters import random number = random.sample(range(0,9999), 10) print(number, file = open("output.txt","a")) I want to add (prefix) characters to a randomly generated number. e.g. AAA(number) so that it will become something like AAA4525. What's the best way to do it? A: import random PREFIX = 'AAA' numbers = random.sample(range(0,10000), 10) # to include also 9999 with open("output.txt","a") as f: for number in numbers: f.write(f'{PREFIX}{number:0>4d}\n') A: Simple Concatenation can do the trick for you .. def converter(): string="AAA" ans= string+str(number) return ans
{ "language": "en", "url": "https://stackoverflow.com/questions/66058468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii Create Command Sort I am looking to sort by ASC or DESC and am not quite sure how to do this using Yii, my code below is as follows but I am not sure where to order by as I need to order by DESC for timestamp and ASC for homeTeamName. $query= Yii::app()->db->createCommand() ->select('*') ->from('livematch') ->where('DATE(timestamp) BETWEEN DATE(NOW()) AND DATE(NOW()) + INTERVAL 7 DAY') ->order(array('timestamp', 'homeTeamName')) ->queryAll(); Any help on this would be great A: You can add it directly like below: $query= Yii::app()->db->createCommand() ->select('*') ->from('livematch') ->where('DATE(timestamp) BETWEEN DATE(NOW()) AND DATE(NOW()) + INTERVAL 7 DAY') ->order(array('timestamp', 'homeTeamName desc')) ->queryAll(); which means: ORDER BY timestamp,homeTeamName DESC A: try like this , $query = Yii::app()->db->createCommand("SELECT * FROM livematch where DATE(timestamp) BETWEEN DATE(NOW()) AND DATE(NOW()) + INTERVAL 7 DAY order by timestamp desc" ); $std_list = $query->queryAll();
{ "language": "en", "url": "https://stackoverflow.com/questions/26276753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues using PHP MySQL Built-In Functions inside a class I am working with a MySQL Database and having some issues while trying to get data from several built-in PHP MySQL methods. I have written a class to interact with the database, and here are the relevant bits: <?php include("includes/Config.inc.php"); include_once("ChromePHP.class.php"); class Database{ private $db; private $hostname; private $username; private $password; private $schema; function __construct() { if(func_num_args() == 0){ $this->hostname = conf_hostname; $this->username = conf_username; $this->password = conf_password; $this->schema = conf_schema; } else{ $params = func_get_args(); $this->hostname = $params[0]; $this->username = $params[1]; $this->password = $params[2]; $this->schema = $params[3]; } $this->open(); } private function open(){ $this->db = mysql_connect($this->hostname, $this->username, $this->password) or die ('Error connecting to mysql'); mysql_select_db($this->schema, $this->db); mysql_query("SET NAMES utf8"); } public function executeQuery($query){ $results = mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error()); return $results; } public function executeNonQuery($query){ mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error()); $info = mysql_info($this->db); if($info){ $bits = explode(' ', $info); return $bits[4]; } return false; } public function close(){ mysql_close($this->db); } public function escape($string){ $output = mysql_real_escape_string($string , $this->db); return $output; } public function getRegionTree(){ $query = "SELECT COUNT(parent.Name) - 2 as level, node.Name AS Name, node.ID, node.Parent FROM Region AS node, Region AS parent WHERE node.LeftVal BETWEEN parent.LeftVal AND parent.RightVal and node.Name <> 'Earth' GROUP BY node.ID ORDER BY node.LeftVal"; $result = $this->executeQuery($query); $last_level = 0; $output = '<ul id="regionTree">'.PHP_EOL; while ($row = mysql_fetch_assoc($result)) { $link = '<li>'.PHP_EOL.'<a href="#" data-self="'.$row["ID"].'" data-parent="'.$row["Parent"].'">'.$row["Name"]."</a>".PHP_EOL; $diff = $last_level - $row["level"]; if($diff == 0){ // Sibling $output .= ($row["level"] != 0) ? '</li>'.PHP_EOL.$link:$link; } elseif($diff < 0){ // Child $demoter = '<ul>'.PHP_EOL; for ($i=0; $i > $diff; $i--) { $output .= $demoter; } $output .= $link; } else{ // Parent $promoter = '</li>'.PHP_EOL.'</ul>'; for ($i=0; $i < $diff; $i++) { $output .= ($row["level"] != 0) ? $promoter.PHP_EOL."</li>":$promoter; } $output .= $link; } $last_level = $row["level"]; } $output .= "</li></ul>"; return $output; } public function addRegion($name, $type, $parentID){ $query = "select Name, Region_Type from Region where ID = ".$parentID; $result = $this->executeQuery($query); if($result){ $row = mysql_fetch_assoc($result); $query = "call AddRegion('".$name."', '".$type."', '".$row["Name"]."', '".$row["Region_Type"]."', @returnCode, @returnMessage)"; $result = $this->executeQuery($query); if($result){ return true; } else{ $query = "select @returnCode as code, @returnMessage as message"; $result = $this->executeQuery($query); while($row = mysql_fetch_assoc($result)){ print_r($row); } return false; } } return false; } public function getInfo(){ return mysql_info(); } public function editRegion($id, $name, $type){ $query = "update Region set Name = '$name', Region_Type = '$type' where ID = $id"; if($this->executeNonQuery($query) > 0){ return true; } return false; } } $db = new Database(); ?> With this Database class I am able to successfully make queries, get region trees, and successfully change data in the database using the ExecuteNonQuery function. However, any attempts I have made to use mysql_info, mysql_affected_rows, or other similar functions fails, making it really difficult to write any error handling code. To make matters stranger yet, if I run the following code: <?php $db = mysql_connect("localhost", "User", "Password") or die ('Error connecting to mysql'); mysql_select_db("DB", $db); mysql_query("update Region set Name = 'test' where ID = 594", $db); echo mysql_info($db); ?> I am able to get results as expected. Any Ideas? A: Are you using mysql_info and mysql_error outside the Database class? And if so how are you referencing the database connection? If you don't identify the database connection then: The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. So internally you should be doing mysql_info($this->db); to get mysql_info. Accessing $db externally requires you to write something to get around it being private. But if you are going to be doing database stuff in an object-oriented mode you really should investigate PDO. A: After adding "or die()" statements in several places in my script, I was surprised to see that nothing was actually failing to work, instead it was failing to work the way I expected it to. The problem I was having as it turns out, was that splitting the output of mysql_info (on the space character) resulted in several indices in the array containing nothing, as would be generated by inconsistent whitespace in the output of mysql_info. The index that I thought (based upon counting spaces visually) would contain an integer instead contained a string, and I was attempting to compare that string against the number 0, which won't work. I have updated my executeNonQuery function as follows: public function executeNonQuery($query){ mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error()); $info = mysql_info($this->db); if($info){ $output = array(); $bits = explode(' ', $info); $output["rowsMatched"] = $bits[2]; $output["rowsChanged"] = $bits[5]; $output["warnings"] = $bits[8]; return $output; } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/9403016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert asp.net Membership-generated UserId into custom table (vb) I've spent a couple of hours trying to find the answer to this, and although there are tutorials all over the 'net none of them work for me (or I am too n00b to understand what they're telling me...) Anyway, I'm creating users in asp.net using Membership. What I want to do is add the generated UserId to a column in a custom table I've created, to link the stuff in the custom table with the user created in aspnet_Users. Here's the code I've got for the registration submit button: Private Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click Dim connectionString As String = WebConfigurationManager.ConnectionStrings("edinsec").ConnectionString Dim createStatus As MembershipCreateStatus Membership.CreateUser(fname.Text, password.Text, email.Text, sq.Text, sa.Text, False, createStatus) ''#Something has to happen here! Dim insertSQL As String insertSQL = "INSERT INTO clients (UserId)" insertSQL &= "VALUES (@userId)" Using con As New SqlConnection(connectionString) Dim cmd As New SqlCommand(insertSQL, con) cmd.Parameters.AddWithValue("@firstname", firstname.Text) Try Try con.Open() Catch ex As SqlException MsgBox("Connection Problem - Please Retry Later", 65584, "Connection Error") End Try cmd.ExecuteNonQuery() MsgBox("Thank you for joining us - we will be in touch shortly.", 65600, "Join Up") Response.Redirect("Default.aspx") Catch Err As SqlException MsgBox("Error inserting record - please retry later.", 65584, "Insertion Error") End Try con.Close() End Using End Sub As you can see I'm trying to grab the Membership-generated userid and insert it into the clients table. I've tried numerous approaches to grabbing the UserId but none work. Membership works to create the user, it's just the part afterwards that I'm stuck on. Any help would be much appreciated :) A: I managed it in the end using this code: Dim userid As Guid = New Guid(Membership.GetUser(username.Text).ProviderUserKey.ToString()) ...where username.Text is the content of the username form input, where the user chooses their username. The relevant parameter line is this: cmd.Parameters.Add("@UserId", g) I get a warning about the method I'm using being deprecated, but it works at least! A: Membership.CreateUser returns a MembershipUser object. You can get the UserId from that returned object. MembershipUser user = Membership.CreateUser(...); Guid userId = (Guid)user.ProviderUserKey;
{ "language": "en", "url": "https://stackoverflow.com/questions/4217705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: KendoUI in angular.js - how to update multiple pointers value I'm trying to use kendo-radialgauge of "kendo.directives" with two pointers but my problem is to update the both pointers from controller. How can I do it ? Two pointers in UI <span kendo-radialgauge k-options="options" k-ng-model="menuOptions" ></span> angular.module("app", ["kendo.directives"]) A: I don't know kendo but I found this: http://docs.telerik.com/kendo-ui/AngularJS/introduction#widget-update-upon-option-changes You can also read about controller-directive communication and about scope.$watch, scope.$on
{ "language": "en", "url": "https://stackoverflow.com/questions/38954898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting colored image to grayscale I am working on processing images that consists of colors that have the same grayscale. In other words, each image is colored with random colors that have the same gray value. When I converted the image using (rgb2grey() from skimage or cv2.cvtColor() from OpenCV), the resulted image has only one gray value (or slightly difference gray values (unperceivable by human eyes). Therefore, the resulted image details unrecognizable. My questions are: * *What are the best way to do before converting these images to grayscale ones? (Please note the colors of these images are not fixed) *Are there any color combinations for which the color-gray conversion algorithms won't work? A: How about using YCbCr? Y is intensity, Cb is the blue component relative to the green component and Cr is the red component relative to the green component. So I think YCbCr can differentiate between multiple pixels with same grayscale value.
{ "language": "en", "url": "https://stackoverflow.com/questions/65220970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sort multidimensional array alphabetically into 2 columns I have an array that looks like this Array ( [0] => Array ( [make] => Alfa Romeo [id] => 2 ) [1] => Array ( [make] => Aston Martin [id] => 3 ) [2] => Array ( [make] => Audi [id] => 4 ) [3] => Array ( [make] => BMW [id] => 8 ) [4] => Array ( [make] => Caterham [id] => 9 ) ) i could like to sort it vertically into 2 columns so it would look like this Alfa Romeo BMW Aston Martin Caterham Audi right now it looks like this when Yii generates a checkbox using the checkBoxList() function Alfa Romeo Aston Martin Audi BMW Caterham right now i have this to sort. but this only works with 1 dimensional arrays function array_chunk_vertical($data, $columns = 2) { $n = count($data) ; $per_column = floor($n / $columns) ; $rest = $n % $columns ; // The map $per_columns = array( ) ; for ( $i = 0 ; $i < $columns ; $i++ ) { $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ; } $tabular = array( ) ; foreach ( $per_columns as $rows ) { for ( $i = 0 ; $i < $rows ; $i++ ) { $tabular[$i][ ] = array_shift($data) ; } } return $tabular ; } A: There's nothing about your existing function that prevents it from being used on an n-dimensional array. In fact, the function you show here, gives exactly the desired output using the provided input. <?php function array_chunk_vertical($data, $columns = 2) { $n = count($data) ; $per_column = floor($n / $columns) ; $rest = $n % $columns ; // The map $per_columns = array( ) ; for ( $i = 0 ; $i < $columns ; $i++ ) { $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ; } $tabular = array( ) ; foreach ( $per_columns as $rows ) { for ( $i = 0 ; $i < $rows ; $i++ ) { $tabular[$i][ ] = array_shift($data) ; } } return $tabular ; } $cars = [ [ 'make' => 'Alfa Romeo', 'id' => 2 ], [ 'make' => 'Aston Martin', 'id' => 3 ], [ 'make' => 'Audi', 'id' => 4 ], [ 'make' => 'BMW', 'id' => 8 ], [ 'make' => 'Caterham', 'id' => 9 ], ]; echo '<table>'; foreach(array_chunk_vertical($cars) as $row) { echo '<tr>'; foreach($row as $car) { echo '<td><input type="checkbox" value="', $car['id'], '" />', $car['make'], '</td>'; } echo '</tr>'; } echo '</table>'; A: In that case you should add your data into a new one dimension array.Try something like the following $a = array(0 => array( 'make' => 'Alfa Romeo', 'id' => 2 ), 1 => array( 'make' => 'Aston Martin', 'id' => 3 ), 2 => array( 'make' => 'Audi', 'id' => 4 ), 3 => array( 'make' => 'BMW', 'id' => 8 ), 4 => array( 'make' => 'Caterham', 'id' => 9 ) ); $b=array(); foreach ($a as $v) { $b[]=$v['make']; } sort($b); print_r($b); Then you can use your working function passing the new array as the parameter. A: try this,add up som condtions to display in your two column <?php $sort=Array ( 0 => Array ( 'make' => 'Alfa Romeo' ,'id' => 2 ), 1 => Array ( 'make' => 'Aston Martin' ,'id' => 3 ) , 2 => Array ( 'make' => 'Audi' ,'id' => 4 ), 3 => Array ( 'make' => 'Caterham' ,'id' => 8 ), 4 => Array ( 'make' => 'BMW' , 'id' => 9 ) ); print_r($sort); sort($sort); echo ' <br/>'; print_r($sort); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/26525023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css - removing background image i have this image in the background: http://yoursdproperty.com/templates/pjo_joomlaforall/images/bgr.png of this page: http://yoursdproperty.com/index.php?option=com_jumi&fileid=8&Itemid=34 how do i remove it? i understand that if i remove it the page will just be white in the background correct? if not, what do i need to do to get rid of the gray and white and just make it white? A: If you change the following style you should get what you want: #background_right { /*background:transparent url(../images/bgr.png) no-repeat fixed center top;*/ background-color:white; margin:0; padding:0; } A: Just remove or outcomment the particular CSS line responsible for this. Or am I thinking too simple about this problem? If so, then please elaborate more about the context of the problem. If it is for instance an autogenerated stylesheet which you don't have control over, then best what you can do is to grab JavaScript (jQuery?) to remove/override the background image in the particular style class. Edit: if you rather want a white background, then you'll need to get rid of the .body_background class as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/2173491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wpf layout with datagrid and expander Im having trouble getting my xaml to work the way i want to. What i want to is this. My ItemsControl should have a height of 70. The rest of the space should be filled with a DockPanel. Inside the DockPanel i have a GridControl (DataGrid from DevExpress) that are supposed to fill all empty space. The gridcontrol is docked to top. Below the gridcontrol but still insdie the dockpanel, i have a Expander that have a maxheight of 480, this should be docked to the bottom. The problem im having is that i can't get the gridcontrol to dynamically change it's height so that it fills all remaining space between the top of the docking panel down to the Expander. What am i doing wrong? <Grid Background="White"> <Grid.RowDefinitions> <RowDefinition Height="70" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> </Grid.ColumnDefinitions> <!--#region ItemControl--> <ItemsControl Grid.Row="0" Grid.ColumnSpan="9" HorizontalAlignment="Stretch" IsTabStop="False" ItemsSource="{Binding Path=ToolbarControlViewModel.CommandButtonList}" Style="{DynamicResource ActionBarPanel}"> <ItemsControl.ItemsPanel> ... </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> ... </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <!--#endregion--> <DockPanel Grid.Row="1"> <!--#region Listview--> <dxg:GridControl x:Name="CMGrid" DockPanel.Dock="Top" Margin="0,0,0,10" ItemsSource="{Binding Path=CustomerManagementListViewModel.Customers}" ScrollViewer.VerticalScrollBarVisibility="Visible"> <dxg:GridControl.Columns> ... </dxg:GridControl.Columns> <dxg:GridControl.View> <dxg:TableView x:Name="CustomerListView" AllowBestFit="True" FocusedRow="{Binding Path=CustomerManagementListViewModel.SelectedCustomer, Mode=TwoWay}" IsColumnMenuEnabled="False" NavigationStyle="Row" ShowGroupPanel="False" AutoWidth="True"/> </dxg:GridControl.View> </dxg:GridControl> <!--#endregion--> <!--#region Controls--> <Expander MaxHeight="480" VerticalContentAlignment="Stretch" DockPanel.Dock="Bottom" Header="{T:Translate Equipment, Format=' {0}:'}" IsExpanded="True" Style="{StaticResource K2M_Epander_Base}" VerticalAlignment="Bottom"> <Expander.Content> <Grid> ... </Grid> </Expander.Content> </Expander> <!--#endregion--> </DockPanel> A: I feel bad getting points for such a quickie but if the question's going to remain I guess we may as well give some closure for future finders. So, DockPanel has its uses but in this scenario it's your culprit. As a DockPanel nested in a layout as such is basically the equivalent of attaching the VerticalAlignment="Top" property to your GridControl. Which interprets as it only consuming the space necessary for it from the top down of the parent row. By removing the DockPanel entirely (since in this scenario it's redundant) and applying the Row declaration directly to the GridControl it has the ability to act as a normal child to the parent Grid container and will consume the space provided by the Row's * declaration. Glad you got it sorted, got to love the quick 'n easy ones. Cheers :)
{ "language": "en", "url": "https://stackoverflow.com/questions/44635345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular testing without mocked $http I have a REST client written to be part of an angularJS application that I want to write tests for; I tried with Jasmine (using passthrough on the $httpBackend) but could not get it to talk to the real endpoint at all (which is a requirement). Does anybody know of a sensible library that allows for this? Or alternatively, a way of wrestling Jasmine into submission? A: you need to inject first $httpbackend describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; $httpBackend.when('GET', "/api/rest/").respond(data_to_respond); })); next write test cases it('getTypes - should return 3 car manufacturers', function () { service.getTypes().then(function(response) { //expect will be here }); $httpBackend.flush(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/38832538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: finding volley requests response time android I have been using volley for making rest calls to server. I am trying to send the response time for each requests to Google analytic to analyze the server latency, in volley jsonobject request is there any way to finding the response time for each requests. If volley doesn't provide this function how can I calculate the response time for each requests?. A: You'll need to calculate this yourself. Here's a quick way to see how long it takes for the response to arrive: private long mRequestStartTime; public void performRequest() { mRequestStartTime = System.currentTimeMillis(); // set the request start time just before you send the request. JsonObjectRequest request = new JsonObjectRequest(URL, PARAMS, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // calculate the duration in milliseconds long totalRequestTime = System.currentTimeMillis() - mRequestStartTime; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { long totalRequestTime = System.currentTimeMillis() - mRequestStartTime; } }); requestQueue.add(request); }
{ "language": "en", "url": "https://stackoverflow.com/questions/29386249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Selection criteria live in master page or content page? Scenario: * *Four or so dropdowns with labels that the user can change. *After user changes the dropdowns a grid below will change *Several pages will reuse this design, but the grid may have different columns and there may be other grids that get added. Question: Where to place these selections? The two obvious choices are: * *Place the selection criteria directly on the master page and access the values in the content page or *Place the selection criteria in a user control that lives on each of the content pages. Pros/Cons for #1: * *Pro - More maintainable because they live on a single master page instead of on each content page *Con - Requires content pages to subscribe to change events Pros/Cons for #2 * *Pro - Don't have to subscribe to change events *Con - less maintainable, because each content page has to figure out what to do with the selections. Can anyone make an argument why one is better than the other? Thanks. A: "Content pages to subscribe to change events" doesn't seem to be either a benefit or a drawback without further elaboration. You cannot really morph it to either category by prefixing "Do" or "Don't". The logic above (if you agree) leaves us with the following choices: 1 * *Pros - More maintainable because they live on a single master page instead of on each content page *Cons - None 2 * *Pros - None *Cons - less maintainable, because each content page has to figure out what to do with the selections. The choice is rather clear if you don't want to throw in more criteria.
{ "language": "en", "url": "https://stackoverflow.com/questions/8156190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Router not working (Heroku + Nginx + PHP Phalcon) I don't get it why the mvc routes are not working. When I access the home page, all the css and js are loaded. "GET /css/main.css HTTP/1.1" 304 But when I access any other controller, I got: method=GET path="/transaction/add" [error] open() "/app/public/transaction/add" failed (2: No such file or directory) "GET /transaction/add HTTP/1.1" 404 Here's my procfile --Procfile-- web: vendor/bin/heroku-php-nginx public/ location / { # try to serve file directly, fallback to rewrite try_files $uri @rewriteapp; } location @rewriteapp { # rewrite all to app.php rewrite ^(.*)$ /index.php/$1 last; } location ~ ^/(app|app_dev|config)\.php(/|$) { try_files @heroku-fcgi @heroku-fcgi; internal; } I'm really lost here. A: This should work: location / { # try to serve file directly, fallback to rewrite try_files $uri @rewriteapp; } location @rewriteapp { # rewrite all to app.php rewrite ^(.*)$ /index.php/$1 last; } location ~ ^/index\.php(/|$) { try_files @heroku-fcgi @heroku-fcgi; internal; } A: Try to follow the instructions in the documentation: http://docs.phalconphp.com/fr/latest/reference/nginx.html server { listen 80; server_name localhost.dev; index index.php index.html index.htm; set $root_path '/var/www/phalcon/public'; root $root_path; try_files $uri $uri/ @rewrite; location @rewrite { rewrite ^/(.*)$ /index.php?_url=/$1; } location ~ \.php { fastcgi_pass unix:/run/php-fpm/php-fpm.sock; fastcgi_index /index.php; include /etc/nginx/fastcgi_params; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~* ^/(css|img|js|flv|swf|download)/(.+)$ { root $root_path; } location ~ /\.ht { deny all; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29418400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest method for SAX parsing in Python I have an XML document (1.5MB) that needs to be parsed in real-time for a web service that I am developing. I am using the cElementTree Python library which, according to this post, is the preferred way to parse XML in Python, but I'm not sure if this is actually the fastest way. I would like to increase parsing performance as well as minimise the memory usage on my server and am testing the SAX approach with ET.iterparse() at the moment. My benchmark shows the following results for purely parsing the same XML document 200 times. * *DOM with ET.XML(): 20.5s *SAX with ET.iterparse(): 32.4s Which is equivalent to roughly 102ms for the DOM versus 162ms for the SAX per XML document. However, I would still like to squeeze more performance out of the SAX approach to match the 102ms of DOM or possibly go even faster, as performance and memory are both critical in my application. I am using one of the common ways for SAX parsing like the code below: from cStringIO import StringIO import xml.etree.cElementTree as ET def parse(xml_string): result = [] io = StringIO(xml_string) context = ET.iterparse(io, events=("start", "end")) for event, elem in context: tag = elem.tag value = elem.text if event == 'end': # get value from element and add to result[] pass elem.clear() return result
{ "language": "en", "url": "https://stackoverflow.com/questions/17100993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot execute crontab command from a php script...from shared host I'm running an application where I need to execute the cron job, once a form is submitted,contains more than 1 lac records in a loop(its on-demand execution of cron job and deletes the job once finished). I'm using php, I tried to configure the job through cpanel as a test and it works...the command was.."/ramdisk/bin/php5 -f /home/user/public_html/domain/cron.php -q", it worked fine. But when I tried to run the same job with the exec() of php, like I wrote this whole command to a file (I do not know where the original crontab file is located otherwise could have written to it, please suggest a way to find its location) and ran that file like "exec("crontab /home/user/cron/Feed_cron"); ", in this cron is not working... I doubted whether the crontab command will not work for particular user.. I tried it from the "root" user....which is the root user....tried the command via SSH or Putty and the response was "command not found". Please find a solution for this, also please give me an idea whether my concept works fine... A: please suggest a way to find its location Try whereis crontab
{ "language": "en", "url": "https://stackoverflow.com/questions/2235950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't get selected spinner item outside @Override method and into another class I have MainActivity and SpinnerActivity, I want to get selected spinner item value from SpinnerActivity into the MainActivity. I tried to declare String as Static, I also tried with getter but without any success. in Spinner Activity I also have if statement, how can I get value outside "if statement" and "@Override method" into another class? MainActivity.class public class MainActivity extends AppCompatActivity { SpinnerActivity spinnerActivity = new SpinnerActivity(); Spinner spinnerProvince; String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince; // String selectedSpinnerProvince = SpinnerActivity.inSpinnerSelectedProvince; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinnerProvince = findViewById(R.id.spinnerProvince); populateSpinnerProvinces(); spinnerProvince.setOnItemSelectedListener(spinnerActivity); } public void populateSpinnerProvinces() { ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.province)); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerProvince.setAdapter(provincesAdapter); } } SpinnerActivity.class public class SpinnerActivity implements android.widget.AdapterView.OnItemSelectedListener { public String inSpinnerSelectedProvince; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getId() == R.id.spinnerProvince) { inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString(); Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show(); } else {// code here} } @Override public void onNothingSelected(AdapterView<?> parent) { } } A: I were about to advice you to use Intent to share data between both activities when i noticed that your "SpinnerActivity" is not really an Activity since it not extends Android Activity class (AppCompactActivity or other classes like this). Your SpinnerActivity is a Listener. You can use it to implement the action to trigger when an action is performed on your Spinner view. For that you need to do it inside the "@Override" method of onItemSelected. If you don't like to use the previous methode because of the Override methode you should implement directly the action to trigger at on click events on your spinner view in your MainActivity by doing this: public class MainActivity extends AppCompatActivity { SpinnerActivity spinnerActivity = new SpinnerActivity(); Spinner spinnerProvince; String selectedSpinnerProvince = spinnerActivity.inSpinnerSelectedProvince; // String selectedSpinnerProvince = SpinnerActivity.inSpinnerSelectedProvince; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinnerProvince = findViewById(R.id.spinnerProvince); populateSpinnerProvinces(); //spinnerProvince.setOnItemSelectedListener(spinnerActivity); spinnerProvince.setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getId() == R.id.spinnerProvince) { inSpinnerSelectedProvince = parent.getItemAtPosition(position).toString(); Toast.makeText(parent.getContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show(); } else {// code here} } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void populateSpinnerProvinces() { ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.province)); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerProvince.setAdapter(provincesAdapter); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65614869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caesar Cyper Python def caesar_encript(txt, shift): chiper = "" for i in range(len(txt)): char = txt[i] if char == " " : chiper += ' ' elif (char.isupper()): chiper += chr((ord(char) + shift - 65) % 26 + 65) elif (char.islower()): chiper += chr((ord(char) + shift - 97) % 26 + 97) return chiper def caesar_decript(chiper, shift): return caesar_encript(chiper, -shift) msg = 'Random Mesage, WOOOWW!' cpr = caesar_encript(msg,4) txt = caesar_decript(cpr,4) print('plain text : ', txt) print('chiper text : ', cpr) I made a code for encryption but the output does not display special characters and I want special characters to be displayed without encryption A: A crude solution would be to replace this if char == " " : chiper += ' ' with this if not char.isalpha(): chiper += char A: The special characters are not considered because they're also being encrypted. This approach places an if condition before that where isalnum() decides only alpha numeric characters to become encrypted. def caesar_encript(txt, shift): chiper = "" for i in range(len(txt)): char = txt[i] if not char.isalnum(): chiper+=char else: if (char.isupper()): chiper += chr((ord(char) + shift - 65) % 26 + 65) elif (char.islower()): chiper += chr((ord(char) + shift - 97) % 26 + 97) Output plain text : Random Mesage, WOOOWW! chiper text : Verhsq Qiweki, ASSSAA!
{ "language": "en", "url": "https://stackoverflow.com/questions/69513622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Checking Application API Version in XCode? Possible Duplicate: Alert when new version of iOS app is available I need code that I can embedd into my project code so that every request from the application to server contains the API version in case my iPhone app gets a new update so it can notify the user to update the new version of the application. Where should I add the code to check this and what line of code is needed for it. I am not getting the right procedure to follow. Please Help, Thank you. A: You can do it like this: * *Just create the separate web-service on server side which have parameter as app version. *Set the global variable on server side which holds the latest version of the app. *Now, from your application, when app will be launched, then call this service with the parameter of api version used in the app. (this api version will be static, because you have done the code for same. And when you will update your app then you will change the api code yourself. Hope you understand). *Check the api version on server side, and if app api using latest version then return TRUE. And if api on app using lower version then return FALSE. *Now, in application, if web-service returns the FALSE then just inform the user by ALERT that, he is using the lower version of the api and download latest app to use the latest api. Hope, you got an idea of what to do. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/14017360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Time for query in RavenDB is too long I have an example for testing time of query in RavenDB. So I use Linq to query and StopWatch for geting timings. But when I run my code, timing seems too long (it is 2401 ms) so I try to query by Ranven Studio and the result, timing is just taking 1 ms. I don't know why it has much more different like that. Ps: My database has 200 000 documents and i have indexes for that, of course. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Raven.Client.Documents; using Raven.Client.Documents.BulkInsert; namespace ConsoleApplication6 { public class Customer { public string Id { get; set; } public string Name { get; set; } } public class SupportCall { public string Id { get; set; } public int Cost { get; set; } public string CustomerId { get; set; } public DateTime StartDay { get; set; } public DateTime EndDay { get; set; } public string Issue { get; set; } } internal class Program { private static char[] _buffer = new char[6]; private static string RandomName(Random rand) { _buffer[0] = (char)rand.Next(65, 91); for (int i = 1; i < 6; i++) { _buffer[i] = (char)rand.Next(97, 123); } return new string(_buffer); } static void Main(string[] args) { using (var store = new DocumentStore { Urls = new[] { "http://localhost:8080" }, Database = "Test" }.Initialize()) { using (var session = store.OpenSession()) { var sp = Stopwatch.StartNew(); SupportCall supportCall = session.Query<SupportCall>() .Include<SupportCall>(s => s.CustomerId) .Where(s => s.Cost == 21821).FirstOrDefault(); Customer customer = session.Load<Customer>(supportCall.CustomerId); sp.Stop(); Console.WriteLine(sp.ElapsedMilliseconds); } Console.ReadKey(); } } } } A: Can you make the same query (actually, better use a different parameters, to avoid the cost of caching) and check again? The most common reason for this to take so long is that you are paying for the first time connection and establishing of the document store setup. The strange part here is that you are doing this on the local host, so I would expect this to be very fast, even on the initial call. You can use Fiddler (change the url to be: "http://localhost.fiddler:8080" so it will capture it) to see what are the costs on the network. I have seen stuff like that happen because of anti virus and packet inspection utils.
{ "language": "en", "url": "https://stackoverflow.com/questions/53670605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python Flask, TypeError: 'NoneType' object is not subscriptable I'm studying Flask very recently and trying to create API. However, when It request json data, this error occurs. if content['words'] is not None: TypeError: 'NoneType' object is not subscriptable could anyone can help this? Thanks my code is below: @app.route("/process",methods=['GET', 'POST']) def process(): content = request.json words = {} if content['words'] is not None: for data in content['words'].values(): words[data['word']] = data['weight'] process_from_text(content['text'], content['maxCount'], content['minLength'], words) result = {'result':True} return jsonify(result A: The problem is most likely that request is not a valid json request. If that is the case then content will be equal to None which means it is not subscriptable.
{ "language": "en", "url": "https://stackoverflow.com/questions/60979321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ggpairs Change the colum label of factor levels It is possible to change the column label of factor levels without having to change the values in the data.frame for example in the following graph can I change the label of Female and Male to F and M respectively without having to change the df? library(GGally) data(tips, package = "reshape") pm <- ggpairs(tips, 1:3, columnLabels = c("Total Bill", "Tip", "Sex")) pm A: After pm <- ggpairs(tips, 1:3, columnLabels = c("Total Bill", "Tip", "Sex")) do this levels(pm$data$sex)[levels(pm$data$sex) == "Male"] = "M" levels(pm$data$sex)[levels(pm$data$sex) == "Female"] = "F" You'll get this plot: It won't change anything in tips dataset: head(tips) total_bill tip sex smoker day time size 1 16.99 1.01 Female No Sun Dinner 2 2 10.34 1.66 Male No Sun Dinner 3 3 21.01 3.50 Male No Sun Dinner 3 4 23.68 3.31 Male No Sun Dinner 2 5 24.59 3.61 Female No Sun Dinner 4 6 25.29 4.71 Male No Sun Dinner 4
{ "language": "en", "url": "https://stackoverflow.com/questions/34276422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is WPF with version 3.5 fits Windows7 and Windows8? i am developing WPF application in visual studio and using .NET 3.5. does the application fits Windows7 and Windows8 OS with no .NET framework additional installation? do i need to add .NET 3.5 installation to setup project? A: In Windows 7 .NET framework 3.5 is part of the operating system so all machines should have it. In Windows 8 or windows 8.1 .NET framework 3.5 is NOT automatically installed (though all machines that are upgraded from win 7 -> win 8 should have it). To run apps that require the .NET Framework 3.5 on Windows 8 or later, you must enable version 3.5 on your computer. There are two ways you can do this: by installing or running an app that requires the .NET Framework 3.5 (that is, by installing the .NET Framework 3.5 on demand), or by enabling the .NET Framework 3.5 in Control Panel. Both options require an Internet connection. If an app requires the .NET Framework 3.5, but doesn't find that version enabled on your computer, it displays a message box, either during installation, or when you run the app for the first time. In the message box, choose Install this feature to enable the .NET Framework 3.5. The above require an internet connection. If this is not possible you will have to include the .exe files of .NET 3.5 in your distribution however as MSDN states: The .NET Framework 4.5 and its point releases are backward-compatible with apps that were built with earlier versions of the .NET Framework. In other words, apps and components built with previous versions will work without modification on the .NET Framework 4.5. However, by default, apps run on the version of the common language runtime for which they were developed, so you may have to provide a configuration file to enable your app to run on the .NET Framework 4.5 So build your project for 3.5 and just deploy it to windows 8 machines. It should run, but its not the "best" environment for the app. The "best" would be to have .NET 3.5 installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/26728939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where is the connection between the two Python venv environments I have two python environments and somehow there is some kind of link between them. /home/testapi/API25/env is the original venv /home/preprodapi/API25/env was created by means of a cpio copy from the first. This worked find for many months. But now a problem has cropped up. The symptom is that in preprodapi the pytz package isnt able to find the timezone Africa/Johannesburg (and presumably others), as evidenced by the stack trace: Traceback (most recent call last): File "/home/preprodapi/API25.8512/validator/echo.py", line 244, in jsonified_wrapper response_obj = request_handler(*args, **kwargs) File "/home/preprodapi/API25.8512/validator/echo.py", line 478, in bearer_token_wrapper return request_handler(*args, **kwargs) File "/home/preprodapi/API25.8512/validator/echo.py", line 1068, in globaldb_connection_wrapper return request_handler(*args, **kwargs) File "/home/preprodapi/API25.8512/validator/echo.py", line 569, in get_school_wrapper return request_handler(*args, **kwargs) File "/home/preprodapi/API25.8512/validator/echo.py", line 697, in school_admin_wrapper return request_handler(*args, **kwargs) File "/home/preprodapi/API25.8512/routehandlers.py", line 4035, in email_report do_email_report(kwargs.get('reportid'), json_attrs, getctx_school().get('schoolname')) File "/home/preprodapi/API25.8512/validator/echo.py", line 1155, in do_email_report tz = pytz.timezone(sender.school.get("local_timezone")) File "/home/testapi/API25/env/lib64/python3.5/site-packages/pytz/__init__.py", line 181, in timezone pytz.exceptions.UnknownTimeZoneError: 'Africa/Johannesburg' Notice how it switches from /home/preprodapi/.... to /home/testapi/... in the final item. But WHY is this happening? (env) [root@ip-172-31-8-200 API25]# deactivate [root@ip-172-31-8-200 API25]# pwd /home/preprodapi/API25 [root@ip-172-31-8-200 API25]# . env/bin/activate (env) [root@ip-172-31-8-200 API25]# pip uninstall pytz Uninstalling pytz-2017.2: Would remove: /home/testapi/API25/env/lib/python3.5/site-packages/pytz-2017.2.dist-info/* /home/testapi/API25/env/lib/python3.5/site-packages/pytz/* Proceed (y/n)? n (env) [root@ip-172-31-8-200 API25]# python Python 3.5.5 (default, Feb 6 2018, 10:57:32) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pytz >>> print(pytz.timezone('Africa/Johannesburg')) Africa/Johannesburg For the record I can't find any soft links between the venv's (env) [root@ip-172-31-8-200 API25]# pwd /home/preprodapi/API25 (env) [root@ip-172-31-8-200 API25]# find env -type l -ls 40549590 0 lrwxrwxrwx 1 root root 3 Feb 4 12:54 env/lib64 -> lib 40549592 0 lrwxrwxrwx 1 root root 15 Feb 4 12:54 env/bin/python3.5m -> /bin/python3.5m 40549593 0 lrwxrwxrwx 1 root root 10 Feb 4 12:54 env/bin/python -> python3.5m 40549594 0 lrwxrwxrwx 1 root root 10 Feb 4 12:54 env/bin/python3 -> python3.5m Help please! P.S note /home/preprodapi/API25.8512 is a cpio copy of /home/preprodapi/API25. I get the exact same results when I test in the API25.8512 sub-directory Note #2: The same does not happen with another venv on this host [root@ip-172-31-8-200 API25.8512]# cd /home/apiuser [root@ip-172-31-8-200 apiuser]# cd API25 [root@ip-172-31-8-200 API25]# . env/bin/activate (env) [root@ip-172-31-8-200 API25]# pip uninstall pytz Uninstalling pytz-2018.9: Would remove: /home/apiuser/API25/env/lib/python3.5/site-packages/pytz-2018.9.dist-info/* /home/apiuser/API25/env/lib/python3.5/site-packages/pytz/* Proceed (y/n)? n A: You need to check your sys.path and find the source of anomalies, if any. See Debugging modifications of sys.path for a way to track changes to sys.path and Can I zip all the python standard libs and the python still able to import it? for how it's constructed. venv is implemented via Py3's stock site.py: If a file named "pyvenv.cfg" exists one directory above sys.executable, sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the "real" prefixes of the Python installation). If "pyvenv.cfg" (a bootstrap configuration file) contains the key "include-system-site-packages" set to anything other than "false" (case-insensitive), the system-level prefixes will still also be searched for site-packages; otherwise they won't. When creating a venv, python and a number of other files are copied into <venv>/bin (<venv\Scripts in Windows), and a pyvenv.cfg is placed into <venv> for site.py to find upon Python startup. activate prepends <venv>/bin to PATH so that the local executable is started instead of the system one when you type "python". Ultimately, this results in a sys.path that combines system-wide standard library with venv-specific 3rd-party modules. It would look something like this: >>> sys.path ['', '<venv>/bin/python36.zip', <system Python platlib>, <system Python purelib>, '<venv>', '<venv>/lib/site-packages'] So, normally, there shouldn't be folders from another venv in sys.path resulting directly from venv logic. They may result from PYTHONPATH, or from some .pth files, or even from your own code. The above diagnostics should show where they come from.
{ "language": "en", "url": "https://stackoverflow.com/questions/54523408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with CAGradientLayer in a custom UIView within a UITableViewCell I have a somewhat special situation that I need help with. I have a CustomView which I am placing in every UITableViewCell in my UITableView. No problems there. Within my CustomView is a UILabel which displays some text given to it. Depending on the length of the text, the width of the CustomView grows/shrinks. All fine. The problem I am having is with a sublayer in my CustomView which is a gradient (CAGradientLayer). The gradient size will not grow/shrink off screen on cells not in view. Let me show you some code... I create my CustomView like so: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; CustomView *custom = [[CustomView alloc] init]; custom.tag = 777; [cell.contentView addSubview:custom]; [custom release]; } } I don't initWithFrame at this stage as the cell could get reused and the width is always wrong. Once the cell is there, I call a method configureCell: where I do the following: CGSize teamMaxSize = CGSizeMake(300, 18); CGSize teamNewSize = [[managedObject valueForKey:@"category"] sizeWithFont:[UIFont systemFontOfSize:kFontSizeTeam] constrainedToSize:teamMaxSize lineBreakMode:UILineBreakModeWordWrap]; CustomView *lozenge = (CustomView *) [cell.contentView viewWithTag:777]; lozenge.frame = CGRectMake(10, 5, teamNewSize.width+12, 18); [lozenge resetSize]; [lozenge setLabel:[managedObject valueForKey:@"category"]]; This works fine, the width of my CustomView is setup as per the length of the 'category' key. The resetSize; method above simply resizes the UILabel I mentioned before to the new frame of the CustomView before I fill it with the value. Anyway, back to my issue. I am creating the background gradient in the drawRect: method of my CustomView. It works fine, however is the size of the CustomView at init. After I resize I need to resize the gradient.frame. So, I tried adding gradient.frame = self.bounds When I call resetSize in my aforementioned code. However when scrolling through the UITableView I can see the gradient literally filling from left to right as it loads into view. Is there anyway I can get this to happen 'off screen' so the CustomView is filled with the gradient as soon as it appears? A: Instead of creating a gradient in drawRect:, have you considered using CAGradientLayer as the layer class of your custom view, e.g.: + (Class)layerClass { return [CAGradientLayer class]; } Then you can perform any setup of your gradient in your initializer, via self.layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/3738782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual studio is encountering an error with taskkill commands I am running a unit test using VS2019, C#. After I build my project errors show. I am able to run my test from the last successful build, but I have no idea how to approach this. The command is coming from a prebuild batch file stored in the project. Severity Code Description Project File Line Suppression State Error The command " taskkill /f /fi "imagename eq BrowserStackLocal.exe" taskkill /f /fi "imagename eq IEDriverServer.exe" taskkill /f /fi "imagename eq chromedriver.exe" taskkill /f /fi "imagename eq geckodriver.exe"" exited with code 1. Test.Tools.TaskKill enter image description here
{ "language": "en", "url": "https://stackoverflow.com/questions/75636126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ArrayList add() method acting weird? I'm working on a (double) linked list implementation using "buckets". In short, A doubly linked list of nodes, each node holding an ArrayList of a set size specified by arguments. I've Initialized my Nodes and list like this: public class MyLinkedList<T> implements ADTListInterface<T> { ArrayList<T> list; private class Node { T value; Node next; Node previous; ArrayList<T> list; public Node(Node n, Node p) { list = new ArrayList<T>(bucketSize); next = n; previous = p; } } private Node head; private Node tail; private int bucketSize; public MyLinkedList(int bucketSize) { this.bucketSize = bucketSize; head = tail = new Node(null, null); } and I have set up my add method like this: public void add(T o) { Node current = head; while (current.list.add(o) != true) { if (current.next != null) { current = current.next; } if (current.next == null) { current.next = new Node(null,current); } } } When testing the add method with bucketSize = 3 and the following commands: list.add("a"); list.add("b"); list.add("c"); I expect the head node to contain a list with elements and order as follows: c,b,a However, the line: current.list.add(o) appears to add the specified object multiple times until it fills the list. so my node turns out to contain the elements: a,a,a Thank you in advance for looking at my code. A: Part of your problem lies in your logic that prints the content of the list and part of it is in your add method. First of all your current node is a local variable of add method. That means second 'if' statement: if (current.next != null) { current = current.next; } is not doing anything useful. You set current to point at the same object as current.next does but then you leave the method and your reference is destroyed. It does not make sense. Assuming you invoked constructor of your list and then added three elements: "a", "b", "c" here is how your Node objects will behave on heap. After constructor finished there is one Node object on the heap which looks like: { list -> {empty}, prev -> null, next -> null } this object is referenced by the head and tail reference variables. Note that if you invoke new ArrayList(bucketSize) it will create empty list with 'bucketSize' initial capacity. After 1st call to add("a"): nodeObject#1 : { list -> {"a"}, prev -> null, next -> nodeObject#2 } nodeObject#2 : { list -> {empty}, prev -> nodeObject#1, next -> null} nodeObject#1 is accesible via head or tail. nodeObject#2 is accesible via head.next or tail.next. After 2nd call to add("b"): nodeObject#1 : { list -> {"a","b"}, prev -> null, next -> nodeObject#2 } nodeObject#2 : { list -> {empty}, prev -> nodeObject#1, next -> null} After 3rd call to add("c"): nodeObject#1 : { list -> {"a","b","c"}, prev -> null, next -> nodeObject#2 } nodeObject#2 : { list -> {empty}, prev -> nodeObject#1, next -> null} Also having prev and next in your Node suggest that your list should be bi directional that means you need to implement methods like add_at_the_end and add_at_the_beginning but that's a different story ( I can show some examples too if needed ). The next question is why you use ArrayList as a Node class field. T value should be enough. Here is my example of simple list implementation without ArrayList. There is iterator method that returns instance of Iterator which can be used to display list's elements. package com.playground; import java.util.ArrayList; import java.util.Iterator; class CustomList<T>{ private class Node{ Node prev; Node next; T value; Node(T rVal, Node p, Node n){ this.value = rVal; this.prev = p; this.next = n; } void setNext(Node n){ this.next = n; } void setPrev(Node p){ this.prev = p; } } private Node head; private Node tail; public void add(T element) { if(tail == null && head == null){ head = new Node(element, null,null); tail = head; } else{ Node tmp = new Node(element, tail, null); tail.setNext( tmp ); tail = tmp; } } public Iterator<T> iterator() { return new Iterator<T>(){ Node current = head; @Override public boolean hasNext() { // TODO Auto-generated method stub return current != null; } @Override public T next() { Node tmp = current; current = tmp.next; return tmp.value; } @Override public void remove() { // TODO Auto-generated method stub } }; } } public class CustomListTest { public static void main(String [] args){ CustomList<String> list = new CustomList<String>(); list.add("my"); list.add("custom"); list.add("list"); Iterator<String> forwardIterator = list.iterator(); while( forwardIterator.hasNext()){ System.out.println( forwardIterator.next()); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/20344851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fixing PHP8 Upgrade - String on String Error I'm trying an upgrade to PHP8 and troubleshooting a theme that is giving a fatal error. PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string I've narrowed it down to the section causing the problem. Commenting these lines loads the site, but of course the shortcodes display as plain text on the front-end. Still trying to learn PHP and from searching I believe a String is getting treated like an Array is my understanding, just having troubles figuring out how to write it compatible for PHP8. // get event in home sortcode function sc_get_events_home($params){ $showLearnMore = $params['show_learn_more']; $numItems = $params['post_per_page'] ? $params['post_per_page'] : 3; $date_now = date('Ymd'); $args = array( 'post_type' => 'events', 'post_status' => 'publish', 'order' => 'ASC', 'orderby' => 'when', 'posts_per_page' => $numItems, 'meta_query' => array( array( 'key' => 'when', 'value' =>$date_now, 'compare' =>'>=', ) ) ); $query = new WP_Query( $args ); $items = $query->posts; if(count($items) <3) { // upcoming < 3 -> get webinar resources // webinar newest $argsWbNewest = array( 'post_type' => 'resources', 'post_status' => 'publish', 'posts_per_page' => 1, 'order' => 'DESC', 'orderby' => 'date', 'tax_query' => array( array( 'taxonomy' => 'type', 'field' => 'slug', 'terms' => array('webinars'), 'operator' => 'IN', ) ) ); $queryWbNewest = new WP_Query( $argsWbNewest ); $itemsWbNewest = $queryWbNewest->posts; wp_reset_postdata(); // webinar newest $argsWbPopular = array( 'post_type' => 'resources', 'post_status' => 'publish', 'posts_per_page' => 3, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' , 'tax_query' => array( array( 'taxonomy' => 'type', 'field' => 'slug', 'terms' => array('webinars'), 'operator' => 'IN', ) ) ); $queryWbPopular = new WP_Query( $argsWbPopular ); $itemsWbPopular = $queryWbPopular->posts; wp_reset_postdata(); } ob_start(); include 'view/sc-events-home.php'; $data = ob_get_contents(); ob_get_clean(); return $data; } add_shortcode( 'get_events_home', 'sc_get_events_home' ); Any guidance on helping me learn the issue would be greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/72717312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The request body is too large and exceeds the maximum permissible limit when generating sas token I am using the below script to generate sas token using bash sas_token=$(curl https://management.azure.com/subscriptions/$subscription_id/resourceGroups/$rg_name/providers/Microsoft.Storage/storageAccounts/$storage_account/listServiceSas/?api-version=2017-06-01 -X POST -d "{\"canonicalizedResource\":\"/blob/$storage_account/$sa_container\",\"signedResource\":\"c\",\"signedPermission\":\"rcw\",\"signedProtocol\":\"https\",\"signedExpiry\":\"$(date -d '+30 minutes' +%FT%TZ)\"}" -H "Authorization: Bearer $token" | jq -r '.serviceSasToken') when i try to upload a large file which is 500mb it gives me the below error The request body is too large and exceeds the maximum permissible limit. 67108864 generated sas token from the above script is : sv=2015-04-05&sr=c&spr=https&se=2021-04-09T06%3A22%3A19.0000000Z&sp=racwdl&sig=xxxx When i generate a sas token from azure portal i get it as below sp=racwdl&st=2021-04-09T05:54:16Z&se=2021-04-09T13:54:16Z&spr=https&sv=2020-02-10&sr=c&sig=xxxx here if you notice the sv that is signedversion is 2020-02-10 and with this sas token i am able to upload large files. So i noticed that in both the above sas token the sv is different so i tried to add signedversion in my code like below sas_token=$(curl https://management.azure.com/subscriptions/$subscription_id/resourceGroups/$rg_name/providers/Microsoft.Storage/storageAccounts/$storage_account/listServiceSas/?api-version=2017-06-01 -X POST -d "{\"canonicalizedResource\":\"/blob/$storage_account/$sa_container\",\"signedResource\":\"c\",\"signedPermission\":\"rcw\",\"signedProtocol\":\"https\",\"SignedVersion\":\"2020-02-10\",\"signedExpiry\":\"$(date -d '+30 minutes' +%FT%TZ)\"}" -H "Authorization: Bearer $token" | jq -r '.serviceSasToken') but it still generates an sv with 2015-04-05 and not with what i specified. can you please tell how to solve this issue A: I don't think there's anything you can do as far as changing the signed version parameter. My guess is that the implementation to generate SAS via Storage Resource Provider API makes use of Storage REST API version 2015-04-05 (signed version parameter) and if you look at request body parameters, you will notice that there's no parameter to specify the signed version parameter in the request. One thing you could do is change your upload implementation and upload your large blob in chunks where the size of each chunk is less than or equal to 64 MB. FWIW, the block size limit was changed from 64 MB to 100 MB in Storage Service version 2016-05-31: https://learn.microsoft.com/en-us/rest/api/storageservices/version-2016-05-31.
{ "language": "en", "url": "https://stackoverflow.com/questions/67016650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ionic 5 - routing to details page with page id issue guys , I am creating and ionic app which has details page with page id, I am trying to configure router, its not redirecting its always on main page , my code is below please check ? parent page route import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { RecepiesPage } from './recepies.page'; const routes: Routes = [ { path: '', component: RecepiesPage }, { path: 'recipedatail', loadChildren: () => import('./recipedatail/recipedatail.module').then( m => m.RecipedatailPageModule) }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class RecepiesPageRoutingModule {} details page routing import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { RecipedatailPage } from './recipedatail.page'; const routes: Routes = [ { path: '', component: RecipedatailPage }, { path: ':recipeId', loadChildren: () => import('./recipedatail.module').then( m => m.RecipedatailPageModule) }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class RecipedatailPageRoutingModule {} A: Check the angular documentation for correct router implementation
{ "language": "en", "url": "https://stackoverflow.com/questions/63322586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Debug Search I am trying to debug an activity that uses the android os main search to search my SQLite database. Is this possible in eclipse? It doesn't appear to be hitting the breakpoint in the onCreate of my search activity. I think it is because my content provider is not starting when I hit search. I see other content providers starting like this one: 04-26 18:48:28.178: INFO/ActivityThread(463): Publishing provider user_dictionary: com.android.providers.userdictionary.UserDictionaryProvider I am assuming this means I am missing something in my app but I have yet to figure out what it is. A: Yes you can debug Android Activity's using eclipse :-) Post your Logcat if you want help with the issue. A: Remember to add android:debuggable="true" to the application element in AndroidManifest.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/5794193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix "error: You need to have libgpg-error.a", when compiling AIDE for ARM? I compiled GPG for ARM recently and had to compile libgpg-error in the process. Today I need to compile AIDE and the following error shows up during ./configure: configure: error: You need to have libgpg-error.a installed to use libgcrypt. I compiled libgpg-error again, with the --enable-static option on ./configure and now I have a libgpg-error.a file in /usr/local/lib. Yet, the configure script from AIDE can't find it apparently. I checked the script but didn't find anything obvious inside. I'm stuck here, what should I check next? A: I am using a debian system and installed the libgpg-error-dev package and it worked. A: Via this forum post, adding --disable-static to ./configure was my fix. I'm installing in a web hosting environment as a user without sudo/root. My full configure command is ./configure --prefix=$HOME --without-zlib --disable-static
{ "language": "en", "url": "https://stackoverflow.com/questions/54746279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create PostFinance payment request PHP: Can anyone help me how to create a payment request using wysow repository? I found this link, but there weren't any solutions. I am am using concrete5's Community Store and am trying to create a PostFinance payment package/addon. I have the following code in /packages/community_store_postfinance/src/CommunityStore/Payment/Methods/CommunityStorePostfinance/CommunityStorePostfinancePaymentMethod.php file (which is a copy of the example in GitHub): $passphrase = new Passphrase($shaInSecret); $shaComposer = new AllParametersShaComposer($passphrase); $ecommercePaymentRequest = new EcommercePaymentRequest($shaComposer); // Set various params: $ecommercePaymentRequest->setPspid($postfinancePsid); $ecommercePaymentRequest->setOrderid($custmerOrder->getOrderId()); $ecommercePaymentRequest->setPostFinanceUri(EcommercePaymentRequest::TEST); $ecommercePaymentRequest->setAmount((Int)$amount); $ecommercePaymentRequest->setCurrency('CHF'); $ecommercePaymentRequest->setCustomername($customerName); $ecommercePaymentRequest->setOwnerAddress($address); $ecommercePaymentRequest->validate(); $formGenerator = new SimpleFormGenerator; $paymentForm = $formGenerator->render($ecommercePaymentRequest); // I then pass this to my redirect view $this->set('paymentForm', $paymentForm); I have debugged and the form is being created and looks correct, as is required by PostFinance and I get redirected the the PostFinance payment confirmation page, but none of the details have been passed to PostFinance. I am just wondering whether I missed something or if I should be adding something else in the request for the form to go through automatically? Any insights would be appreciated. Thanks. A: A value set by $this->set() will be lost, when redirecting. You would need to set it into the session. Or you do the form generating in the method where you want to redirect to (you could call the code from above in this method, but instead of a redirect you need to return the generated form). But I think there are other problems: $this->set() is normally a method from a controller (page-, block- etc. controller). But you are using it in a class from the src folder. Another problem seems to be the path: packages/community_store/postfinance/src/CommunityStore/Payment/Methods. Should this not be packages/postfinance/src/CommunityStore/Payment/Methods because the package name is postfinance and not community_store? A: Just in case anyone else wanted to know my solution, it was a dumb error on my part as all I had to do was return or echo $paymentForm; This solved my problem and successfully sent the form to PostFinance. Although now I have the problem of not being able to get the PostFinance backend generated signature to match, PostFinance Signature not matching
{ "language": "en", "url": "https://stackoverflow.com/questions/63034791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Binding `ready` and `load` events From one man who currently works on Google I saw code which looks similar to this: $(document).bind('ready load', function() { ... }); There are 2 intertwined questions: * *Since I'm only novice in JS, I don't understand the purpose of this binding. Why we need both ready and load? I tend to think that sometimes we need ready, sometimes load, but not both. *Also, I tend to think that ready is for document, and load is for window. That's mean: $(document).ready(function() { ... }); $(window).load(function() { ... }); But from the first snippet, it could be seen, that both ready and load are used for document. So, my assumption (ready is for document, and load is for window) isn't correct? A: The major difference between ready and load i think is the one below: * *ready fires when the dom is ready, this means that the elements hierarchy is ready, even if the content (i.e an image still loading) has not yet finished completely. It is safe to handle the DOM at this stage. *load fires when even the content has finished loading for a given element $(smthing).load. This means that if attached to the document, this event will fire after all content is loaded (i.e images finished downloading etc ) EDIT: Also take a look here jQuery - What are differences between $(document).ready and $(window).load?
{ "language": "en", "url": "https://stackoverflow.com/questions/48497297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF Client, AllowCookies and clearing any current cookie? I have a WPF client that is using WCF to call into a service hosted in IIS. My WCF client has AllowCookies='true' so that the forms authentication cookie that IIS is using is passed back and forth with each WCF call automatically. This all works just fine. But I need the ability to clear out any forms authentication cookie my WCF client is caching so that my next request is not authenticated. Is there any way to do this? A: On wcf client, you would have access to HttpContext.Current.Request Now this Request object contains cookies. You could loop over the cookie collection and remove the one you need. foreach(var cookie in request.Cookies) { // } An excellent article at code project which explains cookie management on WCF client UPDATE HttpContext is only available at server side, so my previous answer was incorrect as pointed by Phil. The correct way to do it would be rather clumsy as you have get hold of HttpRequest itself MyWebServiceClient client = new MyWebServiceClient(); using ( new OperationContextScope( client.InnerChannel ) ) { HttpRequestMessageProperty request = new HttpRequestMessageProperty(); //get the instance of your AuthCookie and make it blank request.Headers["AuthCookie"] = ""; OperationContext.Current.OutgoingMessageProperties[ HttpRequestMessageProperty.Name] = request; client.InvokeSomeMethod(); } Found this example here
{ "language": "en", "url": "https://stackoverflow.com/questions/11625542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Class locals as predicates pre C++11 The following code compiles without errors/warnings when being built with C++11 mode, using GCC and Clang. However if I attempt to compile without C++11 mode and error occurs in the 2nd scope. #include <algorithm> #include <vector> struct astruct { int v; }; struct astruct_cmp0 { bool operator()(const astruct& a0, const astruct& a1) { return a0.v < a1.v; } }; int main() { std::vector<astruct> alist; { // Works - no errors std::stable_sort(alist.begin(),alist.end(),astruct_cmp0()); } { struct astruct_cmp1 { bool operator()(const astruct& a0, const astruct& a1) { return a0.v < a1.v; } }; // error: template argument uses local type 'astruct_cmp1' std::stable_sort(alist.begin(),alist.end(),astruct_cmp1()); } return 0; } My question is: What was the C++11 change that allows the local struct definition? could someone please point me to the specific section in the standard (section 9.8 perhaps?) A: In C++03 function local types are not viable template arguments. In C++11 function local types are viable template arguments. The key quote in C++03 is 14.3.1 [temp.arg.type] paragraph 2: The following types shall not be used as a template-argument for a template type-parameter: * *a type whose name has no linkage *... In C++11 this constraint is removed. The relevant section on when linkage is defined is 3.5 [basic.link] (in both standard) which is fairly long and points to entities without linkage by exclusion, paragraph 8 in C++03: Names not covered by these rules have no linkage. ... Types defined within a function are not listed in "these rules".
{ "language": "en", "url": "https://stackoverflow.com/questions/26749011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Errors in color resources I'm getting lint errors attempting to use color resources. According to the documentation, the following should be valid. <?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <color name="actionbar_title"></color> </resources> But this gives "Attribute is missing the Android namespace prefix". Amending to <?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <color android:name="actionbar_title"></color> </resources> clears the error but in a layout file the following definition <TextView android:id="@+id/title" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="0dp" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/actionbar_title" /> gives the error "error: Error: No resource found that matches the given name (at 'textColor' with value '@color/actionbar_title'). Any and all help will be appreciated. EDIT: As pointed out by type-a1pha, the above did not specify a color - I've copied from a test version. However <?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <color android:name="actionbar_title">#ffffff</color> </resources> gives the lint warning Unexpected text found in layout file: "#ffffff" but the color resource is still not recognised in the layout xml file. A: You need to actually define the color: <color name="white">#FFFFFF</color> that is, give its hexadecimal code. A: <color name="actionbar_title"></color> the color is empty i see. <color name="actionbar_title">#000000</color> A: You should put your file under "values" folder instead of the "color" folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/17735564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }