text
stringlengths
64
81.1k
meta
dict
Q: Create a horizontal line between ListBoxItems (horizontally oriented ListBox) I want to create a listbox like this: -----|-----|-----|-----|-----|----- The |'s are my listboxitems which I have separated using margins. This works fine. What I want is the listbox to have a background that contains this line. Or at least have it in the background. I tried a separator but that is not what I want because that is also clickable since I used it in the itemtemplate. Any ideas? Thanks A: I'm trying to create a timeline like control. I now fixed it using this: <ListBox.Template> <ControlTemplate> <Border BorderThickness="2" BorderBrush="Black"> <Grid> <Rectangle Height="2" HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="Black"/> <ScrollViewer Padding="{TemplateBinding Padding}"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> </ScrollViewer> </Grid> </Border> </ControlTemplate> </ListBox.Template> This works fine in a testproject, but I'm having some problems in my main project. The rectangle remains under the scrollviewer. Well... making progress. Hope to fix this thing soon. Thanks for your answers so far!
{ "pile_set_name": "StackExchange" }
Q: Sequencing code in a multithreaded environment I have a multithreaded C++ MFC application. I have one worker thread to execute my program logic, and the main thread is dedicated to handling GUI events. The GUI thread spawns the program logic threads, and detaches execution from it, like this - void CMyDocument::InGUIThread() { std::thread tProgramLogic(programLogicThreadFunction); tProgramLogic.detach() } My program logic takes roughly 5 minutes to execute. Here is my problem : I want to call a function in the main GUI thread after my program logic has finished execution. How do I signal my main thread from the programLogic thread as it nears the end of execution? P.S. The reason I detach my programLogic thread is so that I dont freeze my main thread, and thus it is responsive to GUI events. A: You could go for a C++11 async solution and poll the result with wait_for, but in your specific case (in a Windows environment) I'd go for an even better solution: 1) Define a custom WM_ message and map it for handling, e.g. #define WM_MYMSG (WM_USER + 42) BEGIN_MESSAGE_MAP(CMyApp, CWinApp) ON_MESSAGE(WM_MYMSG, ThreadHasFinished) END_MESSAGE_MAP() 2) Post WM_MYMSG when your logic thread ends to the main window with 3) Handle the logic's termination in ThreadHasFinished
{ "pile_set_name": "StackExchange" }
Q: SharePoint 2013, ADFS, return URL We have integrated our SharePoint environment with ADFS. Configured everything and we are able to authenticate using ADFS. However, after the successful login from the ADFS page, we are redirected to the root site instead of the requested URL. below is the sample URL of the ADFS login page: https://federation-sts.company.com/adfs/ls/?wa=wsignin1.0&wtrealm=https://abcstg.company.com&wctx=https%3a%2f%2fabcstg.company.com%2fsites%2fsamplesite%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252Fsites%252Fsamplesite A: I had this issue in past, it is due to some configuration steps missing. On ADFS side, when you " configure the url" during the relying party trust wizard...Make sure you added /_trust/ at the end of your web app url. Like https://url/_trust/ Also Make Sure Realm Identifier Is Same On Both Side(SharePoint And Adfs).It Is Case Senstive. https://www.google.com/amp/s/samlman.wordpress.com/2015/02/28/configuring-sharepoint-2010-and-adfs-v2-end-to-end/amp/
{ "pile_set_name": "StackExchange" }
Q: Maximum possible number of rectangles that can be crossed with a single straight line I found this challenge problem which states the following : Suppose that there are n rectangles on the XY plane. Write a program to calculate the maximum possible number of rectangles that can be crossed with a single straight line drawn on this plane. I have been brainstorming for quite a time but couldn't find any solution. Maybe at some stage, we use dynamic programming steps but couldn't figure out how to start. A: Here is a sketch of an O(n^2 log n) solution. First, the preliminaries shared with other answers. When we have a line passing through some rectangles, we can translate it to any of the two sides until it passes through a corner of some rectangle. After that, we fix that corner as the center of rotation and rotate the line to any of the two sides until it passes through another corner. During the whole process, all points of intersection between our line and rectangle sides stayed on these sides, so the number of intersections stayed the same, as did the number of rectangles crossed by the line. As a result, we can consider only lines which pass through two rectangle corners, which is capped by O(n^2), and is a welcome improvement compared to the infinite space of arbitrary lines. So, how do we efficiently check all these lines? First, let us have an outer loop which fixes one point A and then considers all lines passing through A. There are O(n) choices of A. Now, we have one point A fixed, and want to consider all lines AB passing through all other corners B. In order to do that, first sort all other corners B according to the polar angle of AB, or, in other words, angle between axis Ox and vector AB. Angles are measured from -PI to +PI or from 0 to 2 PI or otherwise, the point in which we cut the circle to sort angles can be arbitrary. The sorting is done in O(n log n). Now, we have points B1, B2, ..., Bk sorted by the polar angle around point A (their number k is something like 4n-4, all corners of all rectangles except the one where point A is a corner). First, look at the line AB1 and count the number of rectangles crossed by that line in O(n). After that, consider rotating AB1 to AB2, then AB2 to AB3, all the way to ABk. The events which happen during the rotation are as follows: When we rotate to ABi, and Bi is the first corner of some rectangle in our order, the number of rectangles crossed increases by 1 as soon as the rotating line hits Bi. When we rotate to ABj, and Bj is the last corner of some rectangle in our order, the number of rectangles crossed decreases by 1 as soon as the line rotates past Bj. Which corners are first and last can be established with some O(n) preprocessing, after the sort, but before considering the ordered events. In short, we can rotate to the next such event and update the number of rectangles crossed in O(1). And there are k = O(n) events in total. What's left to do is to track the global maximum of this quantity throughout the whole algorithm. The answer is just this maximum. The whole algorithm runs in O(n * (n log n + n + n)), which is O(n^2 log n), just as advertised. A: (Edit of my earlier answer that considered rotating the plane.) Here's sketch of the O(n^2) algorithm, which combines Gassa's idea with Evgeny Kluev's reference to dual line arrangements as sorted angular sequences. We start out with a doubly connected edge list or similar structure, allowing us to split an edge in O(1) time, and a method to traverse the faces we create as we populate a 2-dimensional plane. For simplicity, let's use just three of the twelve corners on the rectangles below: 9| (5,9)___(7,9) 8| | | 7| (4,6)| | 6| ___C | | 5| | | | | 4| |___| | | 3| ___ |___|(7,3) 2| | | B (5,3) 1|A|___|(1,1) |_ _ _ _ _ _ _ _ 1 2 3 4 5 6 7 We insert the three points (corners) in the dual plane according to the following transformation: point p => line p* as a*p_x - p_y line l as ax + b => point l* as (a, -b) Let's enter the points in order A, B, C. We first enter A => y = x - 1. Since there is only one edge so far, we insert B => y = 5x - 3, which creates the vertex, (1/2, -1/2) and splits our edge. (One elegant aspect of this solution is that each vertex (point) in the dual plane is actually the dual point of the line passing through the rectangles' corners. Observe 1 = 1/2*1 + 1/2 and 3 = 1/2*5 + 1/2, points (1,1) and (5,3).) Entering the last point, C => y = 4x - 6, we now look for the leftmost face (could be an incomplete face) where it will intersect. This search is O(n) time since we have to try each face. We find and create the vertex (-3, -18), splitting the lower edge of 5x - 3 and traverse up the edges to split the right half of x - 1 at vertex (5/3, 2/3). Each insertion has O(n) time since we must first find the leftmost face, then traverse each face to split edges and mark the vertices (intersection points for the line). In the dual plane we now have: After constructing the line arrangement, we begin our iteration on our three example points (rectangle corners). Part of the magic in reconstructing a sorted angular sequence in relation to one point is partitioning the angles (each corresponding with an ordered line intersection in the dual plane) into those corresponding with a point on the right (with a greater x-coordinate) and those on the left and concatenating the two sequences to get an ordered sequence from -90 deg to -270 degrees. (The points on the right transform to lines with positive slopes in relation to the fixed point; the ones on left, with negative slopes. Rotate your sevice/screen clockwise until the line for (C*) 4x - 6 becomes horizontal and you'll see that B* now has a positive slope and A* negative.) Why does it work? If a point p in the original plane is transformed into a line p* in the dual plane, then traversing that dual line from left to right corresponds with rotating a line around p in the original plane that also passes through p. The dual line marks all the slopes of this rotating line by the x-coordinate from negative infinity (vertical) to zero (horizontal) to infinity (vertical again). (Let's summarize the rectangle-count-logic, updating the count_array for the current rectangle while iterating through the angular sequence: if it's 1, increment the current intersection count; if it's 4 and the line is not directly on a corner, set it to 0 and decrement the current intersection count.) Pick A, lookup A* => x - 1. Obtain the concatenated sequence by traversing the edges in O(n) => [(B*) 5x - 3, (C*) 4x - 6] ++ [No points left of A] Initialise an empty counter array, count_array of length n-1 Initialise a pointer, ptr, to track rectangle corners passed in the opposite direction of the current vector. Iterate: vertex (1/2, -1/2) => line y = 1/2x + 1/2 (AB) perform rectangle-count-logic if the slope is positive (1/2 is positive): while the point at ptr is higher than the line: perform rectangle-count-logic else if the slope is negative: while the point at ptr is lower than the line: perform rectangle-count-logic => ptr passes through the rest of the points up to the corner across from C, so intersection count is unchanged vertex (5/3, 2/3) => line y = 5/3x - 2/3 (AC) We can see that (5,9) is above the line through AC (y = 5/3x - 2/3), which means at this point we would have counted the intersection with the rightmost rectangle and not yet reset the count for it, totaling 3 rectangles for this line. We can also see in the graph of the dual plane, the other angular sequences: for point B => B* => 5x - 3: [No points right of B] ++ [(C*) 4x - 6, (A*) x - 1] for point C => C* => 4x - 6: [(B*) 5x - 3] ++ [(A*) x - 1] (note that we start at -90 deg up to -270 deg) A: Solution In the space of all lines in the graph, the lines which pass by a corner are exactly the ones where the number or intersections is about to decrease. In other words, they each form a local maximum. And for every line which passes by at least one corner, there exist an associated line that passes by two corners that has the same number of intersections. The conclusion is that we only need to check the lines formed by two rectangle corners as they form a set that fully represents the local maxima of our problem. From those we pick the one which has the most intersections. Time complexity This solution first needs to recovers all lines that pass by two corners. The number of such line is O(n^2). We then need to count the number of intersections between a given line and a rectangle. This can obviously be done in O(n) by comparing to each rectangles. There might be a more efficient way to proceed, but we know that this algorithm is then at most O(n^3). Python3 implementation Here is a Python implementation of this algorithm. I oriented it more toward readability than efficiency, but it does exactly what the above defines. def get_best_line(rectangles): """ Given a set of rectangles, return a line which intersects the most rectangles. """ # Recover all corners from all rectangles corners = set() for rectangle in rectangles: corners |= set(rectangle.corners) corners = list(corners) # Recover all lines passing by two corners lines = get_all_lines(corners) # Return the one which has the highest number of intersections with rectangles return max( ((line, count_intersections(rectangles, line)) for line in lines), key=lambda x: x[1]) This implementation uses the following helpers. def get_all_lines(points): """ Return a generator providing all lines generated by a combination of two points out of 'points' """ for i in range(len(points)): for j in range(i, len(points)): yield Line(points[i], points[j]) def count_intersections(rectangles, line): """ Return the number of intersections with rectangles """ count = 0 for rectangle in rectangles: if line in rectangle: count += 1 return count And here are the class definition that serve as data structure for rectangles and lines. import itertools from decimal import Decimal class Rectangle: def __init__(self, x_range, y_range): """ a rectangle is defined as a range in x and a range in y. By example, the rectangle (0, 0), (0, 1), (1, 0), (1, 1) is given by Rectangle((0, 1), (0, 1)) """ self.x_range = sorted(x_range) self.y_range = sorted(y_range) def __contains__(self, line): """ Return whether 'line' intersects the rectangle. To do so we check if the line intersects one of the diagonals of the rectangle """ c1, c2, c3, c4 = self.corners x1 = line.intersect(Line(c1, c4)) x2 = line.intersect(Line(c2, c3)) if x1 is True or x2 is True \ or x1 is not None and self.x_range[0] <= x1 <= self.x_range[1] \ or x2 is not None and self.x_range[0] <= x2 <= self.x_range[1]: return True else: return False @property def corners(self): """Return the corners of the rectangle sorted in dictionary order""" return sorted(itertools.product(self.x_range, self.y_range)) class Line: def __init__(self, point1, point2): """A line is defined by two points in the graph""" x1, y1 = Decimal(point1[0]), Decimal(point1[1]) x2, y2 = Decimal(point2[0]), Decimal(point2[1]) self.point1 = (x1, y1) self.point2 = (x2, y2) def __str__(self): """Allows to print the equation of the line""" if self.slope == float('inf'): return "y = {}".format(self.point1[0]) else: return "y = {} * x + {}".format(round(self.slope, 2), round(self.origin, 2)) @property def slope(self): """Return the slope of the line, returning inf if it is a vertical line""" x1, y1, x2, y2 = *self.point1, *self.point2 return (y2 - y1) / (x2 - x1) if x1 != x2 else float('inf') @property def origin(self): """Return the origin of the line, returning None if it is a vertical line""" x, y = self.point1 return y - x * self.slope if self.slope != float('inf') else None def intersect(self, other): """ Checks if two lines intersect. Case where they intersect: return the x coordinate of the intersection Case where they do not intersect: return None Case where they are superposed: return True """ if self.slope == other.slope: if self.origin != other.origin: return None else: return True elif self.slope == float('inf'): return self.point1[0] elif other.slope == float('inf'): return other.point1[0] elif self.slope == 0: return other.slope * self.origin + other.origin elif other.slope == 0: return self.slope * other.origin + self.origin else: return (other.origin - self.origin) / (self.slope - other.slope) Example Here is a working example of the above code. rectangles = [ Rectangle([0.5, 1], [0, 1]), Rectangle([0, 1], [1, 2]), Rectangle([0, 1], [2, 3]), Rectangle([2, 4], [2, 3]), ] # Which represents the following rectangles (not quite to scale) # # * # * # # ** ** # ** ** # # ** # ** We can clearly see that an optimal solution should find a line that passes by three rectangles and that is indeed what it outputs. print('{} with {} intersections'.format(*get_best_line(rectangles))) # prints: y = 0.50 * x + -5.00 with 3 intersections
{ "pile_set_name": "StackExchange" }
Q: Find string to regular expression programmatically? Given a regular expression, is is possible to find a string that matches that expression programmatically? If so, please mention an algorithm for that, assuming that a string exists. Bonus question: Give the performance/complexity of that algorithm, if able. PS: Note I am not asking this: Programmatically derive a regular expression from a string. More likely I am asking the reserve problem. A: Generex is a Java library for generating String from a regular expression. Check it out: https://github.com/mifmif/Generex Here is the sample Java code demonstrating library usage: Generex generex = new Generex("[0-3]([a-c]|[e-g]{1,2})"); // Generate random String String randomStr = generex.random(); System.out.println(randomStr);// a random value from the previous String list // generate the second String in lexicographical order that match the given Regex. String secondString = generex.getMatchedString(2); System.out.println(secondString);// it print '0b' // Generate all String that matches the given Regex. List<String> matchedStrs = generex.getAllMatchedStrings(); // Using Generex iterator Iterator iterator = generex.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } // it prints: // 0a 0b 0c 0e 0ee 0ef 0eg 0f 0fe 0ff 0fg 0g 0ge 0gf 0gg // 1a 1b 1c 1e 1ee 1ef 1eg 1f 1fe 1ff 1fg 1g 1ge 1gf 1gg // 2a 2b 2c 2e 2ee 2ef 2eg 2f 2fe 2ff 2fg 2g 2ge 2gf 2gg // 3a 3b 3c 3e 3ee 3ef 3eg 3f 3fe 3ff 3fg 3g 3ge 3gf 3gg Another one: https://code.google.com/archive/p/xeger/ Here is the sample Java code demonstrating library usage: String regex = "[ab]{4,6}c"; Xeger generator = new Xeger(regex); String result = generator.generate(); assert result.matches(regex); A: Assume you define regular expressions like this: R := <literal string> (RR) -- concatenation (R*) -- kleene star (R|R) -- choice Then you can define a recursive function S(r) which finds a matching string: S(<literal string>) = <literal string> S(rs) = S(r) + S(s) S(r*) = "" S(r|s) = S(r) For example: S(a*(b|c)) = S(a*) + S(b|c) = "" + S(b) = "" + "b" = "b". If you have a more complex notion of regular expression, you can rewrite it in terms of the basic primitives and then apply the above. For example, R+ = RR* and [abc] = (a|b|c). Note that if you've got a parsed regular expression (so you know its syntax tree), then the above algorithm takes at most time linear in the size of the regular expression (assuming you're careful to perform the string concatenations efficiently).
{ "pile_set_name": "StackExchange" }
Q: Matlab's writetable() function only exporting partial data of a table The writetable() function at the end of my code only exports the first row (namely FR_1w, FR_2w and FR_3w), whereas I want the entire table to be exported and written as .xls or .xlsx. V=[{A B C};... {A1 B1 C1};... {A2 B2 C2}]; X=cell2table(V); X.Properties.VariableNames= {'FR_1w' 'FR_2w' 'FR_3w'}; X.Properties.RowNames= {'4Weeks' '12Weeks' '24Weeks'}; writetable(X, 'X.xlsx') n.b. Variables in table V are 3x1 cells. A, for example, contains: A: My workaround solution: Z=[{A{1,1} B{1,1} C{1,1}};... {A{2,1} B{2,1} C{2,1}};... {A{3,1} B{3,1} C{3,1}};... {A1{1,1} B1{1,1} C1{1,1}};... {A1{2,1} B1{2,1} C1{2,1}};... {A1{3,1} B1{3,1} C1{3,1}};... {A2{1,1} B2{1,1} C2{1,1}};... {A2{2,1} B2{2,1} C2{2,1}};... {A2{3,1} B2{3,1} C2{3,1}}]; Tstat = cell2table(VV); Tstat.Properties.VariableNames = {'ok1' 'ok2' 'ok3'}; Tstat.Properties.RowNames = {'one' 'two' 'three' 'four' 'five' ... 'six' 'seven' 'eight' 'nine'}; writetable(Tstat, 'TstatOverview.xlsx')
{ "pile_set_name": "StackExchange" }
Q: Is this the wrong way to go about updating a table I wrote this code to try to update the q_id column of table a with the q_id values of table b. I feel as if this is inefficient and the wrong way to go about it because it's taking a very long time to run. Is there a better way to do this? UPDATE tbl1 a,tbl2 b SET a.q_id = b.q_id WHERE a.col IS NOT NULL AND a.col = b.col A: Your query is equivalent to: UPDATE tbl1 a JOIN tbl2 b ON a.col = b.col SET a.q_id = b.q_id; The comparison to NULL is unnecessary. However, that will not help performance. An index on tbl2(q_id, col) should help performance considerably. If you are updating lots of rows (says hundreds of thousands or more), you have to deal with logging issues. In this case, breaking up the update into multiple steps might be a wise option. Also, if there are multiple matches for each record in tbl1, then that might also slow down the query.
{ "pile_set_name": "StackExchange" }
Q: Install Internet Explorer 8 on windows 7 I recently installed Internet Explorer 9 but now want to revert back to Internet Explorer 8. How do I do it. I uninstalled IE9 but unlike Windows XP, I don't get IE8 option. A: Uninstall IE9 from Programs and Features->Windows Updates. A: Visit MS IE8 Downloads and download the version you require 32 or 64 bit
{ "pile_set_name": "StackExchange" }
Q: Remove empty decimal with .droplast() in swift 3 I'm trying to remove empty trailing decimals and instead of using an extension for float I want to consider using droplast() if the result has any trailing zeros: if result.contains(".0") { result.characters.dropLast() } if result.contains(".00") { result.characters.dropLast(2) } This does not seem to work and I get the warning: Result of call to 'droplast()' is unused A: Alternative solution using regular expression, the number of decimal places doesn't matter: var result = "1.00" result = result.replacingOccurrences(of: "\\.0+$", with: "", options: .regularExpression, range: result.startIndex..<result.endIndex) Considering the entire string you can even omit the range parameter: result = result.replacingOccurrences(of: "\\.0+$", with: "", options: .regularExpression)
{ "pile_set_name": "StackExchange" }
Q: how to return the number of days according on its month using java I was given this assignment for my homework: create a program in java that accepts an unsigned integer n and return the number of days according to its month. For example if n = 6, the return value is 30 because 6th month of june has 30 days. Assume no leap year. This is my attempt, but it doesn't work as expected. Can anyone give me pointers as to why. public class daysmonths { public static void main(String []args) { for (int i = 1; i<=12; i++){ int e = f(i); System.out.println(i + " = " + e + " days "); } } public static int f(int i){ if ((i == 1)|(i == 3)|(i == 5)|(i == 7)|(i == 8)|(i == 10)|(i == 12)) return 31; else if ((i == 4)|(i == 6)|(i == 9)|(i == 11)) return 30; else return 28; } } A: The below code uses the java Calendar class by setting it's month to the input month and getting its max date by getActualMaximum() method. Also it will return 29 for leap years. public static void main(String args[]){ int month = 6; Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, month-1); System.out.println(cal.getActualMaximum(Calendar.DATE)); }
{ "pile_set_name": "StackExchange" }
Q: Learning names of spammers Currently, some spam waves, especially when sport events happen, are flooding the internet. As I strongly doubt that the usernames of the spammers aren't computer generated, I thought it might be interesting to try learning spammer names programatically somehow. A user name should be between 2 and 15 characters, begin with a letter and contain only letters, numbers, _ or -. A sample list of names would be riazsports0171 maya34444 thelmaeatons tigran777 newlive100 darbeshbaba litondina10 nithuhasan newlive100 bankuali lldztwydni554 monomala505 nasiruddin1500 lldztwydni554 ariful3032 nazmulhasan I do only have a fairly basic knowledge of algorithms (from university). My question is, which machine learning algorithms and/or string metrics I could use for predicting if an arbitary username is probably a spammer or not. I thought about using cosine string similaritz, because its fairly simple. A: Interesting. But I don't think string similarity algorithms are the best solution. I'd try to extract features from the names, and use a classification algorithm. SVM usually provides very good results comparing to other classification algorithms, but there are other algorithms as well (For example: Naive Bayes, Decision Tree, KNN) each with its advantages and disadvantages. The tricky part will be to extract the features. You should be creative. Some options are: number of digits, number of consecutive letters, number of consecutive consonant, usage of capitalization, correct usage of capitalization, is matching a certain regex, ... (You could also use other features not from the string, such as number of msgs sent by this user to you, ....) Next, you need to create a training set. This training set will contain both spammers and non-spammers user names, which are manually labeled for spammers or non-spammers. Feed the training set to your algorithm of choice, and it will create a classifier, which you will be able to use to predict if new users are spammers or not. You can evaluate effectiveness of each algorithm by using cross validation on your data.
{ "pile_set_name": "StackExchange" }
Q: ZipArchive generating temp files but not writing content and no error given I'm using PHPExcel to generate Excel files but it's not working. I have debugged down to this piece of code: $objZip = new ZipArchive(); $ro = new ReflectionObject($objZip); $zipOverWrite = $ro->getConstant('OVERWRITE'); $zipCreate = $ro->getConstant('CREATE'); // Try opening the ZIP file // Debug result: both open() return true here if ($objZip->open($pFilename, $zipOverWrite) !== true) { if ($objZip->open($pFilename, $zipCreate) !== true) { throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing."); } } // Debug result: $objZip->close() would return true here // Add [Content_Types].xml to ZIP file // Debug result: it stops running on this line, no errors or exceptions $objZip->addFromString('[Content_Types].xml', ...); The line $objZip->addFromString() generates temp files in the directory, but it seems unable to write into these files somehow, as they are empty: -rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.0BRqEn -rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.3Hbl1n -rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.5otErm ... Presumably it's a permission issue, but the PHP user www1 has write permission in the directory and fwrite() works well on these temp files as I tried. PHP version is 5.4.16. Any ideas please? A: Turned out to be a problem in PHP update. Resolved by restarting the web server.
{ "pile_set_name": "StackExchange" }
Q: How to obtain the text content between two anchor tags I have a html content as shown below.Is there any way to obtain using Jquery the text in between the two anchor tags without wrapping any div or span tags around the text named "user1" .I need the output as "user1". Could someone please help me. <div class="test 1"> <input id="field1" type="hidden" value="terminal"> <a class="Prev" title="prevoius" href="#">previous</a> User1 <a class="btnNext" title="next" href="#">next</a> </div> A: Something like this should work: var theText = $('.Prev')[0].nextSibling.textContent || $('.Prev')[0].nextSibling.innerText; Here's a fiddle
{ "pile_set_name": "StackExchange" }
Q: MySQL: how to get distinct numbers in this way? In my MySQL data base, I have a table(eg,T) with mac address and time (eg,2012-4-30 23:00:00). I want to filter out those mac address which appeared in this week, but not in the previous week. How could I do that in one sentence? I tried to use multiple select, but haven't found the way. Thanks in advance. A: Without the table structure, I would suggest something like: SELECT [DISTINCT] Mac FROM table t WHERE t.Time BETWEEN '2012-01-09 00:00:00' AND '2012-01-16 23:59:59' AND NOT EXISTS (SELECT * FROM FROM table t2 WHERE t2.Mac = t.Mac AND T2.Time BETWEEN '2012-01-01 00:00:00' AND '2012-01-08 23:59:59'
{ "pile_set_name": "StackExchange" }
Q: Using a progress bar in Visual Basic while running a batch script in background I've got a simple Visual Basic Program that I've put together that calls some batch scripts that causes them to be hidden while it copies files and now I'd like to use a progress bar to give the user a visual because I've hidden the cmd window. Thanks in advance for the help! Here is the code: Public Class Choices Private Sub Choices_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Private Sub btnDocuments_Click(sender As Object, e As EventArgs) Handles btnDocuments.Click Dim wsh wsh = CreateObject("WScript.Shell") wsh.Run("C:\Batch\myDocs.Bat", 0, True) End Sub Private Sub btnDesktop_Click(sender As Object, e As EventArgs) Handles btnDesktop.Click Dim wsh wsh = CreateObject("WScript.Shell") wsh.Run("C:\Batch\desk.Bat", 0, True) End Sub Private Sub btnFavorites_Click(sender As Object, e As EventArgs) Handles btnFavorites.Click Dim wsh wsh = CreateObject("WScript.Shell") wsh.Run("C:\Batch\favs.Bat", 0, True) End Sub Private Sub btnAll_Click(sender As Object, e As EventArgs) Handles btnAll.Click Dim wsh wsh = CreateObject("WScript.Shell") wsh.Run("C:\Batch\all.Bat", 0, True) End Sub End Class A: While you are using older VB code, you have it tagged as VB.NET, and I'm answering accordingly. You need need to execute your batch files in a way that you can get the output of the batch files to then show to your user. You can do this by executing the batch files using an instance of the Process object, and redirecting the output. To do this in an asynchronous fashion, you would attach the event handlers for OutputDataReceived and ErrorDataReceived and calling BeginOutputReadLine and BeginErrorReadLine. To get you started, I'm providing a small sample code for the case of Documents: Private Sub btnDocuments_Click(sender As Object, e As EventArgs) Handles btnDocuments.Click DoWork("C:\Batch\myDocs.Bat") End Sub Sub DoWork(ByVal batFileName As String) Using p As New Process() p.StartInfo.FileName = batFileName p.StartInfo.UseShellExecute = False p.StartInfo.CreateNoWindow = True p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True AddHandler p.OutputDataReceived, AddressOf BatFileProcess_OutputDataReceived AddHandler p.ErrorDataReceived, AddressOf BatFileProcess_ErrorDataReceived p.Start() p.BeginOutputReadLine() p.BeginErrorReadLine() End Using End Sub Private Sub BatFileProcess_OutputDataReceived(sender As Object, e As DataReceivedEventArgs) Me.Invoke(Sub() ' Perform UI update here for normal output. End Sub) End Sub Private Sub BatFileProcess_ErrorDataReceived(sender As Object, e As DataReceivedEventArgs) Me.Invoke(Sub() ' Perform UI update here for error output. End Sub) End Sub Note that this update will be from a thread separate from the UI thread, thus the need to use Invoke accordingly.
{ "pile_set_name": "StackExchange" }
Q: What is title of this retro game with catchy fast techno-dance theme song? My friend showed me a game installed on his PC back in 2006 and we captured the below eurodance-like song from it. Our paths diverged and I haven't spoken to him in years but I recently found the track again on my HDD. The game was originally on a CD attached to a game magazine. I'm fairly certain it's the intro/theme music from that game, and that the game was for PC. I'd like to find out the game title. I tried to google what games were attached there, but can't find the lists from all of them, we captured this song by Audacity, and this is all I have. It seems to me (but do not remember a lot) it rather was a 2D game, and probably platform (maybe action takes place in space?). I am sure it was PC and no younger than 2006. It may be Japanese but I am not sure. A: Found it. This is Hyperballoid Deluxe
{ "pile_set_name": "StackExchange" }
Q: 2nd degree matrix equation Let $X$ be a matrix with 2 rows and 2 columns. Solve the following equation: $$ X^2 = \begin{pmatrix} 3 & 5\\ -5 & 8 \end{pmatrix} $$ Here is what I did: Let $ X = \begin{pmatrix} a & b\\ c & d \end{pmatrix} $. After multiplying I got the following system: $$ \left\{\begin{matrix} a^2 + bc = 3\\ ab + bd = 5\\ ac + cd = -5\\ d^2 + bc = 8 \end{matrix}\right. $$ At this point I got stucked. If you know how to solve this please help me! Thank you! A: We have the following criteria which you already stated correctly, but you missed one more information $(5)$ - still, you can solve this root problem without this additional knowledge by plugging in recursively - which comes from the determinant, we get then \begin{align} a^2 + bc &= 3 \tag1\\ ab + bd &= 5\tag2 \\ ac + cd &= -5\tag3 \\ d^2 + bc &= 8\tag4 \\ \det(X)=ad-bc&=7=\sqrt{\det(M)} \tag{5a} \end{align} Remark remember that we have $\det(AB)=\det(A)\det(B)$ This gives us \begin{align} (1)-(4)&=a^2-d^2=(a-d)(a+d)=-5\\ (2)&=b(a+d)=5 \\ (3)&=c(a+d)=-5 \\ (1)+(5a)&=a(a+d)=10 \end{align} so we get from $(2)\wedge(3)$ $b=-c$ and further $a-d=c$ and $a=-2(a-d)\iff\frac32a=d$ therefore \begin{align} a(a+d)=10=a(a+\frac32a)=\frac52a^2\iff4=a^2 \end{align} and thus we get for $a=2$ \begin{align} a=2,d=3,c=-1,b=1 \end{align} so $$ X_1=\begin{pmatrix}2 &1\\ -1&3\end{pmatrix} $$ and for $a=-2$ \begin{align} a=-2,d=-3,c=1,b=-1 \end{align} so $$ X_2=\begin{pmatrix}-2 &-1\\ 1&-3\end{pmatrix}=-X_1 $$ Remark due to Robert Israel: Indeed we have to investigate the other possible determinant solution \begin{align} \det(X)=ad-bc&=-7 \tag{5b} \end{align} then we get \begin{align} (1)+(5b)&=a(a+d)=-4 \\ (1)-(4)&=a^2-d^2=(a-d)(a+d)=-5 \end{align} which gives us $\frac54a=(a-d)\iff-\frac14a=d$ and therefore \begin{align} a(a+d)=-4=a(a-\frac14a)\iff-4=\frac34a^2 \end{align} which leads, if we stay in the field of the real numbers, to a contradiction. However, one might find for example other complex solutions. For a more detailed discussion please check out the comment section.
{ "pile_set_name": "StackExchange" }
Q: Is there any binning function that returns the 'binned matrix' instead of the bin indices for each point? I have a matrix that contains NO2 measurements for a certain part of the globe, along with 2 matrices of the same size that contain the latitudes and longitudes. NO2 = np.random.rand(100,100) lat = np.random.rand(100,100)*90. lon = np.random.rand(100,100)*180 I want to bin these NO2 values based on lat and lon into bins of 0.125 degrees, that look like this: latBins = np.linspace(-90,90,180/.125+1) lonBins = np.linspace(-180,180,360/.125+1) Now, I know that numpy.digitize and numpy.histogram can return me the indices of the bins that each NO2 value belongs to, but I want the actual binned matrix. This matrix looks as follows: binnedMatrix = np.zeros((1440,2880,15)) with each bin having a depth of 15. If I would now call binnedMatrix[0][0] (which holds all points with longitudes between -180.,-179.875 and latitudes between -90.,-89.875), I would like as a result all the NO2 values that were binned within these lats and lons. This would make it possible to just store this matrix somehwere, which is what I want. Is there any function that returns this matrix? Or is there any way this can be done without a for loop? A: I've came across a similar problem and your last comment seems to be relevant. Assuming points in three-dimensional space with axes x, y and z, I want to put all values z in a bin respective to their x and y positions. This answer uses np.digitize and is valid for one-dimensional arrays, but can be adjusted to suit three-dimensions. In [1]: import numpy as np In [2]: data = np.random.randint(0, 100, 3000).reshape(-1, 3) In [3]: data Out[3]: array([[59, 94, 85], [97, 47, 71], [27, 10, 23], ..., [48, 61, 87], [72, 22, 86], [80, 47, 45]]) In [4]: bins = np.linspace(0, 100, 10) In [5]: bins Out[5]: array([ 0. , 11.11111111, 22.22222222, 33.33333333, 44.44444444, 55.55555556, 66.66666667, 77.77777778, 88.88888889, 100. ]) In [6]: digitized = np.digitize(data[:, 0:2], bins) In [7]: digitized Out[7]: array([[6, 9], [9, 5], [3, 1], ..., [5, 6], [7, 2], [8, 5]]) In [8]: data[np.equal(digitized, [6, 9]).all(axis=1)] Out[8]: array([[59, 94, 85], [56, 94, 80], [63, 97, 73], [64, 94, 13], [58, 92, 29], [60, 97, 53], [65, 92, 95], [64, 91, 40], [59, 92, 93], [58, 94, 77], [58, 89, 66], [60, 89, 19], [65, 95, 13], [65, 89, 39]]) In [9]: data[np.equal(digitized, [6, 9]).all(axis=1)][:, 2] Out[9]: array([85, 80, 73, 13, 29, 53, 95, 40, 93, 77, 66, 19, 13, 39]) To solve your problem, use data[np.equal(digitized, [index_latitide, index_longitude]).all(axis=1)[:, 2]. This will retrieve all your NO2 values, although you can get more than 15 for each bin.
{ "pile_set_name": "StackExchange" }
Q: Howto: add class when section is in viewport I am trying to get a drawing animation effect similar to https://stackoverflow.com/a/45378478 (Preview: https://codepen.io/jbanegas/pen/LjpXom) to load when the user scrolls to this section of the page. It's intended to add multiple of these drawing boxes as the user navigates the page. I realize that jQuery is sort of outdated now, but this is on a WordPress website that already utilizes this framework. jQuery <script type='text/javascript'> $(document).ready(function(){ $('.thisisatest').addClass('draw'); }); </script> HTML <div class="thisisatest"></div> I've tried replacing the .ready() with: onload - https://www.w3schools.com/jsref/event_onload.asp .scroll() - https://api.jquery.com/scroll/ Any help would be greatly appreciated. A: You are missing the basics. Apart from adding on scroll event you need to find out if element is in view port obviously. Here is vanilla JS solution... It will work on all div's with .thisisatest class. References Read the link on how the isInViewport function work. var isInViewport = function(elem) { var distance = elem.getBoundingClientRect(); return ( distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth) ); }; // read the link on how above code works var findMe = document.querySelectorAll('.thisisatest'); window.addEventListener('scroll', function(event) { // add event on scroll findMe.forEach(element => { //for each .thisisatest if (isInViewport(element)) { //if in Viewport element.classList.add("draw"); } }); }, false); EXAMPLE: jsfiddle
{ "pile_set_name": "StackExchange" }
Q: Android Tablets resolution and density support Hello Everyone......... I am working on android tablets that supports 1280x800 and 1024x600 resolution. What is the best approach for UI design to use dip or px for layout designing. My problem is I want to support all Android Tablets in market with both of these resolutions but there LCD density may vary between 160 to 240 dpi. What to do in this situation? Android tablets have 240 dpi density or 160 dpi density or may have both? Please tell which tablets devices have which density support? Is it possible to workon both densities with same screen resolution through same xml layout? A: yes make sure, we make a single layout thate work for all screen or tabs in any density. Android provide multiple support screen features. <supports-screens android:resizeable="true" android:largeScreens="true" android:normalScreens="true" android:anyDensity="true"></supports-screens> and also putup all imeges in hdpi folder mdpi folder ldpi folder A: For layout designing dip is definitely the best approach because you have density independence : http://developer.android.com/guide/practices/screens_support.html As far as I know, since dpi is dots per inch if you have one resolution you should only have one density. For calculating easily density see : http://members.ping.de/~sven/dpi.html http://en.wikipedia.org/wiki/Comparison_of_Android_devices#Tablet_computers
{ "pile_set_name": "StackExchange" }
Q: A Simple Algorithm for Imposing Semi-definite Constraints What is the simplest algorithm to implement, to impose semi-definite constraints? $\min_{X\succeq 0} f(X) $, where $X$ is an $n \times n$ symmetric matrix, and $f$ is a general smooth convex nonlinear function. Suppose size of $X$ is small, e.g. $n = 20$. I myself can name some methods (like interior point methods, etc), but have not experience in implementation, so do not know which one is simpler to start with. A: I'd say a projected gradient method is likely going to work well for a simple problem like that. That is, alternate between gradient steps $$X_+ = X - \alpha \nabla f(X)$$ and projection steps: $$X_{++} = \mathop{\text{arg}\,\text{min}}_{X\succeq 0} \|X-X_+\|_F$$ The projection is relatively simple: given a Schur decomposition $X_+=U\Sigma U^T$, then $X_{++}=U\Sigma_+ U^T$, where $\Sigma_+$ is formed by replacing any negative (diagonal) elements of $\Sigma$ with zero: $(\Sigma_+)_{ii}=\max\{\Sigma_{ii},0\}$. If $f(X)$ is not strongly convex, you may want to consider an accelerated first-order method; search for "Nesterov's optimal gradient" or "Nesterov's accelerated gradient" in your favorite search engine for a start. My Matlab toolbox TFOCS might be helpful for you here, but it is by no means necessary. An interior-point method is OK, and would be good if you need high accuracy. But it can be a bit difficult to assemble the Newton system. Certainly, with a problem of your smaller size, it will be tractable on a PC. Do you have a specific $f$ in mind?
{ "pile_set_name": "StackExchange" }
Q: carry out firebase authentication from a service class? I have an activity for new users that consists of 3 edit texts, one for entering their email address, setting their password and entering receipt numbers. Before signing up using firebase users are supposed to pay for services through the banks and use the receipt number to confirm payment in the app, when the user clicks the sign up button the entered receipt number is sent to the private server, which sends back an ID. This all works, but I am trying to send the parsed ID number from the json response along with the users inputed email address and password to a service class, where a sign up method starts after 30 seconds. In the sign up method, the ID is sent to the server for verification and when a valid json response is received from the server, it creates a new firebase user using the string password and email address passed from the main activity. I however get a null pointer error in the same line where the email address and password is put in the firebase create new user method. Below is how I get the email address and password from the main activity public Signupservice() { String a; String b; } ...... @Override public int onStartCommand(Intent intent, int flags , int startId){ a=intent.getStringExtra(FILENAMED); b=intent.getStringExtra(FILEEXD); ...... firebaseAuth.createUserWithEmailAndPassword(a, b).addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { Toast.makeText(getApplicationContext(), "signupunsuccessful: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"suucessfull",Toast.LENGTH_SHORT).show(); However I receive the following error from the logcat in reference to the first line of code from the method create user with email and password 2019-10-02 20:40:15.539 20184-20184/com.chomba.haroldking.kupa E/AndroidRuntime: FATAL EXCEPTION: main Process: com.chomba.haroldking.kupa, PID: 20184 java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference at com.chomba.haroldking.kupa.Signupservice.parseData(Signupservice.java:159) Below is how string is sent to the service class Intent startServiceIntent=new Intent(Signupuser.this,Signupservice.class); startServiceIntent.putExtra(FILENAMED,emailIDfed); startServiceIntent.putExtra(FILEEX,gce); startServiceIntent.putExtra(FILENAMEDD,paswdfed); Please render assistance A: firebaseAuth is null. It looks like you have not assigned it before first using it. Make sure to assign it first: firebseAuth = FirebaseAuth.getInstance().
{ "pile_set_name": "StackExchange" }
Q: PHP Убирать параметры из URL, если содержащие цифры Ссылки на товары на сайте имеют вид такой test.ru/catalog/holodilniki/3574/ Если мы добавляем к последнему уровню (где цифры - id товара) какой-то параметр (при том это может быть что угодно и начинаться как угодно: test.ru/catalog/holodilniki/3574_blabla/ test.ru/catalog/holodilniki/3574&chtoto/ test.ru/catalog/holodilniki/3574?lalala/ То все равно остаемся на странице товара. Если задача поставить на страницы товаров атрибут rel="canonical", а для этого надо знать непосредственно верную ссылку - без параметра. Вопрос: можно ли как-то "очистить" определенную часть строки, в моем случае /3574/ от всех параметров - от всего, что не цифры? A: Если я правильно понял Вашу задачу, то можно использовать это выражение: '/\d+\K\pP[^\/]+\/$/m' https://regex101.com/r/rlCIzz/2 На примере возьмем строки, и преобразуем их. На выходе получим нужный результат. $string = ' test.ru/catalog/holodilniki/3574_blabl232a/ test.ru/catalog/holodilniki/3574&chto2323to/ test.ru/catalog/holodilniki/3574?lalala/ '; echo preg_replace('/\d+\K\pP[^\/]+\/$/m', '/', $string); // test.ru/catalog/holodilniki/3574/ https://3v4l.org/kFha9
{ "pile_set_name": "StackExchange" }
Q: State of GeoServer SQL Server Extension Does anyone know what the current state of the SQL Server extension for GeoServer is? When it came out in 2008, there were a lot of complaints of poor performance, as the comments in this blog show: http://blog.geoserver.org/2008/11/10/146/. Has any further work been done on it since then? A: It has extension (rather than community module) status, so there is at least some support. However there are better database options (those in core distribution are likely better supported than extensions, which in turn are better supported than community modules, broadly speaking). I'd generally suggest PostGIS first. Whether SQL Server and the geoserver (mostly GeoTools) module suit your needs depends on your situation (which you haven't really described) and to some extent, opinion. I can only suggest trying it with representative workloads. I'd still suggest PostGIS except that this would really be an opinion and we try to avoid that.
{ "pile_set_name": "StackExchange" }
Q: How many ways are there for a child to take 10 pieces of candy with 4 types of candy if the child takes at most 5 pieces of any type of candy? How many ways are there for a child to take 10 pieces of candy with 4 types of candy if the child takes at most 5 pieces of any type of candy? My solution begins like , $ 10 \choose 4$ is the answer,consistent to $ n-1 \choose r $ as this is similar to finding the number of non-zero positive integer solution of the equation $X_1 + X_2 + X_3 + x_4 = 10$ ,but i dont know how to account for the amount of candy the child takes at most, which is throwing me off. A: Let $x_k$ be the number of pieces of candy of type $k$ the child takes. Then we wish to determine the number of solutions in the nonnegative integers of the equation $$x_1 + x_2 + x_3 + x_4 = 10 \tag{1}$$ subject to the restrictions that $x_k \leq 5$ for $1 \leq k \leq 4$. The number of solutions to equation 1 is equal to the number of ways three addition signs can be placed in a row of $10$ ones, which is $$\binom{10 + 3}{3}$$ since we must choose which three of the thirteen symbols ($10$ ones and $3$ addition signs) are addition signs. From these, we must eliminate those solutions in which the child takes more than five pieces of candy of one type. Since the child select $10$ pieces of candy, it is not possible for the child to take more than five pieces of more than one type of candy. Suppose the child takes more than five pieces of candy of type 1. Let $y_1 = x_1 - 6$. Then $y_1$ is a nonnegative integer. Substituting $y_1 + 6$ for $x_1$ in equation 1 yields \begin{align*} y_1 + 6 + x_2 + x_3 + x_4 & = 10\\ y_1 + x_2 + x_3 + x_4 & = 4 \end{align*} which is an equation in the nonnegative integers with $$\binom{4 + 3}{3} = \binom{7}{3}$$ solutions. Since the child could have taken more than five pieces of candy from any of the four types, the number of ways the child can select ten pieces of candy without taking more than five of one type is $$\binom{13}{3} - \binom{4}{1}\binom{7}{3}$$
{ "pile_set_name": "StackExchange" }
Q: calling c++ function from c I need to access a C++ function from C but I get some error like :- /tmp/ccUqcSZT.o: In function `main': main.c:(.text+0x5): undefined reference to `load_alert_to_db' collect2: error: ld returned 1 exit status My main.c code is:- #include <stdio.h> extern void load_alert_to_db(void); int main(void){ /* Create empty queue */ load_alert_to_db(); return 0; } C++ code implementation db_manager.cpp is:- #include <sstream> #include <iostream> #include <sstream> #include <string> #include <ctime> #include <cstdlib> #include <algorithm> #include <time.h> #include <cstring> #include <fstream> //using namespace oracle::occi; #include <iostream> using namespace std; extern "C" void load_alert_to_db(void) { cout<<"db occi"<<endl; } makefile is:- CC= g++ all: $(CC) -c -Wall -Werror -fPIC db_manager.cpp $(CC) -shared -o libdb_manager.so db_manager.o gcc -L/home/oracle/Desktop/storage/ -Wall main.c -o data -ldb_manager gcc -o data main.c clean: rm -f *.o data so please help me which one is my problem. I am also include export LD_LIBRARY_PATH=/home/oracle/Desktop/storage/:$LD_LIBRARY_PATH environmental variable in .bash_profile A: gcc -o data main.c Not sure why you have this line in your makefile since it will compile main.c without reference to the previously created library and hence cause an undefined-symbol error such as the one you're seeing. This is especially so, since you appear to have done it the right way on the preceding line: gcc -L/home/oracle/Desktop/storage/ -Wall main.c -o data -ldb_manager However, the entire point of using makefiles is so that it figures out the minimum necessary commands for you, based on dependencies. Lumping a large swathe of commands into a single rule tends to defeat that purpose. You would be better off making your rules a little more targeted, such as (untested but should be close): all: data data: main.o libdb_manager.so gcc -o data main.o -ldb_manager main.o: main.c gcc -o main.o main.c libdb_manager.so: db_manager.cpp g++ -c -Wall -Werror -fPIC -o db_manager.o db_manager.cpp g++ -shared -o libdb_manager.so db_manager.o That way, if you make a small change to one part (like main.c), it doesn't have to go and compile/link everything in your build tree.
{ "pile_set_name": "StackExchange" }
Q: PHP Session through MVC I'm having trouble understanding how the session works with php through mvc. My spaghetti code worked like a charm, and implementing it in mvc gives me trouble. I can successfully log in. The problem is keeping a session for the logged in user, and displaying e.g the logout button. My login view: <div class="container"> <div class="login"><br> <h4>Login</h4> <?php echo "<form method='POST' action='login-user.inc.php'> <form class='login-inner'> <input type='text' name='username' placeholder='Username' autocomplete='off' /><br /><br /> <input type='password' name='password' placeholder='Password' /><br /><br /> <input class='button' type='submit' name='submit' value='Login' /> </form> </form>"; ?> </div> </div> The login view goes through the login-user.inc.php: <?php namespace View; use \Controller\SessionManager; use \Util\Util; use \Exceptions\CustomException; require_once 'mvc/Util/Util.php'; Util::initRequest(); $messageToUser = ""; $controller = ""; if(isset($_POST['username']) && isset($_POST['password']) && !isset($_POST[Util::USER_SESSION_NAME])){ if(!empty($_POST['username']) && !empty($_POST['password'])){ $username = htmlentities($_POST['username'], ENT_QUOTES); $password = htmlentities($_POST['password'], ENT_QUOTES); try{ $controller = SessionManager::getController(); $controller->loginUser($username, $password); echo "<p class = 'positiveMessageBox'>You are logged in! :) Welcome!</p>"; }catch(CustomException $ex){ echo "<p class = 'warningMessageBox'>".$ex->getMessage()."</p>"; }catch(\mysqli_sql_exception $ex){ echo "<p class = 'negativeMessageBox'>An error in connection with database occurred! Please contact administration of this website.</p>"; }finally{ SessionManager::storeController($controller); } }else{ echo "<p class = 'warningMessageBox'>Both username field and password field have to be filled! Try again!</p>"; } } @$_GET['page'] = $_SESSION['pageId']; include Util::VIEWS_PATH."redirect.php"; ?> My sessionhandler.php: <?php namespace Controller; use Controller\Controller; /** * This class stores and retrieves session data * @package Controller */ class SessionManager{ const CONTROLLER_KEY = 'controller'; const BROWSER_COMMENT_COUNT_KEY = 'browserCommentsCount'; private function __construct(){} /** * This method stores controller instance in the current session * @param \Controller\Controller $controller */ public static function storeController(Controller $controller){ $_SESSION[self::CONTROLLER_KEY] = serialize($controller); } /** * This method returns Controller instance * If Controller instance do not exists then returns new instance * @return \Controller\Controller */ public static function getController(){ if(isset($_SESSION[self::CONTROLLER_KEY])) return unserialize($_SESSION[self::CONTROLLER_KEY]); else return new Controller(); } } ?> My util, that is first and last initialized with the session_start(): <?php namespace Util; /** * Utility class * @package Util */ final class Util{ const VIEWS_PATH = 'src/view/'; const CSS_PATH = 'src/css/'; const IMG_PATH = 'src/img/'; const USER_SESSION_NAME = 'username'; private function __construct(){} /** * This method initialises autoload function and starts session * This method should should be called first in any PHP page that receiving a HTTP request */ public static function initRequest(){ \session_start(); self::initAutoload(); } private static function initAutoload(){ spl_autoload_register(function($class) { require_once 'mvc/' . \str_replace('\\', '/', $class) . '.php'; }); } } ?> This goes through the controller etc. This is what happens after a successful login. public function login(LoginData $userLoginData){ $userDAO = new UserDAO(); if($userDAO->doUsernameExistInDB($userLoginData->getUsername())){ if(password_verify($userLoginData->getPassword(), $userDAO->getUserPasswordFromDB($userLoginData->getUsername()))){ session_regenerate_id(); $_SESSION['username']; }else throw new CustomException("Password do not match with username you entered!"); }else{ throw new CustomException("We could not find the username you entered."); } } And finally the redirect.php that is supposed to show the logout button: <?php if (!empty($_SESSION[\Util\Util::USER_SESSION_NAME])) { echo '<li><a href="logout-user.inc.php">Logout</a><br><a>Welcome '.$_SESSION[\Util\Util::USER_SESSION_NAME].'</a></li>'; } else { echo '<li><a href="index.php?page=login">Login</a><br><a href="index.php?page=register">Register</a></li>'; } ?> I'm wondering why a session isn't initialized when logging in. It keeps telling me that I can still log in, when I already have. What am I missing here? A: In your login function, you seem to just call the $_SESSION['username']. Shouldn't you be affecting it the username of the connected user ? Then, in your redirect.php, when you're checking \Util\Util::USER_SESSION_NAME which corresponds to username, it must be empty, and then always shows the 'Login' button. Hope this helps !
{ "pile_set_name": "StackExchange" }
Q: Platform-specific dependencies of portable class libraries I have a piece of code that compiles for both the Silverlight and the .NET targets. It depends on Json.NET and SharpZipLib. My goal is to make a portable library that Silverlight and .NET projects can both link against. Since there is no version of SharpZipLib targeting "portable-net40+sl50", I have a problem. However, if I knew how, I would be willing to write the wrapper code myself. So: How can I write a portable library that depends on Silverlight's SharpZipLib when being linked against from Silverlight and depends on .NET's SharpZipLib when being linked against from .NET? Is that at all possible or is that something only Microsoft can do? A: If your code uses a limited sub-set of the SharpZipLib API, you could create a "dummy" PCL library comprising this API subset, but without any functionality implemented. What you then must do is to change the strong name (assembly name and signing) and version of the existing .NET and Silverlight SharpZipLib:s to be the same as your "dummy" PCL SharpZipLib and re-compile the platform specific libraries as well. With this set of assemblies (PCL, .NET and Silverlight) you will now be able to consume the PCL library from other PCL libraries. In a platform specific application that makes use of PCL libraries that in turn consumes the SharpZipLib library, you should explicitly reference the platform specific SharpZipLib library that has the same strong name and version as the PCL analogue. You should find more about this technique ("bait-and-switch") here and here. The PCL Storage project is also a good example of where this technique has been applied.
{ "pile_set_name": "StackExchange" }
Q: Not apply styles defined i created a ResourceDictionary , and defined a style for Windows <Style TargetType="{x:Type Window}" x:Key="WindowDefaultStyle"> <Setter Property="FontFamily" Value="Tahoma" /> <Setter Property="FlowDirection" Value="RightToLeft" /> <Setter Property="FontSize" Value="11" /> </Style> <!-- Window file --> <Window Style="{DynamicResource ResourceKey=WindowDefaultStyle}"> apply style in design but when run program not apply.:( Note: I have updated my code so other people can simply use it. A: Try setting the x:Keyon the Style along with TargetType like this - <Style x:Key="{x:Type Window}" TargetType="{x:Type Window}"> <Setter Property="FontFamily" Value="Tahoma" /> <Setter Property="FlowDirection" Value="RightToLeft" /> <Setter Property="FontSize" Value="11" /> </Style> Edit: You need to explicitly apply style to your window by giving your style some key. For reference please see these links - WPF window style not being applied How to set default WPF Window Style in app.xaml?
{ "pile_set_name": "StackExchange" }
Q: XNA Vertex Normal Calculation not working for Cube I have a function which calculates Vertex Normals for most primitives just right. But it can't seem to deal with Cubes. When I try the diffuse light shader it gives me this result (same on the right hand side) This is my code to Calculate Normals: public virtual void GenerateNormals() { for (int i = 0; i < vertices.Length; i++) vertices[i].Normal = new Vector3(0, 0, 0); for (int i = 0; i < indices.Length / 3; i++) { Vector3 firstvec = vertices[indices[i * 3 + 1]].Position - vertices[indices[i * 3]].Position; Vector3 secondvec = vertices[indices[i * 3]].Position - vertices[indices[i * 3 + 2]].Position; Vector3 normal = Vector3.Cross(firstvec, secondvec); normal.Normalize(); vertices[indices[i * 3]].Normal += normal; vertices[indices[i * 3 + 1]].Normal += normal; vertices[indices[i * 3 + 2]].Normal += normal; } for (int i = 0; i < vertices.Length; i++) if (vertices[i].Normal != Vector3.Zero) vertices[i].Normal.Normalize(); } The Cube's Vertices are generated like that: Vector3[] vectors = new Vector3[8]; vectors[0] = new Vector3(-1, 1, -1); vectors[1] = new Vector3(1, 1, -1); vectors[2] = new Vector3(-1, 1, 1); vectors[3] = new Vector3(1, 1, 1); vectors[4] = new Vector3(-1, -1, -1); vectors[5] = new Vector3(1, -1, -1); vectors[6] = new Vector3(-1, -1, 1); vectors[7] = new Vector3(1, -1, 1); vertices = new VertexPositionNormalColored[24]; //Top vertices[0].Position = vectors[0]; vertices[0].Color = TopColor; vertices[1].Position = vectors[1]; vertices[1].Color = TopColor; vertices[2].Position = vectors[2]; vertices[2].Color = TopColor; vertices[3].Position = vectors[3]; vertices[3].Color = TopColor; //Bottom vertices[4].Position = vectors[4]; vertices[4].Color = BottomColor; vertices[5].Position = vectors[5]; vertices[5].Color = BottomColor; vertices[6].Position = vectors[6]; vertices[6].Color = BottomColor; vertices[7].Position = vectors[7]; vertices[7].Color = BottomColor; //Left vertices[8].Position = vectors[2]; vertices[8].Color = LeftColor; vertices[9].Position = vectors[0]; vertices[9].Color = LeftColor; vertices[10].Position = vectors[6]; vertices[10].Color = LeftColor; vertices[11].Position = vectors[4]; vertices[11].Color = LeftColor; //Right vertices[12].Position = vectors[3]; vertices[12].Color = RightColor; vertices[13].Position = vectors[1]; vertices[13].Color = RightColor; vertices[14].Position = vectors[7]; vertices[14].Color = RightColor; vertices[15].Position = vectors[5]; vertices[15].Color = RightColor; //Back vertices[16].Position = vectors[0]; vertices[16].Color = BackColor; vertices[17].Position = vectors[1]; vertices[17].Color = BackColor; vertices[18].Position = vectors[4]; vertices[18].Color = BackColor; vertices[19].Position = vectors[5]; vertices[19].Color = BackColor; //Front vertices[20].Position = vectors[2]; vertices[20].Color = FrontColor; vertices[21].Position = vectors[3]; vertices[21].Color = FrontColor; vertices[22].Position = vectors[6]; vertices[22].Color = FrontColor; vertices[23].Position = vectors[7]; vertices[23].Color = FrontColor; And the indices like that: indices = new int[36]; //Top indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 2; indices[4] = 3; indices[5] = 1; //Back indices[6] = 16; indices[7] = 17; indices[8] = 18; indices[9] = 18; indices[10] = 19; indices[11] = 17; //Left indices[12] = 8; indices[13] = 9; indices[14] = 10; indices[15] = 10; indices[16] = 11; indices[17] = 9; //Front indices[18] = 20; indices[19] = 21; indices[20] = 22; indices[21] = 22; indices[22] = 23; indices[23] = 21; //Right indices[24] = 12; indices[25] = 13; indices[26] = 14; indices[27] = 14; indices[28] = 15; indices[29] = 13; //Bottom indices[30] = 4; indices[31] = 5; indices[32] = 6; indices[33] = 6; indices[34] = 7; indices[35] = 5; I hope experts can help me find the solution. Thanks in advance! A: You get this result because vertices in two different triangles do not have the same order. In a right handed system, your first triangle {(-1,1,-1), (1,1,-1) , (-1,1,1)} is in clockwise order while the second {(-1,1,1), (1,1,1) , (1,1,-1)} is counterclockwise. The normals for these triangles will have different directions.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET + ModalPopupExtender + Click Event I have an ASP.NET application that is using ASP.NET AJAX. I am using the ASP.NET AJAX Toolkit to present a dialog to a user. When the user clicks 'Yes' in the dialog, I want to handle that event in the code behind. However, I noticed that my click event is not being reached. Here is the main code: <asp:Panel ID="dialogContinuePanel" runat="server" style="display:none;" DefaultButton="yesButton"> <div>Are you sure you want to continue?</div> <div> <asp:ImageButton ID="yesButton" runat="server" AlternateText="Yes" ImageUrl="/resources/yes.png" OnClick="yesButton_Click" /> <asp:ImageButton ID="noButton" runat="server" AlternateText="No" ImageUrl="/resources/no.png" /> </div> </asp:Panel> <asp:LinkButton ID="hiddenLinkButton" runat="server" Text="" /> <cc1:ModalPopupExtender ID="dialogErrorExtender" runat="server" OkControlID="yesButton" TargetControlID="hiddenLinkButton" PopupControlID="dialogContinuePanel" CancelControlID="noButton" /> My Code Behind: protected void yesButton_Click(object sender, EventArgs e) { string argument = yesButton.CommandArgument; // Do some processing and redirect the user } How do I handle the click event of a Button that is used with a ModalPopupExtender? What am I doing wrong? A: You need to remove the OkButton property from your modal popup extender definition. I know this seems counter-intuitive, but when you add that reference, it actually hooks things up to work on the client side without causing postbacks. So just try this: <cc1:ModalPopupExtender ID="dialogErrorExtender" runat="server" TargetControlID="hiddenLinkButton" PopupControlID="dialogContinuePanel" CancelControlID="noButton" />
{ "pile_set_name": "StackExchange" }
Q: Golang are package block variables thread safe? According to the Go spec: "The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block." Are package block variables thread safe? E.G. If I have a package block variable to store the current user for a web app: var CurrentUser *string Request 1 comes in: Set CurrentUser to "John" Request 2 comes in: Set CurrentUser to "Fred" In Request 1 what is the value of CurrentUser? A: No, package variables are not thread safe. In your example, CurrentUser could change from "John" to "Fred" at any time—although the goroutine handling Request 1 is not guaranteed to see the change. So you need to use a local variable to store any data that is different for different goroutines.
{ "pile_set_name": "StackExchange" }
Q: Linear voltage regulator with a solar panel? I'm wondering how to go about reasoning about the losses in a linear voltage regulator connected to a solar panel. The OC voltage of the panel is around 22V, the maximum power voltage is around 18V, and I'd down-regulate it to 12V for a battery pack. So far, I got this: The more current I draw from the panel, the lower its voltage will be. Since the battery can sink in as much current as I can provide it (it's a tiny panel, let's say 0.5A), the voltage will probably drop significantly. The current will be maximal in this phase but the voltage drop across the LDO will be minimal (let's say 0.5A * 2V = 1W dissipation). As the battery gets charged, it will draw less and less current, and the solar panel voltage will rise. When it rises above the LDO voltage, the LDO will start dissipating more power as heat, however, at that point the current will be minimal. When the battery is charged at a steady voltage (let's say it's 12V), the voltage on the input of the LDO will be near the OC voltage, but the current through it and into the battery will be negligible. Does this make sense? Am I missing something? Edit: I'm not asking about exact calculations, just a confirmation about is this line of reasoning ok. A: The more current I draw from the panel, the lower its voltage will be. Since the battery can sink in as much current as I can provide it (it's a tiny panel, let's say 0.5A), the voltage will probably drop significantly. The current will be maximal in this phase but the voltage drop across the LDO will be minimal (let's say 0.5A * 2V = 1W dissipation). It also depends on how much sunlight hits the panel (notice the different amounts of power in the graph below, its a different panel but the same principles apply), which determines the power the panel can provide. Assuming you are providing your panel with the full amount of light (usually 1000W/m^2) you'll get some efficiency rating of that amount (usually 15-10%). For a 200cm^2 panel (0.04m^2) this would be 40W of sunlight and anywhere from 6W to 4W. (plug in the numbers for yours, they are usually on a nameplate on the back) The more current (or larger load you have) the less power your cell can provide. Take a look at the graph below, on one color there is a I-V curve and a power curve. The power (and efficiency) goes to near zero if your drawing too much current. Using an LDO can work assuming that your cell is providing more power than your source is sinking, which means you'll need a much larger panel. You'll be operating at the voltage of the LDO and your efficiency will not be nominal. Typically batteries are charged with constant current, then constant voltage. As the battery gets charged, it will draw less and less current, and the solar panel voltage will rise. When it rises above the LDO voltage, the LDO will start dissipating more power as heat, however, at that point the current will be minimal. Correct, but the current won't always be minimal, it will drop from it's nominal charging current to the 'float charge'. So at some point your LDO could be dissipating a lot of heat depending on the voltage of your cell. When the battery is charged at a steady voltage (let's say it's 12V), the voltage on the input of the LDO will be near the OC voltage, but the current through it and into the battery will be negligible. The voltage on the input of the LDO will depend on what part of the I-V curve the panel is on which will be determined by the amount of sunlight, the panel, and how much current your drawing. It would be best to plan on the LDO dissipating most of the power through it and put a hefty heatsink on it. While true that near the float charge the LDO will be dissipating minimal current, the system should be sized for the worst case condition so the LDO doesn't burn up. If the max voltage on the cell is 36V, and the max current draw is 1A then that is (36V-12V)*1A=24W into the LDO.
{ "pile_set_name": "StackExchange" }
Q: IntelliJ Idea - resource SQL files not being copied to target I have some problems with IntelliJ Idea not copying SQL resource files into target directory, so I have to copy them there manualy. I have SQL reosurce pattern in project's compiler settings. I have standart structure maven project - with /etc/ folder holding property files which gets copied without problem. /etc/ folder holds /sql/ folder which i need to be copied as well, but it gets not copied at all. /etc/ folder is set as source folder. My folder structure: -etc -conf -sql -src -main -test A: This should work fine, but could be a bug specific to your configuration. Could you please submit an issue with a sample project and pom.xml?
{ "pile_set_name": "StackExchange" }
Q: realloc dynamic array of char array I have to store some char arrays in an array. But I don't know how many of them I will have to store. What would be the best: initializing my array with a small size (like 1) and then realloc everything? How am I supposed to use realloc or malloc? I cannot use vectors nor stl containers nor strings unfortunately. Increasing the size of a vector is very easy and I tried to understand malloc and realloc but I don't... char ** array=(char**)malloc(10*sizeof(char*)); for (int i=0;i<10;i++) array[i]="10"; array=(char **)realloc(array,(sizeof(array)+1)*sizeof(char*)); array[10]="12"; I understood the basic principle yes. Is it in this way? A: Well, it seems you can not use vectors but normally that's exactly their purpose. The problem with your solution is it's more C than C++, you use a char array whereas in C++ you should use a string, and you use malloc and realloc whereas in C++ you should use new. Furthermore, you need to allocate memory for every level of indirection you have, so for a char ** you need at least 2 calls to malloc. Here is a corrected solution (it's still almost C, not really C++, notice you don't use a single C++ header): #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { //allocate a buffer of 10 pointers size_t array_size = 10; char ** array=(char **)malloc(array_size * sizeof(*array) ); if (!array) return -1; //now allocate the 10 pointers with a buffer to hold 42 characters for (int i = 0; i < array_size; i++) { array[i]= (char *)malloc( 42 * sizeof (*array[i]) ); if (!array[i]) return -1; strcpy(array[i], "10"); } //for some reason we need to increase array size by 1 ++array_size; array = (char **)realloc(array, array_size * sizeof(*array) ); array[array_size-1] = (char *)malloc(42 * sizeof(*array[array_size-1]) ); if (!array[array_size-1]) return -1; strcpy(array[array_size-1], "12"); }
{ "pile_set_name": "StackExchange" }
Q: Get height of children when floating left I have a parent div and inside two child div which are floating left. What I am trying to get is that get the 100% height depending upon the child. So if one child is bigger then the whole container should have its height. This is my scss .whole-message-wrapper { width: 100%; .message-info-wrapper { background-color: yellow; float: left; width: 5%; .message-icons { .message { } .attachment { } } } .message-wrapper { background-color: red; float: left; width: 95%; } } I don't want to have fixed height, any ideas? So I want the yellow child to have the same height as the parent. A: You can easily fix these kind of issues using Flex. Apply display:flex for your parent, It will fix the issue. .whole-message-wrapper { width: 100%; display:flex; } .message-info-wrapper { background-color: yellow; float: left; width: 5%; } .message-wrapper { background-color: red; float: left; width: 95%; } <div class="whole-message-wrapper"> <div class="message-info-wrapper">Message Info Wrapper</div> <div class="message-wrapper"> <p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Angular 4 Routing Could people stop suggesting this post be tagged with angular-4 routing? I am aware of that tag. My problem, however, was not to do with the routing of Angular 4 - it was kindof a mistake question coz I didn't understand what was going on at the time. The solution here will not help people who want help with actual Angular 4 routing so I disagree that it should be tagged as such and I will keep rejecting that alteration. I reiterate: It was a mistake to try to launch an angular web-app using a standard hosting package without first understanding PHP, nodejs, the dist folder and a whole bunch of other stuff. I see a lot of people making similar mistakes, but they need to know it is not routing problem so much as a not-knowing-about-websites problem, and they should just do as I did and buckle down and learn stuff. My angular 4 routing is not working. Angular 4 routing is different to Angular 2. Please could only people who have encountered similar issues with Angular 4 comment. There seem to have been a lot of changes and I set up my routing following the 2017 guidelines. Flagging old solutions to this is just confusing and unhelpful - especially as I am new to Angular and only have experience of 4. I don't want to use HashLocationStrategy * I can navigate to my domain, and then use my menu component to navigate between pages, but when I type in mydomain/home I see a blank page. Looks like other people asked similar questions about previous versions of Angular, but I can't see anyone with a newer setup. I have import { routes } from './app.router'; in app.module.ts and import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ArtComponent } from './art/art.component'; import { MusicComponent } from './music/music.component'; import { EventsComponent } from './events/events.component'; export const router: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full'}, { path: 'home', component: HomeComponent }, { path: 'art', component: ArtComponent }, { path: 'music', component: MusicComponent }, { path: 'events', component: EventsComponent } ]; export const routes: ModuleWithProviders = RouterModule.forRoot(router); in app.router.ts I'm afraid I'm very new to Angular! These are the errors in Chrome Inspector: polyfills.71b130084c52939ca448.bundle.js:1 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. (anonymous) @ polyfills.71b130084c52939ca448.bundle.js:1 firebug-lite.js:30396 [Deprecation] 'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead. getMembers @ firebug-lite.js:30396 home Failed to load resource: the server responded with a status of 404 () I have narrowed this issue down to problems with the build similar to those here: https://github.com/angular/angular-cli/issues/5113 There does not seem to be a satisfactory answer to that question - if anybody could tell me where to point my --base-href to make my build work? A: My Angular code turned out to be fine. The problem was with the server with my hosting provider. I needed to include a .htaccess file with my dist package
{ "pile_set_name": "StackExchange" }
Q: Do app store reviews take significantly longer for localized apps? I know the review process is unpredictable at best. To avoid a discussion of opinions, I'm looking for answers from people who have submitted apps without localizations, then submitted the same app later with the only changes being the addition of localization in several languages. If the review process is significantly longer than the original app, then the answer may be yes. I'm curious if they need to send the app to different countries for review, as some countries will block certain types if information (China, for example). Of course if you can post information other than this which is still relevant it would be appreciated. A: If you are submitting the app during the christmas holiday season rush, review times may be more. The average per day app submission in this time is lot higher due to Apple shutdown during holidays, and developers trying to get their app just in time before shutdown. That said, here's my observation for non-holiday seasons submission. We have an app that has been localized for 24 locales, including China. I never experienced any specific pattern in changes in review times before localization was put (was english only at one time, later all the localizations were added) vs after localizations were added. I had one time an update that went live within 48 hours of submission with around 19 localizations (including chinese, finnish, russian etc in it) in it. On the other hand, once a Finnish only app that I submitted took almost 2 weeks. Most of my apps are utility or education. I think its more to do with type of app + rating (if its got some controversial material in it) + when you submit it (christmas holiday season or not).
{ "pile_set_name": "StackExchange" }
Q: Nested choice element in XML Schema? What I'm trying to do is, declare an parent element called "data", which are having 6 sub element of these two element are conditional that means if element A is choose then B is not appear in "data". Like this: <data> <A>text1</A> <B>text1</B> <C>text1</C> <D>text1</D> <E>text1</E> or <F>text1</F> </data> Requirement 1 : all element can appear in any order and any number of times. Requirement 2 : Element E & F are conditional means only one of then is apear in data. My xsd code is this: <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="sequence" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded" > <xs:element ref="A" /> <xs:element ref="B" /> <xs:element ref="C" /> <xs:element ref="D" /> <xs:choice> <xs:element ref="E" /> <xs:element ref="F" /> <xs:element ref="G" /> </xs:choice> </xs:choice> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="status"/> </xs:complexType> </xs:element> I have tried all these link but still not getting my solution. XSD - how to allow elements in any order any number of times? Nested sequence in XSD XSD nested element A: Your are running afoul of a constraint on content models known variously as the "ambiguity rules" (in SGML), the "determinism rules" (so called in XML, which declined to call them ambiguity rules because in fact what is forbidden is not actually ambiguity, but non-determinism of the finite state automaton formed in a particular way from the content model), or the "unique particle attribution rules" (so called because the lead editor of XSD 1.0 appears to have thought they were different in some way from the determinism rules of XML; I've forgotten what the difference was supposed to be, and only remember that it was based on a misunderstanding of the XML rules). They don't actually have a good technical motivation (they were a design error in SGML, carried forward into XML for compatibility reasons and into XSD for no good reason at all), and (as you have found) they complicate the construction of legal content models, which is one reason some people are so happy with Relax NG, which mostly eliminates them. But since for better or worse they are part of so many languages for XML document grammars, it is worth knowing how to comply with them. The language you describe is: any sequence of A, B, C, or D elements, intermixed either with E elements or with F elements. To describe this language in a deterministic content model, you may find it helpful to think about what different states an automaton would have to have, in order to recognize such a language. In one state, any of the elements A to F is legal. Elements A through D leave us in that state. But once we see an E or an F, we move into a different state, in which A through D and either E or F (whichever we saw first) is legal, but the other (F or E) is not accepted. So we need three states. Note that each state corresponds to a language of its own: the sequence of elements we can see that put us into that state and leave us in that state. If we name the states initial, eee, and eff, we can summarize the languages with a regular expression which is easily translated into XSD: L(initial) = (A|B|C|D)* L(eee) = E, (A|B|C|D|E)* L(eff) = F, (A|B|C|D|F)* Note that from the first state, we can move to the second or the third, but once we are in either of those states, we never leave it. This means that the language we want is effectively L(initial) followed by a choice of L(eee) or L(eff). So one XSD formulation would be: <xsd:group name="initial"> <xsd:sequence> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element ref="A"/> <xsd:element ref="B"/> <xsd:element ref="C"/> <xsd:element ref="D"/> </xsd:choice> </xsd:sequence> </xsd:group> <xsd:group name="eee"> <xsd:sequence> <xsd:sequence minOccurs="0"> <xsd:element ref="E"/> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element ref="A"/> <xsd:element ref="B"/> <xsd:element ref="C"/> <xsd:element ref="D"/> <xsd:element ref="E"/> </xsd:choice> </xsd:sequence> </xsd:sequence> </xsd:group> <xsd:group name="eff"> <xsd:sequence minOccurs="0"> <xsd:element ref="F"/> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element ref="A"/> <xsd:element ref="B"/> <xsd:element ref="C"/> <xsd:element ref="D"/> <xsd:element ref="F"/> </xsd:choice> </xsd:sequence> </xsd:group> <xsd:complexType name="data"> <xsd:sequence> <xsd:group ref="initial"/> <xsd:choice> <xsd:group ref="eee"/> <xsd:group ref="eff"/> </xsd:choice> </xsd:sequence> </xsd:complexType> <xsd:element name="data" type="data"/> This amounts to describing your language in a different way: a sequence of A, B, C, or D elements, followed optionally either by an E and then any sequence of A, B, C, D, or E elements, or by an F and then any sequence of A, B, C, D, or F elements. It is worth spending as much time as it takes to persuade yourself that the language so described is the same as the language you describe in your description of the problem.
{ "pile_set_name": "StackExchange" }
Q: Laravel Form Button Cancel Using Laravel, I have a form and I want to include a "cancel" button that just redirects back to a different route. Since the button is within the form element, when clicked it attempts to submit the form. In the Laravel docs I don't see a good way to do this. Any suggestions or would using Javascript be best? Thanks, <div class="form-group pull-right"> <a href="{{ route('home') }}"><button class="btn btn-default btn-close">Cancel</button></a> <button type="submit" class="btn btn-global">Register</button> </div> A: Though it's a very late answer, But it might help others. You can just redirect back where you have come from. Simply use the following code. <a href="{{url()->previous()}}" class="btn btn-default">Cancel</a> It will send you back where you have came. A: <a> elements in bootstrap can have the btn class and they will look just like a button, so you can take the button out and just have cancel be a link: <div class="form-group pull-right"> <a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a> <button type="submit" class="btn btn-global">Register</button> </div>
{ "pile_set_name": "StackExchange" }
Q: How add button on NavigationBar dynamically (in runtime)? - Swift 2.0 I'm trying to add navigation bar dynamically, but something a little strange is happening. My Screen is just a UINavigation and a View with red background: And this is my Swift code: import UIKit class ViewController: UIViewController { @IBOutlet var navBar: UINavigationBar! @IBOutlet var viewLongPress: UIView! var viewLongPressInitialPosition: CGPoint! var frameSize: CGSize { get { return self.view.frame.size } } override func viewDidLoad() { super.viewDidLoad() navBar.frame.size.height = 64.0 viewLongPress.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "viewLongPressAction:")) viewLongPressInitialPosition = viewLongPress.frame.origin } func viewLongPressAction(sender: UILongPressGestureRecognizer) { let locationInView = sender.locationInView(self.view) if sender.state == .Began { } else if sender.state == .Changed { viewLongPress.frame.origin = CGPoint(x: locationInView.x - (viewLongPress.frame.width / 2), y: locationInView.y - (viewLongPress.frame.height / 2)) } else if sender.state == .Ended { if locationInView.y <= navBar.frame.height { let item = UINavigationItem() item.rightBarButtonItems = [UIBarButtonItem(title: "Test", style: .Plain, target: nil, action: "noAction:")] navBar.items?.append(item) } viewLongPress.frame.origin = viewLongPressInitialPosition } } func noAction(sender: AnyObject) { } } I'm trying to add a UINavigationItem to finish dragging the view on top of the navigation bar. But when I add the button, the navigation bar looks like this: The button should be added and look like this: I think I'm missing something, but I can not solve. I tried to add a second button (leftBar), but the title disappeared. And if you already have a button, how do I add one more button? Can someone help me? Thanks for the answer. A: You're replacing your whole UINavigationItem which is probably not what you want. Try self.navigationItem.rightBarButtonItem = ... instead. You don't even have to interact with the actual navigation bar, just the current view controller's navigation item (which aslo contains its title). Edit: it looks like your navBar already has a navigation item. What happens if you do this assignment instead: self.navBar.items.first?.rightBarButtonItem = ...
{ "pile_set_name": "StackExchange" }
Q: Monitoring app launches on an iOS device While I'm no expert on iOS development, I have read through the API docs on Apple's developer site and I can't find anything on this. Before I presume that it's impossible let me ask here: Can I somehow monitor application launches on a standard iOS device? By "standard" I mean not jailbroken and using only public iOS v4 APIs. Any insight is appreciated. Thanks. A: No, there's no access to system-level stuff like that at all. The somewhat-small sandbox makes certain types of apps impossible, but does provide a lot of protection for the user.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't the code after this promise invocation run? When I try to add any code after handing a function to a promise to run when it finishes, it never runs. See this example. (function() { var url = //some url that I know works var promise = $.get(url); $.when(promise).then(function(xml) { alert("Promise resolved."); })(); //This code doesn't run! alert("Code after promise."); })(); I thought that execution immediately went to the next line after $.when. Isn't that the whole point of using promises? The "Promise resolved" alert goes off fine, but the "Code after promise" never appears. What am I missing? A: You have an unnecessary () after this block: $.when(promise).then(function(xml) { alert("Promise resolved."); })(); Change it to: $.when(promise).then(function(xml) { alert("Promise resolved."); }); One of the comments stated that you need a $ at the beginning of your code. This is not true. You are simply creating a closure here, and this is perfectly acceptable syntax for such. I would, however, recommend prefixing your script with a ; so that if it is included after any other closures, it ensures that they are closed. This is just generally good practice when using closures in JavaScript.
{ "pile_set_name": "StackExchange" }
Q: Codeigniter: Accessing a array in view I am completely new in the codigniter i just started day befire Yesterday i am having a problem Here is my snippet of my controller code $allcalldetails_array = array( 'id' => $row->id, 'customer_id' => $row->customer_id ); $this->session->set_userdata('logged',$allcalldetails_array); I want to iterate the $allcalldetails_array in my views please tell me the way to do this i tried iterating logged but could not get anything . If i am printing the array in my views like print_r($allcalldetails_array); but this is also disappointing me .Please help me to get back on track . Thanks A: Its not necessary for session variables to be parsed via controller, access it on view directly: $logged = $this->session->userdata('logged'); print_r($logged);
{ "pile_set_name": "StackExchange" }
Q: How to exit/skip outter do-while after finishing If-Then in nested(inner) do-while I am a newbie to VBA dealing with some real-work problem, I have a problem exit do-while after finishing the inner(nested) do-while. *The code works fine, there is no issue, but I want to know how to make it more efficient by exit/skip outter do-while once the inner if-then is matched and ## is done. here is what the code looks like(FYI I delete some codes for ease of reading) : For Each w In Worksheets If () Then Do While (i) ' outter do-while Do While () 'inner(nested/1st do-while) If () Then 'match something here ## do something here Exit Do 'break the inner do-while End If Loop i = i + 20 'question here!!how should I break outter do-while? Loop End If Next w So, my goal is that once if-then is matched and ##content is done, how could I directly go to "next w", aka jump to next worksheet? I tried "goto+line" but it doesn't work, is there another way? A: you may try something like this: Dim exitLoop As Boolean '<--| default initial value is 'False' For Each w In Worksheets If () Then Do While (i) And Not exitLoop ' outer do-while Do While () and Not exitLoop 'inner(nested/1st do-while) If () Then 'match something here ## do something here exitLoop = True Exit Do 'break the inner do-while End If Loop i = i + 20 'question here!!how should I break outter do-while? Loop exitLoop = False '<--| set back default value End If Next w
{ "pile_set_name": "StackExchange" }
Q: Python: How to override data attributes in method calls? My question is how to use data attributes in a method but allow them to be overridden individually when calling the method. This example demonstrates how I tried to do it: class Class: def __init__(self): self.red = 1 self.blue = 2 self.yellow = 3 def calculate(self, red=self.red, blue=self.blue, yellow=self.yellow): return red + blue + yellow C = Class print C.calculate() print C.calculate(red=4) Does it makes sense what I am trying to accomplish? When the calculate function is called, I want it to use the data attributes for red, blue, and yellow by default. But if the method call explicitly specifies a different parameter (red=4), I want it to use that specified value instead. When I run this, it gives an error for using 'self.' in the parameters field (saying it's not defined). Is there a way to make this work? Thanks. A: You cannot refer to self since it's not in scope there yet. The idiomatic way is to do this instead: def calculate(self, red=None, blue=None, yellow=None): if red is None: red = self.red if blue is None: blue = self.blue if yellow is None: yellow = self.yellow return red + blue + yellow "Idiomatic", alas, doesn't always mean "nice, concise and Pythonic". Edit: this doesn't make it any better, does it... def calculate(self, red=None, blue=None, yellow=None): red, blue, yellow = map( lambda (a, m): m if a is None else a, zip([red, blue, yellow], [self.red, self.blue, self.yellow])) return red + blue + yellow
{ "pile_set_name": "StackExchange" }
Q: nginx server use HTTP/2 protocol version by default? I have various nginx server and recently I note that by default response these servers responses using the HTTP/2 version of protocol. I don't have configured the http2 parameter in nginx.conf. Is this the right behavior? A: No, that is not the default. If you observe HTTP2 despite not configuring it in NGINX, you likely have a CDN in front of it, e.g. Cloudflare.
{ "pile_set_name": "StackExchange" }
Q: How to create a XFS-formatted disk/folder I am playing around with ScyllaDB in docker. To have ScyllaDB operate most efficient in docker production setup it needs a XFS-formatted disk. Do you know how to create a XFS container volumes, file of disk - in Linux and MacOs? Thanks A: The best way to do that is to create a partition or LVM volume, and then format it with xfs normally, using some tool like mkfs.xfs. Once you are done, you can use the -v flag in docker to pass that to your container.
{ "pile_set_name": "StackExchange" }
Q: Requirement of streaming server for playing video in html I have some .mp4 and files which I want to view through my web application. The application has been built using spring2.5 and struts2 There is a jsp page which has links to the .mp4 files. As soon as a link is clicked, a ajax call is going to fetch the path of the .mp4 file and embed it in the jsp page, which then starts playing the same. My questions are 1) Whether I need a streaming server like Red5 to play the video files or not ? 2) What might be the advantages or disadvantages of using or not using a streaming server in the above case? 3) Will the format of files like .flv, .avi, .mp4 affect the decision? A: I have to have 50 reputation to comment but none to answer ?? We use Wowza streaming server. I am not familar with red5. FFmpeg also streams. In your case wowza would be better but ffmpeg is great for debugging stufff. With wowza you have test players and the urls get built for you - makes life a little easier. If you post flv, avi, mp4, etc on a web server and link to it, when the browser fetches that link webserver (not streaming server) /client down load the entire file - then will play. This is true also of mp3 files (so you can post it, fetch it and see what happens, because they are typically smaller files - the download time is less). The streaming server download 'chuncks' of the file plays etc. With both ffmpeg and wowza the type of file you start with is not terrible important (flv, mp4, avi, etc) All work. A) ffmpeg to stream simple video - open stream with vlc player - if working move on to next. B) read Wowza (or other streaming server) to do quality streaming.
{ "pile_set_name": "StackExchange" }
Q: 'getView' overrides nothing I am new about android studio. I tried to use ArrayAdapter. But when i complete my codes, it says "'getView' overrides nothing".I getting this error in "return teksatirview code. this is my arrayadapter class: package com.example.burcrehberi import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import kotlinx.android.synthetic.main.teksatir.view.* class BurcArrayAdapter( var gelencontext: Context, resource: Int, textViewResourceId: Int, var burcAdlari: Array<String>, var burcTarih: Array<String>, var burcResimleri: Array<Int> ) : ArrayAdapter<String>(gelencontext, resource, textViewResourceId, burcAdlari) { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var teksatirview = convertView if (teksatirview == null) { var inflater = LayoutInflater.from(gelencontext) teksatirview = inflater.inflate(R.layout.teksatir, parent, false) } var burcImageView = teksatirview?.imgburcsembol var burcisim = teksatirview?.tvburcadi var burctarih = teksatirview?.tvburctarih burcImageView?.setImageResource(burcResimleri[position]) burcisim?.setText(burcAdlari[position]) burctarih?.setText(burcTarih[position]) return teksatirview } } A: Your problem in parent: ViewGroup?. According to signature it must be non-null type. But it's nullable in your signature, so it's completely different function in kotlin. Just change to: override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { And return type View? to View too.
{ "pile_set_name": "StackExchange" }
Q: Vertical harpoon (half-arrow) notation I am studying a paper about Subgroups of Infinite Symmetric Groups by Macpherson and Neumann; throughout the paper, the authors use the notation $\upharpoonright$. For example, when they seek to topologize an infinite symmetric group $Sym(\Omega)$, they define the closure of a subset $X$ of $Sym(\Omega)$ as such: $\{f \in Sym(\Omega) \ |$ for all finite subsets $\Phi$ of $\Omega$ there exists $x \in X$ such that $x\upharpoonright\Phi=f\upharpoonright\Phi\}$ The authors don't define this notation, but they use it in several proofs. What do the authors mean when they use it? A: It is the truncation of a function to a particular set. That is, the subset of the function that has first-entries from the particular set.
{ "pile_set_name": "StackExchange" }
Q: Why are Constructors Evil? I recall reading an article about constructors being evil (but can't place it). The author mentioned that constructors are a special case of methods; but have restrictions (such as that they cannot have a return value). Are constructors evil? Is it better to have no constructors and instead rely on a method like Initialize, along with default values for member variables? (Your answer can be specific to C# or Java, if you must pin down a language.) A: That sounds like Allen Holub. One might argue that constructors are evil solely to drive web traffic :) They are no more evil than any other language construct. They have good and bad effects. Of course you can't eliminate them -- no way to construct objects without them! What you can do, though, and this is the case that Allen was making, is you can limit your actual invocation of them, and instead favor, when sensible, factory methods like your Initialize. The reason for this is simple: it reduces coupling between classes, and makes it easier to substitute one class for another during testing or when an application evolves. Imagine if your application does something like DatabaseConnection dc = new OracleDatabaseConnection(connectionString); dc.query("..."); and imagine that this happens in a hundred places in your application. Now, how do you unit test any class that does this? And what happens when you switch to Mysql to save money? But if you did this: DatabaseConnection dc = DatabaseConnectionFactory.get(connectionString); dc.query("..."); Then to update your app, you just have to change what DatabaseConnectionFactory.get() returns, and that could be controlled by a configuration file. Avoiding the explicit use of constructors makes your code more flexible. Edit: I can't find a "constructors" article, but here's his extends is evil one, and here's his getters and setters are evil one. A: They aren't. In fact, there is a specific pattern known as Inversion of Control that makes ingenious use of Constructors to nicely decouple code and make maintenance easier. In addition, certain problems are only solvable by using non default constructors.
{ "pile_set_name": "StackExchange" }
Q: vscode - expanding folders in version 1.31.0 I just updated my VSCode to the latest version of 1.31.0. Everything looks fine and there are a bunch of cool new features, but it seems that something has changed in the behavior of expanding and collapsing folders in the explorer pane. Up until this version, expanding and collpasing of folders was available by simply clicking on the little arrow icon to the left of the folder, like it is in any standard system that displays a tree of folders and files. Since the latest update, as mentioned here, this seems to be impossible any more and the E&C actions on folder can be done only by double clicking the folder. Is that a bug or a wanted feature, for some reason?? If that's a wanted feature, I think this is a very wrong decision, because what is the arrow there for, then?? I don't understand why this has changed... Where can I raise an issue about that? Where can I report that? A: Actually, this turned out to be a real bug in release 1.31 of VSCode... When the opening of files is set to "doubleClick" instead of "singleClick" (Settings -> Workbench -> List: Open Mode), the folders can be expanded or collapsed only by double clicking them and the "twistie" arrow does not work any more. Only when leaving the default settings on "singleClick" (or switching back to it, if changed from default), then the arrows work as they should. This is a bug because these arrows should always serve their original purpose (which is to expand and collapse folders, of course), regardless to the settings of opening files. My original report about this can be found here: https://github.com/Microsoft/vscode/issues/68050 Then, it turned to a fix by one of the developers: https://github.com/Microsoft/vscode/pull/68088 And after it was accepted and merged, it is designated to be a part of the next minor release (1.31.1).
{ "pile_set_name": "StackExchange" }
Q: Error in WordPress import I am changing my website hosting, so I made a backup for everything, themes, DB and used the Export utility in WP to export all posts, pages, etc. Now I am trying to import posts, pages, users in the new hosting but I am getting the following errors: Failed to create new user for John Their posts will be attributed to the current user. Failed to create new user for guest. Their posts will be attributed to the current user. Failed to create new user for Sam. Their posts will be attributed to the current user. Failed to import Media “MW profile” Failed to import Media “LA house” Failed to import Media “Gold” Failed to import Media “Archive” Failed to import Media “21882183” ...etc I checked the import xml file, paths inside it but I don't see any problem as paths in the import XML file are exactly the same as images real paths. So can someone please tell me what I might be doing wrong here, and how to solve this problem? A: Here's what I'd do: Copy all the files and folders from the old hosting to the new hosting. Dump the database on the old hosting, and import it to the new hosting. (at this step you'll have a full, complete backup of your original WP install). If necessary, adjust the database connection parameters on your wp-config.php file to reflect your new hosting (some hosts force the db prefix name, and it could be different from your original db name). You should now have an identical WP install on every aspect.
{ "pile_set_name": "StackExchange" }
Q: How can I print a file from the command line? Is there a way to run a file through a print driver without opening the application? Ex: run a .docx file, without opening word, and save it to file? A: Since it is a .docx-file Microsoft Word is probably the best program to do the task. I would have a look at the [command line arguments] to Word: Have a look at the following switches: /q, /n, /mFilePrintDefault and /mFileExit (/q and /n explained in the page above, and /mXxxx refers to macros. Have a look att google.) Example: WINWORD.EXE your_document.docx /mFilePrintDefault /mFileExit /q /n The following page seems to explain how to convert it to PDF.
{ "pile_set_name": "StackExchange" }
Q: explode function doesn't work for me? I want to change the string into array after using foreach() so how is it done? $g = ""; $changer = explode(",", $g); foreach ($y as $key => $c) { foreach ($c['movie'] as $rr) { $g .= $rr->movieName . ","; } } A: Based on your answer, theres a much easier way to do it than what you're doing: foreach ($y as $key => $c) { foreach ($c['movie'] as $rr) { $changer[] = $rr->movieName; } }
{ "pile_set_name": "StackExchange" }
Q: Python. Collect data until the end of json file binance_prices = {} def get_binance_price(): Prices = "https://api.binance.com/api/v3/ticker/price" r = requests.get(url=Prices) data = r.json() for coin in range(0,375): binance_prices.update( { data[coin]["symbol"]: data[coin]["price"]} ) I'm trying to get all coin prices from Binance and the code above works fine, but the problem is that if they will add a new coin, I won't catch it. So I thought about changing for coin in range(0,375): for counter = 0 while True: counter = counter + 1 binance_prices.update( { data[counter]["symbol"]: data[counter]["price"]} ) but how do I leave the loop? A: You wouldn't do this at all. You'd iterate through the data, not an arbitrary number. for coin in data: binance_prices.update( { coin["symbol"]: coin["price"]} ) It's an important principle in Python that you always iterate directly over a collection, rather than using range and an index.
{ "pile_set_name": "StackExchange" }
Q: Xamarin studio 5.9.7 the type or namespace name 'Xamarin' could not be found I tried to find a solution to use Xamarin.Forms but the solution in other question don't work for Xamarin studio 5.9.6 (same as for version 5.9.7 build 22 after an update) using System; using Xamarin.Forms; namespace test { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } } } The only available References when I tried to add that is Xamarin.Andoid.NUnitLite I get the error cs0103 I just found how to add the package to the project , right click package in project solution and try add Xamarin.Forms but i have another error And now the error is: Adding Xamarin.Forms... Adding 'Xamarin.Forms 1.3.3.6323' to test. Could not install package 'Xamarin.Forms 1.3.3.6323'. You are trying to install this package into a project that targets 'portable-net45+dnxcore50+win+wp80+MonoAndroid10+xamarinios10+MonoTouch10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. I tried to install the 4.6 Assembly with this link http://www.microsoft.com/en-us/download/details.aspx?id=40727 because it seems Xamarin.Forms needs the 4.6 one, some one can confirm that ? but i don't know how to add that correctly to the directory: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework If of course it is the solution, and try to repair the xamarian install to include that Under OSX here is the working pcl profile78: Because of this same error: Could not install package 'Xamarin.Forms 1.5.0.6447'. You are trying to install this package into a project that targets 'portable-net45+sl50+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. Can some one tell witch Assembly contained in Xamarin.Forms 1.5.0.6447 ? A: Try removing the ASP.NET Core 5.0 reference or deleting the ASP.NET Core 5.0.xml file from the Profile78\SupportedFrameworks directory. I had a similar error when making a new project. Check this thread. https://bugzilla.xamarin.com/show_bug.cgi?id=34520
{ "pile_set_name": "StackExchange" }
Q: setNeedsDisplay() is not calling draw(_ rect: CGRect) I found similar questions in this website but none of them solved my issue. Please carefully read the whole code. The setNeedsDisplay() function is not calling the draw(_ rect: CGRect) when I want to draw a line on MyView. I created a view called "myView" in storyboard as sub View of "MyViewController" and created a IBOutlet to the view controller. Then I created a class called "MyViewClass" and set it as the class of "myView" in storyboard. I set the bool value drawLine to true and call function updateLine(), the problem is the setNeedsDispaly() is not triggering the draw(_ rect: CGRect) function. import UIKit class MyViewClass : UIView{ var drawLine = Bool() // decides whether to draw the line func updateLine(){ setNeedsDisplay() } override func draw(_ rect: CGRect) { if drawLine == true{ guard let context = UIGraphicsGetCurrentContext() else{ return } context.setLineWidth(4.0) context.setStrokeColor(UIColor.red.cgColor) context.move(to: CGPoint(x: 415 , y: 650)) context.addLine(to: CGPoint(x:415 , y: 550)) context.strokePath() } } } class myViewController:UIViewController { @IBOutlet weak var insideView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let myViewInstance = MyViewClass() myViewInstance.drawLine = true myViewInstance.updateLine() } } I'm fairly new to Swift. Any help will appreciated. Thanks. A: You have 2 issues: you're not giving the new view a frame so it defaults to zero width and zero height you're not adding the view to the view heirarchy let myViewInstance = MyViewClass(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) myViewInstance.backgroundColor = .white // you might want this a well myViewInstance.drawLine = true self.view.addSubview(myViewInstance) myViewInstance.updateLine() A cleaner way to have your view redraw when a property (such as drawLine) is changed is to use a property observer: var drawLine: Bool = true { didSet { setNeedsDisplay() } } That way, the view will automatically redraw when you change a property and then you don't need updateLine(). Note that setNeedsDisplay just schedules the view for redrawing. If you set this on every property, the view will only redraw once even if multiple properties are changed. Note: viewDidLoad() would be a more appropriate place to add your line because it is only called once when the view is created. viewWillAppear() is called anytime the view appears so it can be called multiple times (for instance in a UITabView, viewWillAppear() is called every time the user switches to that tab).
{ "pile_set_name": "StackExchange" }
Q: Why sam package publishes the artifacts to bucket? As part of packaging the SAM application, the application published to s3 bucket as shown below: sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file output.yaml Why sam package provides --s3-bucket option? Is this mandatory option? What is the purpose of publishing artifacts to s3 bucket? A: --s3-bucket option in sam package command is mandatory. What the command does is that it takes your local code, uploads it to S3 and returns transformed template where source location of your local code has been replaced with the S3 bucket URI (URI of object - zipped code - in the S3 bucket). Main advantage of uploading artifact to S3 is that it is faster to deploy code that already sits within AWS network than send it through the Internet during deployment. Another thing is that plain CloudFormation let's you inline lambda function code without pushing it to S3 but there are limitations to this approach. If your lambda function needs to use external libraries that are not part of AWS provided lambda environment for a particular runtime or your function's size is big then you still need to zip your function's code together with its dependencies and upload it to S3 before continuing. SAM just makes this easier for you so that you don't have to do this step manually.
{ "pile_set_name": "StackExchange" }
Q: Cancel swipe left on tableview cell when showing more buttons in swift I was wondering if there was a proper way to cancel the swipe left on a tableview cell so that it slides back to hide the buttons. I'm not really sure how to correctly say that, lol. But please see the GIF below. In the first GIF I have no code after the cancel button gets pressed, and the buttons stay visible. The only idea I had was to reload the cell with this code self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) But this gives a look of the buttons shifting up, whereas I'd prefer it to appear the cell shifts backing into place to the right. See the reload GIF below. How should I be doing this properly? See below for my code that adds the buttons and what their functions are. override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Edit") { (action, indexPath) in if (indexPath == self.indexSelect) { print("Editting Selected Cell") } else { print("Editting a difference cell than selected") } let section: Sections = self.frc.objectAtIndexPath(indexPath) as! Sections let count: Int = self.sectionCount(section.section!) var msg: String? let sectionName: String = section.section! if (count > 0) { msg = "There are \(count) other Items using this Section currently. Editing the Section name \"\(sectionName)\" will affect them all. \n\nThis will be changed immediately!" } let alert = UIAlertController(title: "Edit Section Name", message: msg, preferredStyle: UIAlertControllerStyle.Alert) let editAction = UIAlertAction(title: "Edit", style: UIAlertActionStyle.Destructive) { UIAlertAction in let sectionName = Util.trimSpaces(alert.textFields![0].text!) if (sectionName != section.section) { if (Util.checkSectionName(sectionName, moc: self.moc!) == false) { let entityDesc = NSEntityDescription.entityForName("Sections", inManagedObjectContext: self.moc!) let newSection: Sections = Sections(entity: entityDesc!, insertIntoManagedObjectContext: self.moc) newSection.section = sectionName do { try self.moc!.save() } catch { fatalError("New item save failed") } let oldSection: Sections = section let fetchReq = NSFetchRequest(entityName: "Catalog") let pred = NSPredicate(format: "sections.section == %@", oldSection.section!) fetchReq.predicate = pred do { let results = try self.moc!.executeFetchRequest(fetchReq) for rec in results { let catalog: Catalog = rec as! Catalog catalog.sections = newSection } do { try self.moc!.save() } catch { fatalError("Failed to Save after Delete") } } catch { fatalError("Fetching Items to delete section failed") } self.moc!.deleteObject(oldSection) do { try self.moc!.save() } catch { fatalError("Failed to Save after Delete") } } else { Util.msgAlert("Duplicate Section Name", msg: "\"\(sectionName)\" section name already exists.", curVC: self) self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } else { self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in //self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } alert.addAction(editAction) alert.addAction(cancel) alert.addTextFieldWithConfigurationHandler { (txtFld) -> Void in txtFld.text = section.section txtFld.autocapitalizationType = UITextAutocapitalizationType.Words txtFld.autocorrectionType = UITextAutocorrectionType.Default txtFld.clearButtonMode = UITextFieldViewMode.WhileEditing } self.presentViewController(alert, animated: true, completion: nil) } edit.backgroundColor = UIColor.init(red: 84/255, green: 200/255, blue: 214/255, alpha: 1) let delete = UITableViewRowAction(style: .Destructive, title: "Delete") { (action, indexPath) in let section: Sections = self.frc.objectAtIndexPath(indexPath) as! Sections let count: Int = self.sectionCount(section.section!) if (count > 0) { let alert = UIAlertController(title: "Confirm Delete", message: "There are \(count) Items using this Section currently. Deleting this Section will reset them all to blank. \n\nThis can't be undone and will take affect immediately!", preferredStyle: UIAlertControllerStyle.Alert) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in } let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive) { UIAlertAction in var blankSection: Sections? var fetchReq = NSFetchRequest(entityName: "Sections") var pred = NSPredicate(format: "section == %@", "") fetchReq.predicate = pred do { let results = try self.moc!.executeFetchRequest(fetchReq) blankSection = (results.first as! Sections) } catch { fatalError("Fetching blank section failed") } fetchReq = NSFetchRequest(entityName: "Catalog") pred = NSPredicate(format: "sections.section == %@", section.section!) fetchReq.predicate = pred do { let group = try self.moc!.executeFetchRequest(fetchReq) for rec in group { let catalog: Catalog = rec as! Catalog catalog.sections = blankSection } } catch { fatalError("Fetching Items to delete section failed") } self.moc!.deleteObject(section) do { try self.moc!.save() } catch { fatalError("Failed to Save after Delete") } if (self.sectionUpdateProtocol != nil) { self.sectionUpdateProtocol!.sectionUpdate(self, section: blankSection!) } //self.navigationController!.popViewControllerAnimated(true) } alert.addAction(deleteAction) alert.addAction(cancel) self.presentViewController(alert, animated: true, completion: nil) } else { self.moc!.deleteObject(section) do { try self.moc!.save() } catch { fatalError("Failed to Save after Delete") } } } return [delete, edit] } A: Just call: tableView.setEditing(false, animated: true)
{ "pile_set_name": "StackExchange" }
Q: Git rebase / merge for public releases I've been digging through the git merge and rebase docs, and something isn't sinking in. I'm actively working on a project in Git, and need to share specific milestones with other developers. I want to share the code exactly as it is at each milestone / release, but not all of my small commits leading up to each release. How do I create a release branch that mirrors a development branch, where the commits on the release branch each contain several commits from the development branch? In other words, the release branch should have a compressed history, but otherwise match the development branch. Originally, I had thought that using a separate branch and using git merge --squash would be effective, creating a new branch with a series of commits that reflect the full set of changes between each release. I now understand that git merge --squash doesn't work for repeated uses. Git rebase would work to collapse several commits into one large commit, but because it changes the commit history, wouldn't change my private history as well as the public releases? I don't want to lose my history of small changes, but want to push combined commits to a shared server. A: Surely, if your commits are both worth keeping and constitute your work towards a public release, then they should form part of your published history? If you don't want to publish your full repository history then you may be better off just using git archive to create release tarballs. Having said that if you really want to create a release branch with a separate history then it is possible. You are setting yourself up for more maintenance overhead, though, as you can never merge from your private history to your public release branch as that would bring in all the private history to your release branch. This is what git does; it tracks where changes come from. You can merge from the release branch to the private branch but as your work is (presumably) coming from the private branch this won't gain you much. Your easiest option is to have a separate release branch which contains only snapshot commits of the state of the private branch at release points. Assuming that you have reached a point where you want to create a commit on the release branch (release) based on the current commit in the private branch (private) and assuming that you have the tree to be released checked out with no changes to the index, here is what you can do. # Low-level plumbing command to switch branches without checking anything out # (Note: it doesn't matter if this branch hasn't yet been created.) git symbolic-ref HEAD refs/heads/release # Create a new commit based on the current index in the release branch git commit -m "Public release commit" # Switch back to the private branch git checkout private You can do this for each release (or sub-release) and the new commit will be built directly on top of the previous release without incorporating any of your private history.
{ "pile_set_name": "StackExchange" }
Q: Android Studio - Button Widget OnClick. Cannot find function I want myButton to execute a function when clicked, I have tried this method as it has worked for me from another project, but I am missing or doing something wrong here as it is not working. I have a button on my XML file with the ID VazhdoButoni, and I have a public gogogo (View v) { on my java. When I go to my XML file and at my button properties, at the onClick choose box, I don't see my public gogogo function there. The class is: public class BikeFragment extends Fragment { The View is: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bike, container, false); } Java code: public void gogogo (View v) { TextView tv = (TextView)v.findViewById(R.id.teksti2); username = ((EditText)v.findViewById(R.id.user2)).getText().toString(); password = ((EditText)v.findViewById(R.id.pass2)).getText().toString(); try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); Connection con = DriverManager.getConnection(url, username, password); // System.out.println("Database connection success."); String result = "Database connection success\n"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from tblItems"); ResultSetMetaData rsmd = rs.getMetaData(); while(rs.next()) { result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n"; result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n"; result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n"; } tv.setText(result); } catch(Exception e) { e.printStackTrace(); tv.setText(e.toString()); } } xml button: <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Vazhdo" android:id="@+id/VazhdoButoni" android:layout_gravity="center_horizontal|bottom" android:layout_marginBottom="340dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" /> A: You missed onClick tag <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Vazhdo" android:id="@+id/VazhdoButoni" android:onClick="gogogo" android:layout_gravity="center_horizontal|bottom" android:layout_marginBottom="340dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" />
{ "pile_set_name": "StackExchange" }
Q: Best HDD Setup for HTPC I am configuring an HTPC that can support up to 4 internal hard drives, as well as RAID levels 0, 1, 5 and 10. My plan is to install Windows 7 Home Premium 64-bit. I have been taught that its best to have a small, fast primary drive for the OS and then a larger secondary drive for data. Though I realize this may be different on an HTPC. I would like to have some redundancy in my data, and I was wondering what would be the best configuration of disks for me. A: I agree with this advice, and it is entirely doable on an HTPC: I have been taught that its best to have a small, fast primary drive for the OS and then a larger secondary drive for data. The reason for this is that if the OS becomes corrupted and you need to reinstall, this setup allows reformatting/reinstalling the system drive with no need to touch the data partitions. But I can't recommend RAID solutions. If you absolutely need the performance, go with hardware RAID-0, keep good backups, and be prepared to restore from backup at the first hardware failure. If you absolutely need the redundancy, a RAID-1 mirroring solution -- preferably software RAID -- is best. Why? Two words: hardware failure. Hardware RAID is chipset dependent. You cannot take a RAID set from one chipset and plug it into another and access your data. Software RAID is slower, but doesn't depend on a RAID chipset. In the event of a controller failure, you won't have to locate an identical controller chip to get a software RAID set up and running again. Personally, I use standard partitions on bare drives -- no RAID, no LVM, no Dynamic Disk. I have a spare drive in the server to backup the important stuff, and another offline that gets plugged in and updated once in a while. That protects me from a drive failure. If the motherboard or drive controller fails, these drives will work immediately on any other hardware. I don't need to find matching chipsets, I don't need to configure a new system to use another system's software RAID set or LVM, and a single drive failure has no effect on my ability to access other drives. Remember, RAID is not a backup. RAID is not a substitute for a backup. RAID-0 is for performance, RAID-1 is for redundancy, RAID-5 is for a little of both. There's another piece of advice that's worth keeping in mind: There are only 2 kinds of people in the world: those who have experienced catastrophic data loss, and those who will experience catastrophic data loss.
{ "pile_set_name": "StackExchange" }
Q: Functional Programming: How to convert an impure function to a pure function when the input needs to be mutated How can I create a pure function that updates an object that's been initialized in another function something like: parentFunction = (inputs: object[], condtionList: string[]) => { const newObject = {f1: val1[], f2: val2[], f3: val3[]...} inputs.forEach(input => { if(condition1){ updateNewObject(condtion1, newObject, input, conditionList) } . . . } return newObject } The below function is impure as it's updating the newObject (mutating the input) how can I convert it to a pure function? updateNewObject(condition, newObject, input, conditionList) { const i = conditionList.indexOf(input.condition) if(i === 0){ newObject.f1.push(input) } else if(i === 1) { newObject.f2.push(input) } . . . } The above has no return value. It takes the newObject as input and based on some conditionals pushes values to the properties of the newObject. Is there anyway to make the above function pure? or do I have to rethink how I am updating newObject? A: Functional programming is not only about purity, it's also about reusability and separation of concerns. It's difficult to write a big complex function, and even harder to test and maintain it. Following functional principles will help us avoid pain and discomfort. Let's start by isolating the behaviours we care about. We identify functions push, update, and pushKey - const identity = x => x const push = (a = [], value) => a.concat([ value ]) const update = (o = {}, key = "", t = identity) => ({ ...o, [key]: t(o[key]) }) const pushKey = (o = {}, key = "", value) => update(o, key, a => push(a, value)) This allows you to perform basic immutable transformations easily - const d1 = { a: [1], b: [] } const d2 = pushKey(d1, "a", 2) const d3 = pushKey(d2, "b", 3) const d4 = pushKey(d3, "c", 4) console.log(d1) // { a: [1], b: [] } console.log(d2) // { a: [1, 2], b: [] } console.log(d3) // { a: [1, 2], b: [3] } console.log(d4) // { a: [1, 2], b: [3], c: [4] } Expand the snippet below to run the program in your own browser - const identity = x => x const push = (a = [], value) => a.concat([ value ]) const update = (o = {}, key = "", t = identity) => ({ ...o, [key]: t(o[key]) }) const pushKey = (o = {}, key = "", value) => update(o, key, a => push(a, value)) const d1 = { a: [1], b: [] } const d2 = pushKey(d1, "a", 2) const d3 = pushKey(d2, "b", 3) const d4 = pushKey(d3, "c", 4) console.log(JSON.stringify(d1)) // { a: [1], b: [] } console.log(JSON.stringify(d2)) // { a: [1, 2], b: [] } console.log(JSON.stringify(d3)) // { a: [1, 2], b: [3] } console.log(JSON.stringify(d4)) // { a: [1, 2], b: [3], c: [4] } This allows you to separate your complex conditional logic into its own function - const updateByCondition = (o = {}, conditions = [], ...) => { if (...) return pushKey(o, "foo", someValue) else if (...) return pushKey(o, "bar", someValue) else return pushKey(o, "default", someValue) } The advantages to this approach are numerous. push, update, and pushKey are all very easy to write, test, and maintain, and they're easy to reuse in other parts of our program. Writing updateByCondition was much easier because we had better basic building blocks. It's still difficult to test due to whatever complexity you are trying to encode, however it is much easier to maintain due to separation of concerns. A: If you want updateNewObject to be pure, have it create a new object that clones the original, mutate that, and then return the new object. updateNewObject(condition, oldObject, input, conditionList) { const newObject = {...oldObject}; const i = conditionList.indexOf(input.condition) if(i === 0){ newObject.f1 = [...newObject.f1, input]; } else if(i === 1) { newObject.f2 = [...newObject.f2, input]; } . . . return newObject; } Note how newObject.f1 = [...newObject.f1, input]; creates a new array - this ensures that we not only don't mutate the object directly, but we don't mutate any of its fields (arrays) and instead create new ones. Then tweak parentFunction so that it uses the value of each returned updateNewObject call: parentFunction = (inputs: object[], condtionList: string[]) => { let newObject = {f1: val1[], f2: val2[], f3: val3[]...} inputs.forEach(input => { if(condition1){ newObject = updateNewObject(condtion1, newObject, input, conditionList) } . . . } return newObject }
{ "pile_set_name": "StackExchange" }
Q: Horizontal alignement of two tikzcd How can I put two copies of this tikzcd on the same line? \[ \begin{tikzcd}[row sep=2.5em] & \text{A} \arrow[dash]{dr}{1} \\ \text{B} \arrow[dash]{ur}{2} \arrow[dash]{rr}{3} && \text{C} \end{tikzcd} \] A: \documentclass{article} \usepackage{amsmath} \usepackage{tikz-cd} \begin{document} \[ \begin{tikzcd}[row sep=2.5em] & \text{A} \arrow[dash]{dr}{1} \\ \text{B} \arrow[dash]{ur}{2} \arrow[dash]{rr}{3} && \text{C} \end{tikzcd} \quad \begin{tikzcd}[row sep=2.5em] & \text{A} \arrow[dash]{dr}{1} \\ \text{B} \arrow[dash]{ur}{2} \arrow[dash]{rr}{3} && \text{C} \end{tikzcd} \] \end{document} If you have different diagrams, you may want to make use of the baseline option, \documentclass{article} \usepackage{amsmath} \usepackage{tikz-cd} \begin{document} \[ \begin{tikzcd}[row sep=2.5em,baseline=(B.base)] & \text{A} \arrow[dash]{dr}{1} & \\ |[alias=B]|\text{B} \arrow[dash]{ur}{2} \arrow[dash]{rr}{3} && \text{C} \end{tikzcd} \quad \begin{tikzcd}[row sep=2.5em,baseline=(B.base)] & \text{A} \arrow[dash]{dr}{1} &\\ |[alias=B]|\text{B} \arrow[dash]{ur}{2} \arrow[dash]{dr}{4} \arrow[dash]{rr}{3} && \text{C} \\ & \text{D} & \end{tikzcd} \] \end{document} or put the diagrams in \vcenter{\hbox{...}} to vertically center them.
{ "pile_set_name": "StackExchange" }
Q: Fragments not inflating menu after switching back and forth I'm completely new to android programming, so I'll try to explain this issue as accurately as possible. I have an application that consists of a MainActivity. This activity houses 3 fragments being controlled using a ViewPager and a FragmentPagerAdapter. When I initially click (through the action bar) or swipe over to the settings fragment, my "Save" and "Cancel" options appear in the action bar. However when I slide away from the fragment (via a swipe), then slide back, the menu fails to load. No matter how many times I move to different fragments and regardless of how I do so (both through tabs and swiping), the menu will not return until the app has either closed or rotated. However, I've checked the logs and no error seems to be throw, but when I place Debug outputs into OnCreateOptionsMenu I can see that it is indeed getting called. Even stranger, if I rotate the display, the menu appears, and OnCreateOptionsMenu is called a couple more times. I also checked visibility and it shows the items is both visible and enabled. It's almost as if the item is being drawn off the screen. SettingsFragment.java public class SettingsFragment extends Fragment implements TextWatcher { private EditText txtCost; private String current = ""; private DatePicker dtDateQuit; private TimePicker dtTimeQuit; public SettingsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_settings, container, false); NumberPicker np = (NumberPicker) rootView.findViewById(R.id.npCigs); np.setMaxValue(100); np.setMinValue(0); txtCost = (EditText)rootView.findViewById(R.id.txtCost); txtCost.addTextChangedListener(this); dtDateQuit = (DatePicker)rootView.findViewById(R.id.dtQuit); dtTimeQuit = (TimePicker)rootView.findViewById(R.id.tmQuit); txtCost.setText("$" + String.valueOf(MainActivity.dblCost) + "0"); dtDateQuit.updateDate(MainActivity.dtStopDate.get(Calendar.YEAR),MainActivity.dtStopDate.get(Calendar.MONTH), MainActivity.dtStopDate.get(Calendar.DAY_OF_MONTH)); dtTimeQuit.setCurrentHour(MainActivity.dtStopDate.get(Calendar.HOUR)); dtTimeQuit.setCurrentMinute(MainActivity.dtStopDate.get(Calendar.MINUTE)); np.setValue(MainActivity.intCigDay); setHasOptionsMenu(true); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { System.out.println("-------------- Starting Inflation --------------"); super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.settings_fragment_menu, menu); System.out.println("-------------- Inflation Finished --------------"); System.out.println("------------ Menu Item: " + menu.getItem(0).getTitle()); System.out.println("------------ Visible: " +menu.getItem(0).isVisible() ); System.out.println("------------ Enabled: " + menu.getItem(0).isEnabled() ); } @Override public void afterTextChanged(Editable s) { String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol()); if(!s.toString().equals(current)){ txtCost.removeTextChangedListener(this); String cleanString = s.toString().replaceAll(replaceable, ""); double parsed = Double.parseDouble(cleanString); String formated = NumberFormat.getCurrencyInstance().format((parsed/100)); current = formated; txtCost.setText(formated); txtCost.setSelection(formated.length()); txtCost.addTextChangedListener(this); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } EDIT: I seem to have stumbled upon a somewhat fix, but it is pretty dirty. In the MainActivity that houses the fragments, in onTabSelected I placed a call to invalidateContextMenu, then I moved the inflater to the MainActivity as well, checking which tab is selected. This makes the menu draw much quicker, but seems like a very strange way to have to do it. Are there any downsides to using this method? A: set your viewpager offset limit to no of tabs you have, like i had 3 viewPager.setOffscreenPageLimit(3);
{ "pile_set_name": "StackExchange" }
Q: creating an object from JSON data I have the following data in a .json file: { "countries": { "sweden": { "currency": "Swedish krona", "majorLanguage": "Swedish", "landArea": { "value": 410330, "uom": "sq km" } }, "japan": { "currency": "yen", "majorLanguage": "Japanese", "landArea": { "value": 364500, "uom": "sq km" } }, "unitedStatesOfAmerica": { "currency": "US dollar", "majorLanguage": "English", "landArea": { "value": 3796742, "uom": "sq mi" } } } } and need to come up with a way to create this object from it: Object { "currency": Object { "japan": "yen", "sweden": "Swedish krona", "unitedStatesOfAmerica": "US dollar" }, "majorLanguage": Object { "japan": "Japanese", "sweden": "Swedish", "unitedStatesOfAmerica": "English" }, "landArea": Object { "japan": Object { "value": 364500, "uom": "sq km" }, "sweden": Object { "value": 410330, "uom": "sq km" }, "unitedStatesOfAmerica": Object { "value": 3796742, "uom": "sq mi" } } } The app that will be consuming this data is written in Vue so using JavaScript to accomplish this would make sense, although my preference is to not use any third party libraries. Specifically, I'm interested in a programmatic approach that doesn't require hard coding of to manually create objects for currency, majorLanguage, landArea. I don't really know how to start tackling this so don't have any sample attempts to post here. A: Nothing fancy here: const result = {}; for (const name in countries) { const country = countries[name]; for (const key in country) { if (!result[key]) result[key] = {}; result[key][name] = country[key]; } }
{ "pile_set_name": "StackExchange" }
Q: if condition too long and including for loop Hi I am a C++ beginner and here is a problem I am facing when writing a function. The bool function isData is used to see whether the array members are all numbers. Usually the size will be 11 or 9 or 7 so I don't want to hard code it. But I am not sure whether for loop work in if condition. And I will be so grateful if you can show me an easier way to do this. bool isData(string temp[], int size) { if( for (int i;i<size;i++) { 59 > +temp[i].at(0) && +temp[i].at(0) > 47 || +temp[i].at(0) == 45 } ) { return true; } else { return false; } } A: for loops doesn't result in true or false, so for in an if won't work. instead, run all elements in a for loop and return false if you find a non-number. Otherwise, return true. Pseudo code for that would be something like this bool isData(String temp[], int size) { for(int i=0; i < size; i++) { if( hasOnlyDigits(temp[i]) ) { return false; } } return true; } hasOnlyDigits is a function that would take in string and check if it's a valid number. Here is a one liner for positive numbers. bool hasOnlyDigits = (temp[i].find_first_not_of( "0123456789" ) == string::npos); It's non trivial to implement a function which handles all inputs like +.23, -33--33. Implement a function that can handle inputs within your input constraints. I'll update this answer if I find a robust way to check.
{ "pile_set_name": "StackExchange" }
Q: jQuery getting array of form params and submitting in Ajax request On a form submit, I'm looking to append data from a different form and submit that and the original form data via an ajax request. The form fields I'm looking to gain are in the following format: <input type="hidden" name="selected[84334][]" value="865804"> <input type="hidden" name="selected[54434][]" value="865807"> <input type="hidden" name="selected[54494][]" value="865808"> <input type="hidden" name="selected[54494][]" value="866212"> and the ajax request that I currently have is: var form_data = $(this).serializeArray(); var more_data = $('input[name="data[]"]', '.fields_container_class').serializeArray(); var data = $.merge( form_data, more_data ); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: $.param(data) }); I've been able to capture the data in the hidden fields with the name of 'data[]', but how can I capture and include the 'selected[][]' fields, but maintain the keys? Thanks for your help Scott A: To select the selected[X][] fields you can use the 'attribute begins with' selector, like this: $('form').on('submit', function(e) { e.preventDefault(); var form_data = $(this).serializeArray(); var more_data = $('input[name="data[]"]', '.fields_container_class').serializeArray(); var even_more_data = $('input[name^="selected"]', '.fields_container_class').serializeArray(); var data = form_data.concat(more_data, even_more_data); console.log(data); // AJAX call... }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="fields_container_class"> <input type="hidden" name="data[]" value="lorem"> <input type="hidden" name="data[]" value="ipsum"> <input type="hidden" name="selected[84334][]" value="865804"> <input type="hidden" name="selected[54434][]" value="865807"> <input type="hidden" name="selected[54494][]" value="865808"> <input type="hidden" name="selected[54494][]" value="866212"> <form> <input type="text" name="foo" value="foobar" /> <button>Submit</button> </form> </div> Note the use of concat() here instead of jQuery's $.merge(). This is because the former allows you to concatenate multiple arrays in one call, the latter does not. Finally, to simplify the logic you can use the spread operator, ..., to merge the arrays at the point of declaration. Beware this is unsupported in IE, though. var data = [ ...$(this).serializeArray(), ...$('input[name="data[]"]', '.fields_container_class').serializeArray(), ...$('input[name^="selected"]', '.fields_container_class').serializeArray() ]
{ "pile_set_name": "StackExchange" }
Q: SFINAE and inheritance I'm looking for a solution to a following problem: #include <string> class A { public: template <typename T> static typename std::enable_if<std::is_same<T, std::string>::value, void>::type foo(T val) { printf("std::string\n"); } template<typename T, typename... Arg> static void multiple(Arg&&... arg) { T::foo(arg...); } }; class B : public A { public: template <typename T> static typename std::enable_if<std::is_same<T, int>::value, void>::type foo(T val) { printf("int\n"); } }; int main() { std::string a; int b = 0; A::multiple<B>(a, b); } All works fine if both foo methods are in the same class or I force foo from proper class (A::foo for std::string and B::foo for int), however I need more than one class, because base class must be extendable. I can't use simple specialization, because I need more SFINAE features like detect for std::pair, std::tuple etc. I also don't want to move foo methods from a class to a namespace. Do you have any Idea how can I solve this issue? A: Here B::foo hides A::foo, you need a using: class B : public A { public: using A::foo; template <typename T> static typename std::enable_if<std::is_same<T, int>::value, void>::type foo(T val) { printf("int\n"); } }; But From namespace.udecl#15.sentence-1: When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list, cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting) Return type doesn't count, so you have to use std::enable_if in parameter: class A { public: template <typename T> static void foo(T val, std::enable_if_t<std::is_same<T, std::string>::value, int> = 0) { printf("std::string\n"); } }; class B : public A { public: using A::foo; template <typename T> static void foo(T val, std::enable_if_t<std::is_same<T, int>::value, int> = 0) { printf("int\n"); } }; Demo Note: you also have typo for template<typename T, typename... Arg> static void multiple(Arg&&... arg) { T::foo(arg...); // B::foo(string, int) } which should be template<typename T, typename... Arg> static void multiple(Arg&&... arg) { (T::foo(arg), ...); // B::foo(string), B::foo(int) }
{ "pile_set_name": "StackExchange" }
Q: Poner auto-incremento en campos agregados a la base de datos Hola a todos espero y me puedan ayudar, tengo el siguiente problema en mi base de datos necesito que al momento de agregar una fila la siguiente sea consecutiva 1,2,3++, ya tengo el id como primarykey y autoincrement pero me toma el id de otra tabla de un usuario que agrega la linea En idViaje necesito que sea 1 y así sucesivamente NOTA: Si se puede 0001 mucho mejor <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $razonSocial = $_POST["razonsocial"]; $idCliente = $_POST["idCliente"]; $cliente = $_POST["Cliente"]; $rfc = $_POST["rfc"]; $moneda = $_POST["moneda"]; $mercancia = $_POST["mercancia"]; $importe = $_POST["importe"]; $tipoOperacion = $_POST["TipoOperacion"]; $fechaAlta = $_POST["FechaAlta"]; $detalles = $_POST["detalles"]; $tipoTransporte = $_POST["TipoTransporte"]; $fechaSalida = $_POST["FechaSalida"]; $fechaLlegada = $_POST["FechaLlegada"]; $folio = $_POST["folio"]; $porigen = $_POST["porigen"]; $eorigen = $_POST["eorigen"]; $corigen = $_POST["corigen"]; $pdestino = $_POST["pdestino"]; $edestino = $_POST["edestino"]; $cdestino = $_POST["cdestino"]; $coberturas = $_POST["Coberturas"]; $poliza = $_POST["poliza"]; $cuota = $_POST["cuota"]; $prima = $_POST["prima"]; $gastosexp = $_POST["gastosexp"]; $iva = $_POST["iva"]; $total = $_POST["total"]; if($cliente == 'X'){ $cliente =''; }else{ query("INSERT INTO merca (idViaje, idCliente, Cliente, rfc, moneda, mercancia, importe, TipoOperacion, FechaAlta, detalles, TipoTransporte, FechaSalida, FechaLlegada, folio, porigen, eorigen, corigen, pdestino, edestino, cdestino, Coberturas, poliza, cuota, prima, gastosexp, iva, total) VALUES ('".$idCliente."','".$idCliente."', '".$cliente."', '".$rfc."', '".$moneda."', '".$mercancia."', '".$importe."', '".$tipoOperacion."', '".$fechaAlta."', '".$detalles."', '".$tipoTransporte."', '".$fechaSalida."', '".$fechaLlegada."', '".$folio."','".$porigen."','".$eorigen."', '".$corigen."', '".$pdestino."', '".$edestino."', '".$cdestino."', '".$coberturas."', '".$poliza."', '".$cuota."', '".$prima."', '".$gastosexp."', '".$iva."', '".$total."')"); } } ?> <div class="row"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-content"> <form id="nclientes" name="nclientes" method="post" action="" class="form-horizontal"> <div class="form-group"> <h3 style="margin-left:20px;">Datos del Asegurado</h3> <label class="col-sm-2 control-label">Razon Social</label> <div class="col-sm-4"> <input name="razonsocial" type="text" autocomplete="off" required title="Completar campo" class="typeahead_2 form-control" <?php if($_COOKIE["lvl"]==2){ echo 'value="'. $_COOKIE["usuario"] . '" disabled'; } ?> /> <input id="idCliente" name="idCliente" type="hidden" value="<?php if($_COOKIE["lvl"]==2){ echo $_COOKIE["idUsuario"]; } ?>" /> A: En tu query tienes esto: query("INSERT INTO merca (idViaje, idCliente, Cliente, rfc, moneda, mercancia, importe, TipoOperacion, FechaAlta, detalles, TipoTransporte, FechaSalida, FechaLlegada, folio, porigen, eorigen, corigen, pdestino, edestino, cdestino, Coberturas, poliza, cuota, prima, gastosexp, iva, total) VALUES ('".$idCliente."','".$idCliente."', '".$cliente."', '".$rfc."', '".$moneda."', '".$mercancia."', '".$importe."', '".$tipoOperacion."', '".$fechaAlta."', '".$detalles."', '".$tipoTransporte."', '".$fechaSalida."', '".$fechaLlegada."', '".$folio."','".$porigen."','".$eorigen."', '".$corigen."', '".$pdestino."', '".$edestino."', '".$cdestino."', '".$coberturas."', '".$poliza."', '".$cuota."', '".$prima."', '".$gastosexp."', '".$iva."', '".$total."')"); Donde en VALUEStienes dos veces $idCliente VALUES ('".$idCliente."','".$idCliente."', haciendo el primero a tu idViaje y el segundo a idCliente (el segundo esta bien). Si en tu base de datos ya tienes idViaje como AUTO_INCREMENT deberias poner como valor a idViaje DEFAULT Tu query quedaría así: query("INSERT INTO merca (idViaje, idCliente, Cliente, rfc, moneda, mercancia, importe, TipoOperacion, FechaAlta, detalles, TipoTransporte, FechaSalida, FechaLlegada, folio, porigen, eorigen, corigen, pdestino, edestino, cdestino, Coberturas, poliza, cuota, prima, gastosexp, iva, total) VALUES (DEFAULT,'".$idCliente."', '".$cliente."', '".$rfc."', '".$moneda."', '".$mercancia."', '".$importe."', '".$tipoOperacion."', '".$fechaAlta."', '".$detalles."', '".$tipoTransporte."', '".$fechaSalida."', '".$fechaLlegada."', '".$folio."','".$porigen."','".$eorigen."', '".$corigen."', '".$pdestino."', '".$edestino."', '".$cdestino."', '".$coberturas."', '".$poliza."', '".$cuota."', '".$prima."', '".$gastosexp."', '".$iva."', '".$total."')");
{ "pile_set_name": "StackExchange" }
Q: Writing a character N times using the printf command I found the following command to repeat a character in Linux: printf 'H%.0s' {1..5000} > H.txt I want, for example, H to repeat 5000 times. What does %.0s mean here? A: That command depends on the shell generating 5000 arguments, and passing them to printf which then ignores them. While it may seem pretty quick - and is relative to some things - the shell must still generate all of those strings as args (and delimit them) and so on. Besides the fact that the generated Hs can't be printed until the shell first iterates to 5000, that command also costs in memory all that it takes to store and delimit the numeric string arguments to printf plus the Hs. Just as simply you can do: printf %05000s|tr \ H ...which generates a string of 5000 spaces - which, at least, are usually only a single byte per and cost nothing to delimit because they are not delimited. A few tests indicate that even for as few as 5000 bytes the cost of the fork and the pipe required for tr is worth it even in this case, and it almost always is when the numbers get higher. I ran... time bash -c 'printf H%.0s {1..5000}' >/dev/null ...and... time bash -c 'printf %05000s|tr \ H' >/dev/null Each about 5 times a piece (nothing scientific here - only anecdotal) and the brace expansion version averaged a little over .02 seconds in total processing time, but the tr version came in at around .012 seconds total on average - and the tr version beat it every time. I can't say I'm surprised - {brace expansion} is a useful interactive shell shorthand feature, but is usually a rather wasteful thing to do where any kind of scripting is concerned. The common form: for i in {[num]..[num]}; do ... ...when you think about it, is really two for loops - the first is internal and implied in that the shell must loop in some way to generate those iterators before saving them all and iterating them again for your for loop. Such things are usually better done like: iterator=$start until [ "$((iterator+=interval))" -gt "$end" ]; do ... ...because you store only a very few values and overwrite them as you go as well as doing the iteration while you generate the iterables. Anyway, like the space padding mentioned before, you can also use printf to zeropad an arbitrary number of digits, of course, like: printf %05000d I do both without arguments because for every argument specified in printf's format string when an argument is not found the null string is used - which is interpreted as a zero for a digit argument or an empty string for a string. This is the other (and - in my opinion - more efficient) side of the coin when compared with the command in the question - while it is possible to get nothing from something as you do when you printf %.0 length strings for each argument, so also is it possible to get something from nothing. Quicker still for large amounts of generated bytes you can use dd like: printf \\0| dd bs=64k conv=sync ...and w/ regular files dd's seek=[num] argument can be used to greater advantage. You can get 64k newlines rather than nulls if you add ,unblock cbs=1 to the above and from there could inject arbitrary strings per line with paste and /dev/null - but in that case, if it is available to you, you might as well use: yes 'output string forever' Here are some more dd examples anyway: dd bs=5000 seek=1 if=/dev/null of=./H.txt ...which creates (or truncates) a \0NUL filled file in the current directory named H.txt of size 5000 bytes. dd seeks straight to the offset and NUL-fills all behind it. <&1 dd bs=5000 conv=sync,noerror count=1 | tr \\0 H >./H.txt ...which creates a file of same name and size but filled w/ H chars. It takes advantage of dd's spec'd behavior of writing out at least one full null-block in case of a read error when noerror and sync conversions are specified (and - without count= - would likely go on longer than you could want), and intentionally redirects a writeonly file descriptor at dd's stdin. A: The %.0s means to convert the argument as a string, with a precision of zero. According to man 3 printf, the precision value in such a case gives [ ... ] the maximum number of characters to be printed from a string for s and S conversions. hence when the precision is zero, the string argument is not printed at all. However the H (which is part of the format specifier) gets printed as many times as there are arguments, since according to the printf section of man bash The format is reused as necessary to consume all of the argu‐ ments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. A: In this case, %.0s always prints one instance of character(s) preceding it, H in this case. When you use {1..5000}, the shell expands it and it becomes: printf 'H%.0s' 1 2 3 4 ... 5000 > H.txt i.e., the printf command now has 5000 arguments, and for each argument, you will get one H. These don't have to be sequential or numeric: printf 'H%.0s' a bc fg 12 34 prints HHHHH -- i.e., the number of arguments, 5 in this case. Note, the ellipses in the 1st example above aren't inserted literally, they're there to indicate a sequence or range.
{ "pile_set_name": "StackExchange" }
Q: Switching local DNS servers disrupts printer I have two DNS servers in my office, Gob and Tobias. They are both running Ubuntu and BIND. Their BIND config files are identical. We've been using Gob for the last month or so. When we switched to Tobias for the first time today, everything kept working fine except we were no longer able to print. Switching back to Gob fixed the problem. Any idea as to why changing DNS servers, which doesn't seem to me to have all that much to do with printing, could make it so people can't print anymore? Edit: After some more testing, it's unclear whether only Gob works, only Tobias works, it works sometimes under either, or if the printing problem is even related to the DNS server switch at all. Pretty cool. A: The problem has gone away by itself, meaning all these answers are probably irrelevant. Sorry about that. Since Stack Overflow's interface forces me to keep my "accept rate" up or else people will whine about it, I'm putting this "answer" here so I can select it in a couple days.
{ "pile_set_name": "StackExchange" }
Q: Where to find definition of CeCreateDatabaseWithProps According to msdn it should be in windbase.h but it is not available instead it is in windbase_edb.h but cordll.lib is linked with windabase.h only. So, i want to know is there any method by which CeCreateDatabaseWithProps can be linked with a appropraite library? Thanks in advance. A: First, coredll.lib isn't linked with any header. CeCreateDatabaseWithProps is defined in windbase_edb.h in the SDK, so you can include the declaration from there. If you look at coredll.lib with dumpbin, you'll see that the linker definition is in there (at ordinal 1897). If your linker isn't finding it first make sure you're targeting the right SDK (it's WinMo 6 only). If it still refuses to link, then manually declare it as an extern at the top of a code page.
{ "pile_set_name": "StackExchange" }
Q: Lack of parabolicity of PDE due to invariancy under diffeomorphisms? Let a nonlinear differential equation is invariant under all diffeomorphisms, then we get lack of parabolicity? A: I'll (try to) answer the question specifically in the case of Ricci flow. View the Ricci flow on a closed manifold $M$ as an initial value problem on the positive cone of positive definite symmetric two-tensors, where given an initial metric $g(0),$ we wish to find a path of metrics $g(t)$ solving, \begin{align} \frac{\partial{g(t)}}{\partial{t}}=-2\text{Ric}_{g(t)}(g(t)). \end{align} Suppose we have a solution $g(t)$ and let $f:M\rightarrow M$ be any diffeomorphism. Then by the naturality of these tensors $f^{*}g$ is a solution as well. If the Ricci flow was a parabolic equation, then (part of) elliptic regularity (using compactness of M) would guarantee that the solution space is finite dimensional. But, as the diffeomorphism group is infinite dimensional, we have exhibited an infinite dimensional space of solutions, hence the equation is not parabolic. More directly, calculating the principal symbol of the linearization of the second order differential operator, \begin{align} \Gamma(S_{>0}^{2}(T^*M))&\rightarrow \Gamma(S^{2}(T^*M))\\ g &\mapsto Ric(g), \end{align} one can explicitly cook up cotangent directions where the principal symbol is non-invertible, also showing that the equation is not parabolic. Someone more well versed in PDE may correct me if I've said something wrong, but this is the gist of the argument. The "DeTurck trick" in these cases is to find a way to "break" this diffeomorphism invariance by changing the metric by a carefully chosen diffeomorphism (which results in an elliptic equation) and then showing that one can back-solve to get an honest solution of the Ricci flow. You can find calculations of the principal symbol and a discussion of these ideas in this honors thesis https://math.stanford.edu/theses/Stetler%20Honors%20Thesis.pdf and follow the references therein for more details.
{ "pile_set_name": "StackExchange" }
Q: Wrong Value returned for If Condition PLSQL In the following PLSQL function where I want to return the "Customer" value if no "Notify Party" exists. The result always returns the Value for the condition "CUSTOMER even thou there exists a "Notify Party". Why is that? I have used this same function but with involved_party_qual_gid in ('CONSIGNEE', 'CUSTOMER') and it worked fine producing the required results. function getNotifyPartyOrCustomer(orderID varchar2) return varchar2 is NameResult varchar2(100); CURSOR c_involved_party is select involved_party_contact_gid, involved_party_qual_gid from order_release_inv_party where involved_party_qual_gid in ('NOTIFY PARTY', 'CUSTOMER') and order_release_gid = orderID; begin for i in c_involved_party loop if i.involved_party_qual_gid = 'NOTIFY PARTY' then NameResult := i.involved_party_contact_gid; return(NameResult); elsif i.involved_party_qual_gid = 'CUSTOMER' then NameResult := i.involved_party_contact_gid; return(NameResult); end if; end loop; end; I have written alternative two functions that produce the same results: 1- Function 1 function getNotifyPartyOrCustomer(orderID varchar2) return varchar2 is NameResult varchar2(100); begin select coalesce((select involved_party_contact_gid from order_release_inv_party where involved_party_qual_gid = 'NOTIFY PARTY' and order_release_gid = orderID), (select involved_party_contact_gid from order_release_inv_party where involved_party_qual_gid = 'CUSTOMER' and order_release_gid = orderID), 'NO DATA' ) AS NAME INTO NameResult from DUAL; return NameResult; end; 2- Function 2 function getNotifyPartyOrCustomer(orderID varchar2) return varchar2 is NameResult varchar2(100); begin select involved_party_contact_gid INTO NameResult from order_release_inv_party where involved_party_qual_gid in ('NOTIFY PARTY') and order_release_gid = orderID; return(NameResult); exception WHEN NO_DATA_FOUND THEN select involved_party_contact_gid into NameResult from order_release_inv_party where involved_party_qual_gid in ('CUSTOMER') and order_release_gid = orderID; return(NameResult); end; But I'm not happy with those two functions, since first,, performance wise, I don't see the point of having to retrieve from the same table twice when I can simply get the results in one retrieval and do my logic on it, and second because I need the if conditions for other logic. I just need to know why it does not work. Appreciate ALL the help. Thank you. A: The result of your first function will depend on the order that the query returns the rows in. Since you're not providing an order by clause, the database can return the rows in any order. If you want to prioritize "NOTIFY PARTY" over "CUSTOMER", you can add the following to the query: order by involved_party_qual_gid desc Your other function that is working acceptably is probably doing so coincidentally. It could change if something causes the database to return the rows in a different order (such as restoring from backup, reorganizing an index, or even just enough data in the table to change the plan). Follow-up Typically, when you're dealing with SQL, if you're iterating over a result set, then you're taking a poor approach. Database engines are really good at dealing with set-based problems, so it's typically best to let the engine deal with as much of the work as you can. In this case, it looks like you don't really care about the results of each row: really you just want the first row that contains "NOTIFY PARTY" and, if no such record exists, you want the first row that contains "CUSTOMER". Let's say your result set returns 500 rows. Why would you want to iterate over all 500, when you only care about the value of 1 row? If I were writing this function, I'd lose the iteration altogether: function getNotifyPartyOrCustomer(orderID varchar2) return varchar2 is NameResult varchar2(100); CURSOR c_involved_party is select involved_party_contact_gid from order_release_inv_party where involved_party_qual_gid in ('NOTIFY PARTY', 'CUSTOMER') and order_release_gid = orderID order by involved_party_qual_gid desc; v_contact_gid order_release_inv_party.involved_party_contact_gid%type; begin open c_involved_party; fetch c_involved_party into v_contact_gid; close c_involved_party; return v_contact_gid; end getNotifyPartyOrCustomer;
{ "pile_set_name": "StackExchange" }
Q: Allocate memory in GPU, flash/air This is more an "implementation" of technology kind of question. In old times, when I worked with C language, you could specify to use VGA memory or ram memory for allocation of bitmaps structures, then you could work with them a lot faster. Now we are in 2013, I create bitmap in AS3, and it is allocated in ram (I've seen no option to use the GPU and 100% of cases im sure it is using the RAM, because it increases exactly the expected bitmap size. ¿Is there any option to use GPU memory? Thanks A: Check out the API docs for flash.display3D.Texture - there are 3 methods: uploadCompressedTextureFromByteArray(data:ByteArray, byteArrayOffset:uint, async:Boolean = false):void Uploads a compressed texture in Adobe Texture Format (ATF) from a ByteArray object. uploadFromBitmapData(source:BitmapData, miplevel:uint = 0):void Uploads a texture from a BitmapData object. uploadFromByteArray(data:ByteArray, byteArrayOffset:uint, miplevel:uint = 0):void Uploads a texture from a ByteArray. So you can't allocate the memory directly in the GPU. You must upload data from a ByteArray or BitmapData, which first exists in RAM. However, to minimize CPU RAM usage, you could potentially reuse a single ByteArray or BitmapData in RAM, change its contents, and upload it many times, or release it after loading. But you can't access the contents of GPU memory directly, as far as I know. As far as "read access", the only way to get data back from the GPU memory (again, a slow workaround) is to draw the Context3D back into a BitmapData via Context3D.drawToBitmapData... basically like a screen grab. The Starling Framework has an example of this functionality via Stage.drawToBitmapData. Basically, the Stage3D APIs weren't setup so you can easily access the GPU memory.
{ "pile_set_name": "StackExchange" }
Q: Days left - subscription expire? How can i get the number of days back when the subscription exipires? I have "vipudlob" in my database. and it's timestamp ex. 2 month forward.? <?php $expire = strtotime("+2 months", time()); $daysback = $expire-time(); echo $daysback%3600; ?> A: You can try $datetime1 = new DateTime(); $datetime2 = new DateTime("+2 months"); $interval = $datetime1->diff($datetime2); echo $interval->format('%R%a days'); Output +61 days
{ "pile_set_name": "StackExchange" }
Q: How to get the Name instead of Id's in SOQL I am using below query to get the records.But in the output I am getting Account Id and Conatct id. How can i get the Account Name , Contact Name instead of Id's? currentRecord = [SELECT Id,Account__c,Contact__c,Country__c,Notes__c,Business__c FROM Sample_Literature_Request__c WHERE Id = :currentRecord.Id]; A: Hi In order to get account and contact name you have to specify that particular field as well in query. For eg in your query you have to add Account__r.name to get account name and Contact__r.name to get contact name. so finally your SOQL query will look like currentRecord = [SELECT Id,Account__c,Account__r.name, Contact__c,Contact__r.name, Country__c,Notes__c,Business__c FROM Sample_Literature_Request__c WHERE Id = :currentRecord.Id]; For more reference please check out salesforce docs.
{ "pile_set_name": "StackExchange" }
Q: Create object from object literal string Is there an easy way to parse an object literal as a string into a new object? I'm looking to turn a string like the following: '{ name: "A", list: [] }' Into an object like: { name: 'A', list: [] } Note: I'm not looking for JSON.parse() as it accepts json strings and not object literal strings. I was hoping that eval would work but unfortunately it does not. A: eval does indeed work, with one tweak: the problem is that the standalone line { name: 'A', list: [] } gets parsed as the interpreter as the beginning of a block, rather than as the start of an object literal. So, just like arrow functions which implicitly return objects need to have parentheses surrounding the objects: arr.map(item => ({ item })) you need to put parentheses around the input string, so that the content inside (that is, the object, which starts with {) is parsed properly as an expression: const input = '{ name: "A", list: [] }'; const obj = eval('(' + input + ')'); console.log(obj); Of course, as with all cases when eval is involved, you should be very sure that the input is trustworthy first.
{ "pile_set_name": "StackExchange" }
Q: Calculating the $100th$ term of a series I came across a series $1,5,13,25,41,61.......$ I have to calculate the $100^{th}$ term of this series. How do I do it? Is there any formula to calculate the $n^{th}$ term of a series? A: Looks to me as though the forward difference is linear so that your equation can be given by a quadratic. $$4,8,12,..$$ It seems as though, $$f(x+1)-f(x)=4x+4$$ Where $f(0)=1$ (and $f(1)=5$). So by summing both sides of this equation from $x=0$ to $n-1$ and noticing that the sum in the LHS telescopes we have, $$f(n)-f(0)=\sum_{x=0}^{n-1} (4x+4)$$ $$f(n)=f(0)+\sum_{x=0}^{n-1} (4x+4)$$ $$f(n)=1+4\frac{(n-1)(n)}{2}+4n$$ Now if instead you want the sequence to start with $f(1)$ instead of $f(0)$, shift current $f$ to the right $1$. $$f(n)=1+2(n-1)((n-1)-1)+4(n-1)$$ $$f(n)=2n^2-2n+1$$ So, $$f(100)=2(100^2)-2(100)+1$$ $$=19801$$
{ "pile_set_name": "StackExchange" }
Q: How to Delete an entry from MapFile in Hadoop Is there any solution to delete an entry from MapFile in Hadoop. I could able to read and write entries to a MapFile, but i am totally unaware of deleting or updating an entry from it. Is there any good solution for the same ? Any help is appreciated. Thanks in Advance. A: hdfs is basically supports data warehousing facilities. You can not modify existing content of any hdfs file, at most you can append new content at bottom of fine. You can refer similar question
{ "pile_set_name": "StackExchange" }
Q: Find the integral $\int \frac{1}{dx}$ I was given a task and it seems this is not a joke. I am shocked and do not even know where to start ... $$\int \frac{1}{dx}=???$$ A: In calculus context, that expression $$\color{red}{\int \frac{1}{dx}}$$ in completely meaningless indeed the symbol $dx$ we use in the integrals is just a symbol to indicate the variable we are considering for integration. We can't manage it as a number.
{ "pile_set_name": "StackExchange" }
Q: Windows 2008 R2 IIS7 windows authentication not working I have a dev and prod Windows 2008 R2 servers with IIS7 and siteminder, which as far as I can tell are setup the same. Issue being the production websites work but the development ones do not. Issue being that when I navigate to any dev website, it says "the page cannot be displayed because an internal server error has occured." I do not get a challenge in dev (which I believe is the cause of the issue), but I do in prod. This goes for classic ASP pages or ASP.NET pages. Some findings :- - IIS has Windows authentication enabled and all others disabled - Windows Authentication Provider is Negotiate (tried Negotiate:Kerberos, same result) - WindowsAuthentication and WindowsAuthenticationModule (Native) are both present in Modules - WindowsAuthentication is installed under Server Manager -> IIS -> Roles - Upon receipt of the above error message, IIS logs shows the access with error 401 2 5 All the solutions I found online either do not have the right setup as I do above, or suggests I disable Windows authentication and enable Anonymous Authentication. If I do so, all works fine but the only issue being my websites require Windows authentication to identify the user. I'm at my wit's end and am just short of reinstalling something in hope it works. Any possibilities or log files that I have overlooked? A: After screwing around a bit I finally solved my problem ... hope this helps someone. I realized in fact ASP pages were working but ASP.NET pages were not working When I had turned on Anonymous Authentication, the ASP.NET pages were now giving 500 0 or 500 19 errors in IIS logs, instead of 401 2 5 with Windows Authentication I tried to launch a ASP.NET page from within the localhost and got then 500 error with a more detailed error saying I should use relative path in httpErrors under web.config (??) At this point I realized I had earlier changed the 403 error to a custom file at the default website level, then changed it back. Despite changing it back to it's previous value, What this ended up doing was adding a "remove" then an "add" tag, both for 403.htm, under httpErrors in the wwwroot/web.config. After I deleted the entire httpErrors segment, my websites started working again. Reverting back to Windows Authentication at this point also worked. So some take aways is to test websites locally first and keep in mind the existing of the wwwroot/web.config giving near untraceable errors ...
{ "pile_set_name": "StackExchange" }
Q: Is it appropriate for answer-ers to embed affiliate/referral codes into answers? Are there any guidelines or direction as to the appropriateness for folks to embed referral codes, affiliate sale codes, or similar things into links given in answers? What prompted this question was that I noted in this question about photo sales sites, Pearsonartphoto responded with a list of services and each of the links includes a referral or affiliate code. Presumably he would receive some sort of credit or commission for folks who click through to the site and register. I can see two viewpoints: one, being that as long as it's a quality answer it'll get voted appropriately and that there's no harm in rewarding the one who provided the answer. On the other hand, I could see folks rushing in to throw affiliate code answers when they might not be the best response. A: We don't allow linking to affiliate accounts any more than we allow people to post overtly commercial links to their own stuff. In your own profile, you are free to do that of course. But please refrain (and flag/remove) affiliate links in posts. Ref: Affiliate links (Amazon and others)
{ "pile_set_name": "StackExchange" }
Q: The existence of Gaussian quadrature weights In the Gaussian Quadrature, $x_1,\dots x_n$ are the roots of $p_n$, where $p_n$ is a Legendre polynomial, as usual. With this, why do there exist unique $A_1,\dots A_n$ such that $$\displaystyle\int_{-1}^1f(x)\,dx=\sum_{i=1}^nA_if(x_i)$$ is exact for $f\in\mathbb{P}_{2n-1}$? A: For any choice of distinct evaluation points $x_1,\dots,x_n$, there exist unique coefficients $A_i$ such that the quadrature rule is exact for polynomials of degree $\le n-1$. This follows by considering the linear system $$\sum_i A_i x_i^d = \int_{-1}^1 x^d\,dx,\qquad d=0,1,\dots,n-1$$ which can be solved for $A$ uniquely because the matrix is the Vandermonde matrix, hence nondegenerate. If $x_i$ are chosen to be the roots of Legendre polynomial, the rule can handle any polynomial $f$ of degree $\le 2n-1$. Indeed, using the long division of polynomials we obtain $f = q p_n +r$ with $q$ and $r$ having degree $\le n-1$. Now, $$ \int_{-1}^1 f = \int_{-1}^1 (q p_n +r) = \int_{-1}^1 r = \sum_i A_i r(x_i) = \sum_i A_i f(x_i) $$ because the term $qp_n$ contributes exactly $0$ to the integral (by orthogonality of $p_n$ to lower degree polynomials) and to the sum (because that's how we chose $x_i$).
{ "pile_set_name": "StackExchange" }
Q: Compare two nested lists and keep the union of elements The title may be misleading. I will try to explain as clear as possible. I have two set of lists : a = [ [(1.5, 13), (1.5, 16)], #first list [(5.4, 100.5), (5.3, 100.5)] #second list ] b = [ [(1, 2), (1.5, 3)], #first list [(5.4, 100.5), (5.3, 100.5)] #second list ] I would like to compare first list of a with first list of b and so on. Remove duplicates if I found any. The final outcome will look like this : c = [ [(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], #first list [(5.4, 100.5), (5.3, 100.5) ] #second list ] As you can see, a and b will eventually append forming c. However, duplicates will not be appended as shown in second list of c. Position is not mutable. How can I achieve this efficiently? A: Use zip to zip the two lists together, and set to remove duplicates from the concatenated pairs: [list(set(x + y)) for x, y in zip(a, b)] # [[(1.5, 16), (1, 2), (1.5, 13), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]] If you want to maintain order(sets are unordered), use a dict and get the keys with dict.fromkeys(assuming Python 3.6+ for ordered dictionaries): [list(dict.fromkeys(x + y)) for x, y in zip(a, b)] # [[(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]] For lower versions of python(dictionaries are unordered), you will need to use a collections.OrderedDict: from collections import OrderedDict [list(OrderedDict.fromkeys(x + y)) for x, y in zip(a, b)] # [[(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]] If you want the tuples to be sorted by the first element, use sorted: [sorted(set(x + y)) for x, y in zip(a, b)] # [[(1, 2), (1.5, 3), (1.5, 13), (1.5, 16)], [(5.3, 100.5), (5.4, 100.5)]]
{ "pile_set_name": "StackExchange" }
Q: Easy way to identify page requests in Sitecore I'd like to identify requests for page in Sitecore from code running toward the end of the httpRequestBegin pipeline. The reason is I want to redirect to an old browser page but I don't want the redirect to happen for media item requests or static content requests. Here's what I was thinking of doing: private static bool IsPageRequest(HttpRequestArgs args) { return Context.Item != null && Context.Item.Axes.IsDescendantOf(args.GetItem(Context.Site.RootPath)); } But it looks suboptimal to me. Is there a more performant way to check this? A: You could do: private static bool IsPageRequest(HttpRequestArgs args) { return Context.Item != null && Context.Item.Paths.IsContentItem; } This seems to be a little more performant. Using Reflector, IsContentItem returns true when the item's path starts with /sitecore/content/. A: A suggestion not to annoy the hell outta your users: Why don't you show an overlay div with the upgrade notification and can cover all/some of the page that the user lands on. Add in a [X] to allow them to close and return to whatever they wanted to do? You could add a static binding to the layout.aspx page and add a Sitecore rule which checks for the presence of your cookie to decide whether to output the message div/content: Personalizing Statically Based Components with the Sitecore Rules Engine Sitecore Rules Engine: How to create a custom condition Sitecore Rules Engine and Conditional Rendering There is some further information on the Sitecore httpRequestBegin Pipeline - In Detail if you still want to proceed down this route. It's really going to depend on your exact requirments. Do you want to redirect without any checks, i.e. invalid item, no layout set etc? If so then after the relevant processor, or otherwise I would look to add your processor immediately after Sitecore.Pipelines.HttpRequest.IgnoreList or Sitecore.Pipelines.HttpRequest.FilterUrlExtensions (although this is deprecated and purely added for backwards compatibility) in <httpRequestBegin>. Your media items should have been handled already at this stage by <preprocessRequest>.
{ "pile_set_name": "StackExchange" }
Q: Get element position relative to screen. (Or alternative solution) I am aware this had been asked before, but no answer actually did the trick as far as I tested them. Basically what I need is to change some element styles as soon as it "hits" the top border of the screen while scrolling down. This element is a 'Back to Top' button that will be sitting in a section and start following the user when they scroll pass said section. I am not asking about CSS properties, I am asking about some JS property or method that allow me to know this. IE: $('#back').distanceFromTopOfTheScreen() // This value will decrease as I scroll down I know there are other soultions, but the client has asked for this behavior. Any idea? A: You can : distance = $('#eleId')[0].getBoundingClientRect().top; For more about getBoundingClientRect() look at the MDN Documentation Note: This value change when you're scrolling, it gives you the distance between the top border of the element and the top of the Page
{ "pile_set_name": "StackExchange" }
Q: Check and uncheck all the check boxes and perform action using drop down menu In my table i have a column for a checkbox, when a user ticks that it should select all other check boxes underneath and if i click it again then the function deselect all the check boxes. I have also added drop down menu so if a user ticks a first box and selects add option then it should invoke some ajax method. This is what i have done: var ajReq = new XMLHttpRequest(); $(document).ready(function () { Table();}); function Table(data) { var DisplayTable = '<table><tr><th>Name</th><th>Name2</th><th><input type="checkbox" id="SelectCheckbox"/></th></tr>'; var counts= 0; for (var getdata in data) { var row = '<tr class=\'row\'select=\'' + data[getdata ].ID+ '\'</tr>'; counts+= '<td>' + data[getdata].Name+ '</td>'; counts+= '<td>' + data[getdata].Name2+ '</td>' counts+= '<td><input type="checkbox" class="SomeAjaxMethod" methd-DoSomething= "' + data[getdata ].ID+'"></td>' counts++; DisplayTable += counts; } table += '</table></div>'; $('#DisplayTable').html(DisplayTable ); } <div id="DisplayTable"></div> $(function () { $("#SelectCheckbox").click(function () { $(".SomeAjaxMethod").attr('checked', this.checked); }); $(".SomeAjaxMethod").click(function () { if (this.checked == false) { $("#SelectCheckbox").attr('checked', false); } }); }); When i add a Breakpoint to #SelectCheckBox it gets executed when a page is load, it should be executing after i selected a checkbox. I am also using drop down menu to perform some action, how do i attach check box to drop down menu, for example after selecting all the staff i want to delete them, i have already wrote SQL delete statment i just want to know how to i link check box with my drop down menu. this is my drop down menu: <div class="dropdown"> <div class="btn-group"> <button type="button" id="id1" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Select... <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a class="Delete-staff">Attended Detention</a></li> <li><a class="Edit-Staff">Letter Sent</a></li> </ul> </div> </div> A: Add a CSS class to the column with the checkboxes. Then use jQuery to check/uncheck every checkbox at the same time. Your HTML should look like this: <table id="myTable"> <tr><th>Name</th><th>Name2</th><th><input type="checkbox" id="SelectCheckbox"/></th></tr> <tr> <td>Name1 from row 1</td> <td>Name2 from row 1</td> <td class="check"><input type="checkbox" class="SomeAjaxMethod" onclick="method_DoSomething('id-from-row-1')"></td> </tr> ... (more rows </table> And your JavaScript like this: function checkUncheckEverything() { var isChecked = $('#SelectCheckbox').is(':checked'); $('#myTable > tbody > tr > td.check > input').prop('checked', isChecked); } $('#SelectCheckbox').on('click', checkUncheckEverything);
{ "pile_set_name": "StackExchange" }
Q: jQuery prevent an image from being clicked on until other function is completed I have a function preload. I want to make it so that the image on my page does nothing when you click on it UNTIL the preloading has completed. page loads preloading begins - clicking on the main image does nothing preloading completes - clicking on the main image will now call the intended function How can this be realized? Thanks A: Use the .load() event handler $('#myImage').load(function() { // Handler for .load() called. });
{ "pile_set_name": "StackExchange" }
Q: What's the purpose of ReflectionFunctionAbstract::getClosureThis()? Along with the introduction of Closures in PHP 5.3, has been introduced a getClosureThis() method on ReflectionFunctionAbstract. Anyone has an idea what it is for? The doc does not say anything about it, Google has been useless so far, and my attempts on different ReflectionFunction/ReflectionMethod objects have all returned NULL. A: As it says: Returns this pointer bound to closure So if you have PHP 5.4: <?php class MyObj {} $foo = function() { }; $obj = new MyObj; $foo = $foo->bindTo($obj); // Inside the newly returned closure, $this == $obj $reflector = new ReflectionFunction($foo); assert($obj === $reflector->getClosureThis()); i.e., It returns the closure's $this pointer.
{ "pile_set_name": "StackExchange" }
Q: Where should I use a type char ** in some case as the input parameter? There is some code piece right here below: main () { char in[8]; char out[255]; iconv_t cd; cd = iconv_open("gb18030", "utf-8"); ... char *p_in = in; char *p_out = out; size_t inlen = strlen(in); size_t outlen = sizeof(out); if (iconv(cd, &p_in, &inlen, &p_out, &outlen) < 0) { ... return -1 } ... return 0; } I can't totally understand the 2nd and 3rd parameters of the call to iconv. Why should that be ** pointer not the * pointer as the input? Can anyone explain the cases in C when the ** pointer should be used? A: Pointer to pointer is used where the passed pointer is need to be modified in the called function and that modification need to be seen in the caller function. This is required because in C arguments are passed by value. So, when an argument is passed to a function then it simply copied to the function's parameter and created a local copy having block scope. Any change to that variable will not be seen in the argument that has been passed. void foo(in x){ x = 10; } int main(void){ int x = 5; foo(x) printf("%d\n", x); // x will be 5 } Same happens with pointers void bar(char *p){ p = "foobar"; } int main(void){ char *p = NULL; bar(p); if(p) printf("p is pointing to %s\n", p); else printf("p is NULL\n"); // This will } Using a pointer to pointer will do the desired job (pointing p to the string "foobar" void bar(char **p){ *p = "foobar"; } int main(void){ char *p = NULL; bar(&p); if(p) printf("p is pointing to %s\n", p); else printf("p is NULL\n"); // This will } Another use is when an array of string is need to passed to a function. Like int main(int argc, char **argv) or void print_fruits(char **fruits, size_t len){ for(int i = 0; i < len; i++) printf("%s\n", fruits[i]); } int main(void){ char *fruits[5] = {"Apple", "Banana", "Cherry", "Kiwi", "Orange"}; print_fruits(fruits, sizeof(fruits)/sizeof(fruits[0])); } Note that in function call print_fruits, fruits in the argument list will decay to pointer to its first element and the expression fruits will become of type char ** after the conversion.
{ "pile_set_name": "StackExchange" }
Q: Easy Drag Drop implementation MVVM I am new to MVVM and I am currently trying to add the drag/drop feature to my application. The thing is I already developed the interface in the code-behind but I am trying now to re-write the code into MVVM as I am only at the beginning of the project. Here is the context: the user will be able to add boxes (ToggleButton but it may change) to a grid, a bit like a chessboard. Below is the View Model I am working on: <Page.Resources> <Style TargetType="{x:Type local:AirportEditionPage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Page}"> <!-- The page content--> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="{Binding ToolKitWidth, FallbackValue=50}" /> <ColumnDefinition Width="*"/> <ColumnDefinition Width="{Binding RightPanelWidth, FallbackValue=400}"/> </Grid.ColumnDefinitions> <!-- The airport grid where Steps and Links are displayed --> <ScrollViewer Grid.ColumnSpan="4" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> <Viewbox Height="{Binding AirportGridHeight}" Width="{Binding AirportGridWidth}" RenderOptions.BitmapScalingMode="HighQuality"> <ItemsControl x:Name="ChessBoard" ItemsSource="{Binding Items}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas Width="{Binding CardQuantityRow}" Height="{Binding CardQuantityColumn}" Background="{StaticResource AirportGridBackground}"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid Width="1" Height="1"> <ToggleButton Style="{StaticResource StepCardContentStyle}"/> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Canvas.Left" Value="{Binding Pos.X}"/> <Setter Property="Canvas.Top" Value="{Binding Pos.Y}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> </Viewbox> </ScrollViewer> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Page.Resources> Items are basically from a class (child of INotifiedPropertyChanged) with a name, an icon and a position (Point). Now, I am trying to make the user able to drag and drop the box (ToggleButton) within the grid wherever he/she wants. However, I am totally lost with Commands, AttachedProperties etc. I spent all the whole day on tutorials and tried drag/drop solutions but with my poor knowledge, I don't know how to apply all of this into my code. On my code-behinded version of the code, it was easy. When the button is left-clicked, I say to a variable of the grid "hey, I am being dragged and dropped". While the user is moving, I changed the Item coordinates and when the user released the left button (left button up), the dragdrop_object variable comes null again. In the frame of the MVVM, I am totally lost. Could you give me some tracks to help me trough ? I intended to give up with MVVM a lot of time, but I know that it is better to keep up even if every little feature takes litteraly hours for me to implement (it should decrease with time...). Do not hesitate if you need further details to answer to my question. A: I found the solution here : Move items in a canvas using MVVM and here : Combining ItemsControl with draggable items - Element.parent always null To be precise, here is the code I added : public class DragBehavior { public readonly TranslateTransform Transform = new TranslateTransform(); private static DragBehavior _instance = new DragBehavior(); public static DragBehavior Instance { get { return _instance; } set { _instance = value; } } public static bool GetDrag(DependencyObject obj) { return (bool)obj.GetValue(IsDragProperty); } public static void SetDrag(DependencyObject obj, bool value) { obj.SetValue(IsDragProperty, value); } public static readonly DependencyProperty IsDragProperty = DependencyProperty.RegisterAttached("Drag", typeof(bool), typeof(DragBehavior), new PropertyMetadata(false, OnDragChanged)); private static void OnDragChanged(object sender, DependencyPropertyChangedEventArgs e) { // ignoring error checking var element = (UIElement)sender; var isDrag = (bool)(e.NewValue); Instance = new DragBehavior(); ((UIElement)sender).RenderTransform = Instance.Transform; if (isDrag) { element.MouseLeftButtonDown += Instance.ElementOnMouseLeftButtonDown; element.MouseLeftButtonUp += Instance.ElementOnMouseLeftButtonUp; element.MouseMove += Instance.ElementOnMouseMove; } else { element.MouseLeftButtonDown -= Instance.ElementOnMouseLeftButtonDown; element.MouseLeftButtonUp -= Instance.ElementOnMouseLeftButtonUp; element.MouseMove -= Instance.ElementOnMouseMove; } } private void ElementOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) { ((UIElement)sender).CaptureMouse(); } private void ElementOnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs) { ((UIElement)sender).ReleaseMouseCapture(); } private void ElementOnMouseMove(object sender, MouseEventArgs mouseEventArgs) { FrameworkElement element = sender as FrameworkElement; Canvas parent = element.FindAncestor<Canvas>(); var mousePos = mouseEventArgs.GetPosition(parent); if (!((UIElement)sender).IsMouseCaptured) return; if (mousePos.X < parent.Width && mousePos.Y < parent.Height && mousePos.X >= 0 && mousePos.Y >=0) ((sender as FrameworkElement).DataContext as Step).Pos = new System.Drawing.Point(Convert.ToInt32(Math.Floor(mousePos.X)), Convert.ToInt32((Math.Floor(mousePos.Y)))); } } And my DataTemplate is now: <DataTemplate> <ContentControl Height="1" Width="1" local:DragBehavior.Drag="True" Style="{StaticResource StepCardContentControl}"/> </DataTemplate> I added the FindAncestor static class in a dedicated file like this: public static class FindAncestorHelper { public static T FindAncestor<T>(this DependencyObject obj) where T : DependencyObject { DependencyObject tmp = VisualTreeHelper.GetParent(obj); while (tmp != null && !(tmp is T)) { tmp = VisualTreeHelper.GetParent(tmp); } return tmp as T; } } (My items are now ContentControls). As the items' positions within the canvas are directly managed with their Pos variable (Canvas.SetLeft and Canvas.SetTop based on Pos (Pos.X and Pos.Y) with Binding), I just update it according to the MousePosition within the Canvas. Also, as suggested in a commentary, I will see if there is something better than the ScrollViewer and Viewbox I'm using.
{ "pile_set_name": "StackExchange" }
Q: VB.NET: how to prevent user input in a ComboBox How do you prevent user input in a ComboBox so that only one of the items in the defined list can be selected by the user? A: Set the DropDownStyle property of the combobox to DropDownList. This will allow only items in the list to be selected and will not allow any free-form user input. A: Use KeyPressEventArgs, Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress e.Handled = True End Sub
{ "pile_set_name": "StackExchange" }
Q: Create a UIImage by rendering UIWebView on a background thread - iPhone Does someone know of a way, or has a creative idea as to how to obtain an UIImage that is rendered from a UIWebView? The catch is, that is must be on a background thread. I'll elaborate: I'm trying to obtain the image from multiple UIWebViews every second+-, and display it on screen (iPhone's of course). Because rendering a layer to a CGContext is a CPU consuming job, I wouldn't like to use the main thread, so not to hang the UI. My attempts so far were: I tried to use renderInContext on the webView's layer to the UIGraphicalContext, but the _WebTryThreadLock error crashed the webviews. I tried creating a CGBitmapContext, and render the webview's layer to it, but got the same result. I tried implementing a copy method (by adding a Category) to CALayer, that deep copied all of the public properties, and sublayers. Afterwards, I tried to renderInContext the layer I copied. I got a UIImage that was partially "correct" - meaning, not all of the layers were rendered, so for example, i would get only the website header (or footer, or body, or search bar, or just a some of the frames). The UIWebview's layer consists of all sort of subclassed CALayers, so this is probably why this approached didn't work. I tried setting the kCATransactionDisableActions in a CATransaction, but it didn't appear to change this behavior (neither of them). I'm pretty close to giving up. Is there a savior among you people? A: UIWebView hates, and I mean really hates, having anything done to it on a background thread. UIKit is not fully thread safe. Drawing to a graphics context is (this was added in iOS 4), but not creating UIViews on a secondary thread. Are you creating your UIWebViews off the main thread? Do you perhaps have some code to share? I would suspect your issues are being caused by the fact you're trying to perform operations to a UIWebView on a secondary thread. The drawing operation to render the view's contents as an image can happen off the main thread, but creating the view itself can't.
{ "pile_set_name": "StackExchange" }
Q: IE not displaying dropdown menu correctly I have a css menu which is working well apart from in IE 7>10 the list is not displaying correctly. The contacts and history heading should be under the other 3 headings and for some reason, the action and history headings are to the right. I have tried various combinations of float and clear, but nothing seems to work. If I adjust the margin value, it then cretaes a large blank area at the bottom, which is not correct. I have included screenshots from FF and that is correct. I would be grateful if someone could show me my error. thanks Screens: html code <ul id="menu"><li> <div class="dropdown_3columns"> <div class="col_3"> <h2> Client Control Panel </h2> </div> <div class="col_1"> <h3> Tickets </h3> <ul> <li> <a href="#">Inbox</a> </li> <li> <a href="#">Sent Tickets</a> </li> <li> <a href="#">Received Tickets</a> </li> <li> <a href="#">Compose Ticket</a> </li> </ul> </div> <div class="col_1"> <h3> Messages </h3> <ul> <li> <a href="#">Broadcast Message</a> </li> <li> <a href="#">Archived messages</a> </li> </ul> </div> <div class="col_1"> <h3> Actions </h3> <ul> <li> <a href="#">Actions</a> </li> <li> <a href="#">View actions</a> </li> </ul> </div> <div class="listSpacer"> --> **this is the area** <div class="col_1"> <h3> History </h3> <ul> <li> <a href="#">User Log</a> </li> <li> <a href="#">Actions Log</a> </li> </ul> </div> <div class="col_1"> <h3> Contacts </h3> <ul> <li> <a href="#">View Contacts</a> </li> <li> <a href="#">Edit Contacts</a> </li> </ul> </div> </div> </div> </li></ul> css code #menu { position:relative; list-style:none; width:96.9%; margin:20px auto 0px auto; height:43px; padding:0px 20px 0px 20px; color: black; /* Background color and gradients */ background: #e0e1e1; background: -moz-linear-gradient(top, #d6d6d6, #aeaeae); background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#d7d7d7), to(#013953)); /* Borders */ border: 1px solid #000000; } #menu li { float:left; display:block; text-align:center; position:relative; padding: 4px 10px 4px 10px; margin-right:30px; margin-top:7px; border:none; z-index:5; } #menu li:hover { border: 1px solid #777777; padding: 4px 9px 4px 9px; /* Background color and gradients */ background: #F4F4F4; background: -moz-linear-gradient(top, #F4F4F4, #EEEEEE); background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#F4F4F4), to(#EEEEEE)); /* Rounded corners */ -moz-border-radius: 5px 5px 0px 0px; -webkit-border-radius: 5px 5px 0px 0px; border-radius: 5px 5px 0px 0px; } #menu li a { font-family:Arial, Helvetica, sans-serif; font-size:12px; color: #000; display:block; outline:0; text-decoration:none; /* text-shadow: 1px 1px 1px #000; */ } #menu li:hover a { color:#161616; text-shadow: 1px 1px 1px #ffffff; } #menu li .drop { padding-right:21px; background:url("../img/drop.png") no-repeat right 8px; } #menu li:hover .drop { background:url("../img/drop.png") no.-repeat right 7px; } .dropdown_1column, .dropdown_2columns, .dropdown_3columns, .dropdown_4columns, .dropdown_5columns { margin:4px auto; float:left; position:absolute; left:-999em; /* Hides the drop down */ text-align:left; padding:10px 5px 10px 5px; border:1px solid #777777; border-top:none; /* Gradient background */ background:#F4F4F4; background: -moz-linear-gradient(top, #EEEEEE, #BBBBBB); background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#EEEEEE), to(#BBBBBB)); /* Rounded Corners */ -moz-border-radius: 0px 5px 5px 5px; -webkit-border-radius: 0px 5px 5px 5px; border-radius: 0px 5px 5px 5px; } .dropdown_1column {width: 140px;} .dropdown_2columns {width: 280px;} .dropdown_3columns {width: 420px;} .dropdown_4columns {width: 560px;} .dropdown_5columns {width: 700px;} #menu li:hover .dropdown_1column, #menu li:hover .dropdown_2columns, #menu li:hover .dropdown_3columns, #menu li:hover .dropdown_4columns, #menu li:hover .dropdown_5columns { left:-1px; top:auto; } .col_1, .col_2, .col_3, .col_4, .col_5 { display:inline; float: left; position: relative; margin-left: 5px; margin-right: 5px; } .col_1 {width:130px;} .col_2 {width:270px;} .col_3 {width:410px;} .col_4 {width:550px;} .col_5 {width:690px;} #menu .menu_right { float:right; margin-right:20px; } #menu li .align_right { /* Rounded Corners */ -moz-border-radius: 5px 0px 5px 5px; -webkit-border-radius: 5px 0px 5px 5px; border-radius: 5px 0px 5px 5px; } #menu li:hover .align_right { left:auto; right:-1px; top:auto; } #menu p, #menu h2, #menu h3, #menu ul li { font-family:Arial, Helvetica, sans-serif; line-height:21px; font-size:12px; text-align:left; text-shadow: 1px 1px 1px #FFFFFF; } #menu h2 { font-size:17px; font-weight:400; letter-spacing:-1px; margin:7px 0 14px 0; padding-bottom:14px; border-bottom:1px solid #666666; } #menu h3 { font-size:12px; margin:7px 0 14px 0; padding-bottom:7px; border-bottom:1px solid #888888; } #menu p { line-height:18px; margin:0 0 10px 0; } #menu li:hover div a { font-size:12px; color:#015b86; } #menu li:hover div a:hover { color:#ff6600; } .strong { font-weight:bold; } .italic { font-style:italic; } .imgshadow { /* Better style on light background */ background:#FFFFFF; padding:4px; border:1px solid #777777; margin-top:5px; -moz-box-shadow:0px 0px 5px #666666; -webkit-box-shadow:0px 0px 5px #666666; box-shadow:0px 0px 5px #666666; } .img_left { /* Image sticks to the left */ width:auto; float:left; margin:5px 15px 5px 5px; } .imgnews_left { /* Image news sticks to the left */ width:auto; float:left; margin:0px 15px 5px 5px; } #menu li .black_box { background-color:#333333; color: #eeeeee; text-shadow: 1px 1px 1px #000; padding:4px 6px 4px 6px; /* Rounded Corners */ -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; /* Shadow */ -webkit-box-shadow:inset 0 0 3px #000000; -moz-box-shadow:inset 0 0 3px #000000; box-shadow:inset 0 0 3px #000000; } #menu li ul { list-style:none; padding:0; margin:0 0 12px 0; } #menu li ul li { font-size:12px; line-height:24px; position:relative; text-shadow: 1px 1px 1px #ffffff; padding:0; margin:0; float:none; text-align:left; width:130px; } #menu li ul li:hover { background:none; border:none; padding:0; margin:0; } #menu li .greybox li { background:#ffffff; border:1px solid #bbbbbb; margin:0px 0px 4px 0px; padding:4px 6px 4px 6px; width:116px; /* Rounded Corners */ -moz-border-radius: 5px; -webkit-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px; } #menu li .greybox li:hover { background:#F4F4F4; border:1px solid #aaaaaa; padding:4px 6px 4px 6px; margin:0px 0px 4px 0px; } .date { font-size: 12px; color: grey; } #menu li:hover a[title] { margin-left: 40px; margin-top: 8px; font-size: 18px; font-family: Verdana, Geneva, sans-serif; /* border-bottom:1px solid #777777; */ } .newsSpace { margin-left: 45px; margin-right: 5px; margin-bottom: 10px; margin-top: 10px; font-size: 12px; font-family: Verdana, Geneva, sans-serif; /* border-bottom:1px solid #777777; */ } .newsPostedDate { float:right; margin-right: 10px; color: orange; font-size: 11px; } .welcomeName { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: orange; } .listSpacer{ margin-top:20px; } A: I replaced your listSpacer div with the following and it worked fine: <br style="clear:both" /> Here it is on jsFiddle: http://jsfiddle.net/r89wY/1/ Note that it's hard to find the right spot to hover. Did you remove the root menu text?
{ "pile_set_name": "StackExchange" }
Q: git log history simplification Let's say I have the following history D---E-------F / \ \ B---C---G---H---I---J / \ A-------K---------------L--M git log --ancestry-path D..M will give me E-------F \ \ G---H---I---J \ L--M However, I would like just the following E \ G---H---I---J \ L--M Or E-------F \ I---J \ L--M Essentially, I would like to traverse down only one path, not two. Is this possible? And if so, what is the command? Edit: I've tried using --first-parent, but this isn't exactly it. git log --first-parent G..M gives me F \ H---I---J \ L--M It includes F, because F is the first parent of I. Instead I'd like H---I---J \ L--M Any help would be appreciated Solution (that worked for me): As @VonC stated, there isn't a single one-liner that does this. So I ended up using a bash script. For each commit in 'git log --ancestry-path G..M' Determine if $commit's parent includes the commit we were previously on If yes, continue. do something interesting. If no, skip that commit. For example, git log --first-commit G..M is H - F - I - J - L - M However, F's parent is E, not H. So we omit F, giving me H - I - J - L - M Yay! A: I don't think this is directly possible (unless you know in advance the exact list to include/exclude, which negates the purpose of walking the DAG) Actually, the OP Ken Hirakawa managed to get the expected linear history by: git log --pretty=format:"%h%n" --ancestry-path --reverse $prev_commit..$end_commit And for each commit, making sure it is a direct child of the previous commit. Here is the script writtten by Ken Hirakawa. Here is my script to create the DAG mentioned in the History Simplification section of the git log man page, for --ancestry-path: You will find at the end the bash script I used to create a similar history (call it with the name of the root dir, and your username). I define: $ git config --global alias.lgg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative" I get: $ git lgg * d7c4459 - (HEAD, M, fromA) M <VonC> * 82b011d - (L) Merge commit 'J' into fromA <VonC> |\ | * 190265b - (J, master) J <VonC> | * ef8e325 - (I) Merge commit 'F' <VonC> | |\ | | * 4b6d976 - (F, fromB) F <VonC> | * | 45a5d4d - (H) H <VonC> | * | 834b239 - (G) Merge commit 'E' <VonC> | |\ \ | | |/ | | * f8e9272 - (E) E <VonC> | | * 96b5538 - (D) D <VonC> | * | 49eff7f - (C) C <VonC> | |/ | * 02c3ef4 - (B) B <VonC> * | c0d9e1e - (K) K <VonC> |/ * 6530d79 - (A) A <VonC> From there, I cannot exclude one of the parents of commit I. The ancestry-path does return: $ git lgg --ancestry-path D..M * d7c4459 - (HEAD, M, fromA) M <VonC> * 82b011d - (L) Merge commit 'J' into fromA <VonC> * 190265b - (J, master) J <VonC> * ef8e325 - (I) Merge commit 'F' <VonC> |\ | * 4b6d976 - (F, fromB) F <VonC> * | 45a5d4d - (H) H <VonC> * | 834b239 - (G) Merge commit 'E' <VonC> |/ * f8e9272 - (E) E <VonC> which is consistent with the log man page: A regular D..M computes the set of commits that are ancestors of M, but excludes the ones that are ancestors of D. This is useful to see what happened to the history leading to M since D, in the sense that "what does M have that did not exist in D". The result in this example would be all the commits, except A and B (and D itself, of course). When we want to find out what commits in M are contaminated with the bug introduced by D and need fixing, however, we might want to view only the subset of D..M that are actually descendants of D, i.e. excluding C and K. This is exactly what the --ancestry-path option does. #!/bin/bash function makeCommit() { local letter=$1 if [[ `git tag -l $letter` == "" ]] ; then echo $letter > $root/$letter git add . git commit -m "${letter}" git tag -m "${letter}" $letter else echo "commit $letter already there" fi } function makeMerge() { local letter=$1 local from=$2 if [[ `git tag -l $letter` == "" ]] ; then git merge $from git tag -m "${letter}" $letter else echo "merge $letter already done" fi } function makeBranch() { local branch=$1 local from=$2 if [[ "$(git branch|grep $1)" == "" ]] ; then git checkout -b $branch $from else echo "branch $branch already created" git checkout $branch fi } root=$1 user=$2 if [[ ! -e $root/.git ]] ; then git init $root fi export GIT_WORK_TREE="./$root" export GIT_DIR="./$root/.git" git config --local user.name $2 makeCommit "A" makeCommit "B" makeCommit "C" makeBranch "fromB" "B" makeCommit "D" makeCommit "E" makeCommit "F" git checkout master makeMerge "G" "E" makeCommit "H" makeMerge "I" "F" makeCommit "J" makeBranch "fromA" "A" makeCommit "K" makeMerge "L" "J" makeCommit "M"
{ "pile_set_name": "StackExchange" }
Q: Why can't I/ How can I move a project's source control location before it's checked-in? In TFS, I add a VS project (which adds the project into source control whether I want it to or not). I realise I've made a mistake with its location, so I want to move the source control folder to the correct location. However, the TFS option to 'move' is greyed-out until the project is checked-in. Is TFS forcing me to check it in, and if so, why? A: Because Move command is used for existing files/folders already checked into the TFS. you have 2 options: Backup your project, undo add, move your project into the correct location and add it again Check in your project into the wrong location and move it to the correct location after check-in
{ "pile_set_name": "StackExchange" }