text
stringlengths
64
89.7k
meta
dict
Q: webcam not working anymore I was using Skype, and suddenly the internal iSight camera stopped working. It's not the first time this has happened. I already fixed this problem with a reboot, but I would like to find a solution without a reboot. Is there a way to push the driver back, or do some more accurate diagnostic? I have MacOSX 10.6.7 on a macbook 13" unibody. A: I found out that the camera is taken over, somehow, by the google talk browser plugin. I solved by doing the following. From a terminal, I issued the following command ps uaxw |grep Firefox It will show a list of the processes under Firefox. One of them may be something like sbo 21173 0.0 0.1 414040 2492 ?? S 5May11 0:07.47 /Applications/Firefox.app/Contents/MacOS/plugin-container.app/Contents/ MacOS/plugin-container /Library/Internet Plug-Ins/googletalkbrowserplugin.plugin -omnijar /Applications/Firefox.app/Contents/MacOS/omni.jar 21168 gecko-crash-server-pipe.21168 org.mozilla.machname.855559451 plugin I wrapped the long line. I then proceeded to kill this process (the pid is the first number) kill 21173 and the iSight started working again.
{ "pile_set_name": "StackExchange" }
Q: Prove that if $A,B$ are closed then, $ \exists\;U,V$ open sets such that $U\cap V= \emptyset$ Prove that if $A,B$ are closed sets such that $A\cap B\neq \emptyset$, there exists $U,V$ open sets such that $A\subset U$, $B\subset V$, and $U\cap V= \emptyset$. I am thinking of going by contradiction, that is: $\forall\; U,V$ open sets such that $A\subset U$, $B\subset V$, and $U\cap V\neq \emptyset$. Let $ U,V$ open. Then, $\exists\;r_1,r_2$ such that $B(x,r_1)\subset U$ and $B(x,r_2)\subset V.$ From here, I don't know how to get a contradiction. Can anyone help me out? A: This is not true in general. Consider $\Bbb{R}$ with the usual topology, and set $A = [0,1]$ and $B = [1,2]$. First, we have $A\cap B = \{1\}\ne\emptyset$. Any two open subsets $U\subset A$ and $V\subset B$ cannot contain $1$ since they would have to contain a small neighborhood around $1$, which neither $A$ nor $B$ do. Thus $1\notin U$ and $1\notin V$. Therefore, $U\cap V \subset A\cap B=\{1\}$, so $U\cap V =\emptyset$. Edit: I just realized that your question asks for $U\cap V$ to be empty, and thus my counterexample is merely an example. Moreover, the question stipulates that $A\subset U$ and $B\subset V$, whereas I assumed the opposite inclusion. If you assume that $A\subset U$ and $B\subset V$, then $A\cap B \ne\emptyset$ always implies that $U\cap V\ne\emptyset$ as Tsemo Atistide pointed out in the comments. If you do in fact assume the opposite inclusion, where you are asking for open sets inside the closed sets, then $U\cap V = \emptyset$ can never hold for closed sets with empty interior, as they contain no open sets by definition. Are you sure the question is correct as written?
{ "pile_set_name": "StackExchange" }
Q: How can I bind a JQuery event to make it only fire once? I have a help popup that I want to close when somewhere else is clicked. Here's what I have: $('.help[data-info]').click(function(){ $('.info[a complicated selector]').toggle(400); $('*:not(.info[the complicated selector]).one('click','',function(){ .info[the complicated selector].hide(400); }); }) But one() isn't what I want before it fires for each element on the page. I only want it to fire once. A: It looks like you are attaching event handlers to every element in your dom except the help popup? Hmm... How about this: Create a single "mask" div that overlays the entire screen, but is transparent (opacity: 0.0). Attach the click event handler only to that mask div. Then open up the info div on top of the overlay div. Clicking anywhere on the page, other than the info div, the event will be captured by the mask div before it gets to anything under it. In your event handler, hide() the info div, and remove the mask div altogether. While testing/experimenting with this, start with a partially opaque mask, not fully transparent).
{ "pile_set_name": "StackExchange" }
Q: Find minimum cost of tickets Find minimum cost of tickets required to buy for traveling on known days of the month (1...30). Three types of tickets are available : 1-day ticket valid for 1 days and costs 2 units, 7-days ticket valid for 7 days and costs 7 units, 30-days ticket valid for 30 days and costs 25 units. For eg: I want to travel on [1,4,6,7,28,30] days of the month i.e. 1st, 4th, 6th ... day of the month. How to buy tickets so that the cost is minimum. I tried to use dynamic programming to solve this but the solution is not giving me the correct answer for all cases. Here is my solution in Java : public class TicketsCost { public static void main(String args[]){ int[] arr = {1,5,6,9,28,30}; System.out.println(findMinCost(arr)); } public static int findMinCost(int[] arr) { int[][] dp = new int[arr.length][3]; int[] tDays = {1,7,30}; int[] tCost = {2,7,25}; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < 3; j++) { if (j==0){ dp[i][j]= (i+1)*tCost[j]; } else{ int c = arr[i]-tDays[j]; int tempCost = tCost[j]; int k; if (c>=arr[0] && i>0){ for (k = i-1; k >= 0; k--) { if (arr[k]<=c){ c = arr[k]; } } tempCost += dp[c][j]; int tempCostX = dp[i-1][j] + tCost[0]; tempCost = Math.min(tempCost,tempCostX); } dp[i][j] = Math.min(tempCost,dp[i][j-1]); } } } return dp[arr.length-1][2]; } } The solution doesn't work for {1,7,8,9,10} input, it gives 10 but the correct answer should be 9. Also, for {1,7,8,9,10,15} it give 13 but the correct is 11. I have posted my solution not for other to debug it for me but just for reference. I was taken a bottom-up dynamic programming approach for this problem. Is this approach correct? A: Let MC(d) denote the minimum cost that will pay for all trips on days 1 through d. The desired answer is then MC(30). To calculate MC(d), observe the following: If there's no trip on day d, then MC(d) = MC(d − 1). As a special case, MC(d) = 0 for all d ≤ 0. Otherwise, the minimum cost involves one of the following: A 1-day pass on day d. In this case, MC(d) = MC(d − 1) + 2. A 7-day pass ending on or after day d. In this case, MC(d) = min(MC(d − 7), MC(d − 6), …, MC(d − 1)) + 7. And since MC is nondecreasing (adding a day never reduces the minimum cost), this can be simplified to MC(d) = MC(d − 7) + 7. (Hat-tip to Ravi for pointing this out.) A 30-day pass covering the whole period. In this case, MC(d) = 25. As you've realized, dynamic programming (bottom-up recursion) is well-suited to this. For ease of coding, I suggest we start by converting the list of days into a lookup table for "is this a trip day?": boolean[] isDayWithTrip = new boolean[31]; // note: initializes to false for (final int dayWithTrip : arr) { isDayWithTrip[dayWithTrip] = true; } We can then create an array to track the minimum costs, and populate it starting from index 0: int[] minCostUpThroughDay = new int[31]; minCostUpThroughDay[0] = 0; // technically redundant for (int d = 1; d <= 30; ++d) { if (! isDayWithTrip[d]) { minCostUpThroughDay[d] = minCostUpThroughDay[d-1]; continue; } int minCost; // Possibility #1: one-day pass on day d: minCost = minCostUpThroughDay[d-1] + 2; // Possibility #2: seven-day pass ending on or after day d: minCost = Math.min(minCost, minCostUpThroughDay[Math.max(0, d-7)] + 7); // Possibility #3: 30-day pass for the whole period: minCost = Math.min(minCost, 25); minCostUpThroughDay[d] = minCost; } And minCostUpThroughDay[30] is the result. You can see the above code in action at: https://ideone.com/1Xx1fd. A: Solved using the same approach of bottom-up dynamic programming. Here is the full solution : public class PublicTicketCost { public static void main(String args[]){ int[] arr = {1,7,8,9,10,15,16,17,18,21,25}; int[] tDays = {1,7,30}; int[] tCost = {2,7,25}; System.out.println(minCost(arr, tDays, tCost)); } public static int minCost(int[] arr, int[] tDays, int[] tCost) { int[][] dp = new int[arr.length][tDays.length]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < tDays.length; j++) { int prevDayIndex = findPrevDayIndex(arr,i,tDays,j); int prevCost = prevDayIndex>=0 ? dp[prevDayIndex][tDays.length-1] : 0; int currCost = prevCost + tCost[j]; if(j-1>=0){ currCost = Math.min(currCost, dp[i][j-1]); } dp[i][j] = currCost; } } //print(dp); return dp[arr.length-1][tDays.length-1]; } private static void print(int arr[][]){ for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } } private static int findPrevDayIndex(int[] arr, int i, int[] days, int j){ int validAfterDate = arr[i] - days[j]; if (validAfterDate<1){ return -1; } for (int k = i-1; k >= 0; k--) { if (arr[k]<=validAfterDate){ return k; } } return -1; } } http://ideone.com/sfgxGo
{ "pile_set_name": "StackExchange" }
Q: Removing unnecessary lines form tableview I have two cells in my tableview, each with a text field. Following these two cells are many addition lines even though there are no cells to follow. How do I remove these lines to create a cleaner look. Side Note: The reason I didn't use static cells created through the storyboard is because the situation requires to create the cells through code. A: And this is for Objective-C tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; Swift 3 tableView.tableFooterView = UIView(frame: .zero)
{ "pile_set_name": "StackExchange" }
Q: php system() shell_exec() hangs the browser Possible Duplicate: Asynchronous shell exec in PHP i need to run a java program in the background. process.php contains shell_exec("php php_cli.php") php_cli.php contains shell_exec("java -jar BiForce.jar settings.ini > log.txt"); I am calling process.php asynchronously using ajax When i click the link in the webpage that calls ajax function (for running process.php) the webage shows "loading". when i click other links at the same time it does not responds. The java program takes about 24 hours to finish executing, so user will not wait until the execution ends. The problem is that the browser keeps on loading and does not go to other pages when clicked the link. I also tried with system(), but the same problem .... Help will greatly be appreciated. A: Using shell_exec waits for the command to hang up, so that's what your script is doing. If your command doesn't have any wait time, then your script will not either. You can call another PHP script from your original, without waiting for it to hang up: $processId = shell_exec( "nohup " . // Runs a command, ignoring hangup signals. "nice " . // "Adjusted niceness" :) Read nice --help "/usr/bin/php -c " . // Path to your PHP executable. "/path/to/php.ini -f " . // Path to your PHP config. "/var/www/php_cli.php " . // Path to the script you want to execute. "action=generate > /process.log " . // Log file. "& echo $!" // Make sure it returns only the process id. ); It is then possible to detect whether or not the script is finished by using this command: exec('ps ' . $processId, $processState); // exec returns the result of the command - but we need to store the process state. // The third param is a referenced variable. // First key in $processState is that it's running. // Second key would be that it has exited. if (count($processState) < 2) { // Process has ended. } A: You could call the command in the page displayed, but appending an & at the end: shell_exec("java -jar BiForce.jar settings.ini > log.txt &"); This way the process is launched on the background. Also, there is no need (unless defined by your application) to create a process.php wich itself calls php via a shell exec. You could archive the same functionality via an include to the other file.
{ "pile_set_name": "StackExchange" }
Q: Oracle SQL: Extract Date & Time from Timestamp Timezone I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT. I'm trying to insert those values into another table but i'm getting a date format not recognized error. How do I fix this? Sample SQL statement INSERT INTO TABLE2 ( DATE_WITH_TIMEZONE, DATE_WITHOUT_TIMEZONE ) SELECT TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'), TO_DATE(TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'), 'YYYY-MM-DD HH:MI:SS AM') FROM TABLE_DATE Sample Data 2016-01-21 09:31:49 AM GMT 2016-02-22 06:37:32 PM GMT 2016-02-23 07:10:52 PM GMT 2016-03-15 08:54:40 PM GMT 2016-03-16 12:10:52 AM GMT If it helps, these are the datatypes of the two columns in TABLE2 DATE_WITH_TIMEZONE TIMESTAMP WITH TIME ZONE DATE_WITHOUT_TIMEZONE DATE A: I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT Assuming that your START_DATE column is of the DATE data type then your statement is incorrect; a DATE column has no format and it is stored internally as 7-bytes. It is only when it is passed to the user interface you are using to access the database that that UI will format the date (and not the database). SQL/Plus and SQL developer will format the date using the NLS_DATE_FORMAT session parameter (which is set per user session and can be changed) so relying on this format can lead to "interesting" bugs where the code you are using does not change but will start and stop working for different users depending on their session settings. You can just do: INSERT INTO TABLE2 ( DATE_WITH_TIMEZONE, DATE_WITHOUT_TIMEZONE ) SELECT FROM_TZ( CAST( START_DATE AS TIMESTAMP ), 'GMT' ), START_DATE FROM TABLE_DATE; If your START_DATE column is of a string datatype (why would you do this?) then you will need to convert it to the appropriate type: INSERT INTO TABLE2 ( DATE_WITH_TIMEZONE, DATE_WITHOUT_TIMEZONE ) SELECT TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ), CAST( TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ) AS DATE ) FROM TABLE_DATE;
{ "pile_set_name": "StackExchange" }
Q: Check if an array only contains one key/value $foo = array('one'); $foofoo = array('onekey' => 'onevalue'); How do you check if an array contains only one key? A: count() will tell you how many elements are in an array if (count($foo) === 1) { echo 'This array contains one value'; }
{ "pile_set_name": "StackExchange" }
Q: Notation for $y$-restriction? $f(x) \; \{a<x<b\}$ can be written $[f(x)]^b_a$. Is there an equivalent notation for $f(x) \; \{a<y<b\}$? Edited to add: for instance, A: As far as I know there isn't, but you could probably make it clear with $[f(x)]_{y \geq a}^{y \leq b}$
{ "pile_set_name": "StackExchange" }
Q: ChartJS disable gridlines outside chart area I'm trying to hide the gridlines drawn outside the chart area, so basically like the option below, but for outside the chart area gridLines: { drawOnChartArea: false, }, A: Presumably you are looking to disable the tick lines which can be achieved via the drawTicks property: new Chart(document.getElementById('canvas'), { type: 'bar', data: { labels: ['a', 'b', 'c'], datasets: [{ label: 'series1', data: [1, 2, 4] }] }, options: { scales: { xAxes: [{ gridLines: { drawTicks: false }, ticks: { padding: 10 } }], yAxes: [{ gridLines: { drawTicks: false }, ticks: { beginAtZero: true, padding: 10 } }] } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> <canvas id="canvas"> gridLines: drawTicks: false; } Refer to the documentation for further information.
{ "pile_set_name": "StackExchange" }
Q: C++ inserting array values into another array, but combining similar values into the same elements So far I have gotten most of my functions working. I am now stuck on my final step. I need to take in an array from my main, to my "histo" function. I need to take repeating values within certain ranges, and put them each into the same array element and count them. Once this is done, I am to print out a histogram with asterisks. the ranges are------bin 0. if score < 10.----bin 1. if score >= 10 but < 20......ect. Then the output; 9| ** 8|* 7| *** and so on until 0. The asterisks need to resemble the amount of numbers that fit within the specified range and stored in an array element. I am stuck on this part and we can't use vectors, or any #includes other than , , and using namespace std; Any advice is great. I have my cout in the main to make sure my math was correct. #include <iostream> #include <iomanip> #include <cmath> using namespace std; /*int histo(int x);*/ double dev(int count, int* scores, double mn); double mean(int count, int* stats); int main() { int scores[101]; int count = 0; int bin[10]; double mn; cout << "Enter a score (-1 to stop): "; do { cin >> scores[count++]; } while (scores[count - 1] != -1); count--; mn = mean(count, scores); cout << "mean: " << mean(count, scores) << endl; cout << "dev: " << dev(count, scores, mn) << endl; system("pause"); return 0; } int histo(int* scores) { int bins[10]{}; int counter = 0; for (int i = 0; i < *scores; i++) { if (*scores < 10) { bins[counter++]; } else if (*scores >= 10 && *scores < 20) { bins[counter++]; } else if (*scores >= 20 && *scores < 30) { bins[counter++]; } else if (*scores >= 30 && *scores < 40) { bins[counter++]; } else if (*scores >= 40 && *scores < 50) { bins[counter++]; } else if (*scores >= 50 && *scores < 60) { bins[counter++]; } else if (*scores >= 60 && *scores < 70) { bins[counter++]; } else if (*scores >= 80 && *scores < 90) { bins[counter++]; } else if (*scores >= 90) { bins[counter++]; } for (int j = 0; j < ) } } double dev(int count, int* scores, double mn) { double x = 0; double y = 0; double d = 0; for (int i = 0; i < count; i++) { x = pow(scores[i] - mn, 2); y += x; } d = sqrt(y / count); return d; } double mean(int count, int* scores) { double total = 0; for (int i = 0; i < count; i++) { total += scores[i]; } return total / count; } I know I went over kill with the if statements. This is just where I am unsure of what to do. A: for (int i = 0; i < *scores; i++) Ok, so scores is a pointer to an array. By de-referencing it you get the value of the first element of that array, but not the count/size of it. if (*scores < 10) { bins[counter++]; } else if (*scores >= 10 && *scores < 20) { bins[counter++]; } bins[counter++] will go out of bounds very soon with this setup, since your scores array is > 10 (not taking the undefined behaviour into account). Also the else statement already implies that *scores >= the previous statement. So the solution to this will be something like this, assuming you want to increase the bin on index n every time: int histo(int *scores, int scoreCount) { int bins[9]{}; for (int i = 0; i < scoreCount; i++) { if (scores[i] < 10) { bins[0]++; } else if (scores[i] < 20) { bins[1]++; } else if (scores[i] < 30) { bins[2]++; } else if (scores[i] < 40) { bins[3]++; } else if (scores[i] < 50) { bins[4]++; } else if (scores[i] < 60) { bins[5]++; } else if (scores[i] < 70) { bins[6]++; } else if (scores[i] < 90) { bins[7]++; } else { bins[8]++; } } // Do stuff with your bins }
{ "pile_set_name": "StackExchange" }
Q: In Swift 4.2, how do I write func<() to compare 3 fields in a class? Here's a simple Swift class with 3 fields: public class Cabbage: Comparable { public let someString: String public let someInt: Int public let someDouble: Double public init(_ someString: String, _ someInt: Int, _ someDouble: Double) { self.someString = someString self.someInt = someInt self.someDouble = someDouble } public static func ==(lhs: Cabbage, rhs: Cabbage) -> Bool { if lhs.someString == rhs.someString { if lhs.someInt == rhs.someInt { if lhs.someDouble == rhs.someDouble { return true } } } return false } public static func <(lhs: Cabbage, rhs: Cabbage) -> Bool { if lhs.someString < rhs.someString { if lhs.someInt < rhs.someInt { if lhs.someDouble < rhs.someDouble { return true } } } return false } } I think my first function, func ==(), is correct. We return true if and only if all the fields are equal. But I do not think my logic is correct for func <(). For example if lhs.someString == rhs.someString, should I then be comparing lhs.someInt and rhs.someInt? And if these two are equal, should I also be comparing lhs.someDouble and rhs.someDouble? Any ideas or recommendations would be much appreciated. A: Yes, it's not sufficient to just check whether lhs.someString < rhs.someString. You also need to determine if lhs.someString > rhs.someString (or if lhs.someString == rhs.someString). There are many ways to write it correctly. Here's one: public static func <(lhs: Cabbage, rhs: Cabbage) -> Bool { if lhs.someString < rhs.someString { return true } if rhs.someString < lhs.someString { return false } if lhs.someInt < rhs.someInt { return true } if rhs.someInt < lhs.someInt { return false } return lhs.someDouble < rhs.someDouble } UPDATE Since Swift 2.2, the standard library has provided comparison operators for tuples of up to six elements (if all the elements are Comparable). Furthermore, thanks to SE-0283, all tuples will soon (probably in whatever comes after Swift 5.3) conform to Comparable (if their elements all conform to Comparable). Here's how SE-0283 defines tuple comparison: Comparing a tuple to a tuple works elementwise: Look at the first element, if they are equal move to the second element. Repeat until we find elements that are not equal and compare them. This definition also applies to the existing tuple comparison operators added in Swift 2.2. It's also called lexicographic order. So we can use tuple comparison to write a shorter version of < for Cabbage: extension Cabbage: Comparable { public static func <(lhs: Cabbage, rhs: Cabbage) -> Bool { return (lhs.someString, lhs.someInt, lhs.someDouble) < (rhs.someString, rhs.someInt, rhs.someDouble) } } We can reduce code duplication by extracting a computed property for the comparison key. Then we can also use it to define the == operator. Here's what I mean: extension Cabbage: Equatable, Comparable { var comparisonKey: (String, Int, Double) { return (someString, someInt, someDouble) } public static func ==(lhs: Cabbage, rhs: Cabbage) -> Bool { return lhs.comparisonKey == rhs.comparisonKey } public static func <(lhs: Cabbage, rhs: Cabbage) -> Bool { return lhs.comparisonKey < rhs.comparisonKey } }
{ "pile_set_name": "StackExchange" }
Q: Is a root, an octave, followed by a 5th a EsusAdd5 If you have a Root - Octave - 5th, does this become a EsusAdd5 even though you don't play the first 5th in the scale or is just a different voicing/shape for Esus? A: It's just a variation of a power chord if something like this is what you are talking about: X:1 L:1/1 M: K:E V:1 clef=treble "E5"[E' E B] | % The octave notes appear in does not affect what you call a chord in general and this only has a root and a 5th. To be a sus you need a root, perfect 4th and perfect 5th (or root, major 2nd and perfect 5th for sus2). An example of a sus and sus2 is below: X:1 L:1/2 M: K:E V:1 clef=treble "Esus"[E A B] "Esus2"[E ^F B]| %
{ "pile_set_name": "StackExchange" }
Q: typescript interface declaration: indexable property a common use case for javascript objects is to use them as key-value storage... sort of like a dictionary: var dictionary = {}, value; dictionary['key a'] = 99; dictionary['key b'] = 12; value = dictionary['key a']; // 99 typescript intellisense goodness can be added by declaring an interface like this: interface IIndexable<T> { [s: string]: T; } and using the interface like this: var dictionary: IIndexable<number> = {}, value: number; dictionary['key a'] = 99; dictionary['key b'] = 'test'; // compiler error: "cannot convert string to number" var x = dictionary['key a']; // intellisense: "x" is treated like a number instead of "any". here's my question: is it possible to declare a stand-alone version of this interface: interface StackOverflow { questions: IIndexable<number>; } ie without using IIndexable? I tried doing something like this but it doesn't compile: interface MyAttempt { questions: [s: string]: number; } A: interface MyAttempt { questions: { [s: string]: number; }; }
{ "pile_set_name": "StackExchange" }
Q: Circular Range Selection Is there an easy way to create a range that isn't a box, rather a circle centered on the ActiveCell? I could just define each row one at a time, but I'm hoping someone here knows a more elegant solution. Circle Range Update: Here's the solution I settled on, thanks to JvDV's help: Sub revealMap(playerLocation As Range, sightDistance As Integer) Dim search As Range, cl As Range Dim stcol As Integer, strow As Integer Dim endrow As Integer: endrow = 1 + sightDistance * 2 Dim endcol As Integer: endcol = 1 + sightDistance * 2 If playerLocation.row - sightDistance < 0 Then strow = 1 endrow = endrow - playerLocation.row Else strow = playerLocation.row - sightDistance End If If playerLocation.Column - sightDistance < 0 Then stcol = 1 endcol = endcol - playerLocation.col Else stcol = playerLocation.Column - sightDistance End If Set search = ActiveSheet.Cells(strow, stcol) For Each cl In search.Resize(endrow, endcol) If (Sqr((Abs(cl.row - playerLocation.row)) ^ 2 + (Abs(cl.Column - playerLocation.Column)) ^ 2) <= sightDistance) And (cl.Interior.ColorIndex = 1) Then Worksheets("Map Ref").Cells(cl.row, cl.Column).Copy (Worksheets("World Map").Cells(cl.row, cl.Column)) End If Next cl End Sub A: Just for fun. As per @BigBen, you'll need some type of logic. So for example a sample for the diamond case: Sub Test() Dim rng1 As Range, rng2 As Range: Set rng1 = ActiveCell For Each cl In ActiveCell.Offset(-3, -3).Resize(7, 7) If Abs(cl.Row - rng1.Row) + Abs(cl.Column - rng1.Column) <= 3 Then If Not rng2 Is Nothing Then Set rng2 = Union(rng2, cl) Else Set rng2 = Union(rng1, cl) End If Debug.Print rng2.Address End If Next cl rng2.Select End Sub Just like @Galimi, I did not account for edge cases. Good luck.
{ "pile_set_name": "StackExchange" }
Q: formating the date in ascending order can you please help me to in the following. I wrote the below query as per the requirement SQL> SELECT mon."months", 2 COUNT (DECODE (e1.ename, 'RAVI', 1, DECODE (e1.ename, 'KIRAN', 1, NULL)) 3 ) AS "num-review" 4 FROM (SELECT TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7), 5 'MON-YYYY' 6 ) "months" 7 FROM DUAL 8 CONNECT BY LEVEL <= 18 9 ORDER BY LEVEL) mon, (select ename, hiredate, to_char(hiredate,'MON-YYYY') "Month" from emp_copy) e1 10 WHERE mon."months"=e1."Month"(+) 11 GROUP BY "months"; months num-review -------- ---------- APR-2013 0 AUG-2013 0 DEC-2012 1 DEC-2013 0 FEB-2013 2 FEB-2014 0 JAN-2013 1 JAN-2014 0 JUL-2013 0 JUN-2013 0 MAR-2013 0 months num-review -------- ---------- MAY-2013 0 NOV-2012 0 NOV-2013 0 OCT-2012 1 OCT-2013 0 SEP-2012 1 SEP-2013 0 18 rows selected. here i have to get the output like Sep-2012 Oct-2012 Nov-2012 Dec-2012 Jan-2013 Feb-2013 Mar-2013 Apr-2013 May-2013 Jun-2013 Jul-2013 Aug-2013 Sep-2013 Oct-2013 Nov-2013 Dec-2013 Jan-2014 Feb-2014 but i am getting the output in the different fashion. can any one please help me to fix the problem. A: Because you're using to_char on the date to get "months", ordering by that will just give you the months alphabetically (as you're seeing). You need to give yourself another field that will be sorted chronologically, which you can do with 'YYYYMM', e.g. and order by that. Here's an example based on your query (simplified to remove your specific tables). Does this help? select "months", count(*) "num", "sort_months" from ( SELECT TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7), 'MON-YYYY') "months", TO_CHAR (ADD_MONTHS (SYSDATE, LEVEL - 7), 'YYYYMM') "sort_months" FROM DUAL CONNECT BY LEVEL <= 18 ORDER BY LEVEL ) group by "months", "sort_months" order by "sort_months";
{ "pile_set_name": "StackExchange" }
Q: CSS background gradient repeating on overflow I'm using a gradient as a background and it stretches out as far as the end of the page however after scrolling/overflow it starts to repeat. How can I stretch the gradient out to the bottom of the page even after scrolling? html { height:100%; width:100%; } body { margin:0; padding:0; width:100%; height:100%; min-height:100%; background-repeat:no-repeat; background-attachment: fixed; background: rgb(242,245,246); /* Old browsers */ background: -moz-linear-gradient(top, rgba(242,245,246,1) 0%, rgba(227,234,237,1) 37%, rgba(200,215,220,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(242,245,246,1)), color-stop(37%,rgba(227,234,237,1)), color-stop(100%,rgba(200,215,220,1))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* IE10+ */ background: linear-gradient(to bottom, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f5f6', endColorstr='#c8d7dc',GradientType=0 ); /* IE6-9 */ } A: It appears you have miss-ordered some of your CSS properties. Take a look at this section. background-repeat:no-repeat; background-attachment: fixed; background: rgb(242,245,246); /* Old browsers */ You have specified the long-hand properties background-repeat and background-attachment, before the short-hand background property. When the background property is read, it will reset all the previously set background properties. Just move them beneath your other background properties, and it will work. html { height:100%; width:100%; } body { margin:0; padding:0; width:100%; height:100%; min-height:100%; background: rgb(242,245,246); /* Old browsers */ background: -moz-linear-gradient(top, rgba(242,245,246,1) 0%, rgba(227,234,237,1) 37%, rgba(200,215,220,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(242,245,246,1)), color-stop(37%,rgba(227,234,237,1)), color-stop(100%,rgba(200,215,220,1))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* IE10+ */ background: linear-gradient(to bottom, rgba(242,245,246,1) 0%,rgba(227,234,237,1) 37%,rgba(200,215,220,1) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f5f6', endColorstr='#c8d7dc',GradientType=0 ); /* IE6-9 */ background-repeat:no-repeat; background-attachment: fixed; } <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1> <h1>blah</h1>
{ "pile_set_name": "StackExchange" }
Q: How load into Hadoop/Hive only the 365 more recent files? I create a table: CREATE EXTERNAL TABLE events ( id bigint, received_at string, generated_at string, source_id int, source_name string, source_ip string, facility string, severity string, program string, message string ) PARTITIONED BY ( dt string ) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' STORED AS TEXTFILE LOCATION 's3://mybucket/folder1/folder2'; Inside s3://mybucket/folder1/folder2 there are multiple folders, in the naming format dt=YYYY-MM-DD/ and inside each folder, 1 file, in the naming format YYYY-MM-DD.tsv.gz I then load the table via MSCK REPAIR TABLE events;. When I do a SELECT * FROM events LIMIT 5;, I get OK Failed with exception java.io.IOException:com.amazonaws.services.s3.model.AmazonS3Exception: The operation is not valid for the object's storage class (Service: Amazon S3; Status Code: 403; Error Code: InvalidObjectState; Request ID: 66C6392F74DBED77), S3 Extended Request ID: YPL1P4BO...+fxF+Me//cp7Fxpiuqxds2ven9/4DEc211JI2Q7BLkc= Time taken: 0.823 seconds Because objects older than 365 days have been moved to Glacier. How do I programmatically load into the able only the 365 more recent files, or better, I can specify load only files newer than/named past a set date? PS: I'm only going to fire up a Hadoop/Hive cluster when needed. It will always start from scratch - no previous data in it - hence the concern being only with adding data, not removing it. A: You would need to avoid Hive from seeing the Glacier-backed partitions by only specifically adding the S3-backed partitions. You would need to do this for each of the 365 dates after you have created the table, like so: CREATE EXTERNAL TABLE ...; ALTER TABLE events ADD PARTITION (dt = '2015-01-01'); ALTER TABLE events ADD PARTITION (dt = '2015-01-02'); ALTER TABLE events ADD PARTITION (dt = '2015-01-03'); ... ALTER TABLE events ADD PARTITION (dt = '2015-12-31'); SELECT * FROM events LIMIT 5;
{ "pile_set_name": "StackExchange" }
Q: Creating correct D3D11 library file for GCC What is the correct way to convert files like d3d11.lib that are provided in the DirectX SDK to the *.a GCC library format? I've tried the common reimp method for converting *.lib files to *.a files, but it doesn't seem to work. Step one involves creating a definitions file: bin\reimp -d d3d11.lib Let's say I want to use the D3D11CreateDevice function that should be provided in this library. If I open the created definitions file everything seems to be OK: LIBRARY "d3d11.dll" EXPORTS (...) D3D11CreateDevice D3D11CreateDeviceAndSwapChain (...) Next I try to create the *.a file using the definitions file and the original lib file: bin\dlltool -v -d d3d11.def -l libd3d11.a This does in fact produce a valid library (and no error messages when dlltool is set to verbose), but if I try to use the function D3D11CreateDevice that should be implemented in it, I get an error: undefined reference to `D3D11CreateDevice' If I ask nm what symbol are present in the library (and filter using grep), I get this: D:\Tools\LIB2A>bin\nm libd3d11.a | grep D3D11CreateDevice File STDIN: 00000000 I __imp__D3D11CreateDeviceAndSwapChain 00000000 T _D3D11CreateDeviceAndSwapChain 00000000 I __imp__D3D11CreateDevice 00000000 T _D3D11CreateDevice The imp function is the function that calls the actual implementation of D3D11CreateDevice inside the DLL. However, that actual implementation is now prefixed by an underscore. Why is "_D3D11CreateDevice" defined while "D3D11CreateDevice" is not even though it is mentioned in the definitions file? A: An outdated version of dlltool will prepend an underscore to every function when converting d3d11lib. Solved it by using a dlltool.exe from MinGW-w64 4.9.2. This dlltool produces a library with the correct function names. When using the regular d3d11.lib provided by Microsoft in combination with headers provided by anyone, a SIGSEGV will occur when stepping into the library at runtime. This means that you do have to convert to the *.a format for some reason not investigated.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use inject $.post() from address bar? I have a javascript in which I use $.post() command to post variables to a php file, I have the URL of the php file hardcoded in the same .js file. I just want to know if it's possible for someone to inject $.post() command from address bar and send invalid data to the PHP file? if yes, how to prevent or how to detect those invalid data? A: Yes, anybody who knows how to code in JavaScript could send an AJAX POST request to your PHP file. As for how to detect the invalid data, that depends entirely on what makes the data invalid. You'll simply need to check the POST values against whatever criteria you're expecting valid data to meet, and then ignore any requests that don't meet those criteria.
{ "pile_set_name": "StackExchange" }
Q: Is struggling from a disease to remain committed on the path of God "greater jihad"? I am suffering from ADHD and I am also autistic. I can be called intelligent but I struggle a lot on personal and mental level due to these problems. My mind is like a fire cracker, new and sometimes absurd thoughts spurt out of it occasionally. Its difficult for me to switch my mind off. Some of those thoughts can be considered religious impropriety. I feel very ashamed and become frantic when these kinds of thoughts come to my mind, but I however struggle a lot to remain a committed Muslim and have deepest reverence for Allah. However, I fear that having these thoughts are a disrespect to Allah and that breaks me. I would like to be a devoted follower of Islam with deepest reverence for Allah, devoid of any such frivolities and believe one day I just might. Nonetheless, is my struggle "greater jihad"? Will these thought offend Allah? Will he be angry or abandon me for having these thoughts which are rather out of my control and not intentional? Also are there any "words" I can say, which can help me with this problem? For example, when I have evil thoughts for others, I rhyme "There is no power other than Allah, Allah Uh-Akbar" and most of those times these thoughts stop. P.S I have recently converted without knowledge of my family and they are an ardent opposer of Islam, thus neither can I offer namaz nor fast in ramadan(I live with them), though I very much want to. Also, I don't know Arabic, so please prefer English translations. A: Short answer to your title: YES Detailed Answer: I won't say it would be considered as greater jihad, although there were some narrations from some companions that state:"fighting oness self is considered greater Jihad" but staying patient while struggling can increase your deeds and hopefully lead to Jannah. As in the hadith in Sahih Bukhary and Musli: 'Ata' bin Abu Rabah reported: Ibn 'Abbas (May Allah be pleased with them) asked him whether he would like that he should show him a woman who is from the people Jannah. When he replied that he certainly would, he said, "This black woman, who came to the Prophet (ﷺ) and said, 'I suffer from epilepsy and during fits my body is exposed, so make supplication to Allah for me.' He (ﷺ) replied: 'If you wish you endure it patiently and you be rewarded with Jannah, or if you wish, I shall make supplication to Allah to cure you?' She said, 'I shall endure it.' Then she added: 'But my body is exposed, so pray to Allah that it may not happen.' He (Prophet (ﷺ)) then supplicated for her". Thus, fighting these improper thoughts and staying patient may hopefully increase your deeds iA As for the improper thoughts, it was already mentioned in a hadith in sahih Muslim that you can say this statement to help get rid of improper thoughts: It is narrated on the authority of Abu Huraira that the Messenger of Allah (ﷺ) said: Men will continue to question one another till this is propounded: Allah created all things but who created Allah? He who found himself confronted with such a situation should say: I affirm my faith in Allah. So what the hadith say, when you have such improper thoughts, it is Ok. Every muslim has these thoughts. just say: "I affirm my faith in Allah." and go on with your life. Do something which can keep you busy from overthinking.
{ "pile_set_name": "StackExchange" }
Q: Django updating model BooleanField not working model public = models.BooleanField(default=False) view @login_required def topic_visibility(request, topic_id, visibility): """Change topic visibility, then redirect to topics page""" topic = Topic.objects.get(id=topic_id) check_instance_ownership(request, topic) if visibility == 0: topic.public = False elif visibility == 1: topic.public = True return redirect('learning_logs:topic', topic_id = topic_id) url pattern path('topic_visibility/<int:topic_id>/<int:visibility>', views.topic_visibility, name="topic_visibility"), A button dropdown allows the user to select whether they want a certain forum topic to be public (True) or private (False). When the user visits the url that calls topic_visibility in the view, nothing is changed. I suspect it may have something to do with the topic model not being saved? A: You did not save the model object, so the change does not persists: @login_required def topic_visibility(request, topic_id, visibility): """Change topic visibility, then redirect to topics page""" topic = Topic.objects.get(id=topic_id) check_instance_ownership(request, topic) if visibility == 0: topic.public = False elif visibility == 1: topic.public = True topic.save() return redirect('learning_logs:topic', topic_id=topic_id) Note: A GET request is not supposed to have side-effects, hence updating objects when a user makes a GET request, is not compliant with the HTTP standard. Therefore it might be better to update a Topic with a POST request.
{ "pile_set_name": "StackExchange" }
Q: Finding $\lambda$ for poisson random variable I'm probably over thinking this, but a question states that there are $3.5$ commercial airline plane crashes per year. What's the probability that there are at least $2$ such accidents next month? For my answer I put that since this is a poisson random variable, we can calculate this by letting $X$ be the number of plane crashes next month. Then: $$P\{X\ge 2\}=1-(P\{X=0 \}+P\{X=1\})$$ Then I thought since the equation is $P\{X=i\}=e^{-\lambda}\frac{\lambda^i}{i!}$ we'd want to take $\lambda $ to be $3.5/12=.29$, since they are asking for next month, not year, giving: $$P\{X\ge2\}= 1-e^{-.29}-.29e^{-.29}$$ But the answer uses $\lambda=3.5$ instead. Why is this? A: For the sake of not leaving this question unanswered: If the question stated that there were $3.5$ crashes monthly, $\lambda$ would therefore be $3.5$. But as it stands, with $3.5$ crashes yearly $\lambda=3.5/12 \sim .29$. And the answer follows from above.
{ "pile_set_name": "StackExchange" }
Q: Write a palindrome that prints "Hello, World!" without using comments Your Task: Print "Hello, World!" using a palindrome. Simple, right? Nope. You have one restriction: you may not use comments. "Comments" include Normal // or # comments Adding extraneous characters to a string literal Triple-quoted string comments Creating a string literal to hide characters You may not use a pre-defined procedure to print "Hello, World!". (like HQ9+'s H command) This is code-golf, so the shortest answer in bytes wins. A: Stuck, 0 bytes I think this wins? An empty program in stuck prints Hello, World! Shamelessly stolen from this answer
{ "pile_set_name": "StackExchange" }
Q: jQuery not recognizing (+) plus sign I am making a calculator program and am having trouble with the addition function. I have the other functions working ("/", "-", "*"), but the plus("+") won't function. The html and JavaScript are included below... <head> <title>RDaniels34 | Calculator</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <link href='https://fonts.googleapis.com/css?family=Montserrat:400,700|Bitter:400,400italic|Josefin+Sans:400,300italic' rel='stylesheet' type='text/css'> <style> <!-- #main { width: 100px; height: 200px; border: 3px solid #c3c3c3; display: -webkit-flex; /* Safari */ -webkit-flex-flow: row-reverse wrap; /* Safari 6.1+ */ display: flex; flex-flow: wrap; justify-content: space-around; } #main div { width: 55px; height: 50px; } --> </style> </head> <body style="background-color: lightyellow;"> <header> <div class="header-div"> <h1>Calculator</h1> <h3>Made by: RDaniels34</h3> </div> </header> <container class="container"> <div class="well well-lg" id="numberDisplay"> <div id="numberDisplay1">0</div> <br> <div id="numberDisplay2">0</div> </div> <div id="separator-line"></div> <div id="buttonGroup"> <button type="button" onclick="clrFunction()" id="clr" class="btn btn-default btn-sm">C</button> <button type="button" onclick="divideFunction()" id="operators" class="divideNum operators btn btn-default btn-sm">/</button> <button type="button" onclick="timesFunction()" id="operators" class="timesNum btn btn-default btn-sm ">X</button> <button type="button" onclick="backspaceFunction()" id="backspace" class="btn btn-default btn-sm fa fa-caret-left" style="font-size:20px"></button> <button type="button" onclick="sevenFunction()" id="numbers" class="numbers btn btn-default btn-sm">7</button> <button type="button" onclick="eightFunction()" id="numbers" class="numbers btn btn-default btn-sm">8</button> <button type="button" onclick="nineFunction()" id="numbers" class="numbers btn btn-default btn-sm">9</button> <button type="button" onclick="addFunction()" id="addNum" class="addNum btn btn-default btn-sm">+</button> <button type="button" onclick="fourFunction()" id="numbers" class="numbers btn btn-default btn-sm">4</button> <button type="button" onclick="fiveFunction()" id="numbers" class="numbers btn btn-default btn-sm">5</button> <button type="button" onclick="sixFunction()" id="numbers" class="numbers btn btn-default btn-sm">6</button> <button type="button" onclick="subtractFunction()" id="minusNum" class="minusNum btn btn-default btn-sm">-</button> <button type="button" onclick="oneFunction()" id="numbers" class="numbers btn btn-default btn-sm">1</button> <button type="button" onclick="twoFunction()" id="numbers" class="numbers btn btn-default btn-sm">2</button> <button type="button" onclick="threeFunction()" id="numbers" class="numbers btn btn-default btn-sm">3</button> <button type="button" onclick="percentFunction()" id="operators" class="percentNum btn btn-default btn-sm ">%</button> <button type="button" onclick="zeroFunction()" id="numbers" class="numbers btn btn-default btn-sm">0</button> <button type="button" onclick="decimalFunction()" id="numbers" class="numbers btn btn-default btn-sm ">.</button> <button type="button" onclick="plusminusFunction()" id="operators" class="operators btn btn-default btn-sm">+/-</button> <button type="button" onclick="rd34Function()" id="rd34" class="btn btn-default btn-sm">RD</button> <button type="button" onclick="equalsFunction()" id="equals" class="btn btn-default btn-sm">=</button> </div> </container> <div id="footer"> Copyright © RDaniels34 - 2016 </div> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="vendor/angular.js" type="text/javascript"></script> <script src="scripts/app.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> </body> JS $(document).ready(function() { var testNumLength = function(firstNumber) { if (firstNumber.length > 10) { $("#numberDisplay2").text(firstNumber.substr(firstNumber.length - 10, 10)); if (firstNumber.length > 15) { $("#numberDisplay1").text(firstNumber.substr(firstNumber.length - 15, 15)); firstNumber = ""; $("#numberDisplay2").text("Err"); } } }; var firstNumber = ""; var secondNumber = ""; var answer = ""; var newAnswer = ""; var operator = ""; $("#numberDisplay2").text(""); $(".numbers").click(function() { firstNumber += $(this).text(); $("#numberDisplay2").text(firstNumber); testNumLength(firstNumber); }); // $(".operators").click(function() { // operator = $(this).text(); // secondNumber = firstNumber; // firstNumber = ""; // $("#numberDisplay2").text(); // }); $(".addNum").click(function() { operator = $(this).text(); secondNumber = firstNumber; firstNumber = ""; $("#numberDisplay2").text(); }); $(".minusNum").click(function() { operator = $(this).text(); secondNumber = firstNumber; firstNumber = ""; $("#numberDisplay2").text(); }); $(".divideNum").click(function() { operator = $(this).text(); secondNumber = firstNumber; firstNumber = ""; $("#numberDisplay2").text(); }); $(".timesNum").click(function() { operator = $(this).text(); secondNumber = firstNumber; firstNumber = ""; $("#numberDisplay2").text(); }); $(".percentNum").click(function() { operator = $(this).text(); secondNumber = firstNumber; firstNumber = ""; $("#numberDisplay2").text(); }); $("#clr").click(function() { firstNumber = ""; $("#numberDisplay2").text("0"); if ($(this).attr("id") == "clr") { firstNumber = ""; } }); $("#backspace").click(function() { firstNumber = firstNumber.substring(0, firstNumber.length - 1); document.getElementById("numberDisplay2").innerHTML = firstNumber; testNumLength(firstNumber); }); $("#equals").click(function() { parseFloat(firstNumber); parseFloat(secondNumber); if (operator == "+") { answer = secondNumber + firstNumber; } else if (operator == "-") { answer = secondNumber - firstNumber; } else if (operator == "X") { answer = secondNumber * firstNumber; } else if (operator == "/") { answer = secondNumber / firstNumber; } else if (operator == "%") { answer = secondNumber / 100; } newAnswer = answer; $("#numberDisplay2").text(answer.toPrecision(5)); testNumLength(answer); }); }); A: At line 206 of your js if (operator == "+") { answer = secondNumber + firstNumber; } else if (operator == "-") { .... try putting this instead if (operator == "+") { answer = parseFloat(firstNumber) + parseFloat(secondNumber); } else if (operator == "-") { .... It is likely that the compiler is treating the "+" as concatenation and not a mathematical operation. EDIT This is me being very nitpicky and an annoying busybody but you could probably also simplify many of your buttons to use something like <button type="button" onclick="addToDisplay(' / ')" id="operators" class="divideNum operators btn btn-default btn-sm">/</button> <button type="button" onclick="addToDisplay(' X ')" id="operators" class="timesNum btn btn-default btn-sm ">X</button> and function addToDisplay(value){ //your code here } Since many of the button functions are almost exactly the same.
{ "pile_set_name": "StackExchange" }
Q: Measuring loading time of Excel I am searching for a solution for over one week. Maybe you have a good solution to this problem: I want to measure the time I need to open an Excel file with Excel. My first solution is that I start the measurement with this line of code: ProcessBuilder command = new ProcessBuilder("cmd", "/c", <EXCEL_PATH>, <FILE-LOCATION>); command.start(); long start = System.currentTimeMillis(); And i check the RAM-Usage via the process explorer. If excel finish loading the ram usage is still the same and I stop the measurement. As you see this is very fuzzy and not a good solution. As second solution I open a SocketServer in JAVA and wait until Excel will call the Workbook_Open()- Method after finishing loading the file. Within this method I send a socket connection to the java server (I give the host and port as parameter to excel) and measure this time. This is very efficient BUT in my company it is not allowed to auto run scripts if they don’t stored in a trusted zone. I cannot change the policy’s so it is not a solution. Does anyone have an idea how to measure the loading time of an Excel-File in Excel? It could not be that their is no solution to track the loading time in Excel? A: Updated answer: You can use DDE for attempting to connect (initiate a conversation) to the desired file repeatedly, and measure the time that passes until you succeed. Please notice it will be far from a precise measuring, and should be used mainly for estimation. Have a look at this project which is based on this one, for an example of using DDE together with Java and MS Excel. Details: You can't connect to an Excel file by DDE before its loading has completed inside Excel program, and that can serve the purpose. Right after starting Excel, you can attempt to connect to the file by DDE (repeatedly or with 100ms delay for avoiding CPU load) until you succeed, and calculate the time after success. Pseudo code: ts = now(); d = DDE("file.xlsx"); while (d.error) { d = DDE("file.xlsx"); } load_time = now() - ts; Old version of answer: If you already use the workbook's VBA, I think there's a simple solution. You can write the current time to some new temporary local file, right before opening the file, and then write the current time (Now) from within the Workbook_Open subroutine, to the same temporary file, at the second line. Then you will be able to track the file until it has 2 lines with an ongoing interval, and calculate the difference between the timestamps.
{ "pile_set_name": "StackExchange" }
Q: images not displayed when iOS app run on device When I run my application on my device, the images are not displayed. When in simulator mode the images are displayed. I receive no copy error messages or any other kind of alerts when I run the app on my device. Any ideas? Also the images in question are in a paged UI Scroll view, which was coded using the following tutorial: http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content The Paging with UIScrollView section of the tutorial. Thanks A: I would start by verifying that you have imported images for the correct resolutions. You may for example, have only added retina images that work in the retina simulator, but not on a low res test device. Additionally, you may want to consider deleting the images from your project and re-adding them making sure to select both the "add to target" and "copy files" check boxes on the import prompt. Edit: Another possibility is that you've made a capitalization error when referencing your images in code. It is important to keep in mind that the simulator is not case sensitive to these things, but the real device is. For example, if you're image is titled "Image.png" you must reference it exactly that way.
{ "pile_set_name": "StackExchange" }
Q: Charles is not registering the localhost charles traffic I am using charles to get the traffic of some devices and it is working corectly. But for some reason it is not registering the traffic from the browser, specifically from localhost, for example: http://localhost:8080/apis/v1/homefeed?index=mobilefrontpage&hsvPubkey=espn-en-homescreen-video-qa&platform=android&profile=sportscenter_v1&locale=co&version=21&device=handset&lang=en&region=us&appName=espnapp&swid=57cb001d-71cb-4e37-a7a0-265d275e6752&enableHero=true&authorizedNetworks=buzzerbeater,espn1,espn2,espn3,espn_free,espnclassic,espndeportes,espnews,espnu,goalline,longhorn,sec&hasMVPDAuthedEver=false&freePreviewTimeAvailable=10&isAuthenticated=false&content=26199860 This petitiion is not registered in charles and I need to mock this one with some of its internal calls, but now it is not possible, because for the charles issue. I tried to use: http://localhost.charlesproxy.com, but I am getting a 404 issue. Any ideas? Thanks A: Using http://localhost.charlesproxy.com is the right choice. You get 404 because the expected resource in URL does not exist. It has nothing to do with Charles and HTTP proxy. According to Charles document: Some systems are hard coded to not use proxies for localhost traffic, so when you connect to http://localhost/ it doesn't show up in Charles. The workaround is to connect to http://localhost.charlesproxy.com/ instead. This points to the IP address 127.0.0.1, so it should work identically to localhost, but with the advantage that it will go through Charles. Actually, you can use any domain that point to 127.0.0.1, not just http://localhost.charlesproxy.com. For example, I have a domain donghz.com which is resolved to 127.0.0.1, you can access http://donghz.com:8080/apis/v1/home... and get the same response too, with HTTP intercepted by Charles.
{ "pile_set_name": "StackExchange" }
Q: Integer but not Laurent sequences Are there any sequence given by a recurrence relation: $x_{n+t}=P(x_t,\cdots,x_{t+n-1})$, where $P$ is a positive Laurent Polynomial, satisfy: if $x_0=\cdots=x_{n-1}=1$, then the sequence is only integer; but does not exhibit Laurent Phenomenon ? What if we allow $P$ to be a rational function? A: Consider $x_{n+3} = \frac{x_n+x_{n+1}}{x_{n+2}}$. With $x_1=x_2=x_3 =1$ this gives the sequence $1,1,1,2,1,3,1,4,1,5,...$ but it certainly is not Laurent because for instance we have $x_5=\frac{x_2x_3+x_3^2}{x_1+x_2}$. A: This reminds me of a question I had seen on both MO and MSE. Sequence A276175 in the OEIS is defined by $$a_n = \frac{(a_{n-1} + 1)(a_{n-2}+1)(a_{n-3} + 1)}{a_{n-4}}$$ with $a_0 = a_1 = a_2 = a_3 = 1$. The OEIS page conjectures it to be an integer for all $n$. The MSE question contains a proof the all $a_n$ are integer (though I haven't read the proof). In the comments of the MO question it is observed $a_8$ is not Laurent. Added in edit: I offer another example which does not exhibit the Laurent phenomenon, but conjecturally is an integer sequence. Consider the sequence defined by $$b_n = \frac{(b_{n-1} + 1)(b_{n-2} + 1)(b_{n-3} + 1)(b_{n-4}+1)}{b_{n-5}}$$ where $b_0 = b_1 = b_2 = b_3 = b_4 = 1$. I computed and after reducing I found the denominator of $b_{10}$ to be $b_0^14(b_1 + 1)b_1^8(b_2 + 1)b_2^4b_3^2b_4$ (not a monomial). I verified this sequence to be integer up to $n=36$, and Kevin O'Bryant later verified up to $n=41$. I asked if the sequence is integer for all $n \geq 0$ in a separate question.
{ "pile_set_name": "StackExchange" }
Q: Eigenvalues and eigenvectors of a specific linear transformation I am working on the following problem: Let $k$ be a field, let $d$ be a positive integer, and let $P_d$ be the $k$-vector space of polynomials of degree $\leq d$ in $k[x,y]$. Compute the eigenvalues and eigenvectors of the linear transformation $x\frac{d}{dx} - y\frac{d}{dy} : P_d \longrightarrow P_d$. So far in my Linear Algebra class, we've only computed eigenvalues and eigenvectors of linear transformations from $\mathbb{R}^n$ to $\mathbb{R}^n$ by considering the associated $n \times n$ matrix so far. Thus, I wasn't sure exactly how to approach this one. But, I tried approaching this just like the other problems we've done. So, in order to find the eigenvalues, we want to find $\lambda \in k$ such that $Tf = \lambda f$, where $f$ is a (nonzero) function in $k[x,y]$ (which would serve as an eigenvector) and $T$ is the linear transformation specified above. This gives *$x\frac{df}{dx} - y\frac{df}{dy} = \lambda f$. How can I now solve equation * for eigenvalues and the associated eigenvectors ? Am I supposed to solve a corresponding differential equation? Even this is tough for me, since I'm not used to solving differential equations for functions in two variables. Or is there an easier approach that I'm not seeing? I wouldn't think that I'm supposed to expand $f$ out to include all of its terms and solve from there -- this can get cumbersome since we're dealing with the polynomial ring in two variables $k[x,y]$. Any help is appreciated. Thanks! A: Consider a general $d$ dimensional polynomial $$ f(x,y) = \sum_{i=0}^d \sum_{j=0}^d a_{ij} x^i y^j. $$ Plugging into our linear operator we obtain $$ \sum_{i=0}^d \sum_{j=0}^d (i-j -\lambda) a_{ij} x^i y^j = 0. $$ Since this needs to hold for each coefficient of $x^i y^j$, we require $(i-j -\lambda)a_{ij} = 0$ to hold for all $i,j$. This immediately implies that the eigenvalues will satisfy $\lambda = \pm n$ for $n = 0, 1, \dots, d$. To find the eigenvectors use the relation that $i-j = \lambda$ and all other $i,j$ pairs will have $a_{ij} = 0$. We obtain the eigenvectors $$\sum_{i-j=\lambda} a_{ij} x^i y^j.$$ EDIT: For example $\lambda = 0$, we have the eigenvector $\sum_{i=0}^d a_{ii} (x y)^i$. In the comments you made it should have been $\lambda = 1$ and $a x$ or $\lambda = -1$ and $b y$.
{ "pile_set_name": "StackExchange" }
Q: How to align a Jumbotron with a form? How can I align the Jumbotron with my form? This example shows my form and how it is off alignment with the form: <div class="jumbotron"> <form class="form-horizontal"> <div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input id="email" type="text" class="form-control" name="email" placeholder="Email"> </div> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input id="password" type="password" class="form-control" name="password" placeholder="Password"> </div> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input id="re-password" type="password" class="form-control" name="re-password" placeholder="Re-enter Password"> </div> <br /> <div class="form-group"> <div class="col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </div> </form> </div> Here is a screenshot for clarification: here is my screenshot using bootstrap4 A: Bootstrap v3.3.7 col uses float: left In contrast, Bootstrap v4 col which uses Flexbox. So I guess that you are using v3.3.7 which needs clear: both to clear the float effect, this is already built-in inside bootstrap css BUT you have to use .row before col becuse .row the one who has the clear property. Finally you just have to add <div class="row"> and it will solve your issue. Check the following Bootply. Update There is also another solution which is .clearfix, Place <div class="clearfix"></div> Directly after .col-md-6 and it will also clear the float. Check updated Bootply using .clearfix. If you are exhausted and want to know more abot Floats and Clear, You may check this Article it will help you.
{ "pile_set_name": "StackExchange" }
Q: CSS Background image only working inline html This is my first question (and first post) on Stackoverflow. Hope to contribute more once I become skilled enough. Anyway, I'm having trouble understanding why my background image appears when I reference it using css that's inline with my html, but not when I put it in a separate css stylesheet that the html links to. Here's what my inline css looks like, which works fine: <style> body { background: url('background.jpg') center center fixed; background-size: cover; } </style> My styles.css file is shown below, which contains the exact same code: <style> body { background: url('background.jpg') center center fixed; background-size: cover; } p { font-family: 'Helvetica Neue' Helvetica; font-color: white; } h1 { color: white; font-family: 'Helvetica Neue'; font-size: 3.5em; text-align: center } .textbox { background-color: beige; height: 100px; width: 100px; padding: 10px; margin: 50px auto; text-align: center; font-family: 'Helvetica Neue' Helvetica; font-weight: 200; } </style> ...but it no longer shows the background image. Everything else from the css file (paragraph formatting, text size/color, etc.) shows up in the browser just fine. Also, the html file, css file, and background image are all in the same directory. So I figured I don't need to use "/background.jpg", "../background.jpg", etc. which I've seen suggested in other cases in other posts on Stackoverflow. I tried to find an answer to this but couldn't find one. Any help is greatly appreciated! A: But, in a separate .css file, I typed the exact same code as above, linking to it in the html file by using: Did you remove the <style> & </style> tags from the CSS file ? For example, like: body { background: url('background.jpg') center center fixed; background-size: cover; } These HTML tags are only required around your CSS rules if you're including CSS directly into your HTML.
{ "pile_set_name": "StackExchange" }
Q: How is *it++ valid for output iterators? In example code, I often see code such as *it++ for output iterators. The expression *it++ makes a copy of it, increments it, and then returns the copy which is finally dereferenced. As I understand it, making a copy of an output iterator invalidates the source. But then the increment of it that is performed after creating the copy would be illegal, right? Is my understanding of output iterators flawed? A: The standard requires that *r++ = t work for output iterators (24.1.2). If it doesn't work, it's not an output iterator by the standard's definition. It is up to the iterator implementation to make sure such statements work correctly under the hood. The reason that you shouldn't keep multiple copies of an output iterator is that it has single pass semantics. The iterator can only be dereferenced once at each value (i.e. it has to be incremented between each dereference operation). Once an iterator is dereferenced, a copy of it cannot be. This is why *r++ = t works. A copy is made of the original iterator, the original iterator is dereferenced and the copy is incremented. The original iterator will never be used again, and the copy no longer references the same value. A: The expression *it++ does not (have to) make a copy of it, does not increment it, etc. This expression is valid only for convenience, as it follows the usual semantics. Only operator= does the actual job. For example, in g++ implementation of ostream_iterator, operator*, operator++ and operator++(int) do only one thing: return *this (in other words, nothing!). We could write for example: it = 1; it = 2; *it = 3; ++it = 4; Instead of: *it++ = 1; *it++ = 2; *it++ = 3; *it++ = 4;
{ "pile_set_name": "StackExchange" }
Q: Multiple for-loops from one $result = $conn->query($query) I have imported data into a table and I am now accessing that data with PHP using the code as follows, <?php require_once 'connect.php'; $query = "SELECT * FROM JunkData"; $result = $conn->query($query); if(!$result) die("Fatal Error"); $rows = $result->num_rows; for ($name = 0; $name < $rows; ++$name) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Name']) . '<br/>'; } $result->close(); $conn->close(); This works! I am really just curious why adding a second for-loop does not work, unless I declare $result again? <?php require_once 'connect.php'; $query = "SELECT * FROM JunkData"; $result = $conn->query($query); if(!$result) die("Fatal Error"); $rows = $result->num_rows; for ($name = 0; $name < $rows; ++$name) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Name']) . '<br/>'; } for ($number = 0; $number < $rows; ++$number) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Number']) . 'Flag<br/>'; } $result->close(); $conn->close(); Doesn't work, although 'Flag' is printed an appropriate number of times. Whereas if I declare $result again. <?php require_once 'connect.php'; $query = "SELECT * FROM JunkData"; $result = $conn->query($query); if(!$result) die("Fatal Error"); $rows = $result->num_rows; for ($name = 0; $name < $rows; ++$name) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Name']) . '<br/>'; } $result = $conn->query($query); for ($number = 0; $number < $rows; ++$number) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Number']) . '<br/>'; } $result->close(); $conn->close(); The code does work. I have tried unsetting a few variables with unset($row) etc and I did notice if I remove the line, $row = $result->fetch_array(MYSQLI_ASSOC); from the second for loop, it will print the last value in the Number column as many times as the loop will run. I hope that is understandable. I am wondering what is happening in the code that I need to re-declare $result if I want to run a second for loop against it. A: There is an internal pointer when you call fetch_* function. In your first for loop, you send the pointer to the end of the result set. So, the next fetch will return nothing. If you run $result->data_seek(0) you will reset this pointer and can reuse: for ($name = 0; $name < $rows; ++$name) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Name']) . '<br/>'; } $result->data_seek(0); //<---- REPLACE HERE for ($number = 0; $number < $rows; ++$number) { $row = $result->fetch_array(MYSQLI_ASSOC); echo htmlspecialchars($row['Number']) . '<br/>'; } Of course, usually there is no need to loop the same result set twice, you may need to rethink your logic and loop only once.
{ "pile_set_name": "StackExchange" }
Q: When endogenous variable is non-normally distributed I am trying to fit an IV probit model with my dependent variable being binary. However, my endogenous variable is a "ratio" variable, which is not normally distributed, thereby preventing me from employing an IV Probit model. I am wondering whether employing LPM with 2SLS could help resolve the issue of non-normality of the endogenous variable? A: The only assumption required of the endogenous variable with this command is that it is continuous. You do not need normality for it, only for the errors in the two equations (which need to be multivariate normal and homoskedastic). You also can't leave anything out of the model. See here for more. Ratios are usually continuous, so you should not have a problem. This restriction comes from the fact that ivprobit is a control function estimator.
{ "pile_set_name": "StackExchange" }
Q: What is the word for "man cave"? In English, the term is used for a special room where a man sets things up for his own personal use and enjoyment, his private space for entertainment and hobbies. The room is decorated and used by the man. I found the term 男の洞窟 in definitions but it indicates an actual cave. I initially assumed that the term was written in katakana, because it is an English slang term, but was unsuccessful. I was searching for a term to indicate the emphasis on a special room where the man is the primary user. A: Personally I haven't seen this term being used around in Japanese literature much. The reason why might be because how small most housing is in Japan, the creation of a man cave would be somewhat luxurious. So there might be no real equivalent other than putting your manstuff in the same room as the bedroom or common space. That said: The easiest is to treat it as a loanword. マンケーブ seems to pop up a few results in a quick google. Weblio suggests the use of 男用{おとこよう}の部屋{へや}, which transmits the intent of a room aimed for male use. 趣味{しゅみ} instead of 男用 would transmit the hobby part albeit not specifying male use. Using a pronoun might help to identify exclusive use. 俺{おれ}の隠{かく}れ家{が} for "My man cave/hideout" could work, giving off the meaning of a space of retreat and relaxation. In the same vein, 俺{おれ}の秘密{ひみつ}基地{きち} might be good too, to give the vibe of a secret hideaway.
{ "pile_set_name": "StackExchange" }
Q: Difference between 「来ませんでした」and「来なかったです」 Possible Duplicate: Is じゃないです equally correct as じゃありません? Both have the same meaning ("did not come") and according to my Japanese co-workers both are acceptable while they can't define the difference. What is the (possibly obscure) difference in meaning between these two sentences? A: Not exactly the same question, but the answer applies as well: Is じゃないです equally correct as じゃありません?
{ "pile_set_name": "StackExchange" }
Q: Let A = {${(x, y) : 0 < x \leq 1, y = \sin (1/x)}$}, B = {${(x, y) : y = 0, 1 < x \leq 0}$} Let $A = \{(x, y) : 0 < x \leq 1, y = \sin (1/x)\}$, $B = \{(x, y) : y = 0, 1 < x \leq 0\}$, and let $S = A \cup B$. Prove that $S$ is not arcwise conneceted. Proof: Assume that $S$ is arcwise connected, then there exists a continuous function $g : [0, 1] \rightarrow S$ such that $g(0) = (0, 0)$ and $g(1) = (1, \sin (1))$ I do not know more... A: Proof. Suppose $f(t)=(a(t),b(t))$ is a continuous curve defined on $[0,1]$ with $f(t)\in A$ for all $t$ and $f(0)=(0,0)$, $f(1)=(\frac{1}{π},0)$. Then by the intermediate value theorem there is a $0<t_1<1$ so that $a(t_1)=\frac{2}{3π}$. Then there is $0<t_2<t_1$ so that $a(t_2)=\frac{2}{ 5π}$. Continuing, we get a decreasing sequence $t_n$ so that $a(t_n)=\frac{2}{(2n+1)π}$. It follows that $b(t_n)=(−1)^n$. Now since $t_n$ is a decreasing sequence bounded from below it tends to a limit $t_n→c$. Since f is continuous $\lim_{n\to\infty}f(t_n)$ must exist. But $\lim_{n\to\infty}b(t_n)$ does not exist.
{ "pile_set_name": "StackExchange" }
Q: HTML table alignment not working correctly I am currently creating a HTML email template. I have a table with 3 columns for the following: [[logo] [text content ] [date]] So the logo should be left aligned, and the date right aligned. However in outlook it doesn't look like the float is being accepted. this is how it currently looks. Here is my current code: <table cellspacing="0" cellpadding="0" border="0" style="display:flex; flex-wrap: wrap; margin-bottom:10px; width:100%;"> <tbody> <tr> <td width="6%"> <img style="float:left; margin-right:10px;" height="24px" width="30px" src="{{imageUrl}}"> </td> <td width="63%;"> {{this.notificationMessage}} </td> <td width="30%" style="text-align:right; margin-left:6px;">{{this.date}} </td> </tr> </tbody> </table> I have been stuck with this issue for sometime, any help is much appreiacted A: HTML should be coded as if it's the year 1999. Tables should be used for layout and the use of modern HTML and CSS is best avoided where possible. In your case above you should just use the align attribute on the table cell e.g. <td align=left"></td> <td align=right"></td> If that doesn't work then try using CSS e.g. <td style="text-align: left;"></td> Here's a good guide to creating HTML email template from Mailchimp: https://templates.mailchimp.com/getting-started/html-email-basics/ A: you can use Float: right and i think you should omit anything about flex ( i mean: display:flex; flex-wrap: wrap;). <html> <body> <table cellspacing="0" cellpadding="0" border="0" style=" margin-bottom:10px; width:100%;"> <tbody> <tr> <td width="6%"> <img style="float:left; margin-right:10px;" height="24px" width="30px" src="img.."> </td> <td width="63%;"> aa </td> <td width="30%" style="text-align:right;float:right; margin-left:6px;">bb </td> </tr> </tbody> </table> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Raw Types in Java I am working through a text book which has the following code: Entry<K,V>[] tempTable = (Entry<K,V>[]) new Entry[size]; When I compile with -Xlint, it says the Entry on the right is missing the type arguments. However, I cannot add the type arguments, as this would lead to generic array creation. I guess my question is two-part: I assume that the code in the text compiles correctly, so is there something I could do to make this work as is? What is the most elegant way to do this? A: Entry<K,V>[] tempTable = (Entry<K,V>[]) new Entry<?,?>[size];
{ "pile_set_name": "StackExchange" }
Q: Play audio from tableview and advance to next file in list I present the user with a table view of all the audio files listed in their documents directory of the app, alphabetically. I would like to allow advancing to the next track using headphones or the iPod audio controls built into iOS, but am not sure how to advance to whatever the next track is in the documents. My code to play it is to simply get the path to documents, and append it with the name of the row they click on in the table view. Is there a simple way to get the next file name from the path? A: You should probably get the contents of the folder in an array and then display it in a table after sorting. By this, every row points to a file in the array, which can be retrieved and played. To get the contents of a folder use the following line: - (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;
{ "pile_set_name": "StackExchange" }
Q: Simple .on('keydown') jQuery event not responding until next key is pressed I'm making a page for a friend and I have a hidden text field and when the user types the text is transposed into a div so that it looks like they're typing on the screen rather than in an input field. Here is a link to the page: http://merkd.com/godis.php Here is the function that I use to respond to the key strokes: $('#hiddenInput').keydown(function() { var input = $('#hiddenInput').val(); var html = '<div style="float: left;">'+input+'</div><div id="cursor">|</div>'; $('#typingArea').html(html); }); The text-field is visible right now so that you can see the problem. When text is entered or deleted, it doesn't respond until the next keypress. So if I type a single letter, nothing shows up until I type the next letter. I looked at the jQuery .on() documentation but I couldn't find anything on this. Any help is much appreciated. P.S. I know it should be in a separate question, but is there an easy way to make a text-field always in focus? I want to make it so that no matter where the user clicks or whatever, if they type, the text will still show up. A: Use .keyup() event because when you first press (keydown), the letter is never typed so the var html is getting previous value. For second part you can bind keypress event in document to focus your input field.
{ "pile_set_name": "StackExchange" }
Q: Oracle: SELECT statement GROUP BY clause I'm working with a table with structure like the following: (not my design, can't be changed) Columns: foreign_key job_type job_code 1 1 AA 1 2 BB 2 1 2 2 CC Values in job_type can only be 1 or 2. Values in job_code can be any varchar. I'm trying to get rows from this table in the following order: foreign_key job_type_1_code job_type_2_code My search query is like this: select foreign_key from my_table where ( job_type = 1 and job_code like 'D%' or job_type = 2 and job_code like 'in_job_2_code%' ) group by foreign_key The problem I have is that this returns job_code BB and CC when I'm expecting no results at all. How can I group these together so that the query will not return any result? A: Below query works if you always have records for both job types: SELECT a.foreign_key, a.job_code as job_type_1_code, b.job_code as job_type_2_code, FROM table_name a INNER JOIN table_name b ON a.foreign_key = b.foreign_key AND a.job_type = 1 AND b.job_type = 2
{ "pile_set_name": "StackExchange" }
Q: Explanation Borel set I'm getting totally crazy with the Borel set, I use this concept for maybe two years, but I still don't know what it really is. I would really appreciate if somebody could finally explain me what is a the Borel set. These are my question: Consider a measurable set $(X,\mathscr M,\mu)$ where $\mathcal T$ the topology of $X$. 1) The Borel set is such that $\mathscr B\subset \mathscr M$ and it's the smallest $\sigma -$algebra generated by all the element of $\mathcal T$. What does it mean? I agree that all element of $\mathcal T$ are in $\mathscr B$, and also all element of $$\{Y\mid \exists U\in\mathcal T: Y=X\backslash U\}$$ by definition of a $\sigma-$algebra, but I know that there is a lot of other set, for exemple, let take the measurable set $(\mathbb R,\mathscr M,m)$ where $m$ is the Lebesgue measure and $\mathbb R$ provide with it's usual topology. Why $[1,2[$ is in the Borel set ? 2) A consequence of the first question, how to prove in general that a set is in the Borel set (excepted if it's an open or a close set, it's clearly obvious) ? 3) What is the fantastic side of this set ? Evry body talks about the Borel set like something gorgeous, where is the genius there ? 4) Does the Borel set of $(X,\mathscr M,\mu)$ depend of $\mu$ ? Or only of the Lebesgue measure ? And is a Lebesgue measurable set is always $\mu-$ measurable ? 5) By the way why a $\sigma -$algebra is called a $\sigma -$algebra ? What the $\sigma $ mean ? I hope my questions are clear. I'll probably complete this post in the future, and when I'll have more answers. A: Lets look at this in a more intuitive way: A collection of sets $\{E_k\}$ forms an algebra if the collection is closed under complements and finite unions. The collection of sets forms a $\sigma-$algebra if the collection is closed under complements and countable unions. A Borel set is any set in a topological space that can be formed from open sets (or, equivalently, from closed sets) through the operations of countable union, countable intersection, and relative complement. This includes any open set, any countable intersection of open sets (known as $G_\delta$ sets), any closed set, any countable union of closed sets (also known as $F_\sigma$ sets), $G_{\delta\sigma}$ sets, $F_{\sigma\delta}$ sets, etc... Now the set $[1,2[$ is a Borel set because $$ [1,2[=\bigcup_{k=1}^\infty \left[1,2-\frac{1}{k}\right] $$ which makes $[1,2[$ a $F_\sigma$ set and hence a Borel set. In general, if a set is neither open nor closed, but Borel, you should be able to create either a $F_\sigma$ set or a $G_\delta$ exactly equal to the set in question, as I did above. Let $X$ be a set and let $\mathcal{P}(X)$ be the power set of $X$, then the collection $\mathcal{B}\subseteq\mathcal{P}(X)$ that consists of all Borel sets from $\mathcal{P}(X)$ forms a $\sigma-$algebra of sets and is the smallest possible collection that can do so collection that forms a $\sigma-$algebra and contains all the open sets from $\mathcal{P}(X)$. In other words, every possible $\require{enclose} \enclose{horizontalstrike}{\sigma-}$algebra that can be formed from $\enclose{horizontalstrike}{\mathcal{P}(X)}$ must contain $\enclose{horizontalstrike}{\mathcal{B}}$ the intersection of all $\sigma-$ algebras that contain the open sets is the Borel $\sigma-$algebra. This is what makes Borel sets so special; they are the skeleton of any $\enclose{horizontalstrike}{\sigma-}$algebra, for lack of a better phrase., especially from a topological standpoint. If you notice in the above discussion, nowhere does the concept of measure become involved. In the case of the Lebesgue measure on $\mathbb{R}$, it turns out that the collection of measurable sets forms a $\sigma-$algebra. But this is simply a consequence of restricting the outer measure to the collection of sets for which countable additivity holds. Now since the collection of measurable sets forms a $\sigma-$algebra, then it must be that every Borel set in $\mathcal{P}(\mathbb{R})$ is measurable as well. And while it is not immediately obvious, there do exist non-Borel sets that are measurable. Thus not all measurable sets are Borel. This is an important distinction! A: To add some informal comments to what was already mentioned here, the word "algebra" is somewhat unfortunate, as the algebraic structure (in the abstract algebra sense) comes from treating the symmetric difference of two member sets as addition, while intersection serves the role of multiplication; however, we are mostly concerned with unions instead of symmetric difference (not all the time-check Littlewood's First Principle!). In this sense, an algebra of sets is a formal Boolean algebra. This is because the intersection (or "multiplication") of any set with itself always returns the set you start with, i.e. $x*x=x$ for all $x$ in the collection. The members of an algebra must include finite unions and complements of members you know are there, as well as the parent set itself. The word "sigma" means that countably infinite unions of members must also themselves be members. Set algebras not specified as "sigma" algebras can exclude countable unions while still remaining algebras. Think of finite subsets of the natural numbers and their respective complements - you can take finite unions all day and your results will be members of this collection, but you would never get the set of all odd natural numbers, so the set of odd natural numbers is not a member of this algebra; but, the set of all odd natural numbers IS a countable union of elements in this set. Since complements are included in algebras, the intersection of any two members of an algebra must be in the algebra, since $A\cap B=\left(A^c \cup B^c\right)^c$. Likewise, countable intersections of members of sigma-algebras are always themselves members of the sigma algebra (in other words, a sigma-algebra is "closed" under countable intersection). With the Borel sigma algebra, the definition "the smallest sigma algebra containing the open intervals" (or open sets; recall, every open set is a countable union of open intervals, though) is somewhat difficult to understand at first glance, and in my opinion is given because it is more formal than defining the Borel sets by activity - i.e. "generating" by any combination of intersection, union, and complements of open sets. It is important to keep in mind, by the way, that Borel sets are more than just countable unions and intersections of open and closed sets. There are countable unions, intersections, complements, etc. of the sets you've mentioned that are also Borel; since a sigma-algebra includes a countable union of members as itself a member of the collection, and likewise with countable intersections of members, then we can take e.g. a countable intersection of a countable union of members and return a Borel set. The "Borel hierarchy" article on Wikipedia is a good exposition of this. Back to the "smallest sigma algebra" definition. Think of it this way: if a sigma algebra includes all open intervals, it must include all complements, countable unions, and countable intersections of open intervals applied in any combination you choose, i.e. EVERY sigma algebra including the open intervals must include such sets, because of the fact that we are considering a sigma algebra in general in the first place (no matter what other members not having to do with open sets happen to be lurking around). On the other hand, if a certain set is included in every single sigma-algebra that includes the open sets, it must be some cut-and-paste operation of unions, intersections and complements on the open sets, because if it is not such a set, it fails to belong to every sigma algebra that includes the open sets; namely, by our very assumption, it fails at least to belong to the sigma-algebra arising only from operating with unions, intersections and compliments on open sets! Hopefully, this clears up the "smallest sigma algebra" characterization for you. As another poster mentioned, the Lebesgue measurable sets include members that are not Borel sets, i.e. cannot be "made" by operating on open sets via complements, and countable unions and intersections. Additionally, there are sets that are not Lebesgue measurable at all (the Vitali set, for instance), in fact every Lebesgue measurable set of positive measure includes a non-measurable subset! Non-Borel measurable sets can be reached in this way; the Cantor set, a set of zero Lebesgue measure, can be mapped via a measurable function to a set of positive measure. Such a set, as mentioned before, contains a nonmeasurable set. Consider the inverse of our measurable function operating on this nonmeasurable subset, and you will get a subset of the measure zero Cantor set, hence you will get a (hopefully) measurable subset (of measure zero). This means a measurable function can, counterintuitively, map a measurable set to a nonmeasurable set. But it cannot map a Borel set to a nonmeasurable set. So we are stuck with a Lebesgue measurable set (of measure zero!) that is not Borel. This is, in fact, why Lebesgue measurable sets are needed rather than just strictly sticking to Borel sets only. If we did the latter, we should hope that all subsets of a set of zero measure are themselves measurable with zero measure, but if we only consider the "easy" Borel sets as the measurable ones, we are hit with the inevitable problem of dealing with the fact that there are zero-measure sets with subsets that aren't even measurable (in that they are not Borel) at all. Lucky for us, Caratheodory verified that a "complete" extension of the standard Borel measure (i.e. the measure that reports the length of intervals) exists that can return a zero measure for every subset of a zero measure set, while still preserving measurements we expect on Borel sets. This is, as you may guess, exactly the Lebesgue measure. The Borel sets are special for the reasons I've already mentioned - they are, intuitively, "elementary" in construction, while non-Borel sets (measurable or no) are typically described in a roundabout way in the context of Lebesgue measure. One can, however, represent every Borel set, at base, as some conglomeration of unions, intersections, and compliments, of open intervals. They may not "look" elementary, e.g. this apparently nonsensical set: $$\bigcap_{k=1}^\infty \bigcup_{n=1}^\infty \bigcap_{i=n}^\infty \bigcap_{j=n}^\infty \{x:\left|f_i(x)-f_j(x)\right|<\frac{1}{k}\}$$ While daunting at first appearance, this is just symbology for the set of points where the sequence of functions converges in the Cauchy sense, with intersection and union standing in for "all" and "there exists (at least one)", respectively: for all $k$ there exists an $n$ such that for all $i,j\geq n$, the distance between $f_i$ and $f_j$ at this point is less than the given "epsilon" bound $1/k$. This set itself is Borel (hence measurable) as it is a porridge of intersections and unions of Borel sets.
{ "pile_set_name": "StackExchange" }
Q: How to send a query to the database using GET through an REST API (Ruby on Rails) I would like to add a query parameter to a GET request such a way that my REST API returns the query's result instead of the result from default index method. Is this possible? Here is my index method: def index users = User.all render( json: ActiveModel::ArraySerializer.new( users, each_serializer: Api::V1::UserSerializer, root: 'users' ) ) end I would like to have an additional method named my_new_index executable by a GET or I would like to have a query submitted as a parameter to the default index method, lets say something like this: query = "select * from users where name like 'A%' order by name desc" A: I'm not sure I understand exactly what you're trying to do but what I would suggest is using the same end point index to return your content filtered. First I'll start by creating a scope like: scope :starting_with, ->(letter) { where('users.name like ?', "#{letter}%") if letter } Then update you index end point to something like: def index users = User.starting_with(params[:letter]).all render( json: ActiveModel::ArraySerializer.new( users, each_serializer: Api::V1::UserSerializer, root: 'users' ) ) end In this quick example the end point receive the params, if it contains a letter params, it will render users filtered by the scope query. If the param is not present, it return all users. FYI it's just a quick example and not perfect, I'm sure you could find ways improve it. Hope it helps :)
{ "pile_set_name": "StackExchange" }
Q: Keras optimizing two outputs with a custom loss I've been recently trying to implement a model, which can be described as following: Given an input matrix and a set of targets, let the model learn, simultaneously, the matrix representation, as well as the targets via a custom loss function. The architecture (simplified): input_matrix = Input(shape=(i_shape,)) layer1 = Dense(100)(input_matrix) output = Dense(3)(layer1) autoencoder_mid = Dense(100)(input_matrix) autoencoder_output = Dense(i_shape)(autoencoder_mid) My idea of a loss function: def customLoss(true_matrix,pred_matrix): def combined_loss(y_true,y_pred): return K.abs(y_true-y_pred) a = K.mean( K.square(y_pred - y_true) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((y_true - 3)/5 )))),axis=-1 ) b = K.mean( K.square(pred_matrix - true_matrix) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((true_matrix - 3)/5 )))),axis=-1) return a+b return combined_loss I compile the model as: net = Model(input_matrix, [output,autoencoder_output]) net = net.compile(optimizer='adam', loss=customLoss(true_matrix=X,pred_matrix=autoencoder_output)) Where I try to fit the network with a standard: net.fit(X, target, epochs=10, batch_size=10) The error I get is: ValueError: Tensor conversion requested dtype float32 for Tensor with dtype float64: 'Tensor("loss/dense_4_loss/Log_3:0", shape=(389, 3890), dtype=float64, device=/device:GPU:0)' My question is, is there any other way of doing this? If so, could you please point me towards a possible solution. Thank you very much. A: You can try this: def customLoss(true_matrix): def combined_loss(y_true,y_pred): y_pred, pred_matrix = y_pred ... return combined_loss net = Model(input_matrix, [output,autoencoder_output]) net.compile(optimizer='adam', loss=customLoss(X)) As the original y_pred will be a touple with (output,autoencoder_output). Concerning the double return, the function will only return the first one, so I'd remove one of the two return lines or combine the two outputs such as: alpha = 0.5 beta = 0.5 ... loss1, loss2 = K.abs(y_true-y_pred), a+b return alpha*loss1 + beta*loss2 Changing alpha and beta upon convenience. Thus, the whole thing could be: def customLoss(true_matrix, alpha = 0.5, beta = 0.5): def combined_loss(y_true,y_pred): y_pred, pred_matrix = y_pred a = K.mean( K.square(y_pred - y_true) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((y_true - 3)/5 )))),axis=-1 ) b = K.mean( K.square(pred_matrix - true_matrix) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((true_matrix - 3)/5 )))),axis=-1) loss1, loss2 = K.abs(y_true-y_pred), a+b return alpha*loss1 + beta*loss2 return combined_loss net = Model(input_matrix, [output,autoencoder_output]) net.compile(optimizer='adam', loss=customLoss(X))
{ "pile_set_name": "StackExchange" }
Q: Git Workflow Questions So, I know this has been asked to death, but in all of my countless hours of searching I've yet to figure this out completely. So here's the workflow I have: Production (live) environment is only updated with patches as needed. Dev environment (on same server as production, different docroot) are the files currently being worked on My local repo which is currently cloned from the Dev environment, but I would like to manage production in another cloned repo using Phpstorm Production and Dev are two completely different deployments, they cannot be merged at the moment as too much is different and it would render production unusable. We are doing some major overhaul in Magento and trying to isolate Dev and Production into their own branches, so neither will have anything to do with each other until the next version release. I'm having major issues with Github integration. When I run git push origin dev or git push origin production, when I go to github to check the changes I am seeing message changes in all 3 branches, and I don't want this happening at all, even if it is metadata on the folders, and not the files themselves being changed. One should have nothing to do with the other until merged. This is getting very frustrating as I don't want either branch to even TOUCH master, until I'm ready to merge anything. I want to be able to pull dev branch to the Dev environment, production branch to Production environment, and have both branches as separate repos on my local system that I can edit each individually. Any advice is greatly appreciated. A: After further research I found the reason why branches were getting mixed up was because I was not using checkout before committing, if its a new local working tree, the remote must first be pulled, then I unzipped a tarball of the modifications to dev on top of the master branch pull, checked out dev, then committed and pushed without issues. Here's a great pdf of github workflow for those interested. http://ftp.newartisans.com/pub/git.from.bottom.up.pdf Also thanks to bish for his helpful article as well.
{ "pile_set_name": "StackExchange" }
Q: Hash of Hash in C I'm kind of new in C because moving back to that after 6 years! wanna Implement a code to store tree for this data like this : string1 = "foo.bar.foo.\*" string2 = "foo.baz.\*" string3 = "foo.\*.bar" foo | | | | bar baz * | | | foo * bar | * trying to do this with HashTable : struct entry_s { char *key; struct entry_s *value; struct entry_s *next; }; but I dont think it works, what is the best way to do that and even though is Hash Map the best data structure that could be used in C? A: It seems that you want to implement a map with two levels: The first level maps strings to second-level maps and the second-level maps another key to a value. For example, in Javascript syntax: data = { "London": { "Paris": 450 }, "Paris": { "Madrid": 600, "Algiers": 700 } } There are several ways to achieve this. Javascript variables carry their types with them, so yozu can use the same Map implemantation for both levels. In C, you could implement two hash tables with different value types, e.g.: struct OItem { // Outer map item const char *key; // string key struct IMap *value; // inner map value struct OItem *next; }; struct OMap { // Outer map struct OItem *head[oSize]; // hash table }; struct IItem { // Inner map item const char *key; // string key int value; // integer value struct IItem *next; }; struct IMap { // Inner map struct IItem *head[iSize]; // hash table }; This will give you the two-level structure above. (These hash tables have fixed sizes, so that you might end up wasting a lot of space when for example the second-level maps are sparse. Perhaps it might be better to use just a single list or a balanced tree here. If you use the second-level map just emulates an object that always hash the same or similar data, consider using a struct here.) You can use this structure and lookup("London", "Paris"), for example. If you don't need access to the inner map, you could also pack both levels into one big hash table by using two keys: struct Item { const char *key1; const char *key2; int value; struct Item *next; }; struct Map { struct Item *head[hSize]; }; When you calculate a hash, use both keys, for example: static unsigned int hash(const char *s1, const char *s2) { unsigned long hash = 5381u; while (*s1) hash = hash * 33 ^ *s1++; hash = hash *33; while (*s2) hash = hash * 33 ^ *s2++; return hash; } When you look up an item, ensure that both keys match: int map_find(const struct Map *map, const char *k1, const char *k2) { unsigned int h = hash(k1, k2) % hSize; struct Item *item = map->head[h]; while (item) { if (strcmp(item->key1, k1) == 0 && strcmp(item->key2, k2) == 0) { return item->value; } item = item->next; } return 0; } This approach is perhaps more restrictive, but has the advantage that you don't have many potentially oversized hash tables, but just one data structure. Finally, whatever you do, don't use the hash table implementation you found on GitHub. The author admits that it was more of a coding exercise. It doesn't deal with releasing the memory after use and has a poor hash function. After you edited in your actual use case, it is clear that you want a trie. You can implement a trie as you suggested. The keys and values can be anything in your implementation, so they can also be strings and trie nodes. You can adappt your existing implementation to use a pointer to a trie node structure as values. (All the comparison stuff stays the same, fortunately.) One problem I see is that with a fixed hash-table size, you will end up wasting a lot of space. If your trie is sparse, it might be better to just use a linked list or a balanced binary tree as map. In any case, you will have to find a suitable lib or roll your own.
{ "pile_set_name": "StackExchange" }
Q: Will OSGI equinox install copy jar to its own folder I an curious of what installing a bundle into Equinox is supposed to do: Will it actually copy my jar to somewhere inside Equinox folder so that when I delete my jar, it will not affect the installed bundle? A: When a bundle is installed (in any OSGi framework), it is persisted in the bundle cache. So yes, you can delete your JAR after installing it. The framework will remember what bundles were installed (and started) across restarts of the framework.
{ "pile_set_name": "StackExchange" }
Q: gdb command files error "Invalid type combination" in while loop I wrote following commands in my gdb command file. while ($i < 3) s end I got the error: Invalid type combination in ordering comparison. Then I tried, the following: while (((int) $i) < ((int) 3)) s end But then I got the error: Invalid cast. How to write a loop in gdb command file? Note: i is the variable in my C program being debugged that is referred as $i in the command file. I couldn't find any examples at this site, which gives some reference material on gdb. A: First, I think it is more appropriate to use watch i >= 3 In order to break when i becomes more than 2. As for looping until a local varible in C is less than 3. This is a gdb script for it: while (i < 3) s end This in C++ code to demonstrate a gdb loop: #include <stdio.h> int main() { for (int i=0; i< 10; ++i) { printf ("i: %d\n", i); } return 0; } This is a gdb test: D:\>gdb -q a Reading symbols from D:\a.exe...done. (gdb) start Temporary breakpoint 1 at 0x401395: file main.cpp, line 4. Starting program: D:\a.exe [New Thread 3780.0x144] Temporary breakpoint 1, main () at main.cpp:4 4 { (gdb) n 5 for (int i=0; i< 10; ++i) { (gdb) 6 printf ("i: %d\n", i); (gdb) while (i<3) >s >end i: 0 5 for (int i=0; i< 10; ++i) { 6 printf ("i: %d\n", i); i: 1 5 for (int i=0; i< 10; ++i) { 6 printf ("i: %d\n", i); i: 2 5 for (int i=0; i< 10; ++i) { 6 printf ("i: %d\n", i); (gdb) p i $1 = 3 (gdb)
{ "pile_set_name": "StackExchange" }
Q: findViewById won't work in InputMethodService, what do i do? I'm trying to create an android keyboard, this code works fine so far package keyboard.rob.com; import... public class xyz extends InputMethodService implements KeyboardView.OnKeyboardActionListener { private LinearLayout mInputView; @Override public View onCreateInputView() { mInputView = (LinearLayout) getLayoutInflater().inflate(R.layout.main, null); return mInputView; } ... but later on when I'm trying to make LinearLayout LinLayBg = (LinearLayout)findViewById(R.id.LL_total); to populate it with buttons, it show "*The method findViewById(int) is undefined for the type zyz *" Any ideas? Thanks! A: i think you are trying to call the method findViewById(int id); from a non instance of a View . Try : mInputView.findViewById(R.id.LL_total); hope it helps A: You should be able to do it this way: View.findViewById(R.id.LL_total);
{ "pile_set_name": "StackExchange" }
Q: Magento: Proper way to iterate over a Varien Object collection If I were to create a collection that would retrieve all products belonging to category with a given ID, as below: $storeId = Mage::app()->getStore()->getId(); $product = Mage::getModel('catalog/product'); $category = Mage::getModel('catalog/category')->load(39); $catName = $category->getName(); $visibility = array( Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG ); $products = $product->setStoreId($storeId) ->getCollection() ->addAttributeToFilter('visibility', $visibility) ->addCategoryFilter($category) ->addAttributeToSelect(array('name'), 'inner') ->setOrder('name', 'asc') ; $collection = $products; How would I then iterate over the collection and access each item's data, item being a product in this case. I would have expected something like the below to give me each items available data but doesn't seem to work: foreach ($collection as $key => $value) { var_dump($value->getData()); } A: You're close. Try doing foreach ($collection as $obj) { echo $obj->getName(); }
{ "pile_set_name": "StackExchange" }
Q: Downvotes com comentários linkados Ao notar tantas reclamações e sugestões e mesmo que digam que é o crescimento da comunidade parece estar um tanto evidente que os votos não são bem usados por uma parte dos usuários e aqueles que sabem votar ficam com medo de comentar (justificar) votos negativos com medo de retaliação (serial downvoter), alguns exemplos das ultimas semanas: Surgiram sugestões de novo-recurso para tentar resolver o suposto problema: Notificação de votos negativos Deveríamos qualificar os votos? Votos negativos deveriam ter custo mais alto? E também ouve duvidas para entender o suposto aumento: O que está acontecendo com os votos negativos? Minhas perguntas são tão ruins assim? Quem está votando? (esse é meio que uma sugestão novo-recurso, mas parece ser mais voltado a uma duvida) A minha sugestão para não apenas coibir o mal uso, mas também para fazer nós que queremos dar criticas construtivas e justificar o downvote seria um comentário padrão ou customizado anonimo semelhante a janela de fechamento, a ideia não é reduzir os downvotes, mas na verdade tornar evidentes os votos negativos que são justos sem parecer que eles foram arbitrários (eu mesmo gostaria de saber os problemas nas minhas postagens com votos negativos para poder melhorá-las e até removê-las se necessário). Seria assim: No momento que clico em negativar, aparece uma janela assim (suponha que ele selecionou a primeira opção): Após o downvote o comentário ficaria anonimo e ficaria assim: Se outro usuário vier a votar também e selecionar a mesma opção (Código não funciona) então não será adicionado um novo comentário, ambos downvotes ficarão vinculados ao mesmo comentário e ele ficará assim: Se um terceiro usuário votar e selecionar a opção Mal escrito, então ficará assim: Se um quarto usuário votar e selecionar ultima opção (do campo de texto) ele poderá digitar um comentário personalizado e anonimo. Desta forma o usuário iria poder se expressar sem ter medo de sofrer ataques de pessoas imaturas que não entendem bem o sistema ou que se acham injustificadas e começam a dar downvotes gratuitos. Outra opção também seria poder reverter os downvotes, mas somente em último caso, a ideia seria uma flag que abriria um pop-up e quem discorda dos votos negativos poderia talvez mandar para a fila de analise (usuários com 500 pontos podem analisar) e lá seria julgado se os votos fazem sentido, uma espécie de triagem. Nessa triagem seria no minimo 3 de 5 votos para reverter os downvotes, se houver 3 votos pra reverter o "comentário anonimo" ligado ao downvote seria removido junto, se forem 2 votos pra reverter e 3 para manter, então nada acontece. (note que os comentários ainda seriam anônimos mesmo pra quem tem acesso a fila, eles só participariam da triagem) A tela seria algo como: A: Discordo. A pergunta começa com uma opinião não substanciada por nenhum exemplo sólido no site principal: parece estar um tanto evidente que os votos não são bem usados por uma parte dos usuários Creio que o meta-drama de alguns poucos usuários assíduos não implica um fenômeno global. Me parece uma complicação extrema ficar explicando uma porcaria dum simples voto. Isto não é o Prêmio Nobel e já temos suficiente com analisar, editar, filtrar, votar, comentar de bom coração... enfim, moderar um monte de conteúdo alheio. Comentários são um sub-produto do site, seu status é de "conteúdo de segunda-classe", e, se tivermos que jogar isso numa fila de análise, vai ser tipo estudar Gases Intestinais quando podiamos estar estudando Alimentação Saudável. Essa história de que o voto negativo "precisa de conserto" (o novo meme do SOpt) é muito simples de resolver: me dá uma lista onde aparecem os posts que foram editados depois do meu voto, adoraria rever uns quantos. [*] O medo de comentar também é simples de resolver: nosso comentário deve se concentrar em como a pessoa pode melhorar seu post. Ponto. Se for usar algum adjetivo, que seja positivo. Só criticar ou linkar pro FAQ é fácil, mas no fim oferecer uma dica útil também é fácil. Talvez um smilie no fim do comentário dissipe qualquer má-interpretação ;) Ficar choramingando porque "Nossa! Minha pergunta/resposta é tão legal, tinha X votos positivos e Zero negativos, e agora tem Um negativo"... bah, give me a break. Dica de veterano: se algum dos seus posts estava em 0 e tomou um voto de vingança, esse mesmo post vai ser o alvo preferido pro seguinte voto de vingança (obviamente, de outra pessoa). Esse é o preço a pagar por verbalizar certas coisas. Façam o favor de engolir o orgulho e assumir o prejuizo (ridículo, no grande esquema das coisas). O sistema automático não registra isso, reclamar com os moderadores não vai adiantar nada, abrir uma meta pergunta é perda de tempo. [*] - Notification on edit of downvoted content - Allow an edit to notify downvoters: “I think I've fixed the issue now - please check”
{ "pile_set_name": "StackExchange" }
Q: Jquery JSON decode multiple arrays I have this multiple set of data as array data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....] I need to get this data using jQuery json = $.parseJSON(data); but how do I access the parsed JSON data? json.id shows the result as undefined. Thanks Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :) A: It isn't JSON. It isn't even JavaScript. If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings). Since it is an array. It doesn't have an id. It has a number of numerical indexes. var someObject = data[0]; The objects stored on those indexes have ids. var id = someObject.id;
{ "pile_set_name": "StackExchange" }
Q: Could Removing A Nintendo Game Boy Game While The Console Is Powered-On Do Any Damage? I've looked all over the Internet to try to find an answer to this, but I can't. I want to know if removing a Nintendo Game Boy game while the console is powered on will do any damage, like rendering the cart and/or console unusable. I don't think it will cause any damage, seeing as most games have volatile RAM and should go back to normal when inserted into the Game Boy again and powered on, but I'd like an actual source. Also, I understand that with a standard Game Boy and game, removing the game while the console is on is impossible, due a plastic arm sliding over to cover the game when the power switch is moved. This is assuming I'm using another Game Boy product that doesn't have that feature, such as the Game Boy Color, or an original model modded to remove the arm. A: What's up? No, not beyond save data corruption. In fact, the Game Boy's big brother console, the Nintendo 64 had games that planned on using live cart swapping as a feature, to link games (most famously with Banjo Kazooie/Banjo Tooie), but it was scrapped due to other concerns (essentially ram being too volatile for it to work reliably). There is one caveat: Poorly designed cartridges could be knocked out of commission by corrupted save data alone. Note also: All of this applies to the OG Game Boy, the Color, the Pocket, the Advance and consoles NES, SNES and N64. From DS onwards, the system is designed specifically to detect cartridge removal and handle it gracefully; and the GC/Wii (U) don't use cartridges anymore. So... why? The question is, of course, why do these systems tolerate this at all? The basic reason is that in straightforward terms: There's nothing there to damage. The consoles mentioned above are, in essence, just a circuit board with a processor on it, some ROM chips that provide libraries, some volatile RAM, I/O, and a power supply. There's no OS or persistent storage or really anything else. When a cartridge is plugged in, it's plugged into what essentially works as an expansion slot on this board, providing the bulk of the actual executable code in ROM, as well as anything else the cartridge might need (such as flash or battery RAM memory for save files). Most of the systems have physical barriers to removing the cartridge (usually the power button engages a lever that inserts itself into a groove in the cartridge, preventing it from being removed (or inserted) while the power is on). The first console Nintendo shipped without a physical barrier like this was the Game Boy Color, which allows a cartridge to be hot swapped; as far as I recall it detects this situation and gracefully shuts down when this happens. This is likely a feature that wasn't present in the earliest Game Boys or home consoles due to the physical barriers simply being easier to implement; but the proliferation of different-shaped Game Boy cartridges made the existing safeguards ineffectual or counter-productive, and the console was made to detect the situation and handle it instead. In any case, the simplicity of design means that there's not really anything for pulling out a cartridge to damage in any meaningful way; which is a premium design feature in a product designed to be roughed around by kids.
{ "pile_set_name": "StackExchange" }
Q: Can not access array elements after transferring the array from Device to Host in CUDA I set up CUDA 6.5 and I'm just trying to run a very basic code. What I'm trying to do is to copy an array from host to device and then copy it back from device to host. int *d_mandelbrot_set; int a[5] = {1,2,3,4,5}; cudaError_t cudaStatus; // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&d_mandelbrot_set, 5 * sizeof(int)); if (cudaStatus == cudaSuccess) cout << "Success\n"; cudaStatus = cudaMemcpy(d_mandelbrot_set, a, 5 * sizeof(int), cudaMemcpyHostToDevice); if (cudaStatus == cudaSuccess) cout << "Success\n"; int *h_mandelbrot_set; cudaStatus = cudaMemcpy(h_mandelbrot_set, d_mandelbrot_set, 5*sizeof(int), cudaMemcpyDeviceToHost); if (cudaStatus == cudaSuccess) cout << "Success\n"; for (int k = 0; k < 5; k++) cout << h_mandelbrot_set[k] << " "; // THIS IS WHAT GIVES THE RUN TIME ERROR But when I try to access elements in h_mandelbrot_set array, it gives a run time error. A: Well, you only defined a pointer (int *h_mandelbrot_set;). Before, calling last cudaMemcpy, you need to allocated memory for this pointer. The following code will work. However, in general, you may like to allocate memory dynamically. int *d_mandelbrot_set; int a[5] = {1,2,3,4,5}; cudaError_t cudaStatus; // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&d_mandelbrot_set, 5 * sizeof(int)); if (cudaStatus == cudaSuccess) cout << "Success\n"; cudaStatus = cudaMemcpy(d_mandelbrot_set, a, 5 * sizeof(int), cudaMemcpyHostToDevice); if (cudaStatus == cudaSuccess) cout << "Success\n"; int h_mandelbrot_set[5]; cudaStatus = cudaMemcpy(&h_mandelbrot_set, d_mandelbrot_set, 5*sizeof(int), cudaMemcpyDeviceToHost); if (cudaStatus == cudaSuccess) cout << "Success\n"; for (int k = 0; k < 5; k++) cout << h_mandelbrot_set[k] << " "; // THIS IS WHAT GIVES THE RUN TIME ERROR
{ "pile_set_name": "StackExchange" }
Q: Objective-C ARC and Instance Variables iOS SDK Are we supposed to convert all of our instance variables we wish to retain to private properties or am I missing something obvious? @interface SomethingElse : Something { NSMutableArray *someArray; } In this example, someArray is initialized in a method with [NSMutableArray initWithObject:someObject] but isn't retained. My particular situation is I'm updating a game, there are a lot of instance variables, so I want to make sure I'm doing this right for the sake of future versions of the sdk. A: Are we supposed to convert all of the local variables we wish to retain to private properties or am I missing something obvious? First, the variable you showed in your example is an instance variable, not a local variable. Local variables are declared inside a block of code (e.g. inside a function or method, or inside some sub-block such as the body of a conditional statement) and have a lifetime that's limited to the execution of the block in which they're declared. Instance variables are declared in a class; each instance of that class gets its own copy of the instance variables declared by the class. Second, no, you don't need to convert all your instance variables to properties. Instance variables are treated as strong references by default under ARC. A property is really just a promise that a class provides certain accessors with certain semantics. Just having an instance variable doesn't mean that you have to provide accessors for that ivar. (Some might say that you should, but you don't have to.) A: A @property is the same as an instance variable unless you use other than the default storage modifier, which is strong for objects. Example, if you want @property (copy) NSString *s; either use an instance variable and remember to call copy each time you set the variable, or use the @property (which is easier).
{ "pile_set_name": "StackExchange" }
Q: Print a BST in the REPL? I'm trying to get a binary search tree's struct print function as below to print out a node (with its children, recursively) in an xml-ish style. The idea being that adding appropriate indentation should make it easier to see the structure of the BST. What I have currently is: (defstruct (node (:print-function (lambda (n s d) (format s "#<~A ~A ~A>" (node-elt n) (node-l n) (node-r n))))) elt (l nil) (r nil)) This prints out a BST as, for example: #<5 #<4 #<2 #<1 NIL NIL> #<3 NIL NIL>> NIL> #<8 #<6 NIL #<7 NIL NIL>> #<9 NIL NIL>>> But I'd like something from which it is easier to visualise the tree structure. I have something like this in mind: #<5 #<4 #<2 #<1 NIL NIL> #<3 NIL NIL>> NIL> #<8 #<6 NIL #<7 NIL NIL>> #<9 NIL NIL>>> Assuming my goal is a good one, the indentation depth of each line must depend on the depth of the recursion. I'm not sure how to do that within the format form above. Actually, maybe this isn't a very good way to display it after all. If not, what is a good way to print out a (small, of course) binary search tree in the REPL, such that one can easily see its structure? (as a tool to help with algorithm development). Thanks. A: You can use logical blocks. (defstruct (node (:constructor bst (elt &optional l r)) (:print-function (lambda (n s d) (declare (ignore d)) (format s "(~s ~@<~s ~_~s ~_~s)~:>" 'bst (node-elt n) (node-l n) (node-r n))))) elt (l nil) (r nil)) When you call PPRINT-LOGICAL-BLOCK, the stream being used becomes a pretty-printing stream during the extent of the block (if it is not already one). Functions that start with pprint- like pprint-newline or pprint-indent respect indentation levels, logical blocks, etc. Usual functions like  terpri or fresh-line do not. The above format defines a logical block after bst, and prints conditional newlines between each element. The added value of this particular printer is that it prints the form readably. Input Thanks to the :constructor option, we can write a BST as follows: (bst t (bst 1 (bst :x) (bst :y)) (bst 2 (bst :a) (bst :b))) Printed result When evaluated, the resulting tree is printed in a way that can be read back to produce an equivalent tree. (BST T (BST 1 (BST :X NIL NIL) (BST :Y NIL NIL)) (BST 2 (BST :A NIL NIL) (BST :B NIL NIL))) Alternative printer You could also define a printer that just prints the form using an intermediate list. This is simpler to write and relies on existing pretty print functions. (defstruct (node (:constructor bst (elt &optional l r)) (:print-function (lambda (n s d) (declare (ignore d)) (princ (list 'bst (node-elt n) (node-l n) (node-r n)) s)))) elt (l nil) (r nil)) Output for modified printer (BST T (BST 1 (BST X NIL NIL) (BST Y NIL NIL)) (BST 2 (BST A NIL NIL) (BST B NIL NIL)))
{ "pile_set_name": "StackExchange" }
Q: Securing a LAN that has multiple exposed external Cat 6 cable runs? We're evaluating putting in an IP-based CCTV system for a third-party upcoming project (part of a wider networking project). The CCTV system is cabled as follows: Cat 6 running from each external camera to a POE switch, patch cable from switch to NVR (network video recorder basically HDD enclosure that records the CCTV). My concern is that there will be multiple long external Cat 6 runs that are essentially very easy entry points into the network. All some one would need to do is cut the cable, put RJ45s on both ends of the cut, place a small switch in-between and then patch themselves into the switch... Apart from the couple of minutes downtime, the CCTV camera could even carry on working. What can I do to secure the network? I can't just not connect that switch to the rest of the LAN because there are third-party apps (home automation controllers like Crestron) that we use that sit on the local network and access the NVR as well as other local area network-attached devices. A: Options that come to mind: Use a Managed Switch to provide access control by physical port. For each physical port, only a specific IP address can be allocated (i.e. that of the camera) This may help detect attacks because if the attacker tries to create an IP conflict to access the rest of the LAN then that will likely interfere with the camera connection. More advanced attackers can probably avoid such detection though. For each IP we now know it can only come from a particular physical port. We then create access control lists by destination IP and TCP port number. Ideally the cameras should use HTTPS and that your receiving station is secured against MiTM by verifying the camera's HTTPS certificate fingerprint. At the very least the cameras should have some kind of authentication before releasing their video stream and configuration interface. If modern WiFi is an option it has a built-in authentication before accessing the LAN based on a shared secret. However, it can be DoSed wirelessly and its security is less easily validated by another party. (proving physical cables secure is easier than proving that a shared secret was not compromised) I've heard of an authentication method designed for restricting Ethernet use but I'm not sure its scope (or if your camera supports it) or whether it will help you without updating all the other devices on the LAN. Perhaps a Managed Switch would help contain the need for updating configuration. Overall review the security of the other devices on your LAN. Windows computers should treat the networks as Public Networks so they do not assume trust. Each device on your LAN should be considered and secured. Of course do not leave any default credentials in place. The passwords must be reset on all new devices both for the CCTV and other devices on your LAN. Don't forget physical barriers :-) A: Put your cameras and video recorder on a separate network segment, and bridge them through a firewall that would allow internal devices to talk to the video recorder while preventing anything on the untrusted side of the network from talking to the other side. This can easily be done with a Linux/BSD machine (with IPtables/PF) and I'm sure there are commercial routers like Cisco or Ubiquiti that would do the trick as well. If your cables end up at a physically secure location before going to the cameras you could also use IPSec with a small server at both ends to encrypt the traffic that goes over the insecure cable, that way an attacker won't be able to do much unless he cracks IPSec. A: Use encrypted VLAN or VPN. Set up a VPN gateway wherever your network switches between internal to external. Make sure that all external cables carry only encrypted data. With encrypted link, you ensure authenticity (data must come from inside trusted network), integrity (data is not modified when traveling on untrusted cable), and confidentiality (data is not leaked through the external cables). The final security concern is availability (service is not interrupted), encryption doesn't solve this. What you can do for availability is to have additional redundant path between the trusted networks and automatic rerouting between them. An attacker would have needed to simultaneously compromise all physical paths to take down the service. Additionally, as you have a camera network, you might want to make sure that anyone that needs to get to access panel and exposed wiring within the unencrypted internal network has to pass through a camera's line of sight. This way, you would record evidence of tampering and gives you a chance to identify the perpetrator.
{ "pile_set_name": "StackExchange" }
Q: Choosing between reference (T&) and const pointer (T* const) Is there any reasonable use case, where one should use const pointer over reference? T obj; T &r = obj; // style-1 T* const p = &obj; // style-2 Both the style can be used for the same purpose. I always prefer the 1st style in the code and consider the later style as deprecated. However I still wonder if missed any use case where 2nd style is better ? Edit: Not limiting to the above example, I talk in a broader sense, void foo (T& r); // style-1 void foo (T* const p); // style-2 [I see from few of the answers that, style-2 allows to pass null.] A: A const pointer (T* const) can be NULL, and that can be useful when passing arguments to a function or when returning values from a function. For example, if you have a search function, you might want it to return NULL if it didn't find anything. You can't do that if it returns a reference type.
{ "pile_set_name": "StackExchange" }
Q: grouping in LINQ query Given a table of thousands of rows of data as shown in the sample below Id Date SymbolId NumOccs HighProjection LowProjection ProjectionTypeId 1 2014-04-09 28 45 1.0765 1.0519 1 2 2014-04-10 5 44 60.23 58.03 1 3 2014-04-11 29 77 1.026 1.0153 1 and a Class defined as Public Class ProjectionPerformance Public symbolId As Integer Public Name as String Public Date as String Public ActualRange as Decimal End Class I am trying to return the following for each symbolId; The symbolId (from this table) The symbol Name (from the symbols table) The Actual Range (High Projection - Low Projection) Can this be done in one query since i am essentially in need of a Dictionary(Of Integer, List(Of ProjectionPerformance)) where the integer is the symbolId and the List is generated from the query? Updated: So as to be a little clearer, Here is what I'm doing so far but contains two LINQ iterations Public Shared Function GetRangeProjectionPerformance(Optional daysToRetrieve As Integer = 100) As Dictionary(Of Integer, List(Of ProjectionPerformance)) Dim todaysDate As Date = DateTime.Now.Date Dim lookbackDate As Date = todaysDate.AddDays(daysToRetrieve * -1) Dim temp As New Dictionary(Of Integer, List(Of ProjectionPerformance)) Using ctx As New ProjectionsEntities() Dim query = (From d In ctx.projections Where d.SymbolId <= 42 AndAlso d.Date >= lookbackDate Join t In ctx.symbols On d.SymbolId Equals t.Id Let actualRange = d.HighProjection - d.LowProjection Select New With { d.Date, d.SymbolId, t.Name, actualRange}).GroupBy(Function(o) o.SymbolId).ToDictionary(Function(p) p.Key) For Each itm In query Dim rpp As New ProjectionPerformance Dim rppList As New List(Of ProjectionPerformance) If itm.Value.Count > 0 Then For x As Integer = 0 To itm.Value.Count - 1 Dim bb As Integer = Convert.ToInt32(itm.Value(x).SymbolId) With rpp .SymbolId = bb .ProjectionDate = itm.Value(x).Date.ToString() .Name = itm.Value(x).Name .ProjectedRange = itm.Value(x).actualRange End With rppList.Add(rpp) Next End If temp.Add(itm.Key, rppList) Next End Using Return temp End Function A: I'm going to answer in C#, but I think you'll get the gist of it anyway. Basically, you can group by SymbolId, build your object graph and then use ToDictionary using the Key to create dictionary. var result = (From d In _projectionEntities.projections Where d.SymbolId <= 42 group d by d.SymbolId into g select new { SymbolId = g.Key, ProjectionPerformances = g.Select(gg=>new ProjectionPerformance{ SymbolId = gg.SymbolId, Name = gg.Symbol.Name, rpDate = gg.Date.ToString(), ActualRange = gg.HighProjection - gg.LowProjection }) .ToDictionary(g=>g.SymbolId);
{ "pile_set_name": "StackExchange" }
Q: Generics to prevent Parent class to be as accepted type I have a situation in which I have to create a generic method that can accept List of child objects but not the parent class objects. Say I have class ClassA {} which is getting extended by class ClassB extends ClassA {} class ClassC extends ClassA {} executeMethod(List</* either ClassB or ClassC but not ClassA */>) Can we achieve it using generics? A: I'm not sure why you can't just allow List<? extends ClassA> but you could try: <T Extends ClassA> void executeMethod(List<? extends T>); //not sure if this will work but worth a try. Or public interface ClassX {} public class ClassA { void executeMethod(List<? extends ClassX); } public ClassB extends ClassA implements ClassX {} public ClassC extends ClassA implements ClassX {}
{ "pile_set_name": "StackExchange" }
Q: Stored Procedure Result? I have a stored procedure which calls other stored procedures and then returns a message. However, the SP is not working as intended: ALTER PROCEDURE [dbo].[sp_Test] -- Add the parameters for the stored procedure here @ID int, @UN nvarchar(30), @PW nvarchar(30), @Message nvarchar(50) out AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Variables Declare @ValidUser nvarchar(75); Declare @Current nvarchar(50); Declare @Log bit = 0; Declare @LogDateTime datetime2 = getdate(); Execute @ValidUser = sp_UserValidation @ID, @UN, @PW, @ValidUser; --sp_UserValidation returns 'Success' If @ValidUser = 'Success' Begin -- 2) Validate Account Execute @Current = sp_ValidateCurrent @ID, @Current; --sp_ValidateCurrent returns 'Account is current' If @ACurrent = 'Account is current' Begin Set @Message = 'Success'; End Else Begin If @Current = 'Grace' Begin Set @Message = 'Grace'; End Else Begin If @AccountCurrent = 'Not Billing' Begin Set @Message = 'Success'; End Else Set @Message = 'Failure' End End End Else Set @Message = 'Not valid.'; Select @Message; END According to my logic, the @Message should equal 'Success', however 'Not valid' is being returned. What am I doing wrong? Please let me know. Thank you. Here is the logic for sp_UserValidation: ALTER PROCEDURE [dbo].[sp_UserValidation] -- Add the parameters for the stored procedure here @ID int, @UN nvarchar(30), @PW nvarchar(30), @Output nvarchar(50) out AS BEGIN SET NOCOUNT ON; Declare @UserCount int = 0; Declare @AccountLocked bit = 1; Declare @FailedAttempts int = 4; Declare @MaxAttempts int = 3; Declare @LastLogin datetime2; Set @Output = 'Error: Please try again'; -- 1) Check that Account Code/UserName/Password combination exists Select @UserCount = count(*) from tblUSER where ID = @AID AND UserName = @UN AND Password = @PW; If @UserCount = 1 Begin -- 2) Check that the User Account is not locked -- 2.a) Get maximum allowed attempts Select @MaxAttempts = Value from tbl_sysTABLE where Title = 'MaxUserAttempts'; -- 2.b) Get total failed attempts since last successful login -- Get Last Successful login date Select @LastLogin = LoginDatetime from tblLOG where ID = @ID AND UserName = @UN AND LoginDatetime in (select max(LoginDatetime) from tblLOG where ID = @ID AND UserName = @UN AND Message = 'Success'); -- Get failed attempts count Select @FailedAttempts = count(*) from tblLOG where LoginDatetime > @LastLogin; -- 2.c) If failed attempts > maximum allowed attempts, account is locked, else account is not locked. If @FailedAttempts < @MaxAttempts Begin Set @Output = 'Success'; End Else Set @Output = 'User account is locked.'; End Select @Output; END A: I am guessing that you want: Execute sp_UserValidation @ID, @UN, @PW, @ValidUser output; Stored procedures don't return strings. Here is the reference that return values are an integer. I'm very surprised it doesn't generate a syntax error when you write it. I suppose this is because return is also used in functions that can return any type. I've always used the return as a status indicator. In your case, you are passing a variable in and then using it, so it makes sense that it would be an output parameter.
{ "pile_set_name": "StackExchange" }
Q: Understanding MVC routing conventions I am looking at an example of MVC Route and it looks like following: routes.MapRoute("Cuisine", "cuisine/{name}", new { controller = "Cuisine", action = "Search", name = ""}) I am just trying to dissect what each element stands for here: "cuisine/{name}" Does this part say that if a request comes with URL starting from word cuisine and there is a second string parameter and route it to this particular Route and consider second part of URL as parameter name? { controller = "Cuisine", action = "Search", name = ""}) If nothing is passed into the parameter then please use empty string as default and if some value is passed for name parameter then use that value? A: "cuisine/{name}" . Does this part say that if a request comes with URL starting from word cuisine and there is a second string paramter and route it to this particular Route and consider second part of URL as parameter name? Yes, that is correct. { controller = "Cuisine", action = "Search", name = ""}) If nothing is passed into the parameter then please use empty string as default and if some value is passed for name parameter then use that value? Yes, that is also correct. However, it is usually more sensible to specify an optional parameter as UrlParameter.Optional. Basically, there are 2 (important) parts to a route configuration. There is a match specification which always consists of the URL parameter and may also include constraints, optional, and required values. A required value is one where you don't specify any default for a route key and also include it as a route segment. If a route doesn't fit the criteria of the match, the framework will attempt the next route in the configuration until it finds a match (or not). It is helpful to think of it as a switch case statement. Then there is a route value specification. This is a combination of the default values and any incoming URL segments that may override or add to them. Note that constant parts of the URL are not included in the route values. The only reason why "Cuisine" is inserted into the route values in your example is because it is defined as a default route value.
{ "pile_set_name": "StackExchange" }
Q: What is the name of the science fiction short story in which a man clones himself and raises his clone in an imitation of his own life? I read this story as a kid in a collection of best science diction short story. It's told I think from the point of view of the clone. I think the reason for trying to redo his own life was so that a romance with his childhood sweetheart would have worked out better. A: The Fifth Head of Cerberus, Gene Wolfe, 1972. Probably the original novella, not the more extended novel that followed. A: Somewhat similar. It's a woman instead of a man. The Lives and Loves of Tiarella Rosa - in the short story collection "A Second chance at Eden" by Peter F Hamilton. (1998) Full story here: http://www.e-reading-lib.org/chapter.php/72415/13/Hamilton_07_A_Second_Chance_at_Eden.html Summary: After her husband dies, Tiarella has him and herself cloned. She ensures that the two children's lives are as close to her own life as possible so that they will fall in love when they meet.
{ "pile_set_name": "StackExchange" }
Q: JS + POST + FORM Здравствуйте. Объясню на примере: Пользователь заходит на страницу index.html с таким содержанием: <form name="buy" action="script.php" method="post"> <select name="type[]" id="type" multiple> <option value="0">Планшет</option> <option value="1">Телевизор</option> <option value="2">Телефон</option> </select> <input type="submit" value="OK"> </form> Выбирает из выпадающего списка "Телевизор" и "Телефон" и нажимает "OK". Страница script.php принимает данные и в случае ошибки выдаёт исходную форму обратно. JS после этого исходя из POST данных добавляет selected к полю "Телевизор" и полю "Телефон". Как такое можно было бы реализовать (в смысле JS составляющую - т.е. интересует исключительно сохранение выбранных полей после обновления страницы)? Наработки: Нашел вот такой скрипт: <script type="text/javascript"> <!-- /** * Сохраняем форму. Функция принимает ссылку на форму. Форма должна иметь * уникальный аттрибут ID. */ function saveFormSession(form) { if(!form||!form.id||!/^[^;=]+$/.test(form.id)) return; var data="", tok, el, safe_name; for(var i=0; i<form.elements.length; i++) { if((el=form.elements[i]).name==""||el.getAttribute("skip_form_save")!=null) continue; safe_name=el.name.replace(/([)\\])/g, "\\$1"); switch(el.type) { case "text": case "textarea": tok="v("+safe_name+"):"+el.value.replace(/([|\\])/g, "\\$1")+"||"; break; case "radio": case "checkbox": tok="s("+safe_name+"):"+(el.checked? "1": "0")+"||"; break; case "select-one": tok="i("+safe_name+"):"+(el.selectedIndex)+"||"; break; default: tok=""; } data+=tok; } if(data>=4000) return alert("Can't save form into cookie, to much data..."); document.cookie="ses"+form.id+"="+escape(data); } /** * Восстановить значение формы. Форма должна иметь уникальный атттрибут ID. */ function restoreFormSession(form) { if(!form||!form.id||!/^[^;=]+$/.test(form.id)) return false; var strt, end, data, nm, dat; if((strt=document.cookie.indexOf("ses"+form.id))<0) return false; if((end=document.cookie.indexOf(";", strt + form.id.length + 3))<0) end=document.cookie.length; data=unescape(document.cookie.substring(strt + form.id.length + 4, end)).split("||"); for(var i=0; i<data.length-1; i++) { nm=/^[vsi]\(((?:[^)\\]|(?:\\\))|(?:\\\\))+)\)\:/.exec(data[i]); nm[1]=nm[1].replace(/\\([)\\])/g, "$1"); dat=data[i].substr(nm[0].length).replace(/\\([|\\])/g, "$1"); switch(data[i].charAt(0)) { case "v": form.elements[nm[1]].value=dat; break; case "s": form.elements[nm[1]].checked=(dat=="1"? true: false); break; case "i": form.elements[nm[1]].selectedIndex=dat; break; } } } //--> </script> Но он не работает с multiple. Как заставить его работать с multiple? A: Если данные формы передаются через form submit с перезагрузкой страниц то заполнение формы следуе провести через php: if ($error) { echo ' <form name="buy" action="script.php" method="post"> <select name="type[]" id="type" multiple> <option value="0"'; if (array_search('0',$_POST['type'])) echo ' selected'; echo '>Планшет</option> <option value="1"'; if (array_search('1',$_POST['type'])) echo ' selected'; echo '>Телевизор</option> <option value="2"'; if (array_search('2',$_POST['type'])) echo ' selected'; echo '>Телефон</option> </select> <input type="submit" value="OK"> </form>'; }
{ "pile_set_name": "StackExchange" }
Q: Click Event not being Fired in fixed position footer on iphone/ipad So i'm having some difficulty with a click event within a page being rendered on iphone/ipad. This works propery in all desktop browsers i have checked as well as within android. The issue lies with clicking on the LIs in the footer. I have attempted to attach a click event to the footer elements via the following: $('#footer li').live('click', function(e) { Site.loadpage($(this).attr('page') + '.html'); }); But nothing happens (no javascript errors or anything). So to get more information i added a more generic click event, where perhaps i would find some other element getting in the way that is capturing the event with this: $('*').live('click', function(e) { alert(e.target); }); With this event, i can click anywhere on my page and i get an alert with the type of element i have clicked on. EXCEPT for in the footer, where nothing at all happening. Here is some further information about the page i am using this with, i can provide more information if necessary, the only other thing that may be relevant is that i am using jquery for this (obviously). I have a page with the following structure: <body> <div id="header"> </div> <div id="content"> </div> <div id="footer"> <ul> <li page="projects" class="projects"><span>Projects</span></li> <li page="people" class="people active"><span>People</span></li> <li page="assignments" class="assignments"><span>Assignments</span></li> <li page="search" class="search"><span>Search</span></li> <li page="more" class="more"><span>More</span></li> </ul> </div> </body> And the following CSS: html { height:100%; width: 100%; margin:0; overflow: hidden; padding: 0px; position: fixed; text-shadow: 0px 0px 0px transparent !important; letter-spacing: 0px; font-family: Helvetica; font-weight: bold; } body { padding: 0px; margin: 0px; height: 100%; width: 100%; overflow: hidden; font-family: Helvetica; } #header { background: url(../images/devices/iphone/header.jpg); color: white; position: fixed; top: 0px; left: 0px; right: 0px; height: 45px; /* ADJUST FOR IPAD */ box-shadow: -5px -5px 4px 7px #888; } #header .center { position: static; display: block; width: 100%; max-height: 45px; /* ADJUST FOR IPAD */ text-align: center; } #header h1.center { margin: 8px 0px 10px 0px; } #content { position: absolute; bottom: 48px; top: 45px; left: 0px; right: 0px; overflow: hidden; } #footer { background: url(../images/devices/iphone/header.jpg); background-size: 48px 100%; position: absolute; bottom: 0px; left: 0px; right: 0px; height: 48px; /* ADJUST FOR IPAD */ color: white; text-align: center; } #footer { text-align: center; } #footer ul { list-style-type: none; padding-left: 0px; margin-left: auto; margin-right: auto; margin-top: 1px; font-size: 8px; } #footer li { padding-top: 35px; padding-bottom: 1px; display: inline-block; background-image: url(../images/inactive-menu.png); width: 62px; background-size: 312px; } #footer li.active { background-image: url(../images/active-menu.png); } #footer li span { width: 57px; padding-top: 10px; } #footer li.projects { background-position: 0px 0px;} #footer li.people { background-position: -62px 0px;} #footer li.assignments { background-position: -124px 0px;} #footer li.search { background-position: -187px 0px;} #footer li.more { background-position: -250px 0px;} A: I don't believe live works in iOS for some reason. Try .on() , that should work. $('*').on('click', function(e) { alert(e.target); });
{ "pile_set_name": "StackExchange" }
Q: Remote Settings file I'm working on a C# project and I would like store the admin's settings in a Settings file (not app.config), I'm wondering if this Settings file can be stored in a remote location like a server database or another computer in the same LAN, this would actually be the best thing because I want to push the admin's settings to all computers so a single file would be essential. Is this even possible? If it is, could someone please point me in the right direction (tuto, link, documentation, etc) on how to create a Settings file and how to establish a remote connection to it. I thought about using a database but I don't see the convenience in using it just to store settings. What do you guys think/suggest?? A: There is no concept of a remote application settings file in Visual Studio / .NET. However, there are many ways you could store and consume remote settings, either via a file or database. A few questions you need to ask yourself is this.... Is it on a Local Network and will it only be consumed by Client software on the Local Network? This would be the case if you were writing Intranet applications on a Corporate Network, for instance. If so, then you can use a Shared Drive to host the file, and read it from any client with the same exact file path. If you are going to consume it across the internet, you could create some type of service which returns a file when called. Something like a Web service if it's being served from a Web Server like Apache or IIS. If its going across the internet though, I would just recommend using a database. Just because it's already set up to consume data across the net, and your record is just a data structure, it can be stored in either a file with x number of fields or a database table record having x fields with the same amount of effort. Sample Code for Custom Config File using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestAsync.Services { public static class AppSettings { public static string SettingsFileLocation {get; set;} public static string Setting1 { get; set; } public static string Setting2 { get; set; } public static DateTime Setting3 { get; set; } static AppSettings() { SettingsFileLocation = @"C:\Wherever\Whatever.config"; LoadConfiguration(); } public static void LoadConfiguration() { using(var fs = new StreamReader(File.OpenRead(SettingsFileLocation))) { Setting1 = fs.ReadLine(); Setting2 = fs.ReadLine(); Setting3 = DateTime.Parse(fs.ReadLine()); fs.Close(); } } public static void SaveConfiguration() { using (var fs = new StreamWriter(File.OpenWrite(SettingsFileLocation))) { fs.WriteLine(Setting1); fs.WriteLine(Setting2); fs.WriteLine(Setting3.ToShortDateString()); fs.Flush(); fs.Close(); } } } }
{ "pile_set_name": "StackExchange" }
Q: Javascript array becomes an object structure I'm experiencing an odd behavior (maybe it isn't odd at all but just me not understanding why) with an javascript array containing some objects. Since I'm no javascript pro, there might very well be clear explanation as to why this is happening, I just don't know it. I have javascript that is running in a document. It makes an array of objects similar to this: var myArray = [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...]; If I print out this array at the place it was created like JSON.stringify(myArray), I get what I was expecting: [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...] However, if I try to access this array from a child document to this document (a document in a window opened by the first document) the array isn't an array any more. So doing JSON.stringify(parent.opener.myArray) in the child document will result in the following: {"0":{"Id":"guid1","Name":"name1"},"1":{"Id":"guid2","Name":"name2"},...} And this was not what I was expecting - I was expecting to get the same as I did in teh parent document. Can anyone explain to me why this is happening and how to fix it so that the array is still an array when addressed from a child window/document? PS. the objects aren't added to the array as stated above, they are added like this: function objTemp() { this.Id = ''; this.Name = ''; }; var myArray = []; var obj = new ObjTemp(); obj.Id = 'guid1'; obj.Name = 'name1'; myArray[myArray.length] = obj; If that makes any difference. Any help would be much appreciated, both for fixing my problem but also for better understanding what is going on :) A: The very last line might be causing the problem, have you tried replacing myArray[myArray.length] = obj; with myArray.push(obj);? Could be that, since you're creating a new index explicitly, the Array is turned into an object... though I'm just guessing here. Could you add the code used by the child document that retrieves myArray ? Edit Ignore the above, since it won't make any difference. Though, without wanting to boast, I was thinking along the right lines. My idea was that, by only using proprietary array methods, the interpreter would see that as clues as to the type of myArray. The thing is: myArray is an array, as far as the parent document is concerned, but since you're passing the Array from one document to another, here's what happens: An array is an object, complete with it's own prototype and methods. By passing it to another document, you're passing the entire Array object (value and prototype) as one object to the child document. In passing the variable between documents, you're effectively creating a copy of the variable (the only time JavaScript copies the values of a var). Since an array is an object, all of its properties (and prototype methods/properties) are copied to a 'nameless' instance of the Object object. Something along the lines of var copy = new Object(toCopy.constructor(toCopy.valueOf())); is happening... the easiest way around this, IMO, is to stringency the array withing the parent context, because there, the interpreter knows it's an array: //parent document function getTheArray(){ return JSON.stringify(myArray);} //child document: myArray = JSON.parse(parent.getTheArray()); In this example, the var is stringified in the context that still treats myArray as a true JavaScript array, so the resulting string will be what you'd expect. In passing the JSON encoded string from one document to another, it will remain unchanged and therefore the JSON.parse() will give you an exact copy of the myArray variable. Note that this is just another wild stab in the dark, but I have given it a bit more thought, now. If I'm wrong about this, feel free to correct me... I'm always happy to learn. If this turns out to be true, let me know, too, as this will undoubtedly prove a pitfall for me sooner or later
{ "pile_set_name": "StackExchange" }
Q: A Crozier Riddle This is a new kind of riddle called a Crozier riddle. Here are the rules: The first letter of each of the answers must be put together and unscrambled to reveal a final word. Here are the clues: (They will start off easy and get increasingly harder) Something a horse says. The largest living land animal. Ten letter name for someone’s job. A flashcard website that makes simple learning tools to help students study. An alternative sugar in gum that is not sugar or aspartame. A song about a good girl gone bad that talks about the Dow. A ten letter word for a problem that resulted from a doctor. The final unscrambled word will be seven letters: _ _ _ _ _ _ _ A: Answers to hints(partial): 1. Neigh 2. Elephant 3. Occupation 4. Quizlet 5. maltitol, mannitol, sorbitol or xylitol(reverse solved) 6. Umbrella(by Rihanna) 7. Iatrogenic (Thanks puzzledPig!) Which anagram to Equinox A: Partial: Something a horse says. Neigh The largest living land animal. Elephant Ten letter name for someone’s job. Occupation A flashcard website that makes simple learning tools to help students study. Quizlet A ten letter word for a problem that resulted from a doctor. Iatrogenic (thanks wikipedia)
{ "pile_set_name": "StackExchange" }
Q: How do I know if a Java class for a particular function exists? I'm a new student to programming and taking my first introduction to Java college class. Certain pre-made functions exist in Java such as Math.pow(x, y); or System.out.println(); but how do I know what other ones are available for use? Do you have some way of looking these up in the API documentation that I don't know? I could browse that data all day and find nothing even close to what I'm trying to accomplish. I wouldn't even know what package it was in. I understand practice makes perfect, but it would be nice to know if something exists before I attempt to create it from scratch. A: Chances are if there's something you think someone else might want to do, there's a library around for it - either built into the JDK or as a 3rd party library. The quickest way for any particular function you're after is just to Google, and you should find out whether it's in the JDK or available as a library pretty quickly. If that fails, then (non-duplicate) questions here asking if anyone knows a library with x functionality for Java are fine too. Eventually, as you say, after a while you'll build up a pretty extensive knowledge of such common functionality - and that may well come quicker than you think.
{ "pile_set_name": "StackExchange" }
Q: How does count work in Ruby when a string is set as the parameter? How does count work in this code: name= "abcdef" puts name.count("aeiou") puts name.count("^aeiou") Does it count for the occurrences of "a", "e", "i", "o" and "u"? If yes, how can I count the occurrences of "aeiou" as a single string? Does the negation include counting for 'spaces'? Why/why not? A: Basically, name.count("aeiou") will return any instances of any characters in name that match "a" or "e" or "i" or "o" or "u". If you want to count as a string you'd use scan like: name.scan(/aeiou/).count count also includes whitespaces.
{ "pile_set_name": "StackExchange" }
Q: True or false: infinite sequence in a compact topological group is dense. This is from an exercise in Bredon's Topology and Geometry: Let $G$ be a compact topological group (assumed to be Hausdorff). Let $g\in G$ and define $A=\{g^n:n=0,1,2...\}$. Then show that the closure $\bar{A}$ is a topological subgroup. Note if the assumption of compactness is dropped, then the statement is false. A counterexample is $\mathbb{N}\subset \mathbb{R}$ as additive sets. Note: if we add the assumption of $G$ being 1st countable, this question is easy to answer. So, if the set $A$ is finite, then it is a cyclic group and it is already closed. In the infinite case, I can only think of the example of an infinite subgroup of the circle group, which is dense in compact group. I am not sure how to proceed with the proof of this general fact. Any hint will be appreciated. A: Here is a proof which assumes that $G$ is first countable. Since $G$ is compact, there is a subsequence $(g^{n_k})_{k\in\Bbb Z_+}$ of $(g^n)_{n\in\Bbb Z_+}$ which converges to some $a\in G$. Clearly, $a$ is in fact an element of $A$. But then the sequence $(g^{n_k-1}a)_{k\in\Bbb Z_+}$ is a sequence of elements of $A$ which converges to $g^{-1}a$. So, $g^{-1}a\in A$. By the same argument, $(\forall N\in\Bbb N):g^{-N}a\in A$. But then $(g^{-n_k-1}a)_{k\in\Bbb Z_+}$ is a sequence of elements of $A$ which converges to $g^{-1}$ and this proves that $g^{-1}\in A$. By the same argument, $(\forall N\in\Bbb N):g^{-N}\in A$. Can you take it from here? If you drop the assumption that $G$ is first countable, you can still get the conclusion that you want to get, using nets in the proof, as suggested by Eric Wofsey in the comments.
{ "pile_set_name": "StackExchange" }
Q: Make ~/ reference the root folder (the same folder as web.config is in) I'm working on a site in asp.net (my first) which is all going very well. That is until I deployed the app to our test environment, where the ~ (tilde) started referencing a folder parent to the root of my project. On my computer the app lives in c:/Documents.../Visual Studio../WebSites/MyApp and ~ resolves correctly. On the test server it lives in a subfolder to an existing site, so the url to the site (both while testing and once it goes live) is something like domain.com/oldexistingsite/myapp. On the test server ~/ resolves to the root of domain.com which breaks the urls to my user controls registered in web.config and all other urls using the ~ operator to make relative urls. Is there any way I can ensure that the ~ operator will resolve paths relative to the root of my app (i.e. the same folder where web.config file for my app is located)? Sorry if this is something totally trivial - this is all new to me ;) A: Sounds like you didn't make the subfolder an application in IIS; In IIS Manager on the server right click on the subfolder and hit properties, then create an application for the folder. Sorry, I don't have IIS installed on my home PC or I'd give you more complete instructions...
{ "pile_set_name": "StackExchange" }
Q: Is the D&D Pantheon as invincible as it appears? I've recently taking up the ill-advised task of skimming Deities and Demigods. Numerous times throughout this book, the idea of PCs killing off the gods is entertained. For example, page 31 says that a sufficiently high level Epic party may have an easy time defeating the deities in the book and page 220 has a section devoted to deicide. I can see this being possible for some pantheons. Numerous members of the Asgardian pantheon are quite weak and almost all of them lack Alter Reality, the Olympian pantheon's Nike and Hercules stand out as targets (low Divine Rank and no Alter Reality), and you might have a shot at the weaker members of the Pharaonic pantheon (e.g. Imhotep is DR 1, lacks any instant-kills, and is level 20 Expert). For these cases, I can at least see what the designers were going for. The thing is, I just don't think that this is possible if the DM is using the D&D Pantheon. With the sole exception of the web extension deity Erbin, every single deity in this pantheon has Alter Reality. In my opinion, even under a strict RAW reading of its benefits (i.e. the Notes section), anyone who has this Salient Divine Ability is invincible. I can't even see how another deity can kill them. To support this point, this is how I envision a battle between anyone who has Alter Reality and anyone else: Before the battle, the deity makes use of its immortality, access to any Divination spell it wants (via Alter Reality), and (usually high) intelligence score to access any of a number of exploits for moving first. As soon as the deity becomes aware of a battle or an upcoming battle, the deity moves first and uses Alter Reality to cast Persistent Time Stop. It now has an entire day to prepare for the fight. If that's not enough, it casts it again and again until it is enough. Given that the deity has Alter Reality, it can do pretty much anything to prepare for the battle. My favorite is dropping an arbitrarily high mass on top of the opponent, but I'm sure that the ability to create temporary magic objects is even more useful (scrolls, any one?). The only limitations are those listed in the rules for Time Stop. The deity either wins as soon as Persistent Time Stop finishes, or has an eternity to prepare an escape plan. In other words, the deity can't lose. With all of this available, how can anyone, PC or otherwise, manage to defeat a deity that has Alter Reality? I can't see how even Epic Spellcasting can overcome this. The only weakness that I can see is in antimagic fields, but deities largely ignore those anyway and have numerous options for countering them via Alter Reality. For example, Wish can destroy Dead Magic Zones, Mage’s Disjunction might be able to destroy the antimagic field without stopping the Persistent Time Stop, and Salient Divine Abilities explicitly ignore antimagic fields. A: The question is too open-ended, so I'm only going to address the approach you spoke of in the body. Your claim hinges on two core capabilities: Going first. Infinite Time Stop. Going first The answer you linked already addressed the majority of this topic - there is no universal "I go first" button, and from a TO perspective the only leg up deities have in this contest is access to the Supreme Initiative. It is admittedly a good leg up too, but not all deities as statted in Dieties and Demigods has it. Let's say the deity uses every advantage it has, including Supreme Initiative and goes first. Infinite Time Stop If a deity is replicating the spell Time Stop via Alter Reality then it is subject to all effects that interact with that spell. Two of those are notable: Spell Stowaway This is an epic feat from the SRD that allows you to "hijack" a spell effect. In the case of Time Stop it brings you along within the casters Time Stop, effectively nullifying it. The 5th spell Temporal Repair [Dragon #350, p.78] This is an area spell that prevents time-altering effects from affecting anyone within its area. For spells of its level or lower it works automatically. For higher level spells it requires passing an opposed caster level check. But there are many ways to boost caster level up the wazoo. Both these approaches suffer from some serious limitations like their limited range among other things. But what we are looking for here is not a definite win, but simply removing the deity's "I win" button, making it a contest of planning, and resources, and "who has the higher number?" once again.
{ "pile_set_name": "StackExchange" }
Q: When Calculating the Inner Product, Why Do We (Seemingly) Always Integrate From $0$ to $1$? I've always seen the inner product $\langle f(x), g(x)\rangle$ written as $$\langle f(x), g(x)\rangle = \int_0^1 f(x)g(x)w(x) \ dx$$ where $w(x)$ is a weight function. But why do we always integrate from $0$ to $1$? And why not other values? If we do integrate over other values, why is integrating over the domain from $0$ to $1$ so common? I would greatly appreciate it if people could please take the time to clarify this. A: It's probably just a function of the material. The eigenfunctions are typically just orthogonal between $a$ and $b$ i.e. $$ \int_{a}^{b} \phi_{n}(x)\phi_{m}(x) \sigma(x) dx =0 , \lambda_{n} \neq \lambda_{m} $$ typically in PDEs you start off with $0$ to $L$ i.e $$ \int_{0}^{L} \phi_{n}(x) \phi_{m}(x) \sigma(x) dx $$ and $\sigma(x) =1$ , $ \lambda_{n} = \left( \frac{n \pi }{L} \right)^{2} $ then $ \phi_{n}(x) = \sin(\frac{ n \pi x}{L})$ for instance when we have $$ \frac{d^{2}\phi}{dx^{2}} + \lambda \phi =0 \\ \phi(0) = 0 \\ \phi(L) = 0$$
{ "pile_set_name": "StackExchange" }
Q: Why the input show the half text while ajax response having full string I have an script which fetching the data from the apis and in ajax success response ajax got:- date: "2018-12-06" date_time: 1544077867 description: "This is second image" id: 2 image_url: "image_url/image.jpg" name: "Second Image" status: 1 While append the data with input field then it will show for example from above data it show the description like "This" while description having "This is a second image". This same thing also done with the name to it will show in input field is "Second" while it contains "Second Image". I posted my code below:- success:function(response){ console.log(response.response.data) console.log(response.response.data.description) $('#elements').append('<input id="name" type="text" value='+response.response.data.name+'><br><br>'); $('#elements').append('<input id="description" type="text" value='+response.response.data.description+'><br><br>'); $('#elements').append('<input id="image_url" type="text" value='+response.response.data.image_url+'><br><br>'); $('#elements').append('<input id="date" type="text" value='+response.response.data.date+'><br><br>'); $('#elements').append('<input id="date" type="hidden" value='+response.response.data.id+'><br><br>'); } A: Put your result stirngs into quotes: <input id="name" type="text" value="'+response.response.data.name+'"> ^ ^
{ "pile_set_name": "StackExchange" }
Q: OAuth 2.0 Token and Lifetime I am trying to understand OAuth 2.0(SERVER SIDE FLOW). Lets take simple example of Google contacts API. As per specifications, I have registered my app with Google and have got Client ID and Client secret.Also i have mentioned callback URL. Getting access token requires me to do Redirect user to a certain URL with required query strings and headers as mentioned in OAuth document on Google site (https://accounts.google.com/o/oauth2/auth bla bla stuff) After user enter their credentials, they are sent back to callback URL as mentioned in my APP which i have already registered with google. here querystring parameter &code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6 bla bla is also appended to call back URL. Thus now have got authorization code Now, i send a request to https://accounts.google.com/o/oauth2/token with authorization code i got in previous step so that i get access token and refresh token. Once i have got this "access token" , i can access (say contact API and get user contacts) Everything is fine upto this point. I also understand that access tokens have limited lifetime and we can get new access token using "refresh token". A.As a developer, is it my responsibility to store and check if the "access token" is valid? B. If my website is a public website with "Login with Google/FB/twitter" account, how do i know that its the same user who has returned back to site after 2 days and i dont need him to ask for login, instead user should be auto-logged in to site ? cauz i dont want him to go through the authorization process as they have already given permission to my app. E.G : I have logged into TechCrunch website using my FB login and can comment on articles. Now even after 1 week if i visit to TechCrunch , i dont have to login again. how do they know that its me and i am already authenticated ? A: When using OAuth 2.0, you get an access token which has an expire time sent along with it. Either you can keep track of when it expires or you can just keep using it until you get an INVALID_TOKEN error. Then you would need to call the refresh token service to get a new access token. Your refresh token is good until revoked. This is OpenID, not OAuth. The flow is similar, but is for logging a user into your service. OAuth is for you retrieving the user's data from another account.
{ "pile_set_name": "StackExchange" }
Q: MYSQL - How to query database by time I have say 12 results in a database with columns called thread message time_posted there are 12 results and they all have the same thread witch is 1002. I'm trying to get all results coming after time_posted "2013-03-19 17:36:08". There are at least 4 entries either side so I should be getting 4 entries that come after this time. So far out of everything I have tried, I have either received an empty array or I got everything except from the row that has 2013-03-19 17:36:08 as a timestamp. Here is what I have tried: public function get_messages($thread){ $time = '2013-03-19 17:36:08'; $statement = $this->database->prepare("SELECT * FROM chat WHERE thread = ? AND time_posted > '$time'"); $statement->bindParam(1, $thread); $statement->execute(); $this->result = $statement->fetchAll(PDO::FETCH_ASSOC); return $this->result; } I have tried it with both < AND > Thanks in advance for any help. All the best. Connor A: Try this: $time = '2013-03-19 17:36:08'; $statement = $this->database->prepare("SELECT * FROM chat WHERE thread = ? AND time_posted >= STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s')"); $statement->bindParam(1, $thread); $statement->bindParam(2, $time ); $statement->execute();
{ "pile_set_name": "StackExchange" }
Q: How to add the array value when the key names are same? I am populating an array in foreach loop foreach ($value as $key ){ $array[$key[label]]= $key[name]; } when the labels are same it over writes the value to that key. Question: when the key values are same I wanted to add the values and store to that key. Any idea? for example: $key[name1]=5 $key[name2]=4 $key[name1]=3 then the $key[name1]=8(5+3) A: Something like: foreach ($value as $key ) { if (isset($array[$key[label]]) { $array[$key[label]] += $key[name]; } else { $array[$key[label]] = $key[name]; } } Oh...and actually you should or wrap label inside quote or it's a variable and you should prepend the $.
{ "pile_set_name": "StackExchange" }
Q: How can I shapechange as an evil Tainted Sorcerer without dying? My PG is a Tainted Sorcerer with high taint score and I have the evil subtype, so this does not kill me. If I cast Shapechange I would lose my evil subtype and I would die unless I choose a monster with evil subtype or undead, right? Is there a way to retain the evil subtype using shapechange? If I instead first cast Infernal Transformation and then Shapechange afterwards, what will happen? A: As per d20 SRD You also gain the type of the new form in place of your own. So, in order to retain evil subtype your new form must have it, though you won't die of high taint since Tainted Sorcerer doesn't apply the taint as a penalty to Con score. Infernal Transformation does modify your type, but if you modify it again with a Shapechange, your previous modification is forfeit. Other than a little bonus to your Str and Con it doesn't give you much in this setup.
{ "pile_set_name": "StackExchange" }
Q: Watermark using John Myczek's Class Hey, I tried implementing a class John madeWatermark. I'm stuck and wondered if anyone can help me .... Added the 2 classes mentioned and on the wpf: <AdornerDecorator> <ComboBox Height="23" HorizontalAlignment="Right" Margin="0,184,664,0" x:Name="cbVideoDevices" VerticalAlignment="Top" Width="316" Initialized="cbVideoDevices_Initialized" SelectionChanged="cbVideoDevices_SelectionChanged"> <Controls:WatermarkService.Watermark> <TextBlock>Type here to search text</TextBlock> </Controls:WatermarkService.Watermark> </ComboBox> </AdornerDecorator> Whatever I try, I keep getting errors as the Control doesn't exist, or the Property does not exit. I get no errors in his classes so I figured the references are good but it seemed to me the System.Windows.Control is missing.... but I can't find it to add it ... Any help, much appreciated. Edit: With Liz's help I got this to work but to let anyone know, who does use this. The AdornerDecorator Creates a box over everything ..... Create the Margin for the AdornerDecorator and move that to desired position Margin and alignments screw with where the watermark is shown .... A: I tried the example and it works for me. However, I did notice the following: The classes did not specify a namespace, so I added one for both classes. In my case "Watermark". namespace Watermark { public static class WatermarkService { ... } } The WatermarkAdorner class in "internal", but that shouldn't bother you unless it is in a different assembly (dll). If it is then make it "public" Then in the xaml, I added a namespace declaration xmlns:Controls="clr-namespace:Watermark" At that point everything worked fine. My slightly simplified xaml looks like this: <AdornerDecorator > <ComboBox Height="23" x:Name="cbVideoDevices" Initialized="cbVideoDevices_Initialized" SelectionChanged="cbVideoDevices_SelectionChanged"> <controls:WatermarkService.Watermark> <TextBlock>Type here to search text</TextBlock> </controls:WatermarkService.Watermark> </ComboBox> </AdornerDecorator> Other than removing your margins, and alignment, it is basically the same as yours. Does that help? As a side-note I didn't like the fact that the watermark still showed when an item was selected in the combobox, so I changed the Control_Loaded method in the WatermarkService as follows: private static void Control_Loaded(object sender,RoutedEventArgs e) { Control control = (Control)sender; if(ShouldShowWatermark(control)) { ShowWatermark(control); } else { RemoveWatermark(control); } }
{ "pile_set_name": "StackExchange" }
Q: How to change mysql port I'm using wampserver. And suddenly mysql wouldn't work. I checked curports from nirsoft and it has red highlight on it. What does it mean?How do I solve this so that I could use mysql again. I'm working on a project but I can't move on if the database won't work. A: for changing the mysql port, just change it in my.ini. Look for this line port=3306 you should check mysql log and windows log for detecting why MySQL is not working. You can also try disabling the firewall
{ "pile_set_name": "StackExchange" }
Q: Issue in generating calendar event using zxing I tried to generate calendar event qr code using Google ZXing API but the image generated by it is not recognisable as an event. I used the same data format specified at different websites but it only creates qr code but not as a recognizable event. BEGIN:VEVENT SUMMARY:Concert DTSTART:20110912 DTEND:20110912 DESCRIPTION:Metallica concert END:VEVENT Please help me to understand what I am missing. Issue is only for calendar event. // In content.java TYPE: public static final String CALENDAR = "CALENDAR_TYPE"; // QREncoder.java else if (type.equals(ContentsTmp.Type.CALENDAR)) { data = trim(data); if (data != null) { enter code here contents = "BEGIN:VEVENT"+data+"END:VEVENT"; displayContents = data; title = "CALENDAR"; } } it will generate qr code, but when i scan image it show type=text A: The status for the more or less inofficial Calendar Event Type is "Unconfirmed, Unreleased, Possibilities". See the zxing doc for more details. There are only a few QR code reader who do support this format, but the majority and the important ones do not support this format. If you want to process those QR codes in your application you have to implement the logic yourself. But if you want to create QR Codes which can be scanned and converted to iCal Events by random QR Code scanners you are out of luck.
{ "pile_set_name": "StackExchange" }
Q: How to denote raising $x^1$ to a power in differential geometry I'm working from a text in which the coordinates of a point in $\mathbb R^n$ are denoted $(x^1,\dots,x^n)$. I'm wondering if there is a standard way to denote the sum of the squares of these coordinates. For example, should I write $$ {x^1}^2 + \dots + {x^n}^2, $$ which doesn't seem very clear, or should I write $$ (x^1)^2 + \dots + (x^n)^2? $$ A: I think you're right, $${x^1}^2+\dots+{x^n}^2$$ is hard to understand (although not really ambiguous once you've looked at it for long enough) but $${(x^1)}^2+\dots+{(x^n)}^2$$ is totally clear. (You could also write $x^1x^1+\dots+x^nx^n$ or $\sum_i x^ix^i$ or $\sum_i(x^i)^2$.)
{ "pile_set_name": "StackExchange" }
Q: MYSQL Trigger Update is not working as supposed I have created an update trigger in MySQL Community Server 5.5.16 but when I try to update statement: Update Account set credit = 100 Where Number = 14001455; I get an error "ERROR 1172 (42000): Result consisted of more than one row". I do not understand why I get this error and what's wrong with my code: delimiter | CREATE TRIGGER t_creditexceed AFTER UPDATE ON Account FOR EACH ROW BEGIN DECLARE n_overdraft INTEGER; DECLARE n_balance INTEGER; DECLARE n_number INTEGER; DECLARE n_credit INTEGER; DECLARE credit_exception condition for SQLSTATE '07030'; SELECT balance, credit, number INTO n_balance, n_credit, n_number FROM Account; IF ((n_balance < (-n_credit)) AND (n_balance >= 1.1 * (-n_credit))) THEN SET n_overdraft = n_balance + n_credit; INSERT INTO overdraft (account_no, over_draft) VALUES (n_number, n_overdraft); END IF; IF (n_balance < 1.1 *(- n_credit)) THEN signal credit_exception; END IF; END; | delimiter ; A: I think your issue is the statement: SELECT balance, credit, number INTO n_balance, n_credit, n_number FROM Account; - it probably returns more than 1 row, and thus MySQL cannot load the values into the variables you defined. Not sure about your intention, but maybe you were looking for NEW. and OLD. values?
{ "pile_set_name": "StackExchange" }
Q: Can I skip an ActionFIlter in ASP.NET MVC? I have an action filter attribute on a base class all my controllers inherit from. I want it (the filter) to work on all methods EXCEPT one. Can it be done? How? A: This is a little hackish, but you could test for the action in the filter's OnActionExecuting method, like so: var controllerName = filterContext.RouteData.Values["controller"].ToString(); var actionName = filterContext.RouteData.Values["action"].ToString(); if (controllerName == "Foo" && actionName == "Bar") { return; } //do normal stuff
{ "pile_set_name": "StackExchange" }
Q: MAX712 charging circuit - diode gets too hot I've built a charger for my 7.2v 3000mAh battery using MAX712 IC. Here is the datasheet: http://pdfserv.maximintegrated.com/en/ds/1666.pdf This is the schematic of my charger: It's almost a schematic from datasheet. Calculations were done with the help of this excellent article: https://www.rcgroups.com/forums/showthread.php?527385-Building-the-Perfect-Nickel-Chemistry-Charger-Part-II Here are my values: Power source: 15V 3A Rsense: 0.25Ohm - 4 1Ohm in parallel. The IC tries to maintain 0.25V across Rsense(R7,R8,R9,R10 in my schematic), so 0.25R gives (0.25V/0.25R = 1A) of fast charge current. When I plug the battery in and turn the thing on I get 1A flowing to the battery. The problem I'm getting is that diode D1 (1N5404 rated 3A - schematic says 1N4004, but I've replaced it on the board) and 2N6107 are getting very hot (can't hold a finger on it for more than a few seconds) on both of them (Q1 even has a heatsink). According to this formula Q1 should dissipate 9W: (Q1 pwr dissipation) = [ (DC IN) - (min. battery voltage) ] * (max. charge current) = (15 - 6) * 1 = 9W The article never mentioned that D1 should be very hot, not any other article I've found, which makes me think something is wrong even though battery gets the correct 1A current. Any ideas why they might be getting too hot? Any other info I can provide? A: For starters: Electronics can get hot. Very hot, in fact. The diode you are using is rated to 150 degrees Celsius. I would advise you to really avoid getting anywhere near that but what I'm trying to get at is that "I can't touch it with my finger so it must be too hot" is a very bad metric - I would be surprised if you can hold your finger on something that is above 45-50 degrees C for anymore than a few seconds. Hence, it could be that the part is 60-70 degrees (which is just fine). Let's run some numbers - keep in mind that I'm using a lot of "rouded" values since this is just a back-of-the-envelope calculation which I wouldn't expect to be accurate within more than 20% anyways: The Diode The diode's datasheet shows that we should expect about 1 volt drop at 1A of current. It also gives us about \$R_{\theta ja} = 20\ K/W\$ (but this is assuming a large lead length. I don't know if you have the part flush on the board or not. Let's assume not - if you do, the thermal performance will be even worse). Given about 1W of dissipation, you need another 20C above the ambient. That's already going to be about 40 degrees, and it's a best-case scenario. If you don't have the 9.5mm lead length mentioned in the datasheet, it's going to get a good amount hotter (I could easily imagine the \$R_{\theta ja}\$ being twice or even three times as large if it's mounted flush to the board with no large copper pads). There is also the question of where you got the part - since you mentioned a heatsink from aliexpress, did you also get your parts from aliexpress? If so, there is always a good chance that the diode you recieved is a fake, and is in fact a far less capable diode. The Transistor 9W is a lot of power, and I very much doubt that that little heatsink you posted in the comments will be able to dissipate that reliably. You already have about \$R_{\theta jc}=3\ K/W\$, so you are looking at a junction temperature of at least 20 degrees above ambient. Even with the heatsink you suggested (5K/W) you are going to get another 45 degrees on top of that, so 65 degrees in total - at a room temperature of 20 degrees Celcius, that's a junction temperature 85 degrees Celcius, and your heatsink sitting at about 65 degrees Celcius! In other words, it seems reasonable that both get quite hot. A: No, it's not getting 'too hot'. No where in the field of electronics is 'too hot' defined as 'too hot to touch.' Electronics get hot. This is a fact of life. Data sheets generally don't tell you if a certain component will get hot because you're supposed to know what things will get hot, how hot they'll get, and why. Power electronics is as much thermals as it is electronics. And there is definitely no unwritten assumption that parts will always be cool enough to touch without burning you. In fact, this is rarely the case. That 1N5404 diode? It's maximum operating temperature is 150° C. If it isn't exceeding that temperature, then it isn't getting 'too hot'. There is nothing wrong with it operating continuously at 140°C for a long time, and in many real devices, diodes can and will operate that hot. Usually only when the ambient temperature as at the highest the product is rated, but still, it happens. If you open up any old electronics with a bridge rectifier, often you'll see discoloration of the PCB in the area around these diodes. This is because those suckers get hot. And its ok. They're designed to operate in those conditions. There are many MOSFETs that are rated to 175°C. The new Silicon Carbide based semiconductors have a theoretical operating range of 400°C (!!), though most are limited to 200-225°C due to their packaging epoxy not able to withstand any higher. Anyway, yes, diodes get hot. Especially when you ask one with a 1.2V voltage drop to carry 1A, like in your case. Frankly, the 1N5404 is a wildly inappropriate diode for this application. So is the 1N4004, I am not sure what Maxim was thinking. But in your case, that diode is dissipating 1.2W at least. If it is getting hot, good. That means the circuit is working. If you don't want it to get hotter than you can touch, too bad, it's going to get too hot for you to touch. Now, if you chose a diode with a lower voltage drop, pretty much any Schottky diode, it will get a little less hot. These diodes typically have about half the voltage drop of a silicon diode, so let's call it 600mV. This will cut the heat produced in half, to 600mW. It's still going to heat up though, but not quiet as much. To put things into perspective, imagine the size of a 1/4W through hole resistor. Try putting 1/4th of a watt through it. It will get hot enough to burn you, but it will also tolerate this temperature perfectly fine, certainly much better than your finger will. That diode is shedding 5 times that. 1.2W might not sound like much, but tiny things get hot without many joules getting added to them. As for the transistor, of course it gets hot, even with a heatsink. That's the entire point of heatsinks. To get hot. They work better if they're hot. They convect more heat via passive airflow, and if they're black, they'll radiate some heat too. Heat is even in the name. The transistor and heatsink are always going to be hot. All that matters is that they don't get too hot. You can lower the temperature it and the heatsink will eventually reach by either Reducing the amount of power it must shed. So, make it waste less than 9W as heat. I don't think you can though with this circuit, as it's linear, and linear regulation works by burning off the excess voltage as heat. Put a larger heatsink on it (this will still warm up, but it will not reach quite as high of an equilibrium temperature). Make the room/ambient temperature cooler. To put it bluntly, there is nothing that is wrong with your circuit, so much as something wrong with your expectations. Sorry. Heaters gonna heat.
{ "pile_set_name": "StackExchange" }
Q: How can I choose soname of shared library? I am working with 2 shared libraries. The one(foo) is using CMake, the other(bar) is using automake. I eliminated version and soversion property of foo, because some distribution problem about symbolic link, and the result is only libfoo.so(there's no symbolic links). The problem is that libbar.so requires libfoo.so.1(I found it with readelf). How can I make libbar.so to use libfoo.so, instead of libfoo.so.1? A: How can I make libbar.so to use libfoo.so, instead of libfoo.so.1 The DT_NEEDED tag in libbar.so is recorded at the time when libbar.so is linked, from the set of DT_SONAMEs of all the libraries it is linked against. That is, if libbar.so has DT_NEEDED of libfoo.so.1, then it must be true that it was linked against libfoo.so with DT_SONAME of libfoo.so.1. If you have libfoo.so without DT_SONAME (or with DT_SONAME of libfoo.so), then relinking libbar.so against that version of libfoo.so is necessary and sufficient to get rid of libfoo.so.1 DT_NEEDED tag.
{ "pile_set_name": "StackExchange" }
Q: Spinner view; selector not working Spinner xml: <Spinner android:id="@+id/sort_by_spinner" android:layout_marginLeft="40dip" android:layout_marginRight="40dip" android:layout_marginBottom="10dip" android:paddingLeft="6dip" android:paddingRight="6dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/title_bar" android:drawSelectorOnTop="true" android:dropDownSelector="@drawable/spinner_selector" /> I've tried using android:background=... buy itself, with dropDownSelector, with and without listSelector=...; with and without listItemDropDownSelector=... and all permutations with drawSelectorOnTop spinner_selector: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="true"> <shape android:shape="rectangle"> <solid android:color="@color/app_tint"/> </shape> </item> <item android:state_selected="true"> <shape android:shape="rectangle"> <solid android:color="@color/app_tint"/> </shape> </item> </selector> I always get the default orange color. I've read numerous posts on this; just can't get it to happen. I have to support v10 and up. What's missing? A: try it as: <Spinner android:id="@+id/sort_by_spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="@dimen/space" android:background="@drawable/selection_normal" android:dropDownSelector="@drawable/list_item_selector" android:spinnerMode="dropdown" /> and the list_item_selector as <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_selected="true" android:drawable="@color/app_tint"></item> <item android:state_pressed="true" android:drawable="@color/app_tint"></item> <item android:drawable="@color/white"></item> </selector> selection_normal is any image for the spinner, you can ignore it if not needed. [EDIT] In order to set highlight the list row of the item touched / clicked do the following: in the getDropDownView instead of getView method in the spinner's adapter set the selector using the code: view.setBackgroundResource(R.drawable.list_item_selector) or using the setBackground method of the view.
{ "pile_set_name": "StackExchange" }
Q: AttributeError: module 'tensorflow' has no attribute 'streaming_accuracy' accuracy = tf.streaming_accuracy (y_pred,y_true,name='acc') recall = tf.streaming_recall (y_pred,y_true,name='acc') precision = tf.streaming_precision(y_pred,y_true,name='acc') confusion = tf.confuson_matrix(Labels, y_pred,num_classes=10,dtype=tf.float32,name='conf') For the above code, I have received the same error in past few days. Isn't the syntax same as it is in the API documentation for tensorflow? A: try to use this instead (in a fresh python file, I would suggest create a /tmp/temp.py and run that) from tensorflow.contrib.metrics import streaming_accuracy and if this doesn't work then either there is an installation problem (In which case reinstall) or you are importing the wrong tensorflow module.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to generate multiple files/classes with intellij code/file templates? I like intellij's code/file templates, they are working really well for me for single files but it would be great to be able to create multiple files/classes at once. I did find this question but since it has been a few years since I was hoping that things might have changed. We are using the mvp pattern in our application so every time we want to create a new view, it requires two classes and two interfaces, which are always in the same pattern. It would be awesome if we could generate all of the infrastructure for this and link up the classes. Any suggestions or new information would be appreciated? Maybe it is time to log a feature request with JetBrains? A: This feature seems to be available in ReSharper (another JetBrains IDE). It still does not seem possible in IDEA yet.
{ "pile_set_name": "StackExchange" }
Q: Filling model fields using both data from form and other sources I got a model that represents user's financial account: class Account(models.Model): currencies_list = [currency.alpha_3 for currency in pycountry.countries] currencies_tuples = ((currency, currency) for currency in currencies_list) user = models.ForeignKey(User) name = models.CharField(max_length=50) currency = models.CharField(max_length=3, choices=currencies_tuples) initial_balance = models.DecimalField(max_digits=10, decimal_places=2) current_balance = models.DecimalField(max_digits=10, decimal_places=2) I want to allow user to create a new account using following view: def new_account(request): if request.method == "POST": form = AccountForm(request.POST) if form.is_valid(): account = form.save(commit=False) account.save() return redirect('index') else: form = AccountForm() return render(request, 'expenses/new_account.html', {'form': form}) and form: class AccountForm(ModelForm): class Meta: model = Account fields = ['name', 'currency', 'initial_balance'] I'm only letting user to fill three fields: name, currency and initial_balance. I want fields user and current_balance to be filled automatically: user by copying currently logged user ID and current_balance by copying value provided by user for initial_balance field. May I kindly ask you to point me in the right direction? A: if form.is_valid(): account = form.save(commit=False) account.user = request.user account.current_balance = form.cleaned_data.get('initial_balance') account.save() return redirect('index')
{ "pile_set_name": "StackExchange" }
Q: Using Python's xml.etree to find element start and end character offsets I have XML data that looks like: <xml> The captial of <place pid="1">South Africa</place> is <place>Pretoria</place>. </xml> I would like to be able to extract: The XML elements as they're currently provided in etree. The full plain text of the document, between the start and end tags. The location within the plain text of each start element, as a character offset. (3) is the most important requirement right now; etree provides (1) fine. I cannot see any way to do (3) directly, but hoped that iterating through the elements in the document tree would return many small string that could be re-assembled, thus providing (2) and (3). However, requesting the .text of the root node only returns text between the root node and the first element, e.g. "The capital of ". Doing (1) with SAX could involve implementing a lot that's already been written many times over, in e.g. minidom and etree. Using lxml isn't an option for the package that this code is to go into. Can anybody help? A: iterparse() function is available in xml.etree: import xml.etree.cElementTree as etree for event, elem in etree.iterparse(file, events=('start', 'end')): if event == 'start': print(elem.tag) # use only tag name and attributes here elif event == 'end': # elem children elements, elem.text, elem.tail are available if elem.text is not None and elem.tail is not None: print(repr(elem.tail)) Another option is to override start(), data(), end() methods of etree.TreeBuilder(): from xml.etree.ElementTree import XMLParser, TreeBuilder class MyTreeBuilder(TreeBuilder): def start(self, tag, attrs): print("&lt;%s>" % tag) return TreeBuilder.start(self, tag, attrs) def data(self, data): print(repr(data)) TreeBuilder.data(self, data) def end(self, tag): return TreeBuilder.end(self, tag) text = """<xml> The captial of <place pid="1">South Africa</place> is <place>Pretoria</place>. </xml>""" # ElementTree.fromstring() parser = XMLParser(target=MyTreeBuilder()) parser.feed(text) root = parser.close() # return an ordinary Element Output <xml> '\nThe captial of ' <place> 'South Africa' ' is ' <place> 'Pretoria' '.\n'
{ "pile_set_name": "StackExchange" }
Q: How to remove 0s from dictionary in python I have an object called result. result.f is a dictionary in the form (as an example): {('a','a'):9, ('a','b'):10, ('a','c'):0} I want to remove the items that equal to 0 from the dictionary result.f. I wrote the following code: new_f=set() for j in result.f.keys(): if result.f[j]!=0: new_f.append(j:result.f[j]) But I have a syntax error: new_f.append(j:result.f[j]) ^ SyntaxError: invalid syntax How can I write the new dictionary in new_f such that new_f equal result.f after removing the items that equal 0 ? UPDATE: If the dictionary is: {('a','a'):9, ('a','b'):10, ('a','c'):0} I want the output to be the same as the previous but without the 0 item: {('a','a'):9, ('a','b'):10} A: Using a list comprehension: for key in [k for k in d if d[k] == 0]: d.pop(key) A: How about: new_f = dict((k,v) for (k,v) in result.f.iteritems() if v != 0) Or written more closely to the OP's form: new_f=dict() for j in result.f.keys(): if result.f[j]!=0: new_f[j] = result.f[j]
{ "pile_set_name": "StackExchange" }
Q: Почему PhpStorm не подключается по ftp? Почему PhpStorm не подключается по ftp? Необходимо подключиться по ftp. Браузеры, Firezilla, Putty и обычный Windows Explorer в Windows 10 нормально подключаются. Passive mode отключал и включал, не работает. Could not connect to FTP server on "x.x.x.x". A: странная штука: делаю копипаст пароля в пхпсторм - не работает. в остальные работает. набираю руками в пхпсторм - работает. мда.
{ "pile_set_name": "StackExchange" }
Q: nearest neighbour search 4D space python fast - vectorization For each observation in X (there are 20) I want to get the k(3) nearest neighbors. How to make this fast to support up to 3 to 4 million rows? Is it possible to speed up the loop iterating over the elements? Maybe via numpy, numba or some kind of vectorization? A naive loop in python: import numpy as np from sklearn.neighbors import KDTree n_points = 20 d_dimensions = 4 k_neighbours = 3 rng = np.random.RandomState(0) X = rng.random_sample((n_points, d_dimensions)) print(X) tree = KDTree(X, leaf_size=2, metric='euclidean') for element in X: print('********') print(element) # when simply using the first row #element = X[:1] #print(element) # potential optimization: query_radius https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html#sklearn.neighbors.KDTree.query_radius dist, ind = tree.query([element], k=k_neighbours, return_distance=True, dualtree=False, breadth_first=False, sort_results=True) # indices of 3 closest neighbors print(ind) #[[0 9 1]] !! includes self (element that was searched for) print(dist) # distances to 3 closest neighbors #[[0. 0.38559188 0.40997835]] !! includes self (element that was searched for) # actual returned elements for index: print(X[ind]) ## after removing self print(X[ind][0][1:]) Optimally the output is a pandas.DataFrame of the following structure: lat_1,long_1,lat_2,long_2,neighbours_list 0.5488135,0.71518937,0.60276338,0.54488318, [[0.61209572 0.616934 0.94374808 0.6818203 ][0.4236548 0.64589411 0.43758721 0.891773] edit For now, I have a pandas-based implementation: df = df.dropna() # there are sometimes only parts of the tuple (either left or right) defined X = df[['lat1', 'long1', 'lat2', 'long2']] tree = KDTree(X, leaf_size=4, metric='euclidean') k_neighbours = 3 def neighbors_as_list(row, index, complete_list): dist, ind = index.query([[row['lat1'], row['long1'], row['lat2'], row['long2']]], k=k_neighbours, return_distance=True, dualtree=False, breadth_first=False, sort_results=True) return complete_list.values[ind][0][1:] df['neighbors'] = df.apply(neighbors_as_list, index=tree, complete_list=X, axis=1) df.head() But this is very slow. edit 2 Sure, here is a pandas version: import numpy as np import pandas as pd from sklearn.neighbors import KDTree from scipy.spatial import cKDTree rng = np.random.RandomState(0) #n_points = 4_000_000 n_points = 20 d_dimensions = 4 k_neighbours = 3 X = rng.random_sample((n_points, d_dimensions)) X df = pd.DataFrame(X) df = df.reset_index(drop=False) df.columns = ['id_str', 'lat_1', 'long_1', 'lat_2', 'long_2'] df.id_str = df.id_str.astype(object) display(df.head()) tree = cKDTree(df[['lat_1', 'long_1', 'lat_2', 'long_2']]) dist,ind=tree.query(X, k=k_neighbours,n_jobs=-1) display(dist) print(df[['lat_1', 'long_1', 'lat_2', 'long_2']].shape) print(X[ind_out].shape) X[ind_out] # fails with # AssertionError: Shape of new values must be compatible with manager shape df['neighbors'] = X[ind_out] df But it fails as I cannot re-assign the result. A: You could use scipy's cKdtree. Example rng = np.random.RandomState(0) n_points = 4_000_000 d_dimensions = 4 k_neighbours = 3 X = rng.random_sample((n_points, d_dimensions)) tree = cKDTree(X) #%timeit tree = cKDTree(X) #3.74 s ± 29.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) #%%timeit _,ind=tree.query(X, k=k_neighbours,n_jobs=-1) #shape=(4000000, 2) ind_out=ind[:,1:] #shape=(4000000, 2, 4) coords_out=X[ind_out].shape #7.13 s ± 87.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) About 11s for a problem of this size is quite good.
{ "pile_set_name": "StackExchange" }
Q: Simplest way to display values from field names listed in design attributes I'm trying to write a really simple component that takes the field names from the design attributes and displays only the field values, not the standard lightning-output-field. There are two(?) ways to approach this, getRecord or return the lightning-record-form and OnLoad do some Javascript to get the field values. I tried @sfdcfox's idea here using getRecord but no matter what I did the '$fieldsFormatted' would not work ('$fieldsFormatted' returned the exact array needed, and hard coding the array returned the exact data needed, but the two together just returned undefined). I have gotten almost there with the lightning-record-form this great example but I am missing the last two steps (returning the field value without specifying the name, and displaying the field value). Getting the Field Value came from this example and both were from @salesforce-sas. HTML <template> <lightning-card title="Design Attribute Demo" icon-name="custom:custom19"> <template if:true={fieldsFormatted}> <lightning-record-form record-id={recordId} object-api-name={objectApiName} mode="view" fields={fieldsFormatted} onload={handleOnLoad}> <template for:each={fieldsFormatted} for:item="fld"> <lightning-output-field key={fld} field-name={fld}></lightning-output-field> <p key={fld}>{fValue}</p> <!-- Q2: Does not render --> </template> </lightning-record-form> </template> </lightning-card> </template> JS import { LightningElement, wire, api } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; export default class DesignerFields extends LightningElement { @api indFields = 'Industry;NumberOfEmployees'; @api objectApiName = 'Account'; @api recordId; @api record; fieldsFormatted = ['Id']; connectedCallback() { this.fieldsFormatted = (this.indFields || 'Id').split(';').map(field => field); console.log(JSON.stringify(this.fieldsFormatted)); } handleOnLoad(event) { const fValue = event.detail.records[this.recordId].fields.Industry.value; //Q1: fValue = "Education" the correct value. But "Industry" Field Name is still hard coded. //How do I get the value for the field in {fld} variable? //Q2: How do I get fValue to render back in the HTML instead of the lightning-output-field //I tried this.dispatchEvent(fValue); and it had an error } } Meta <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>48.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <property name="indFields" label="Field Names" type="String" required="true" default="Industry;NumberOfEmployees" description="The Field Names." /> </targetConfig> </targetConfigs> </LightningComponentBundle> How do you suggest I get the value rendered instead of showing the lightning-output-field please? A: Here is an approach that leverages lightning/uiRecordApi to get all relevant data and does not rely on a lightning-record-edit/view-form. All visible styling provided is custom styling and can be removed/changed. @op: please ignore fieldNames in screenshot, I am aware they were explicitly not requested. XML <?xml version="1.0" encoding="UTF-8" ?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>48.0</apiVersion> <isExposed>true</isExposed> <masterLabel>Section with Fields</masterLabel> <targets> <target> lightning__RecordPage </target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <property name="fieldNames" label="Field Names" type="String" required="true" default="Name,Industry,NumberOfEmployees" description="Commma seperated list of fully qualified API fieldnames that should be displayed in this section" /> </targetConfig> </targetConfigs> </LightningComponentBundle> HTML <template> <lightning-card title="Get Field Values" icon-name="standard:question_best"> <div class="slds-card__body_inner"> <h2 class="slds-text-heading_small"> Current Settings </h2> <p> recordId: {recordId} / objectApiName: {objectApiName} / configuredFields: {fieldNames} </p> <h2 class="slds-text-heading_small slds-var-m-top_medium"> Field Values </h2> <template for:each={results} for:item="field"> <p key={field.fieldName}>{field.fieldName}: {field.value}</p> </template> </div> <template if:true={errorMessage}> <pre>{errorMessage}</pre> </template> </lightning-card> </template> JS import { LightningElement, api, wire } from "lwc"; import { getRecordUi } from "lightning/uiRecordApi"; export default class RecordpageSection extends LightningElement { @api fieldNames; @api recordId; @api objectApiName; apiFieldnames = []; errorMessage; results = []; connectedCallback() { this.fieldNames.split(",").forEach(fieldName => { this.apiFieldnames.push(this.objectApiName + "." + fieldName); }); } @wire(getRecordUi, { recordIds: "$recordId", layoutTypes: "Compact", modes: "View", optionalFields: "$apiFieldnames" }) recordInformation({ error, data }) { if (data) { let fieldInfo = data.records[this.recordId].fields; let matchingFields = []; Object.keys(fieldInfo).forEach(fieldName => { let qualifiedFieldname = this.objectApiName + "." + fieldName; //originalIndex is used to sort results as configured let originalIndex = this.apiFieldnames.indexOf(qualifiedFieldname); if (originalIndex > -1) { matchingFields[originalIndex] = { fieldName: fieldName, value: fieldInfo[fieldName].value }; } }); this.results = matchingFields; } else if (error) { this.errorMessage = JSON.stringify(error); } } }
{ "pile_set_name": "StackExchange" }
Q: Which versions of Struts2 support the @include_page Freemarker tag? The Freemarker documentation notes: ...some Web Application Frameworks don't use FreemarkerServlet, so include_page is not available. Struts 2.1.6 seems to support the @include_page annotation, but I upgraded to Struts 2.1.8.1, and it doesn't seem to support it. Does anyone know definitively which version of Struts2 supports the @include_page annotation? I am interested mainly in versions higher than 2.1.6. A: Don't worry about it. As per Ischin's suggestion, just use this as a nice alternative: <@s.include value="file_name" />
{ "pile_set_name": "StackExchange" }
Q: Unchecking all RadioButtons in a For Each Control loop I've got 7 RadioButtons on my form, 5 in one group, 2 in another. When they were in GroupBoxes, checking one of the RadioButtons didn't uncheck the other ones in the same GroupBox, for some reason - I think because the AutoCheck value was set to False, which it had to be because otherwise when the form loaded, one of the RadioButtons would be checked by default, and I don't want this to happen. So, to uncheck the other RadioButtons within the same GroupBox, I'm trying to write a subroutine which is called, after setting the value to True in the RadioButton_Click event. For Each c As Control In Me.Controls If TypeOf c Is RadioButton Then If c.Name <> "rbtnAllSuppliers" AndAlso c.Name <> "rbtnIndividual" Then If c.Name <> rbtn.Name Then For Each rbt As RadioButton In Me.Controls If rbt.Name = c.Name Then rbt.Checked = False End If Next End If End If End If Next This code moreorless works. For each control on the form, if it's a RadioButton which isn't called rbtnAllSuppliers or rbtnIndividual (The 2 seperate RadioButtons, and it's not the RadioButton that is being set to True, then set it to False. The issue being, it is counting the 2 Labels as RadioButtons, or at least casting them to be so, so it errors when trying to set a ``Checkedvalue of theLabel`. I then tried something similar For Each c As Control In Me.Controls If c.GetType Is GetType(RadioButton) Then If c.Name <> "rbtnAllSuppliers" AndAlso c.Name <> "rbtnIndividual" Then If c.Name <> rbtn.Name Then AddHandler DirectCast(c, RadioButton).Checked, AddressOf c. End If End If End If Next But I'm not sure what I would put for the AddressOf code? What would go in here as the delegate? If I put AddressOf currentSubroutine(), surely an infinite loop will be created? Is there a way to uncheck all RadioButtons using a similar method that I'm not aware of? What's the best way to go about achieving this? A: By using Me.Controls.OfType(Of RadioButton) you can avoid having to check the type inside your loop, and will ensure that every control is a RadioButton
{ "pile_set_name": "StackExchange" }