source
sequence
text
stringlengths
99
98.5k
[ "math.stackexchange", "0000017246.txt" ]
Q: Is there a way to rotate the graph of a function? Assuming I have the graph of a function $f(x)$ is there function $f_1(f(x))$ that will give me a rotated version of the graph of that function? For example if I plot $\sin(x)$ I will get a sine wave which straddles the $x$-axis, can I apply a function to $\sin(x)$ to yield a wave that straddles the line that would result from $y = 2x$? A: Once you rotate, it need not remain a function (i.e. one $x$ value can have multiple $y$ values corresponding to it). But you can use the following transformation $$x' = x\cos \theta - y \sin \theta$$ $$y' = x \sin \theta + y \cos \theta$$ to rotate by an angle of $\theta$. Point $(x,y)$ gets rotated to point $(x',y')$. Note: this is a rotation about the origin. In your case of $y = 2x$, you need to rotate by $\arctan(2)$. See this for more info: Rotation Matrix. A: For common functions, it ms very easy. $f(x)$ rotated $\phi$ is can be calculated by $(x+f(x)\cdot i)(\cos(\phi)+\sin(\phi)\cdot i)$ as coordinates instead of complex numbers. Let's, however, replace $x$ with $t$, just to reduce confusion. $(t+f(t)\cdot i)(\cos(\phi)+\sin(\phi)\cdot i) = t\cos(\phi)-f(t)\sin(\phi)+t\sin(\phi)\cdot i+f(t)\cdot \cos(\phi)\cdot i$ In parametric form, that's: $X=t\cos(\phi)-f(t)\sin(\phi)$ $Y=t\sin(\phi)+f(t)\cos(\phi)$ To convert that to a function, we find $t$ as a function of $x$ and plug that into $Y$ as a function of $t$. This is possible with some equations, such as $f(t)=t^2$ or $f(t)=\dfrac 1t$. However, with the sine function, it's not very easy. In fact, there is no definite function for the rotation of a sine function. However, you can represent it as an infinite polynomial. The parametric of this graph would be $X=\dfrac{t-2\sin(t)}{\sqrt5}$ $Y=\dfrac{2t+\sin(t)}{\sqrt5}$ To approximate a polynomial $y$-as-a-function-of-$x$ formula, we find the coefficients for each part of this formula. The $x^0$ coefficient is the $y$-intercept divided by $0!$ ($y$ when $x$ is zero)/$0!$ The $x^1$ coefficient is the $y$-intercept of the derivative divided by $1!$ $((y$ when $x$ is $0.00001)-(y$ when $x$ is $0))/0.00001/1!$ The $x^2$ coefficient is the $y$-intercept of the second derivative divided by $2!$ $((y$ when $x$ is $0.00002)-2*(y$ when $x$ is $0.00001)+(y$ when $x$ is $0))/0.00001/0.00001/2!$ The $x^3$ coefficient is the $y$-intercept of the third derivative divided by $3!$ $((y$ when $x$ is $0.00003)-3*(y$ when $x$ is $0.00002)+3*(y$ when $x$ is $0.00001)-(y$ when $x$ is $0))/0.00001/0.0001/0.0001/3!$ In case you haven't noticed, I'm using Pascal's triangle in this calculation. I hope this helps! A: Yes you can, but it might not be a function. Say y = f(x) is the curve you want to rotate. Then the equation of the curve of f(x) rotated by n radians is: ycos(n) - xsin(n) = f(ysin(n) + xcos(n)) Try it out here: https://www.desmos.com/calculator
[ "stackoverflow", "0005384093.txt" ]
Q: Is there a data structure for a list ordered by value? I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following: // {Position, Name, Score} Object[][] data = { {1, "-", 0}, {2, "-", 0}, {3, "-", 0}, {4, "-", 0}, {5, "-", 0}, {6, "-", 0}, {7, "-", 0}, {8, "-", 0}, {9, "-", 0}, {10, "-", 0} }; I want to be able to add a new score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table. I know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best? A: Use a TreeSet with a custom comparator. Also, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects A: Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point. More info here Collections.binarySearch
[ "stackoverflow", "0011546420.txt" ]
Q: Reading a file and displaying the sum of names within that file What I would like the final code to execute is read a string of names in a text document named, 'names.txt'. Then tell the program to calculate how many names there are in that file and display the amount of names. The code I have so far was meant to display the sum of the numbers in a text file, but it was close enough to the program I need now that I think I may be able to rework it to gather the amount of strings/names and display that instead of the sum. Here is the code so far: def main(): #initialize an accumulator. total = 0.0 try: # Open the file. myfile = open('names.txt', 'r') # Read and display the file's contents. for line in myfile: amount = float(line) total += amount # Close the file. myfile.close() except IOError: print('An error occured trying to read the file.') except ValueError: print('Non-numeric data found in the file.') except: print('An error occured.') # Call the main function. main() I am still really new to Python programming so please don't be too harsh on me. If anyone can figure out how to rework this to display the amount of numbers/names instead of the sum of numbers. I would greatly appreciate it. If this program cannot be reworked, I would be happy to settle for a new solution. Edit: This it an example of what the 'names.txt' will look like: john mary paul ann A: If you just want to count the lines in the file # Open the file. myfile = open('names.txt', 'r') #Count the lines in the file totalLines = len(myfile.readlines()): # Close the file. myfile.close()
[ "stackoverflow", "0009880738.txt" ]
Q: How not to set the user's email address in django social-auth I have django social-auth installed (from omab) and the users have an email address in database that is the one I want to keep but when the users log in from facebook using social-auth, their email gets replaced by the one they have in their facebook account. I am not sure the settings are the one by default or not and cannot find how to stop this behavior. A: Have you tried SOCIAL_AUTH_PROTECTED_USER_FIELDS? :) From the manual: The update_user_details pipeline processor will set certain fields on user objects, such as email. Set this to a list of fields you only want to set for newly created users: SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email',] Also more extra values will be stored if defined. Details about this setting are listed below in the OpenId and OAuth sections. A: I found it, in the pipeline the responsible for that is social_auth.backends.pipeline.user.update_user_details I just removed it from the pipeline and now the details like email address and name are left to the user to fill. A: I'm posting my solution (update user details, not overwrite them) so it may help someone. Based on pipeline.user.update_user_details I coded the following: def fill_user_details(backend, details, response, user, is_new=False, *args, **kwargs): """Fills user details using data from provider, without overwriting existing values. backend: Current social authentication backend details: User details given by authentication provider response: ? user: User ID given by authentication provider is_new: flag source: social_auth.backends.pipeline.user.update_user_details """ # Each pipeline entry must return a dict or None, any value in the dict # will be used in the kwargs argument for the next pipeline entry. # # If any function returns something else beside a dict or None, the # workflow will be cut and the value returned immediately, this is useful # to return HttpReponse instances like HttpResponseRedirect. changed = False # flag to track changes for name, value in details.iteritems(): # do not update username, it was already generated if name in (USERNAME, 'id', 'pk'): continue # set it only if the existing value is not set or is an empty string existing_value = getattr(user, name, None) if value is not None and (existing_value is None or not is_valid_string(existing_value)): setattr(user, name, value) changed = True # Fire a pre-update signal sending current backend instance, # user instance (created or retrieved from database), service # response and processed details. # # Also fire socialauth_registered signal for newly registered # users. # # Signal handlers must return True or False to signal instance # changes. Send method returns a list of tuples with receiver # and it's response. signal_response = lambda (receiver, response): response signal_kwargs = {'sender': backend.__class__, 'user': user, 'response': response, 'details': details} changed |= any(filter(signal_response, pre_update.send(**signal_kwargs))) # Fire socialauth_registered signal on new user registration if is_new: changed |= any(filter(signal_response, socialauth_registered.send(**signal_kwargs))) if changed: user.save()
[ "math.stackexchange", "0003578354.txt" ]
Q: If a circle intersects the hyperbola $y=1/x$ at four distinct points $(x_i,y_i), i=1,2,3,4,$ then prove that $x_1x_2=y_3y_4$. If a circle intersects the hyperbola $y=1/x$ at four distinct points $(x_i,y_i), i=1,2,3,4,$ then prove that $x_1x_2=y_3y_4$. I have really no idea on how to approach this question. One clumsy way might be to consider an arbitrary circle $(x-a)^2+(y-b)^2=r^2$, such that it intersects the hyperbola $y=1/x$ at four distinct points $(x_i,y_i), i=1,2,3,4,$ and then manipulate stuffs to finally get the equality $x_1x_2=y_3y_4$, though I am not sure. A: take the point on hyperbola as (t,$\frac{1}{t})$. Put it in the equation of the circle, you will get a fourth degree equation where $t_i$ corresponds to $x_i$ and $\frac{1}{t_i}$ corresponds to $y_i$. Use theory of equations and you should get the result. It will be little easier if you consider the circle as $x^2+y^2=a^2$ but you may go ahead with general case also.
[ "stackoverflow", "0046145046.txt" ]
Q: Exception Handling Unreachable code Following is my code, when I am commenting statement-2 then it complies fines but when I uncomment it gives Compile Time Error "Unreachable Code". I understand why I am getting error after uncommenting it, but my question is even if I comment it still the bad() is unreachable as I am throwing an exception is catch then why it is not giving error for it ? class Varr { public static void main(String[] args) throws Exception { System.out.println("Main"); try { good(); } catch (Exception e) { System.out.println("Main catch"); //**Statement 1** throw new RuntimeException("RE"); } finally { System.out.println("Main Finally"); // **Statement 2** throw new RuntimeException("RE2"); } bad(); } } A: but my question is even if i comment it still the bad() is unreachable as i am throwing an exception is catch then why it is not giving error for it ? Because the execution will not necessary enter in the catch statement. Suppose that good() doesn't thrown any exception, so you don't enter in the catch and therefore bad() is then executed : public static void main(String[] args) throws Exception { System.out.println("Main"); try { good(); // doesn't throw an exception } catch (Exception e) { System.out.println("Main catch"); throw new RuntimeException("RE"); } bad(); // execution goes from good() to here }
[ "stackoverflow", "0036946884.txt" ]
Q: Finding the index of an object within an array efficiently I am trying to find the index of an object within an array. I know there is a way to do this with underscore.js but I am trying to find an efficient way without underscore.js. Here is what I have : var arrayOfObjs = [{ "ob1": "test1" }, { "ob2": "test1" }, { "ob1": "test3" }]; function FindIndex(key) { var rx = /\{.*?\}/; // regex: finds string that starts with { and ends with } var arr = []; // creates new array var str = JSON.stringify(arrayOfObjs); // turns array of objects into a string for (i = 0; i < arrayOfObjs.length; i++) { // loops through array of objects arr.push(str.match(rx)[0]); // pushes matched string into new array str = str.replace(rx, ''); // removes matched string from str } var Index = arr.indexOf(JSON.stringify(key)); // stringfy key and finds index of key in the new array alert(Index); } FindIndex({"ob2": "test1"}); JSFIDDLE This works but I am afraid it isn't very efficient. Any alternatives? A: Here's one way to do it, somewhat reliably and a little more efficiently, using some() and stopping as soon as the objects don't match etc. var arrayOfObjs = [{ "ob1": "test1" }, { "ob2": "test1" }, { "ob1": "test3" }]; function FindIndex(key) { var index = -1; arrayOfObjs.some(function(item, i) { var result = Object.keys(key).some(function(oKey) { return (oKey in item && item[oKey] === key[oKey]); }); if (result) index = i; return result; }); return index; } var index = FindIndex({"ob2": "test1"}); document.body.innerHTML = "'{\"ob2\": \"test1\"}' is at index : " + index; A: A hash table with an example of access. var arrayOfObjs = [{ "obj1": "test1" }, { "obj2": "test1" }, { "obj1": "test3" }], hash = {}; arrayOfObjs.forEach(function (a, i) { Object.keys(a).forEach(function (k) { hash[k] = hash[k] || {}; hash[k][a[k]] = i; }); }); document.write('<pre>' + JSON.stringify(hash['obj2']['test1'], 0, 4) + '</pre>'); document.write('<pre>' + JSON.stringify(hash, 0, 4) + '</pre>'); A: One way of doing this would be to use every to see if each key in the "filter" has a matching, correct value in an object. every ensures that the loop stops as soon as it finds a mismatched or missing value. function log(msg) { document.querySelector('pre').innerHTML += msg + '\n'; } var arr = [ { a: 1 }, { b: 2 }, { c: 3, d: 4 }, { a: 1 // Will never reach this since it finds the first occurrence } ]; function getIndex(filter) { var keys = Object.keys(filter); for (var i = 0, len = arr.length; i < len; i++) { var obj = arr[i]; var match = keys.every(function(key) { return filter[key] === obj[key]; }); if (match) { return i; } } return -1; } log(getIndex({ a: 1 })); log(getIndex({ b: 2 })); log(getIndex({ c: 3 })); log(getIndex({ c: 3, d: 4 })); log(getIndex({ e: 5 })); // Doesn't exist, won't find it <pre></pre>
[ "stackoverflow", "0021364854.txt" ]
Q: Code not writing output to file This code is not writing the output to the file. It only dumps the data in the .data file not the output which should be a range from 0 to 1. import math f = open('numeric.sm.data', 'r') print f maximum = 0 # get the maximum value for input in f: maximum = max(int(input), maximum) f.close() print('maximum ' + str(maximum)) # re-open the file to read in the values f = open('numeric.sm.data', 'r') print f o = open('numeric_sm_results.txt', 'w') print o for input in f: # method 1: Divide each value by max value m1 = float(input) / (maximum) o.write(input) print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5) o.close() f.close() A: o.write(input) should be o.write(str(m1)) and probably you want to add a newline or something: o.write('{0}\n'.format(m1))
[ "stackoverflow", "0001918677.txt" ]
Q: What kind of cool graphics algorithms can I implement? I'm going to program a fancy (animated) about-box for an app I'm working on. Since this is where programmers are often allowed to shine and play with code, I'm eager to find out what kind of cool algorithms the community has implemented. The algorithms can be animated fractals, sine blobs, flames, smoke, particle systems etc. However, a few natural constraints come to mind: It should be possible to implement the algorithm in virtually any language. Thus advanced directx code or XNA code that utilizes libraries that aren't accessible in most languages should not be posted. 3D is most welcome, but it shouldn't rely on lots of extra installs. If you could post an image along with your code effect, it would be awesome. Here's an example of a cool about box with an animated 3D figure and some animated sine blobs on the titlebar: And here's an image of the about box used in Winamp, complete with 3D animations: A: I tested and ran the code on this page. It produces an old-school 2D flame effect. Even when I ran it on an N270 in HD fullscreen it seemed to work fine with no lag. The code and all source is posted on the given webpage. A: Metaballs is another possibly interesting approach. They define an energy field around a blob and will melt two shapes together when they are close enough. A link to an article can be found here. A: Something called a Wolfram Worm seems so be an awesome project to attempt. It would be easy to calculate random smooth movement by using movement along two connected bezier curves. Loads of awesome demos can be found on this page: http://levitated.net/daily/index.html (source: levitated.net)
[ "stackoverflow", "0004341872.txt" ]
Q: named queries in hibernate 3 only? I have read in a book saying that named queries are introduced in version 3 of hibernate only. However I remember using them in Hibernate 2. Can someone validate which is correct? A: If I believe this documentation of the API, I would say that named queries were there back in version 2.0. Hibernate API Documentation Yet, it is not clearly mentioned, I believe only since I found this link for a search to "Hibernate 2.0 documentation" on Google, and it is not the same documentation of the actual version, plus it mentions hibernate-2 in the URL.
[ "stackoverflow", "0022262052.txt" ]
Q: Show difference in days in Date::Manip::Delta_Format I'm calculating the difference between 2 dates what are a few days apart, but the result I get from Delta_Format shows the days in hours. print Delta_Format(DateCalc(ParseDate("2014-03-07 14:16:23"), ParseDate("2014-03-03 18:43:10")), 0, ("%Mv", "%dv", "%hv", "%mv", "%sv")) . "!\n"; Gives me this output: 0 0 -91 -33 -13! Which means zero months, zero days, 91 hours, 33 minutes, 13 seconds. How do I make Delta_Format show me 3 days, 19 hours, 33 minutes, 13 seconds? A: Basically you're trying to normalize your Date::Manip::Delta. You can specify different modes to DateCalc function in the 4th parameter, and the mode=1 is normalize. Unfortunately, the way it's implemented allows for negative values, and I'm not sure how to force just positives. This is one reason why I've never used this module in any serious way :) use Date::Manip; use strict; use warnings; my $date1 = ParseDate("2014-03-07 14:16:23"); my $date2 = ParseDate("2014-03-03 18:43:10"); my $delta = DateCalc($date2,$date1, \my $err, 1); print Delta_Format($delta, "%Mv %dv %hv %mv %sv"); # 0 4 -4 -26 -47 One alternative using Time::Piece use Time::Piece; use strict; use warnings; my $tp1 = Time::Piece->strptime("2014-03-07 14:16:23", "%Y-%m-%d %H:%M:%S"); my $tp2 = Time::Piece->strptime("2014-03-03 18:43:10", "%Y-%m-%d %H:%M:%S"); my $diff = $tp1 - $tp2; print $diff->pretty, "\n"; #3 days, 19 hours, 33 minutes, 13 seconds
[ "superuser", "0001324437.txt" ]
Q: NAS does not reconnect to network after router reboot My Synology NAS does not reconnect to the network when the router reboots or when Internet goes down and then comes back. I am connected over ethernet and the network light is on but I cannot ping the NAS or access it through the webpage. What could be the reason for this? Edit 2018-05-23: Added bounty. This is a weird issue. All the other devices in my network (hard-wired or wireless) reconnect to the network/Internet after the Internet comes back up but my NAS does not respond when I try to ping the machine (ping 192.168.1.xxx or ping NAS) A: Solved my issue. I had my NAS' MAC address assigned a static IP in my router. In the NAS, I had the IP obtained by DHCP. I changed this to a Static IP (same IP in the router) and this fixed my issue. Must have been an issue of same IP on network or something but anyway, now the NAS will automatically reconnect to network if it ever loses connection my router.
[ "stackoverflow", "0060204111.txt" ]
Q: Specific SQL query to count I'm developing a CRM, that's why I created poles to separate my users. I created a view which gathered all the information of a user. I'm looking to know how to count the number of users logged in by pole. In my VIEW I have a user_online field. I also have a pole_name field. I tried this request but it doesn't work. SELECT pole_name, COUNT(user_online) AS nbr_online FROM `ViewProjet_userPoleRole` GROUP BY pole_name Which gives me the total number of users of a pole and therefore not if it is online. And finally, here is my entire VIEW. I have tried several requests, but I cannot. A: I think you can use conditional aggregation as following: SELECT POLE_NAME, SUM(CASE WHEN USER_ONLINE = 'Y' THEN 1 ELSE 0 END) AS NBR_ONLINE FROM VIEWPROJET_USERPOLEROLE GROUP BY POLE_NAME or If you want to know only Poles with minimum one online user then put the condition in the WHERE clause as follows: SELECT POLE_NAME, COUNT(1) AS NBR_ONLINE FROM VIEWPROJET_USERPOLEROLE WHERE USER_ONLINE = 'Y' GROUP BY POLE_NAME If you represent online user by some other kind of norms then use them in WHEN clause of the CASE statement accordingly. Cheers!!
[ "stackoverflow", "0044267062.txt" ]
Q: primeng v2.0.6 p-dialog is not a modal in angular 2.4.10 I am using a primeng modal v2.0.6 in an angular 2.4.10 component: The following is my html template: <section class="content-header"> <h1> Dino 3D Viewer Experiment </h1> </section> <!-- Main content --> <section #phone class="content"> <button pButton id="screenshot" class="no-spinner" type="button" (click)="callAlert('screenshot')" label="screenshot"></button> <button pButton id="download" class="no-spinner" type="button" (click)="downloadStl()" label="download geometry"></button> <button pButton id="dialog" class="no-spinner" type="button" (click)="showDialog()" label="open modal"></button> </section> <p-dialog header="Godfather I" [(visible)]="display" modal="modal" width="300" [responsive]="true"> <p>The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from the war, but does not intend to become part of his father's business. Through Michael's life the nature of the family business becomes clear. The business of the family is just like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence whenever anything stands against the good of the family.</p> <p-footer> <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"> <button type="button" pButton icon="fa-close" (click)="display=false" label="No"></button> <button type="button" pButton icon="fa-check" (click)="display=false" label="Yes"></button> </div> </p-footer> </p-dialog> the following is my component.ts file: @Component({ selector: 'dino-viewer', templateUrl: './dino-viewer.html', styleUrls: ['./dino-viewer.component.css'] }) export class dinoViewerComponent { display: boolean; callAlert(aMessage) { alert(aMessage); } showDialog() { this.display = true; } } and the following is the unfortunate result: after some reading I have tried to add the following to the element: appendTo="body" appendTo="@body" appendTo="@(body)" appendToBody="true" but the modal does not show as modal. Any suggestion? Thank you very much for your help, Dino A: I find the solution to my own problem. The project was missing the css libraries: primeng/resources/themes/omega/theme.css font-awesome/css/font-awesome.min.css primeng/resources/primeng.min.css Hope this helps someone.
[ "math.stackexchange", "0000342293.txt" ]
Q: Three points on a circle If three points are randomly chosen on the boundary of a circle, what is the probability that there exists a diameter of the circle such that all three points lie on the same side of it? I have a solution, but I'm very curious to see how others do it (and whether we get the same answer)! Thanks. A: Choose the points on the unit circle in the complex plane, with arguments $\theta_1, \theta_2, \theta_3$. If it happens that the differences $\theta_2 - \theta_1$ and $\theta_3 - \theta_1$ are both between $0$ and $\pi$ modulo $2\pi$, then the points are on the same half circle. From independence of the variables, the probability of this happening is $\frac {1} {4}$. Now we need to consider symmetrical cases - the above is the case that the first point is "to the right" of the next two points, but either point could be "on the right" of the other two points. The three cases are symmetrical and disjoint, so the total probability is $\frac 3 4$. The general case of $n$ points can be solved the same way and it results in $\frac n {2^{n-1}}$.
[ "math.stackexchange", "0002266634.txt" ]
Q: comparison of two types of decomposition of finite abelian groups If $G$ is a finite abelian group then $G$ has a decomposition into two types: (1) one is direct product of cyclic groups of some prime power order (may be with repitition) (2) other is direct product of cyclic groups where order of one component divides order of next one (invariant factors). In the comparison of these two factorisations, I came across following natural question, which is usually not raised or discussed in classrooms or in books. Q. What information about $G$ can be immediately given from one factorization which is not immediate from other factorization? For example, if we know factorization $\mathbb{Z}_{d_1}\times \cdots\times\mathbb{Z}_{d_r}$ with $d_i|d_{i+1}$, we can say what is exponent, whether group is cyclic. I don't know beyond this, for what purpose one fattorisation is useful than other. A: Going from the second to the first involves factorization of integers, which is believed to a computationally difficult problem (the security of your bank account probably depends on this). But it is computationally easy to go from (1) to (2). So one answer is that (1) provides you immediately with a prime factorization of $|G|$ (and makes it easy to compute Sylow subgroups), whereas (2) does not.
[ "stackoverflow", "0054998037.txt" ]
Q: How to remove longer element in each group in SQL? I have a table: name1 name2 abc def abc de xy cdf xy che mnp qpr mnp qprt mnp qp I want to remove the longer name2 for each group of name1. More specifically, for each group of name1, the first two characters of the shorter name2 should be the same as the longer one. Moreover, the number of row of each group should be 2, i.e., groups with rows more than 2 are not considered. Here is the expected output:(only def is removed) name1 name2 abc de xy cdf xy che mnp qpr mnp qprt mnp qp How to write the SQL command? A: Something like this should work: SELECT name1, name2 FROM ( SELECT name1, name2, COUNT(*) OVER (PARTITION BY name1) AS grp_cnt, s.similar_cnt FROM mytable t OUTER APPLY ( SELECT COUNT(*) similar_cnt FROM mytable WHERE name1 = t.name1 AND name2 <> t.name2 AND t.name2 LIKE name2 + '%' ) AS s ) AS x WHERE x.grp_cnt > 2 OR x.similar_cnt = 0 Demo here Explanation: COUNT(*) OVER (PARTITION BY name1) counts the population of each name1 group of records OUTER APPLY is used to check for records having the same name1 and similar name2 values. Similar here means same as the other one but shorter. You can easily adjust similarity checking by fiddling with the WHERE clause of the OUTER APPLY subquery.
[ "stackoverflow", "0027081845.txt" ]
Q: Importing quoted data into SQL, losing data I have 3 large txt files with tab delimited data that is enclosed in quotes. Here is an example line from one of the files: "deleted for privacy" 185 "12/31/2005" "01/16/2009" "deleted for privacy" false 1 "Accounting Issues" "deleted for privacy" 0 0 0 1 0 0 "deleted for privacy" I've removed some potentially sensitive information, but you get the idea. It seems to be tab delimited, most values are enclosed in quotes, but not all of them. The problem is the two date columns are showing up blank for some rows after I import the file into SQL. So, for instance, one of the original files has 5 million rows like the one above with NO blanks in those date columns. Once I bring it into SQL, about a million of those 5 million rows have no value in those date columns. I'm not getting any errors during the import process. One of the 3 large files is small enough that I'm able to open it in notepad and remove the quotes from all of the values before importing into SQL. This seems to fix the problem. No date values seem to be lost if I remove the quotes before importing into SQL. The problem is 2 of the 3 files are too large to open in notepad to remove the quotes PRIOR to importing. A: You don't mention the tool that you're using to do the bulk import, I'll assume bcp or BULK INSERT statement. I assume that the datatypes of the corresponding columns are of date-time type. In that case SQL server is probably mis-interpreting the date format as dd/mm/yyyy format (European), rather than mm/dd/yyyy (American) style. Values that cannot be converted in the given style are set to NULL. I usually solve data import issues such as this by importing into a scratch table, where all columns are varchar(max), and then running a post processing stored procedure to transfer imported rows from the scratch table into the final table, defining explicit conversions as required. An alternative to this would be to import using a custom dtsx package, and define the conversions required as a Data Conversion Transformation task.
[ "history.stackexchange", "0000002367.txt" ]
Q: Were the Vikings descendents of the Tribe of Dan? I've heard the Vikings were descendents of the Hebrew Tribe of Dan. Is it true? http://en.wikipedia.org/wiki/Nordic_Israelism http://www.ensignmessage.com/archives/tracingdan2.html A: In short: no. Culturally, the Vikings are well-documented to be part of the Norse culture of the Dark Ages, which in turn is clearly descended from an earlier common Germanic culture. Linguistically, the Vikings spoke Old Norse, which is part of the North Germanic branch of Indo-European. The Israelites spoke Ancient Hebrew, which is part of the Semitic branch of the Afro-Asiatic language family. If the Vikings had been an Israelite tribe, you'd expect them to speak Hebrew, or have Hebrew borrowings in their language (which they don't). Israelites picking up a Germanic language would be expected to end up with something more like Yiddish, which is riddled with Hebrew influence. Genetically, there's some very interesting material to look at about Y-chromosomal haplogroups. Jewish communities worldwide have a high proportion of certain haplogroups (such as the famous J1c3, common among Kohen families). Scandinavia (where the Vikings lived) has an extremely low proportion of those haplogroups. Here's a Wikipedia article on haplogroup J1 to get you started. The website you linked to makes some interesting claims, but they don't link them together very well. For example, they make a claim that the tribe of Dan might not have been Israelite at all, and then they jump straight into assuming that the tribe was connected to Tarshish, without any evidence of that. Later, they identify the tribe of Dan with the legendary Tuatha de Danann without any evidence other than having vaguely similar names. Then, they claim that the Scythians were Israelites, based solely on the Jewish holiday called Sukkot. Here's a great article from Mark Rosenfelder explaining this phenomenon: How Likely are Chance Resemblances between Languages?.
[ "stackoverflow", "0055574087.txt" ]
Q: Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php) I try to make a page index.blade, but i getting error Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php) I am using laravel 5.4 PHP 7.0.33 Is there anything wrong with the code? My Controller <?php namespace App\Http\Controllers; use App\Category; use Illuminate\Http\Request; class CategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $categories = Category::orderBy('created_at', 'DESC')->paginate(10); return view('categories.index', compact('categories'));// } My index.blade this is my view/categories/index.blade.php @extends('layout.master') ​ @section('title') <title>Manajemen Kategori</title> @endsection ​ @section('content') <div class="content-wrapper"> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Manajemen Kategori</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Kategori</li> </ol> </div> </div> </div> </div> ​ <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> @card @slot('title') <div class="card"> <div class="card-header with-border"> <h3 class="card-title">{{ $title }}</h3> </div> <div class="card-body"> {{ $slot }} </div> {{ $footer }} </div> @endslot @if (session('error')) @alert <div class="alert alert-{{ $type }} alert-dismissible"> {{ $slot }} </div> @endalert @endif ​ <form role="form" action="{{ route('kategori.store') }}" method="POST"> @csrf <div class="form-group"> <label for="name">Kategori</label> <input type="text" name="name" class="form-control {{ $errors->has('name') ? 'is-invalid':'' }}" id="name" required> </div> <div class="form-group"> <label for="description">Deskripsi</label> <textarea name="description" id="description" cols="5" rows="5" class="form-control {{ $errors->has('description') ? 'is-invalid':'' }}"></textarea> </div> @slot('footer') <div class="card-footer"> <button class="btn btn-primary">Simpan</button> </div> </form> @endslot @endcard </div> <div class="col-md-8"> @card @slot('title') List Kategori @endslot @if (session('success')) @alert(['type' => 'success']) {!! session('success') !!} @endalert @endif <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <td>#</td> <td>Kategori</td> <td>Deskripsi</td> <td>Aksi</td> </tr> </thead> <tbody> @php $no = 1; @endphp @forelse ($categories as $row) <tr> <td>{{ $no++ }}</td> <td>{{ $row->name }}</td> <td>{{ $row->description }}</td> <td> <form action="{{ route('kategori.destroy', $row->id) }}" method="POST"> @csrf <input type="hidden" name="_method" value="DELETE"> <a href="{{ route('kategori.edit', $row->id) }}" class="btn btn-warning btn-sm"><i class="fa fa-edit"></i></a> <button class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button> </form> </td> </tr> @empty <tr> <td colspan="4" class="text-center">Tidak ada data</td> </tr> @endforelse </tbody> </table> </div> @slot('footer') ​ @endslot @endcard </div> </div> </div> </section> </div> @endsection My route web.php Route::resource('/kategori', 'CategoryController', ['except' => ['create', 'show']]); A: It should be like this public function index() { $categories = Category::orderBy('created_at', 'DESC')->paginate(10); $title = ''; //your title return view('categories.index', compact('categories','title')); } because title not getting value from controller.
[ "math.stackexchange", "0002667905.txt" ]
Q: Perfect squares that ends in $4$s Prove that there is an infinity of perfect squares which have $4$ as the last 3 digits. Prove that there are no perfect squares which have $4$ as the last 4 digits. This is a problem form a math contest (Romanian Math Olympiad, county level) for fifth graders. No calculators allowed. I couldn't even come quickly with a solution at highschool level, so any help is highly appreciated. A: If you observe that $1444=38^2$, the perfect squares $$(1000k+38)^2=1000000k^2+76000k+1444$$ end in $444$. For the second question, notice that the last four digits of a perfect square only depend on the last two digits of the root, and we have $$66^2<4444<67^2.$$
[ "stackoverflow", "0020758603.txt" ]
Q: app crashes on changing min sdk version and target version I have this app working on my test phone ,but i got an parsing package error in samsung phone. On further googling gave me the solution to change the sdk version to 1.I changed the min sdk version to 1 (initially 13) and android target to 1(initially 13), and my app is crashing ,can some one help me on this . This is the eclipse logcat E/AndroidRuntime(10146): FATAL EXCEPTION: main E/AndroidRuntime(10146): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mystictreegames.pagecurl/com.mystictreegames.pagecurl.StandaloneExample}: android.view.InflateException: Binary XML file line #6: Error inflating class com.mystictreegames.pagecurl.PageCurlView E/AndroidRuntime(10146): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343) E/AndroidRuntime(10146): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) E/AndroidRuntime(10146): at android.app.ActivityThread.access$600(ActivityThread.java:162) E/AndroidRuntime(10146): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) E/AndroidRuntime(10146): at android.os.Handler.dispatchMessage(Handler.java:107) E/AndroidRuntime(10146): at android.os.Looper.loop(Looper.java:194) E/AndroidRuntime(10146): at android.app.ActivityThread.main(ActivityThread.java:5371) E/AndroidRuntime(10146): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(10146): at java.lang.reflect.Method.invoke(Method.java:525) E/AndroidRuntime(10146): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) E/AndroidRuntime(10146): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) E/AndroidRuntime(10146): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime(10146): Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class com.mystictreegames.pagecurl.PageCurlView E/AndroidRuntime(10146): at android.view.LayoutInflater.createView(LayoutInflater.java:613) E/AndroidRuntime(10146): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) E/AndroidRuntime(10146): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) E/AndroidRuntime(10146): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) E/AndroidRuntime(10146): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) E/AndroidRuntime(10146): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) E/AndroidRuntime(10146): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:281) E/AndroidRuntime(10146): at android.app.Activity.setContentView(Activity.java:1881) E/AndroidRuntime(10146): at com.mystictreegames.pagecurl.StandaloneExample.onCreate(StandaloneExample.java:22) E/AndroidRuntime(10146): at android.app.Activity.performCreate(Activity.java:5122) E/AndroidRuntime(10146): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081) E/AndroidRuntime(10146): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307) E/AndroidRuntime(10146): ... 11 more E/AndroidRuntime(10146): Caused by: java.lang.reflect.InvocationTargetException E/AndroidRuntime(10146): at java.lang.reflect.Constructor.constructNative(Native Method) E/AndroidRuntime(10146): at java.lang.reflect.Constructor.newInstance(Constructor.java:417) E/AndroidRuntime(10146): at android.view.LayoutInflater.createView(LayoutInflater.java:587) E/AndroidRuntime(10146): ... 22 more E/AndroidRuntime(10146): Caused by: java.lang.IllegalArgumentException: x + width must be <= bitmap.width() E/AndroidRuntime(10146): at android.graphics.Bitmap.createBitmap(Bitmap.java:554) E/AndroidRuntime(10146): at com.mystictreegames.pagecurl.PageCurlView.init(PageCurlView.java:419) E/AndroidRuntime(10146): at com.mystictreegames.pagecurl.PageCurlView.<init>(PageCurlView.java:208) E/AndroidRuntime(10146): ... 25 more A: Don't set your target SDK version to 1. Set it to your actual target: the level where you have developed and tested your app. When you set your target to less than 4, you'll get a compatibility mode enabled which scales your resources automatically, assuming everything is MDPI (reference). This automatic scaling is the likely cause for the exception java.lang.IllegalArgumentException: x + width must be <= bitmap.width().
[ "pt.stackoverflow", "0000261392.txt" ]
Q: BufferedReader retorna sempre null Apesar de algumas perguntas já existirem com o assunto similar, não consegui uma resposta exata, por isso recorro mais uma vez ao Stack. Estou a desenvolver um sistema cliente-servidor, já tinha o projeto mais adiantado, e resolvi comecar do início: CLIENTE Tive que eliminar algumas linhas de codigo para perceber onde se encontrava o erro. O erro encontra-se quando faço uso do in.read() ou in.readLine(), acaba sempre por retornar uma excepção. private Socket socket = null; private int port = 2048; private String host; private Utilizador utilizador; private Mensagem mensagemServidor; private static PrintWriter out = null; private static BufferedReader in = null; // private static ObjectOutputStream objectOut; //private static ObjectInputStream objectIn; private static int vefVariable; private static String mensagemServidorThr; /** * Construtor para ser usado na conecção ao servidor pela primeira vez pelo * utilizador * * @param hostInstace * @param user */ public Socket_Client(String hostInstace, Utilizador user) { this.host = hostInstace; this.utilizador = user; } /** * Construtor para ser usado para envio de mensagem do cliente para o * servidor * * @param user utilizador que envia a mensagem * @param mensagem mensagem que o utilizador mandou. */ public Socket_Client(Mensagem mensagem) { this.mensagemServidor = mensagem; } public void connecttoServer() throws IOException { try { socket = new Socket(host, port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Não existe informação com o servidor" + host); } catch (IOException e) { System.err.println("Não existe informação com o servidor" + host); } out.println("tudobem"); System.out.println(in.read()); } SERVIDOR public static void main(String[] args) throws IOException { ServerSocket srvSckt = null; int porto = 2048; boolean listening = true; //conecao ao servidor try { srvSckt = new ServerSocket(porto); System.out.println("Conecção ao Servidor efectuada com sucesso!"); }catch(IOException ex) { System.err.println("Impossível coneção a porta \t" +porto); } Socket clientSocket = null; clientSocket = srvSckt.accept(); } Penso que falte a comunicacao com a parte do servidor, mas ja tentei e continua a nao funcionar, desta vez nao me aparece os elementos da interface grafica. A: O servidor aceita a conexão mas logo em seguida o programa é terminado, portanto a conexão vai ser fechada. O método readLine retorna null (read retorna -1) pois a conexão foi fechada logo após ter sido aberta. Aqui o trecho do código em questão (com problema) comentado: public static void main(String[] args) throws IOException { ... clientSocket = srvSckt.accept(); // aceita a conexão } // main, programa, conexão terminam/fecham em outras palavras, está faltando o código que vai tratar da comunicação com o cliente. Pelo menos tem que fazer uma leitura do clientSocket para ler a frase enviada pelo cliente e, em seguida enviar a resposta para o cliente. Normalmente isso ocorre num loop até a conexão ser fechada, dependendo do protocolo usado (por exemplo: cliente envia "exit" para terminar a conexão). Exemplo (muito simplificado): public static void main(String[] args) throws IOException { ... clientSocket = srvSckt.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String str = in.readLine(); System.out.printf("Servidor recebeu \"%s\"\n", str); out.write('X'); out.flush(); // outros comandos, se terminar o main provavelmente o cliente // não irá receber a respota try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } clientSocket.close(); }
[ "stackoverflow", "0005698601.txt" ]
Q: How can I update using jQuery and NOT from a file the contents of a div? how can I reload the contents of a div not by using the .load('file') ? Just the contents of it (they are dynamically updated upon refresh). <div id="myreload"> . . . </div> This is a code I used to use <script language="JavaScript"> $(function() { var SANAjax = function(){ $('#details').empty().addClass('loading') .load('home.php', function() { $(this).removeClass('loading') }); } setInterval(SANAjax, 5000 ); }); </script> Thank you all. A: $('#myreload').html('your contents here');
[ "travel.stackexchange", "0000110084.txt" ]
Q: In which countries are Australian citizens legally allowed to work while visiting as a tourist besides New Zealand and Georgia? I know as an Aussie I'm allowed to work while vising Georgia as I did so in 2011/12. I also know I'm allowed to work in New Zealand as Australians are granted a special status there. But are there any other countries where this is possible, as a tourist? I don't intend to be an expat, actually moving to any country where special work visas, residency, or anything more complicated along those lines is required. I'm only interested in countries where I can arrive as a tourist yet I'm still permitted legally to work there. A: Shamelessly plagiarizing myself: There's one more place where an Australian citizen can work completely legally and indefinitely on a tourist visa: Svalbard! Under the terms of the Svalbard Treaty, any citizen of a treaty signatory, including Australia, may "become residents and to have access to Svalbard including the right to fish, hunt or undertake any kind of maritime, industrial, mining or trade activity." Squint hard enough, and it looks just like Bondi Beach! Shown here in summer. (Photo mine.) Now, there are a couple of minor catches... Located at 78°N, Svalbard's main town Longyearbyen (pop. 2600) is by far the world's most northernmost civilian settlement, and rather resembles Mordor after it has frozen over: lots of black rock, virtually no plants larger than lichen. This means an average February day is −21°C, a balmy summer day in August is 3°C, and oh, there's no sunlight whatsoever during the polar night between late October and mid-February. Also, you need to carry a rifle if traveling anywhere outside the town due to the large and hungry polar bear population. The only practical way to get to Svalbard is Norway, which can and does enforce its own visa rules. That said, once there Norway and Schengen rules (eg. the 90-in-180 limit) do not apply, all you need to demonstrate is that you have the means to support yourself. Essentially all private accommodation on Svalbard is owned by companies in Svalbard, which means finding a place to rent is tough to impossible. Now you could just stay in a hotel, but... If you thought Norway was expensive, imagine Norwegian prices with a hefty bonus for shipping everything through some of the roughest sea on Earth. You won't get much change back from US$20 if you buy a kebab and a Coke. So hey, it's not exactly a tropical paradise island, but at least working there is perfectly legal!
[ "stackoverflow", "0035661085.txt" ]
Q: Selecting specific rows from a python dataframe for an ols regression in PANDAS How do I select specific rows from a python dataframe for an ols regression in PANDAS? I have a pandas dataframe with 1,000 rows. I want to regress column A on columns B + C, for the first 10 rows. When I type: mod = pd.ols(y=df[‘A’], x=df[[‘B’,’C’]], window=10) I get the regression results for rows 991-1000. How do I specify that I want the FIRST (or second, etc.) 10 rows? Thanks in advance. A: I think you can use iloc: mod = pd.ols(y=df['A'].iloc[2:12], x=df[['B','C']].iloc[2:12], window=10) Or ix: mod = pd.ols(y=df.ix[2:12, 'A'], x=df.ix[2:12, ['B', 'C']], window=10) If you need all groups use range: for i in range(10): #print i, i+10 mod = pd.ols(y=df['A'].iloc[i:i + 10], x=df[['B','C']].iloc[i:i + 10], window=10) If you need help about ols, try help(pd.ols) in IPython, because this function in pandas docs is missing: In [79]: help(pd.ols) Help on function ols in module pandas.stats.interface: ols(**kwargs) Returns the appropriate OLS object depending on whether you need simple or panel OLS, and a full-sample or rolling/expanding OLS. Will be a normal linear regression or a (pooled) panel regression depending on the type of the inputs: y : Series, x : DataFrame -> OLS y : Series, x : dict of DataFrame -> OLS y : DataFrame, x : DataFrame -> PanelOLS y : DataFrame, x : dict of DataFrame/Panel -> PanelOLS y : Series with MultiIndex, x : Panel/DataFrame + MultiIndex -> PanelOLS Parameters ---------- y: Series or DataFrame See above for types x: Series, DataFrame, dict of Series, dict of DataFrame, Panel weights : Series or ndarray The weights are presumed to be (proportional to) the inverse of the variance of the observations. That is, if the variables are to be transformed by 1/sqrt(W) you must supply weights = 1/W intercept: bool True if you want an intercept. Defaults to True. nw_lags: None or int Number of Newey-West lags. Defaults to None. nw_overlap: bool Whether there are overlaps in the NW lags. Defaults to False. window_type: {'full sample', 'rolling', 'expanding'} 'full sample' by default window: int size of window (for rolling/expanding OLS). If window passed and no explicit window_type, 'rolling" will be used as the window_type Panel OLS options: pool: bool Whether to run pooled panel regression. Defaults to true. entity_effects: bool Whether to account for entity fixed effects. Defaults to false. time_effects: bool Whether to account for time fixed effects. Defaults to false. x_effects: list List of x's to account for fixed effects. Defaults to none. dropped_dummies: dict Key is the name of the variable for the fixed effect. Value is the value of that variable for which we drop the dummy. For entity fixed effects, key equals 'entity'. By default, the first dummy is dropped if no dummy is specified. cluster: {'time', 'entity'} cluster variances Examples -------- # Run simple OLS. result = ols(y=y, x=x) # Run rolling simple OLS with window of size 10. result = ols(y=y, x=x, window_type='rolling', window=10) print(result.beta) result = ols(y=y, x=x, nw_lags=1) # Set up LHS and RHS for data across all items y = A x = {'B' : B, 'C' : C} # Run panel OLS. result = ols(y=y, x=x) # Run expanding panel OLS with window 10 and entity clustering. result = ols(y=y, x=x, cluster='entity', window_type='expanding', window=10) Returns ------- The appropriate OLS object, which allows you to obtain betas and various statistics, such as std err, t-stat, etc.
[ "stackoverflow", "0007444818.txt" ]
Q: Data Structure -- representation of cards This is a data structure/mapping question. I'm using MSSQL, with .NET and EF (and MVC if that's important). I have a table that represents a deck of cards. The states of a card are: Face down in the deck Face up in the deck (discarded) In front of a player In a player's hand ...and there can be X players. I have a table that represents players as well, with their own unique key. Assume that each player is in a single game, and one deck of cards is in one game. At first, I thought there would be a one-to-many relationship between players and cards, enforced by a foreign key in the database. Player 1P has card 1C, 2C, and 4C, so cards 1C, 2C, 4C and "1P" under the PlayerID. Then there is a bit field to represent if the card was face up or face down. That works for state 3 and state 4. How should I handle state 1 and 2? Some options: Make the PlayerID on the Card table nullable. When I was using EF, I was running into foreign key constraints. Edit: I was running into foreign key constraints, but when I tried it now, it looks like it's working as one would expect. Creating a dummy player called "Deck", and assign all cards in state 1 and 2 to this player. But, this didn't seem elegant; the Deck player had a lot of other baggage that I didn't want to deal with, and if I started doing multiple games, I'd need multiple Deck players. Scrap the foreign key in the database, and make the PlayerID nullable. Enforce the constraint in the code. But then I can't do things like Player.Cards() without some extra extension code. Have two more bit fields: "IsInDeck" and "IsDiscarded" (or some field that represents multiple states, like an int that is 0: in deck; 1: in hand; 2: in front of player; 3: discarded). That way, we don't really care what the PlayerID is if the card is in the "Discarded" state. Some other option I haven't thought of. Ideas? Thanks in advance. A: You could try a schema like this: The tables PLAYER, CARD, and DECK are hopefully pretty clear. LOCATION_TYPE is a list of the kinds of locations that might apply. This would include things like "in a player's hand", "in front of a player", "face down in the deck" and "discard pile". You could use a physical table for LOCATION_TYPE or you could use an enum. The advantage of a table is that you could include some business rules like whether the location type requires a PLAYER FK in CARD_LOCATION and whether the card is visible or invisible (face up/down). CARD_LOCATION is therefore the intersection that tells you where each card is at any given time. Your Player.Cards navigation property will work well as will your Card.Location navigation property. It is important to note that the FK from CARD_LOCATION to PLAYER is optional.
[ "stackoverflow", "0012295690.txt" ]
Q: JQuery each function? Script: var degress = GiveDegrees(); $(function () { //alert(GiveDegrees()); //output: 89,91,87,90,91 }); function GiveDegrees() { var divs = $('p.wx-temp'); var degrees = new Array(); $.each(divs, function (i, j) { degrees.push(stringToNum($(this).text())); }); return degrees; } function stringToNum(str) { return str.match(/\d+/g); } I have this : $("p.wx-temp").each(degress, function (index) { $(this).append(degress[index], "<sup>°C</sup>"); alert("I works"); }); But It does not work. when I write like this: $("p.wx-temp").each(function (index) { $(this).append("<sup>°C</sup>"); alert("I works"); }); It works. Is there no overload method for .each() function .each(data, function (index)) ? degrees array is integer array that include five int as 89,91,87,90,91. How can I use .each function to add array values to each p element. Thanks. A: Why would you need to bring degress into the each at all? It’s already available, using closures: $("p.wx-temp").each(function(index) { $(this).append(degrees[index], "<sup>°C</sup>"); alert("I works"); }); OR var $elems = $("p.wx-temp"); $.each(degrees, function(i, val) { $elems.eq(i).append(val, '<sup>°C</sup>'); }); If the elements length matches the array length, it should make no difference wich one you loop, but the first one is probably faster (although using a native array loop would be fastest). Note that you are spelling degrees and degress differently in the two sections.
[ "math.stackexchange", "0003804114.txt" ]
Q: Differentiable linear mappings I'm reading Advanced calculus of several variable, by Edwards C.H. On page 60 is written the following theorem : Theorem 1.2. "The mapping $f:\Bbb{R}\to\Bbb{R^m}$ is differentiable at $a\in \Bbb{R^m}$ if and only if there exists a linear mapping $L:\Bbb{R} \to \Bbb{R^m}$ such that $$\lim_{h\to 0}\frac{f(a+h)-f(a)-L(h)}{h}=\bar{0}\space\space\space\space\space(6)$$ in which case $L$ is defined by $L(h)=d_{fa}(h)=hf'(a)."$ It would seem like $(6)$ is trying to convey the idea, that $f'(a)$ maybe approximated by some linear mapping $L(h)$, provided of course that $h$ is small. In the proof of the "$\leftarrow$" direction is written : "Suppose there exists a linear mapping satisfying $(6)$. Then there exists $\bar{b} \in \Bbb{R^m}$ such that $L(h)=h\bar{b}"$ There is no reference to any theorem, but it seems like the existence of such a $\bar{b}$ draws from the fact that $L(h)=hf'(a)$ and some connection between $f'(a)$ and $\bar{b}$. How can we conclude the existence of this $\bar{b}$? A: Not $f'(a)$ but $f(a+h)-f(a)$ may be approximated by a linear application. The writing $h\bar b$ is strange. But, if $L:\mathbb R^n\to \mathbb R^m$ is linear, there is a matrix $A\in \mathbb R^{m\times n}$ s.t. $L(h)=Ah$. So, in your case, $A\in \mathbb R^{m\times 1}$, and $Ah=h A$, so $\bar b$ is just the matrix of $L$.
[ "stats.stackexchange", "0000308730.txt" ]
Q: Simulation of a Poisson Process I am trying to simulate the compound Poisson process using the next algorithm that I found in a textbook on stochastic processes. Let $S_0 = 0$. Generate i.i.d. exponential random variables $X_1, X_2, \ldots$ Let $S_n=X_1+\cdots + X_n,$ for $n = 1, 2, \ldots$ For each $k = 0, 1, \ldots,$ let $N_t = k,$ for $S_k\le t\le S_{k+1}$ S <- vector(mode="integer", length=100) S[1] = 0 ## Generation of Exponential random variables with parameter lambda X <- rexp(n=100, rate=0.1) for(n in 1:100){ S[n] = sum(X[1:n]) } But, I am not clear about how to write the step $4$, maybe I need to put the integer between two $S_k$ (the arrival times)? I am interested in the counting process $N_t$. Furthermore, how do you plot it? I have something like that, but I am not clear if the arrival times are ok, because, in the first plot on the left, I see that every arrival time is not necessarily in the vertical line of the process, and on the right all the arrival times have the same length, I think that it contradicts the independence of the arrival times. nro<-10 S<-vector(mode="integer",length = nro) S[1]=0 ##Generation of Exponential random variables with parameter lambda X<-rexp(n =nro,rate = 2) for(n in 1:nro) S[n]=sum(X[1:n]) S<-cumsum(X) n_func <- function(t, S) sapply(t, function(t) sum(S < t)) t_series <- seq(0, max(S), by = max(S)/nro) #Plot of the trajectory and add lines in the arrival times par(mfrow=c(1,2)) plot(t_series, n_func(t_series, S),type = "s",ylab=expression(N[t]),xlab="t",las=1,cex.lab=0.8,main="Poisson Process",cex.axis=0.8) grid() abline(v = S,col="red",lty=2) plot(t_series, n_func(t_series, S),type = "s",ylab=expression(N[t]),xlab="t",las=1,cex.lab=0.8,main="Poisson Process",cex.axis=0.8) grid() abline(v = t_series,col="blue",lty=4) A: You want to get a function of $t$ that gives the count of events. So simply do n_func <- function(t, S) sapply(t, function(t) sum(S <= t)) t_series <- seq(0, max(S), by = max(S)/100) plot(t_series, n_func(t_series, S) $S$ is basically the time stamps of each Poisson events in your sample. So you want to just count the number of events that have time stamped before $t$.
[ "stackoverflow", "0016179590.txt" ]
Q: Regular Expression What is Matched Let's say you have a regular expression like this: \d+\.?\d* (mg |teaspoon |mcg |tablet |units |puffs |tab )*(\d )*(P\.O\. )*((once )*daily|B\.I\.D\.*|(once )*a day|Q\.I\.D\.|nightly|P\.R\.N\.|T\.I\.D\.|every (other )*(day|morning)) Which matches a variety of expressions including: 1 teaspoon once daily 1.5 mg 10 mg 1 P.O. nightly etc. What I'm trying to understand is given that say 1.5 mg and 1.5 mg daily are matches, will a java regular expression always match to the longest string? A: In this case if the rest of the pattern matches with the longer String, the longest String will be returned, instead of the shortest one. public static void main(String[] args) { String regex = "\\d+.?\\d* (mg |teaspoon |mcg |tablet |units |puffs |tab )(\\d )(P.O. )*((once )daily|B.I.D.|(once )a day|Q.I.D.|nightly|P.R.N.|T.I.D.|every (other )(day|morning))"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher("1.5 mg 10 mg 1 P.O. nightly"); while(m.find()){ System.out.println(m.group()); } } Prints: 10 mg 1 P.O. nightly
[ "stackoverflow", "0042874404.txt" ]
Q: reference to a value behind a pointer I want a reference to a value behind a pointer. class UnicastCall { protected: std::fstream *m_stream_attachement_destination_; ... public: auto GetStreamAttachementDestination_AsPointer() -> decltype(m_stream_attachement_destination_) { return m_stream_attachement_destination_; } //THIS WORKS auto GetStreamAttachementDestination_AsReference() -> decltype(*m_stream_attachement_destination_) & { return *m_stream_attachement_destination_; } //IS THIS CORRECT? .... }; But I get an error. error: use of deleted function 'std::basic_fstream<_CharT, _Traits>::basic_fstream(const std::basic_fstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' auto fs = concrete_call->GetStreamAttachementDestination_AsReference(); A: You are trying to copy an std::fstream, which is not allowed. The error is not in your class but at the call site. auto fs = ... does not create a reference but attempts to call the copy constructor; the auto is a substitute only for std::fstream, not the &. Try this instead: auto& fs = concrete_call->GetStreamAttachementDestination_AsReference();
[ "stackoverflow", "0003473881.txt" ]
Q: Android MediaStore setting photo name to NULL I have an app that allows the user to take and save a new picture using the Intent ACTION_IMAGE_CAPTURE. After the user accepts the newly taken picture, I create a ContentValue object to set the picture information, and then I insert the picture into the MediaStore and send a broadcast so that the user can see the photo when opening a picture viewer app such as gallery: ContentValues newImage = new ContentValues(3); newImage.put(Media.DISPLAY_NAME, mPicName); newImage.put(Media.MIME_TYPE, "image/png"); newImage.put(MediaStore.Images.Media.DATA, path); mPictureUri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, newImage); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mPictureUri)); All of this code works fine. The photo is correctly saved, and I can view the photo using gallery. The problem is that when I view the photo in gallery and select "Details" it shows the photo name as "null." And yes, I know for a fact that the variable mPicName above is not null and always has the correct value. The odd thing is that, when running my app on my Droid running Android 2.1, when I choose to copy files to/from the phone and my computer, I open up the Droid on my Windows computer, and when I go into my app's created folder for photos and view the new photo, the name is correct. Then, when I disable copying files from the phone/computer and go back into gallery to view the file on my Droid, the name is suddenly correct and is no longer null. Can someone tell me why the name is null after my code runs, and why the name is correct after viewing the file on my computer rather than on the phone? Is there a way to get the name non-null right when the picture is saved? I'd bet that the name would be correct if I turned my phone off and turned it back on, but I'm not sure how exactly to get force things to work immediately. A: Answer is by looking at the sources of MediaStore. One places is here: http://devdaily.com/java/jwarehouse/android/core/java/android/provider/MediaStore.java.shtml Basically they also add a thumbnail representation of the image and instead of Media.DISPLAY_NAME they use Media.TITLE. I used that code adapted a little and worked fine.
[ "stackoverflow", "0016584888.txt" ]
Q: Logback DBAppender DDL? I am interested in using slf4j-logback in my project, and would like to use the DBAppender. Apparently, unless you implement your own DBNameResolver, you must abide by the specific table criteria/schema outlined in the link above. Specifically, you need 3 tables with very specific columns. Although the information on that page is fairly verbose, it doesn't include any "table metadata" (keys, indexes, default values, etc.) and I'm wondering if we're left to add those at our own discretion or if they need to be defined with specific values. I tried looking for a DDL or SQL script for creating these tables, but couldn't find any. Do such scripts exist? How have other SOers dealt with the creation of these DBAppender tables? Thanks in advance! Edit: I found this article on Grails discussing DBAppender: You must create the database tables yourself. There are three tables, and the Logback distribution ships with sample DDL for several popular databases. I downloaded the latest (1.0.13) distribution and searched it high and low for .ddl and .sql files, and found something that resembled what I was looking for, located at: logback-1.0.13/logback-access/src/main/java/ch/qos/logback/access/db/script/mysql.sql # Logback: the reliable, generic, fast and flexible logging framework. # Copyright (C) 1999-2010, QOS.ch. All rights reserved. # # See http://logback.qos.ch/license.html for the applicable licensing # conditions. # This SQL script creates the required tables by ch.qos.logback.access.db.DBAppender. # # It is intended for MySQL databases. It has been tested on MySQL 5.0.22 with # INNODB tables. BEGIN; DROP TABLE IF EXISTS access_event_header; DROP TABLE IF EXISTS access_event; COMMIT; BEGIN; CREATE TABLE ACCESS_EVENT ( timestmp BIGINT NOT NULL, requestURI VARCHAR(254), requestURL VARCHAR(254), remoteHost VARCHAR(254), remoteUser VARCHAR(254), remoteAddr VARCHAR(254), protocol VARCHAR(254), method VARCHAR(254), serverName VARCHAR(254), postContent VARCHAR(254), event_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ); COMMIT; BEGIN; CREATE TABLE access_event_header ( event_id BIGINT NOT NULL, header_key VARCHAR(254) NOT NULL, header_value VARCHAR(1024), PRIMARY KEY(event_id, header_key), FOREIGN KEY (event_id) REFERENCES access_event(event_id) ); COMMIT; However these tables (access_event and access_event_header) are not the same 3 tables as what the documentation cites (logging_event, logging_event_property, and logging_event_exception). So I'm still at a loss here... A: I looked at the source code for 1.0.13's DBAppender. The Javadocs for the DBAppender class state: The DBAppender inserts access events into three database tables in a format independent of the Java programming language. However when you dig down into the code, the log messages are actually just being appended to access_event_header and access_event, not 3 tables like the Javadocs say. So, in conclusion: The logback Javadocs and developer docs are not up to date with the latest release, and do not reflect the true table structure that the DBAppender requires.
[ "stackoverflow", "0049659421.txt" ]
Q: RxJava2: Need help to convert java code into rx I am newbie in RxJava and need help to improve my code. Here is what I've done: public Single<List<MenuItemsBlocks>> loadMenuItemsBlocks() { Completable.fromAction(() -> DataStoreRepository.deleteMenuItemsBlock()) .subscribeOn(Schedulers.io()).blockingAwait(); List<MenuItemsBlocks> blocks = new ArrayList<>(); Set<String> aliasList = getAliasFromMenuItems(); for (String alias : aliasList) { List<MenuItemsBlocks> itemsBlocks = ApiRepository.getMenuItemBlocks(alias) .subscribeOn(Schedulers.io()) .flatMapIterable(list -> list) .map(item -> new MenuItemsBlocks( item.getId(), item.getType(), item.getImagePosition(), item.getTextField(), item.getSortOrder(), item.getFileTimeStamp(), alias )) .doOnNext(block -> DataStoreRepository.saveMenuItemsBlock(block)) .subscribeOn(Schedulers.io()) .toList() .blockingGet(); blocks.addAll(itemsBlocks); } return Single.just(blocks); } There is no problem at runtime with this code, but I want to improve it in rx style, I've tried to rewrite it something like this (but it's not working): public Single<List<MenuItemsBlocks>> loadMenuItemsBlocks() { Completable.fromAction(() -> DataStoreRepository.deleteMenuItemsBlock()) .subscribeOn(Schedulers.io()).blockingAwait(); Set<String> aliasList = getAliasFromMenuItems(); return Observable.fromIterable(aliasList) .switchMap(alias -> ApiRepository.getMenuItemBlocks(alias) .subscribeOn(Schedulers.io()) .flatMapIterable(list -> list) .map(item -> new MenuItemsBlocks( item.getId(), item.getType(), item.getImagePosition(), item.getTextField(), item.getSortOrder(), item.getFileTimeStamp(), alias )) .doOnNext(block -> DataStoreRepository.saveMenuItemsBlock(block)) .subscribeOn(Schedulers.io()) .toList() ); } And I am stuck with it and need your help! A: First of all, if you have blockingAwait in non-test code, you are doing it wrong. Second, you probably need concatMap instead of switchMap as it will just keep switching to later list elements, cancelling the outstanding API calls. public Single<List<MenuItemsBlocks>> loadMenuItemsBlocks() { return Completable.fromAction(() -> DataStoreRepository.deleteMenuItemsBlock()) .subscribeOn(Schedulers.io()) .andThen(Single.defer(() -> { Set<String> aliasList = getAliasFromMenuItems(); return Observable.fromIterable(aliasList) .concatMap(alias -> ApiRepository.getMenuItemBlocks(alias) .subscribeOn(Schedulers.io()) .flatMapIterable(list -> list) .map(item -> new MenuItemsBlocks( item.getId(), item.getType(), item.getImagePosition(), item.getTextField(), item.getSortOrder(), item.getFileTimeStamp(), alias )) .doOnNext(block -> DataStoreRepository.saveMenuItemsBlock(block)) .subscribeOn(Schedulers.io()) ) .toList(); })); }
[ "stackoverflow", "0039686106.txt" ]
Q: How to get the total amount of memory used by OpenGL in mobile devices? I've found the answer for desktops, but I could not find anything for Android/iOS (assume I can use up to OpenGL ES 3.0). So this is the same question for mobile devices: Is it possible to get the total memory in bytes used by OpenGL by my application programatically? Note: I am OK with a non-universal solution (AFAIK universal solution does not exists), but something that works at least on popular devices (iOS/Snapdragon/..) A: No, it's not possible via any standard API. Most graphics drivers will account any graphics memory to the process, so you can always use the "top" command line utility to get total process memory. It's not able to isolate the graphics memory, but it should give you an idea how how much your process is using in total. That said, you probably have a pretty good idea how much data you uploaded/allocated storage for using the GLES API, which is probably a good finger in the air estimate for total memory. Most of the bulk storage related to application assets.
[ "stackoverflow", "0022580771.txt" ]
Q: Neural Network Categorical Data Implementation I've been learning to work with neural networks as a hobby project, but am at a complete loss with how to handle categorical data. I read the article http://visualstudiomagazine.com/articles/2013/07/01/neural-network-data-normalization-and-encoding.aspx, which explains normalization of the input data and explains how to preprocess categorical data using effects encoding. I understand the concept of breaking the categories into vectors, but have no idea how to actually implement this. For example, if I'm using countries as categorical data (e.g. Finland, Thailand, etc), would I process the resulting vector into a single number to be fed to a single input, or would I have a separate input for each component of the vector? Under the latter, if there are 196 different countries, that would mean I would need 196 different inputs just to process this particular piece of data. If a lot of different categorical data is being fed to the network, I can see this becoming really unwieldy very fast. Is there something I'm missing? How exactly is categorical data mapped to neuron inputs? A: Neural network inputs As a rule of thumb: different classes and categories should have their own input signals. Why you can't encode it with a single input Since a neural network acts upon the input values through activation functions, a higher input value will result in a higher activation input. A higher input value will make the neuron more likely to fire. As long as you don't want to tell the network that Thailand is "better" than Finland then you may not encode the country input signal as InputValue(Finland) = 24, InputValue(Thailand) = 140. How it should be encoded Each country deserves its own input signal so that they contribute equally to activating the neurons.
[ "stackoverflow", "0033712728.txt" ]
Q: Using python to measure Wi-Fi I am working on a school project in which I must measure and log Wi-Fi (I know how to log the data, I just don't know the most efficient way to do it). I have tried using by using subproject.check_output('iwconfig', stderr=subprocess.STDOUT) but that outputs bytes, which I really don't want to deal with (and I don't know how to, either, so if that is the only option, then can someone explain how to handle bytes). Is there any other way, maybe to get it in plain text? And please do not just give me the code I need, tell me how to do it. Thank you in advance! A: You are almost there. I assume that you are using python 3.x. iwconfig is sending you text encoded in whatever character set your terminal uses. That encoding is available as sys.stdin.encoding. So just put it together to get a string. BTW, you want a command list instead of a string. raw = subprocess.check_output(['iwconfig'],stderr=subprocess.STDOUT) data = raw.decode(sys.stdin.encoding)
[ "dba.stackexchange", "0000000449.txt" ]
Q: Tool to generate large datasets of test data Many times when trying to come up with an efficient database design the best course of action is to build two sample databases, fill them with data, and run some queries against them to see which one performs better. Is there a tool that will generate (ideally straight into the database) large (~10,000 records) sets of test data relatively quickly? I'm looking for something that at least works with MySQL. A: The best tool (if you can find it) is DataFactory. (Sadly out of print). I've generated absolutely delightful (and quite authentic-looking) datasets from it. Generatedata.com is... acceptable, but doesn't scale very well. DataGenerator is something to keep an eye on. And while DTM Data Generator is clunky and a poor substitute for DataFactory, it exists and is being sold, and I've used it to generate mildly acceptable data. A: RedGate has a tool similar to what you're looking for, but it's destination is intended to be MS SQL Server. http://www.red-gate.com/products/sql-development/sql-data-generator You might also check out the following article: http://www.sqlservercentral.com/articles/Advanced+Querying/jointestdata/197/ A: I typically generate my own, using some known data as input -- if it's too random, it's not always a good test; I need data that's going to be distributed similarly to my final product. All of the larger databases that I have to tune are scientific in nature -- so I can usually take some other investigation as input, and rescale it and add jitter. (eg, taking data that was at a 5 min cadence with millisecond precision, and turning it into a 10 sec cadence w/ milisecond precision but a +/- 100 ms jitter to the times) ... But, as another alternative, if you don't want to write your own, is to look at some of the benchmarking tools -- as they can repeat things over and over again based on a training set, you can use them to insert lots of records (and then just ignore the reports on how fast it did it) ... and then you can use that same tool for testing how fast the database performs once it's populated.
[ "stackoverflow", "0024230433.txt" ]
Q: Algorithm of A^B(A power B) for Big numbers Can you help me to find Algorithim of A^B(A power B) for big numbers( say up to 9*10^18) without using any libraries(Like java Math.Biginteger)? I know JAVA, so it would be great if the code written in java. A: A good algorithm for exponentiation is the square and multiply Below I have included some pseudo code from the same wikipedia article. 1. y := 1; i := l-1 2. while i > -1 do 3. if ni=0 then y:=y2' i:=i-1 4. else 5. s:=max{i-k+1,0} 6. while ns=0 do s:=s+1 [2] 7. for h:=1 to i-s+1 do y:=y2 8. u:=(ni,ni-1,....,ns)2 9. y:=y*xu 10. i:=s-1 11. return y
[ "mathoverflow", "0000076928.txt" ]
Q: Grothendieck-Riemann-Roch interpretation of a calculation Let $X$ be some smooth projective variety over $\mathbb{C}$ and let $$\mathscr{H}_{q}(X):=ch(\Omega_{X}^{q})Td(X).$$ For $Y$ a certain elliptic fibration $$\varphi:Y\to B$$ where $B$ is of arbitrary dimension, I have been computing $$\varphi_{*}\mathscr{H}_{q}(Y)$$ where $\varphi_{*}$ is the proper pushforward. The total space $Y$ is a subvariety of a projective bundle $$\mathbb{P}(\mathscr{O}\oplus \mathscr{L}\oplus \mathscr{L}\oplus \mathscr{L})$$ where $\mathscr{L}$ is a line bundle on $B$. I have computed that $\varphi_{*}Td(Y)=(1-e^{-L})Td(B)$ $$\varphi_{*}\mathscr{H}_{1}(Y)=(1-e^{-L})\mathscr{H}_{1}(B)+(-4-e^{-L}+3e^{-2L}+2e^{-3L})Td(B),$$ where $L=c_1(\mathscr{L})$. What I would like is an explanation of the result of these calculations in terms of Grothendieck-Riemann-Roch as I have only recently acquainted myself with GRR. Thanks everyone. A: Let $T\phi$ be the relative tangent bundle. So we have an exact sequence $0\to T\phi\to TY\to \phi^*TB\to 0$. Now GRR and the projection formula gives $$ \phi_*{\rm Td}(Y)=\phi_*({\rm Td}(T\phi){\rm Td}(\phi^*TB))= {\rm Td}(TB)\phi_*({\rm Td}(T\phi))={\rm ch}(1-R^1\pi_*({\cal O}_Y)){\rm Td}(TB) $$ which suggests that ${\cal L}=R^1\pi_*({\cal O}_Y)^\vee=\pi_*(\Omega_\phi):=\pi_*(T\phi^\vee)$ (by Grothendieck duality). I will take this for granted; up to $\otimes$ by a torsion bundle, it is forced upon you by the equation; if $\cal L$ and $\pi_*(\Omega_\phi)$ differ by a torsion line bundle, the calculations below still work. Furthermore, applying GRR and the projection formula again, we may compute $$ \phi_*{\cal H}_1(Y)=\phi_*({\rm ch}(\Omega_Y){\rm Td}(TY))= \phi_*(\ [\phi^*{\rm ch}(\Omega_B)+{\rm ch}(\Omega_\phi)]{\rm Td}(T\phi)\phi^*{\rm Td}(TB)\ )= $$ $$ {\rm Td}(TB){\rm ch}(\Omega_B)\phi_*({\rm Td}(T\phi))+{\rm Td}(TB)\phi_*({\rm Td}(T\phi) {\rm ch}(\Omega_\phi))= $$ $$ {\rm Td}(TB){\rm ch}(\Omega_B)\phi_*({\rm Td}(T\phi))+{\rm Td}(TB){\rm ch}({\cal L}- R^1\pi_*(\Omega_\phi))= $$ $$ {\rm Td}(TB){\rm ch}(\Omega_B)\phi_*({\rm Td}(T\phi))+{\rm Td}(TB){\rm ch}({\cal L}-1)= $$ $$ {\rm Td}(TB){\rm ch}(\Omega_B)(1-{\rm ch}({\cal L}^\vee))+{\rm Td}(TB){\rm ch}({\cal L}-1)= (1-e^{-L}){\cal H}_1(B)+(e^{L}-1){\rm Td}(TB)\,\,\, (*) $$ Now use the fact that $\cal L$ is actually a torsion bundle, because the discriminant modular form will trivialise ${\cal L}^{\otimes 12}$ (or possibly a higher power, if one needs to introduce level structures). This last fact is also a consequence of GRR, since $$ \phi_*({\rm Td}(T\phi))=\pi_*({\rm ch}(1))\phi^*\phi_*({\rm Td}(T\phi))=0={\rm ch}(1-R^1\pi_*({\cal O}_Y)) $$ (because $T\phi=\pi^*\pi_* T\phi)$. Hence, one gets, all in all, that $$ \phi_*{\rm Td}(TY)=0 $$ and in view of (*), that $$ \phi_*{\cal H}_1(Y)=0 $$ which is equivalent to the two equations you are considering, since ${\cal L}$ is a torsion line bundle (observe that the degree $0$ part of $−4−e^{-L}+3e^{−2L}+2e^{−3L}$ vanishes).
[ "stackoverflow", "0043129153.txt" ]
Q: Bootstrap 3 merge rows and columns I can't figure out what is the problem with my code. I'm very new in bootstrap my problem is kinda trivial. One of my field is out of position. I have tried a different route by making only one row and instead of increasing the div sizes I reduced them, but it had the exact same problem. (Run the code in full screen mode). Please if you can help me out! .row { background-color: yellow; } .col-sm-3, .col-sm-6 { border:solid 2px black; } div { height:200px; } .two-div { height:400px; } .three-div { height:600px; } <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-3 three-div pull-left">Works</div> <div class="col-sm-6">Works</div> <div class="col-sm-3 two-div pull-right">Works</div> </div> <div class="row"> <div class="col-sm-3 two-div">Works</div> <div class="col-sm-3 three-div">Works</div> </div> <div class="row"> <div class="col-sm-3 two-div pull-right">Works</div> </div> <div class="row"> <div class="col-sm-6">:(</div> </div> </div> </body> </html> A: With some nesting and pull-right on the appropriate columns you can reverse the float:left and make it work (albeit a hack!)... http://www.codeply.com/go/rgHEL6DW12 <div class="container"> <div class="row"> <div class="col-sm-9"> <div class="row"> <div class="col-sm-4 three-div">works</div> <div class="col-sm-8">works</div> <div class="col-sm-4 three-div pull-right">works</div> <div class="col-sm-4 two-div pull-right">works</div> <div class="col-sm-8 pull-right"> ;-) </div> </div> </div> <div class="col-sm-3"> <div class="row"> <div class="col-sm-12 two-div">works</div> <div class="col-sm-12 two-div">works</div> </div> </div> </div> </div> Think about it like this... http://www.codeply.com/go/rgHEL6DW12
[ "stackoverflow", "0003271083.txt" ]
Q: Passing context into timer..is this safe I'm using a timer which needs context. Now I have the following code : mContext=context; mEventID=eventID; CountDownTimer cdTimer = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { // Do nothing onTick... Sorry } public void onFinish() { int deletedRows = mContext.getContentResolver().delete() // ..rest of code } }; cdTimer.start(); Is this safe to use , or may I be leaking the context here? btw. This is in a broadcastreceiver. A: You should not pass the Context into the Thread, instead refer to it by it's parent name. something like this class MyClass { ... CountDownTimer cdTimer = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { // Do nothing onTick... Sorry } public void onFinish() { int deletedRows = myClass.this.context.getContentResolver().delete() // ..rest of code } }; ... } So you probably need to call the context by your broadcast receiver's name eg: MyReceiver.this.context assuming context is a member of the class.
[ "mathematica.stackexchange", "0000123577.txt" ]
Q: How to make a customized plot function that can plot functions with optional parameter? Suppose I make the following function to plot contour lines for a complex function: ContourRe[Func_, xrange_, yrange_, Nlines_: 30, size_: 400] := ContourPlot[Re[Func[x + I*y]], {x, xrange[[1]], xrange[[2]]}, {y, yrange[[1]], yrange[[2]]}, ContourShading -> False, Contours -> Nlines, ContourStyle -> Red, ImageSize -> size] How can I generalize it so that the input function Func can have additional parameters? For example I have: F1[z_]:=Exp[z]+3*I F2[z_,a_:-2]:=a*Exp[z] How should I modify ContourRe so that it can take both F1 and F2 as arguments and plot them? It is like in python in which many of the built-in scipy functions have args={} for us to specify any parameters associated with the input function. In mathematica there are things like OptionsPattern and OptionValue, but after looking at the documentations I don't really know how to use them in this specific example. A: I would use SubValues: define your functions with more than one []. This both makes it easier to write the plotting function, and it keeps the conceptually two different things, parameters and variables, separate. f2[a_:-2, b_:0][z_] := a*Exp[z] + b contourRe[fu : (func_[args__] | func_), xrange_, yrange_, nLines_: 30, size_: 400] := ContourPlot[Re[fu[x + I*y]], {x, xrange[[1]], xrange[[2]]}, {y, yrange[[1]], yrange[[2]]}, ContourShading -> False, Contours -> nLines, ContourStyle -> Red, ImageSize -> size] I changed the variable names to start with lower-case, both to avoid clashes with built-ins, and to make autocompletion more useful :) Now both contourRe[f2[], {-2, 2}, {-3, 3}] and contourRe[f2[3,4], {-2, 2}, {-3, 3}] work. Functions without parameters also work, e.g. contourRe[Sin, {-2, 2}, {-3, 3}] A: I would refashion the plotting procedure to accept pure functions. Note that the range values (like x1) can be captured within parameter definition. plot[f_Function, {x1_, x2_}, {y1_, y2_}, nLines_: 30, size_: 150] := ContourPlot[Re[f[x + I y]], {x, x1, x2}, {y, y1, y2}, ContourShading -> False, Contours -> nLines, ContourStyle -> Red, ImageSize -> size] Then: (* f1 = Exp[#] + 3 I &; *) f1 = Function[z, Exp[z] + 3 I]; f2[a_: - 2] := Function[z, a Exp[z] + Sin[a z]] plot[f1, {-5, 5}, {-5, 5}] (* f2[] is the call with default a, not just f2 *) plot[f2[.2], {-5, 5}, {-5, 5}] plot[10 Log[#] &, {-5, 5}, {-5, 5}]
[ "stackoverflow", "0035811503.txt" ]
Q: Laravel 5: PHPUnit and no code coverage driver available I would like to use PHPUnit to create code coverage reports. I have tried a lot of installation setups found on the web. But nothing seems to work out. I use the latest version of Laravel 5 (>5.2) and PHPUnit v. 5.0.10. Further, I use MAMP on Mac OS X 10.9.5 running PHP 7. When I run PHPUnit that is integrated in my Laravel distribution, I receive the following error. $ vendor/bin/phpunit -v PHPUnit 5.0.10 by Sebastian Bergmann and contributors. Runtime: PHP 7.0.0 Configuration: /Applications/MAMP/htdocs/myProject/phpunit.xml Error: No code coverage driver is available` My composer file looks like: "require-dev": { "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.*", "phpunit/phpunit": "5.0.*", "phpunit/php-code-coverage": "^3", "symfony/css-selector": "2.8.*|3.0.*", "symfony/dom-crawler": "2.8.*|3.0.*" }, I have also tried the following command: /Applications/MAMP/bin/php/php7.0.0/bin/phpdbg -qrr ../../../htdocs/myProject/vendor/bin/phpunit -v This seems to set up the code coverage driver well, but it ends up in an exception: $ /Applications/MAMP/bin/php/php7.0.0/bin/phpdbg -qrr ../../../htdocs/myProject/vendor/bin/phpunit -v PHPUnit 5.0.10 by Sebastian Bergmann and contributors. Runtime: PHPDBG 7.0.0 Configuration: /Applications/MAMP/htdocs/myProject/phpunit.xml [PHP Fatal error: Uncaught ErrorException: include(/Applications/MAMP/htdocs/myProject/app/Exceptions/Handler.php): failed to open stream: Too many open files in /Applications/MAMP/htdocs/myProject/vendor/composer/ClassLoader.php:412 Stack trace: ... The phpunit.xml looks as follows: <?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="bootstrap/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> <testsuites> <testsuite name="Application Test Suite"> <directory>./tests/</directory> </testsuite> </testsuites> <logging> <log type="coverage-html" target="./tests/codeCoverage" charset="UTF-8"/> </logging> <filter> <whitelist> <directory suffix=".php">app/</directory> </whitelist> </filter> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> </php> </phpunit> Is it possible to use PHPUnit that comes with the Laravel framework together with code coverage? How should I set it up and use it? Thanks a lot for your help. A: It seems like you are missing the Xdebug extension. If you're using homebrew you can install it like: brew install php70-xdebug After that, don't forget to edit your php.ini file to enable the extension. php -i | grep xdebug After checking that xdebug is enabled you should be able to do code coverage A: Update for anyone else stuck; pecl install xdebug A: Update for PHP 7.1 xdebug is essential for code lookup and coverage , so xdebug is must to be installed or enabled in test environment. xdebug in production environment is not suggestible, it will affect performance if you turned on brew install php71-xdebug
[ "serverfault", "0000405915.txt" ]
Q: Does the Intel DX79TO motherboard support x8 devices (SAS HBAs) on PCIe x16 slots? Context: I have an Intel DX79TO motherboard and a Sun SAS3081E-S/LSI 1060E-S HBA card with a PCIe x8 interface. I plug the HBA into my mobo next to my graphics card, and the HBA power lights illuminate, but the BIOS and OSes (tried Linux, ESXi, Win7) don't see the HBA at all. Question: Does the DX79TO motherboard support non-x16/non-GPU devices in its PCIe x16 slots? According to this question, some consumer motherboards don't support this, but I can't figure out whether or not this motherboard/family does. The answer will affect whether I buy a new motherboard or RMA the SAS card, with money attached to each course, so I figured I'd ask here first. What I've Tried: I've read the spec/manuals for the motherboard and the HBA, and I didn't see anything regarding whether or not the x16 slots were back-compatible to lower lane widths/non graphics-card devices, or whether or not the card could run in wider slots than x8. I've tried contacting Intel, but that was over a month ago and I haven't yet heard anything back except an automated "we got your email!" message. A: The PCI Spec specifies that any combination may be used in slots/cards and must work (though the slot does not have to physically accommodate larger cards). Thus per the spec an 8x card must work in a 16x slot. It's possible your specific board is non-compliant (though highly unlikely); if it's non-compliant it's probably a bug in the card or BIOS.
[ "stackoverflow", "0028954168.txt" ]
Q: PHP: How to use a class function as a callback I have a class with methods which I want to use as callbacks. How to pass them as arguments? Class MyClass { public function myMethod() { $this->processSomething(this->myCallback); // How it must be called ? $this->processSomething(self::myStaticCallback); // How it must be called ? } private function processSomething(callable $callback) { // process something... $callback(); } private function myCallback() { // do something... } private static function myStaticCallback() { // do something... } } UPD: How to do the same but from static method (when $this is not available) A: Check the callable manual to see all the different ways to pass a function as a callback. I copied that manual here and added some examples of each approach based on your scenario. Callable A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset(). // Not applicable in your scenario $this->processSomething('some_global_php_function'); A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. // Only from inside the same class $this->processSomething([$this, 'myCallback']); $this->processSomething([$this, 'myStaticCallback']); // From either inside or outside the same class $myObject->processSomething([new MyClass(), 'myCallback']); $myObject->processSomething([new MyClass(), 'myStaticCallback']); Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. // Only from inside the same class $this->processSomething([__CLASS__, 'myStaticCallback']); // From either inside or outside the same class $myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']); $myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+ $myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+ Apart from common user-defined function, anonymous functions can also be passed to a callback parameter. // Not applicable in your scenario unless you modify the structure $this->processSomething(function() { // process something directly here... }); A: Since 5.3 there is a more elegant way you can write it, I'm still trying to find out if it can be reduced more $this->processSomething(function() { $this->myCallback(); }); A: You can also to use call_user_func() to specify a callback: public function myMethod() { call_user_func(array($this, 'myCallback')); } private function myCallback() { // do something... }
[ "stackoverflow", "0046616773.txt" ]
Q: What AWS EC2 Instance Types suitable for chat application? Currently i'm building a chat application base on NodeJs So i considered choose which is the best instance type for our server? Because AWS have a lot of choice: General purpose, compute optimize, memory optimize .... Could you please give me advise :( A: You can read this - https://aws.amazon.com/blogs/aws/choosing-the-right-ec2-instance-type-for-your-application/ Actually it doesn't matter what hosting you chose -AWS, MS Azure, Google Compute Engine etc... If you want to get as much as you can from your servers and infrastructure, you need to solve your current task. First of all decide how many active users at the same time you will get in closest 3-6 months. If there will be less than 1000k active users (connections) per second - I think you can start from the smallest instance type. You should check how you can increase CPU/RAM/HDD(or SSD) of your instance. SO when you get more users you will have a plan how to speed up your server. And keep an eye on your server analytics - CPU/RAM/IO utilizations when you are getting more and more users. The other questions if you need to pass some certifications related to security restrictions...
[ "stackoverflow", "0040136451.txt" ]
Q: tableToJson is not working when table has one row only I am using tableToJson from here I have the following modal window: <div class="modal fade" id="myModalShopOrder" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Add Batch</h4> </div> <div class="modal-body"> <label class="control-label">Designation:</label> <div id='complaintProgress' style="position: relative;"> <input type="text" class="form-control" name="DesignationShopOrder" id="DesignationShopOrder"> </div><br> <div class="well"> <table class="table table-hover table-striped table-responsive table-bordered" id="shopOrderTable" > <thead> <tr> <th data-override="ShopOrderDes">Designation</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <button type="button" onclick="addShopOrder();" class="btn btn-success">Submit</button> </div> </form> </div> </div> </div> And there is the script that I am running to add the item to the table: <script> function addShopOrder(){ var designation = document.getElementById('DesignationShopOrder').value; var table = document.getElementById("shopOrderTable").getElementsByTagName('tbody')[0]; var row = table.insertRow(-1); row.hidden = false; var cell1 = row.insertCell(0); cell1.innerHTML = designation; var shopOrders = $('#shopOrderTable').tableToJSON(); shopOrders.pop(); var infoRec = new Array(); infoRec = JSON.stringify(shopOrders); document.getElementById('shopOrderSender').value = infoRec; } </script> I click the button to add, and my tableToJson array is empty! If I click twice, I get the array with data! Why I need to click twice? If I have one line in table, I want to convert it too! There are the images with the firebug details inside the red rectangle! Thanks in advance A: Probally due to "shopOrders.pop();" you are removing the last item, if you only have one you are removing it
[ "dba.stackexchange", "0000195151.txt" ]
Q: How to reduce table partition timing for existing table in SQL Server Repost from: https://stackoverflow.com/questions/48169487/how-to-reduce-table-partition-timing-for-existing-table-in-sql-server I have a problem with table partition, I am working in a very big database, It is around 2 terabyte. So we planned to split the large tables into different partitions at last year. On that time we were divided a table into two partitons. One partition was located in primary file group and another one was located in secondary file group named as PartitionFG1. So we got lots of benefits from this activity like index maintenance and performance. And then we have planned to create another one partition for the same table for this upcoming year records. So we have created a new secondary file group and we have altered the partition scheme to use new secondary file group named as PartitionFG2. So we have alter the partition function to split the range, here is the problem. Here the new range value split and moves the data into new partition but not into the new file group. For example table’s max PK value is 1000, so I used split range value as 1000. So it should not be taken any time to move data to new partition, because new partition will contains 0 records only. Now I am going describe the scenario by sequence. Table Creation CREATE TABLE Tbl_3rdParatition(PK NUMERIC(18,0) identity(1,1),Line Varchar(100)) CREATE CLUSTERED INDEX CidxTbl_3rdParatition ON Tbl_3rdParatition (pk ASC) Insert record into table DECLARE @I INT DECLARE @CNT INT SET @I=1 SET @CNT = 1000 WHILE (@I< = @CNT) BEGIN INSERT INTO Tbl_3rdParatition (Line) VALUES ('Primary') SET @I=@I+1 END Now we have inserted 1000 records into the table. We can verify the table’s row and partition by below query. SELECT p.partition_number, fg.name, p.rows FROM sys.partitions p INNER JOIN sys.allocation_units au ON au.container_id = p.hobt_id INNER JOIN sys.filegroups fg ON fg.data_space_id = au.data_space_id WHERE p.object_id = OBJECT_ID('Tbl_3rdParatition') So it ensures primary file group contains all records of the table. Now I am going to split the table into 2 partitions. CREATE PARTITION FUNCTION PF_Tbl_3rdParatition(NUMERIC(18,0)) AS RANGE LEFT FOR VALUES(500); CREATE PARTITION SCHEME PS_Tbl_3rdParatition AS PARTITION PF_Tbl_3rdParatition TO ([PRIMARY],[SWPPartitionFG1]) CREATE UNIQUE CLUSTERED INDEX CidxTbl_3rdParatition ON dbo.Tbl_3rdParatition(PK) WITH(DROP_EXISTING = ON)ON PS_Tbl_3rdParatition(PK) ; Now it is divided into 2 partitions. It took some time to move 500 records to SWPPartitionFG1. Now I am going to create a new partition on another file group. ALTER PARTITION SCHEME PS_Tbl_3rdParatition NEXT USED [SWPPartitionFG2] ALTER PARTITION FUNCTION PF_Tbl_3rdParatition() SPLIT RANGE (1000) ALTER INDEX [CidxTbl_3rdParatition] ON [dbo].[Tbl_3rdParatition ] REBUILD WITH (SORT_IN_TEMPDB = OFF, ONLINE = ON, MAXDOP = 1) As of above query, 3rd partition should have 0 records. That is correct. But 3rd partition should be stored in SWPPartitionFG2 correct? But second partition’s data fully moved into SWPPartitionFG2. And the 3rd partition is allocated in SWPPartitionFG1 it is wrong!. So it takes too much of time to transfer the data from FG1 to FG2. I desired to store the 3rd partition data in third file group (SWPPartitionFG2). Then only it will not take large time in partitioning process. For this reason we want lots of time to create a new partition. Our client will not give that much of down time for us. Our Actual table size is 300 GB. 2nd partitions SWPPartitionFG1 File group contains 200 GB of data. So it requires 2:30 hrs time to move the data From FG1 to FG2. Please help me reduce the time in this activity. A: ALTER PARTITION SCHEME PS_Tbl_3rdParatition NEXT USED [SWPPartitionFG2] ALTER PARTITION FUNCTION PF_Tbl_3rdParatition() SPLIT RANGE (1000) ALTER INDEX [CidxTbl_3rdParatition] ON [dbo].[Tbl_3rdParatition ] REBUILD WITH (SORT_IN_TEMPDB = OFF, ONLINE = ON, MAXDOP = 1) Why are you rebuilding the clustered index after creating the new partition? When you SPLIT a RANGE LEFT function, the partition containing the new boundary is split. The new partition on SWPPartitionFG2 is created to the left of the SWPPartitionFG1 partition. The new partition on SWPPartitionFG2 becomes partition 2 and the original SWPPartitionFG1 partition is renumbered as partition 3. Existing rows in the spilt partition that are less than or equal to the new boundary are moved into the new partition during the process. This is a very expensive operation, requiring about 4 times the logging of normal DML. That is why one should plan to split only empty partitions, or at least ensure no rows must be moved. It would be best to use a RANGE RIGHT function here so that incremental boundaries are created to the right of the SPLIT partition. Create a new RANGE RIGHT partition function and scheme and rebuild indexes specifying the new scheme with the 'DROP_EXISTING = ON` option. I would expect this to take much less time than the current operation and, going forward, the SPLIT to create incremental partition boundaries will be a fast meta-data only operation. CREATE PARTITION FUNCTION PF_Tbl_3rdParatition_Right(NUMERIC(18,0)) AS RANGE LEFT FOR VALUES(500,1000); CREATE PARTITION SCHEME PS_Tbl_3rdParatition_Right AS PARTITION PF_Tbl_3rdParatition_Right TO ([PRIMARY],[SWPPartitionFG1],[SWPPartitionFG2]); CREATE UNIQUE CLUSTERED INDEX CidxTbl_3rdParatition ON dbo.Tbl_3rdParatition(PK) WITH(DROP_EXISTING = ON) ON PS_Tbl_3rdParatition_Right(PK); See Table Partitioning Best Practices for more information.
[ "stackoverflow", "0019950713.txt" ]
Q: Scanner input validation in while loop I've got to show Scanner inputs in a while loop: the user has to insert inputs until he writes "quit". So, I've got to validate each input to check if he writes "quit". How can I do that? while (!scanner.nextLine().equals("quit")) { System.out.println("Insert question code:"); String question = scanner.nextLine(); System.out.println("Insert answer code:"); String answer = scanner.nextLine(); service.storeResults(question, answer); // This stores given inputs on db } This doesn't work. How can I validate each user input? A: The problem is that nextLine() "Advances this scanner past the current line". So when you call nextLine() in the while condition, and don't save the return value, you've lost that line of the user's input. The call to nextLine() on line 3 returns a different line. You can try something like this Scanner scanner=new Scanner(System.in); while (true) { System.out.println("Insert question code:"); String question = scanner.nextLine(); if(question.equals("quit")){ break; } System.out.println("Insert answer code:"); String answer = scanner.nextLine(); if(answer.equals("quit")){ break; } service.storeResults(question, answer); } A: Try: while (scanner.hasNextLine()) { System.out.println("Insert question code:"); String question = scanner.nextLine(); if(question.equals("quit")){ break; } System.out.println("Insert answer code:"); String answer = scanner.nextLine(); service.storeResults(question, answer); // This stores given inputs on db }
[ "salesforce.stackexchange", "0000241200.txt" ]
Q: How to get DataCategory name and not Unique name from Knowledge Base with SOQL? I started using the Knowledge base and i want to pull out all the knowledge base category group names from it.  I am using the following SOQL statement: Select Id, Question__c, Answer__c, (Select DataCategoryName, DataCategoryGroupName FROM DataCategorySelections) FROM Knowledge__kav But somehow the soql inside the soql prints out the unique name of the data category group instead of the normal name. Any advices how can i fix this? Thanks, Darko A: I found a better and easier solution to this without using a restAPI after reading the knowledge dev guide. The solution was easier than it appear. All I needed to do is toLabel() Select Id, Question__c, Answer__c, (Select toLabel(DataCategoryName), toLabel(DataCategoryGroupName) FROM DataCategorySelections) FROM Knowledge__kav Cheers, Darko
[ "tex.stackexchange", "0000403755.txt" ]
Q: chessfss: black pieces as figure notation Consider the following example: \documentclass{article} \usepackage{xskak} %\usetextfig \usesymfig \begin{document} \textsymfigsymbol{Q} \end{document} This printes the white queen. How do I print the black queen instead of the white? I can't find anything relating to this in the manual. Update I didn't explain myself well very well the first time: I would like a single command where I'm able to switch between white and black, and not just type a command for the white pieces and another command for the black pieces ... Something like the solution here where I change notation style depending on \usetextfig or \usesymfig but where I'm also able to change the color of each typeset piece form a single command. It it possible to create such a command? (I hope it makes sense.) Nevermind the exact vertical positioning of the black pieces (see Ulrike's answer to my original question for an explanation); I can fiddle with that myself. A: The relevant manual for chess fonts is chessfss not xskak. Beside this: it depends on the font. The only one with black figurines I'm aware of is berlin (part of https://ctan.org/tex-archive/fonts/chess/enpassant): \documentclass{article} \usepackage{xskak} %\usetextfig \usesymfig \setchessfontfamily{berlin} \begin{document} \textsymfigsymbol{Q} {\fontshape{bl}\selectfont \textsymfigsymbol{Q}} \end{document} With other fonts you can only fake it with a black queen from the board font. But as she doesn't sit on the baseline you normally need to lower it: \documentclass{article} \usepackage{xskak} %\usetextfig \usesymfig \setboardfontsize{10pt} \begin{document} \textsymfigsymbol{Q} \BlackQueenOnWhite \raisebox{-2pt}{\BlackQueenOnWhite} \end{document}
[ "stackoverflow", "0058136382.txt" ]
Q: Python Thread run function return value I have pandasDataframes and i would like to apply a function on it. I would like to have many iterations, so i think it would be nice to use multiple threads. This is how it looks like: def my_function(data_inputs_train): #..... do something with dataframe.... #..... group by for loops etc ....... #..... create new dataframe..... return newPandasDataFrame class myThread (threading.Thread): def __init__(self, threadID, data_inputs_train): threading.Thread.__init__(self) self.threadID = threadID self.data_inputs_train = data_inputs_train def run(self): result_df = my_function(data_inputs_train) thread1 = myThread(1, data_inputs_train) thread2 = myThread(2, data_inputs_train) So both thread should return a new dataframe, and after both thread finished i would like to concatenate the two result that returned from two thread. How can i do that? How could is return any object from the run() function, and how can i access it in my thread1object? Thank you! UPDATE by first answer but its not works, there are indent problems too. class myThread (threading.Thread): def __init__(self, threadID, name, sleep, cust_type, data_inputs_train): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.sleep = sleep self.cust_type = cust_type self.data_inputs_train = data_inputs_train #here i need to get the newPandasDataFrame object. result_df = fdp.optimze_score_and_cl(data_inputs_train) def returnTheData(self): return result_df A: So this is the base of your program.. I am just using example data to show how you could set it up def myFunction(x): df = pd.DataFrame(['1', '2'], columns = ['A']) return df class myThreads(threading.Thread): def __init__(self, threadID, name, sleep, cust_type, data_inputs_train): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.sleep = sleep self.cust_type = cust_type # call the methods you need on your data... self.data_inputs_train = myFunction(data_inputs_train) def returnTheData(self): return self.data_inputs_train df = pd.DataFrame(['1'], columns = ['A']) thread1 = myThreads(1, "EX1", 1, 'EX', df) thread2 = myThreads(2, "IN1", 2, 'IN', df) thread1.start() thread2.start() thread1.join() thread2.join() df1 = thread1.returnTheData() df2 = thread2.returnTheData() print(df1) print(df2) You declare your threads.. Start them and basically have them run what ever you want.. join() Allows the main function to wait until all the threads have finished their processing. df2 = thread2.returnTheData() And you just call a function to return the data that you need. The working code https://repl.it/repls/ClearHugeOutlier
[ "serverfault", "0000984850.txt" ]
Q: OpenVPN traffic incorrectly routed outside tunnel when accessing server IP My setup consists of a client and a server where the client is connected to the server using OpenVPN. It's configured to route all traffic through the tunnel. This works well, the ip is the server ip and traceroute shows that the traffic is routed through the servers network. There's one exception though, when connecting to a domain pointing to the same server, the traffic is routed outside the VPN tunnel, i.e. the server shows the clients real ip and traceroute shows the traffic being routed through the clients ISP. My wish is to route all traffic through the the tunnel, even traffic which ends up on the server and it is necessary to use the domain name instead of the servers local ip. Any ideas? The server is running Windows 10 and the issue appears on clients when using OpenVPN on Windows 10, Linux and OpenVPN Connect on iOS. The issue is NOT present when using OpenVPN Connect on Android. It would be interesting to understand why it works on Android as well. Here's my server config: port 1194 proto udp4 dev tun ca "C:\\Program Files\\OpenVPN\\config\\ca.crt" cert "C:\\Program Files\\OpenVPN\\config\\server.crt" key "C:\\Program Files\\OpenVPN\\config\\server.key" dh "C:\\Program Files\\OpenVPN\\config\\dh2048.pem" server 10.8.0.0 255.255.255.0 ifconfig-pool-persist "C:\\Program Files\\OpenVPN\\log\\ipp.txt" 5 client-config-dir "C:\\Program Files\\OpenVPN\\config\\ccd" push "redirect-gateway def1 bypass-dhcp" push "dhcp-option DNS 208.67.222.222" push "route 255.255.255.0" duplicate-cn keepalive 10 120 cipher AES-256-CBC persist-key persist-tun explicit-exit-notify 1 And client config: client dev tun_c_ovpn proto udp4 remote <address> 1194 resolv-retry infinite keepalive 5 10 nobind persist-key persist-tun cipher AES-256-CBC A: The reason that connections to your Web server (which is hosted on the same machine as your OpenVPN server) is not routed through your VPN tunnel is normal behavior. If you would route all traffic destined to your OpenVPN/Web server through your OpenVPN tunnel, your encapsulated traffic would never be able to reach the VPN server because your system will try to route these over the same VPN tunnel which already encapsulated this traffic. Because of this the OpenVPN servers become unreachable and would disconnect. I cannot say how Android does this exactly. A method could be policy based routing and can be achieved with iptables/nftables to mark the OpenVPN specific packets. Policy based routing is not available on Windows OS's (AFAIK)! Alternative Solution An alternative solution is hosting your own DNS server and forward requests to the OpenDNS servers except for some zones you define yourself. Create a zone in your DNS server and point your domain to the internal IP address of your tun device. From your configuration it seems like it is 10.8.0.1 Change the DNS push option in your server.conf to push "dhcp-option DNS 10.8.0.1 It might be needed to add some iptable/nftable rules to allow these requests.
[ "stackoverflow", "0028122470.txt" ]
Q: Python-Merge sort difficulties I attempted to implement a merge sort, here is my code: def mergeSort(array): result=[] n=len(array) if n==1: result=array else: a=round(n/2) first=mergeSort(array[0:a]) second=mergeSort(array[a:n]) for i in range(len(first)): for j in range(len(second)): if first[i]<second[j]: result.append(first[i]) i=i+1 else: result.append(second[j]) j=j+1 return result a=[5,4,1,8,7,6,2,3] b=mergeSort(a) print(b) Unfortunately, the result turns out to be [1]. What is wrong with my function? A: A number of things... Firstly, this is a recursive function, meaning you cannot create a list within the function, as you did here: result=[] This will simply reset your list after every recursive call, skewing your results. The easiest thing to do is to alter the list that is passed as a parameter to merge sort. Your next problem is that you have a for loop within a for loop. This will not work because while the first for loop iterates over first, the second for loop will iterate over second for every increment of i, which is not what you want. What you need is to compare both first and second and extract the minimum value, and then the next minimum value, and so on until you get a sorted list. So your for loops need to be changed to the following: while i < len(first) and j < len(second): Which leads me to final problem in your code. The while loop will exit after one of the conditions are met, meaning either i or j (one or the other) will not have reached len(first) or len(second). In other words, there will be one value in either first or second that is unaccounted for. You need to add this unaccounted value to your sorted list, meaning you must implement this final excerpt at the end of your function: remaining = first if i < j else second r = i if remaining == first else j while r < len(remaining): array[k] = remaining[r] r = r + 1 k = k + 1 Here r represents the index value where the previous while loop broke off. The while loop will then iterate through the rest of the remaining values; adding them to the end of your sorted list. You merge sort should now look as follows: def mergeSort(array): if len(array)==1: return array else: a=round(len(array)/2) first=mergeSort(array[:a]) second=mergeSort(array[a:]) i = 0 j = 0 k = 0 while i < len(first) and j < len(second): if first[i]<second[j]: array[k] = first[i] i=i+1 k=k+1 else: array[k] = second[j] j=j+1 k=k+1 remaining = first if i < j else second r = i if remaining == first else j while r < len(remaining): array[k] = remaining[r] r += 1; k += 1 return array I tried to not alter your code as much as possible in order to make it easier for you to understand. However, if your difficulty in understanding what I did persists, try de-bugging your merge sort using multiple print statements so that you can follow the function's progress and see where it goes wrong.
[ "math.stackexchange", "0000088074.txt" ]
Q: Why is this matrix multiplication identity true? Let $X$ be an $n \times p$ matrix, and let $\mathbf 1$ be a vector of $1$'s of length $n$. Why does the following hold (assuming $X'X$ is not singular): $$\left( X'X \right)^{-1}X' \mathbf 1 = \begin{pmatrix}1\\0\\\vdots\\0\end{pmatrix}.$$ (I know this is basic, but I am not sure how to tackle this.) Thanks. A: I just realized that Tal Galili must have neglected to tell us that the first column of $X$ is a column whose every entry is $1$. That typically happens in certain kinds of applications, and typically $n\gg p$. As I said in a comment: Assuming $n>p$, and the rank of $X$ is $p$ so that the inverse actually exists, the vector $\left( {X'X} \right)^{ - 1}X'a$ is the $p×n$ vector of coefficients in a linear combination of the columns of X, and that linear combination is the projection of the $n×1$ vector $a$ onto the column space of $X$. Any reasonable answer should bear that in mind. So take the $1$ to mean a whole column of scalar $1$s. Then we should get the coefficients of the linear combination of columns of $X$ that gives us a column of $1$s. Since that's the first column of $X$, we get $1,0,0,0,\ldots,0$, i.e. $1$ times the first column plus $0$ times each of the other columns. That's the only way to do it since the columns of $X$ are linearly independent, as is implicitly stated in the question in the form of presupposing that $X'X$ is invertible. Later note: The more leisurely explanation: The $p\times p$ matrix $X'X$ is invertible only if $X$ has $p$ linearly independent columns. So that must be the case. That implies $n\ge p$. In typical applications $p$ is fairly small and $n$ is much bigger. In typical applications in statistics, $n$ is the sample size. Given any $n\times 1$ column vector $Y$, the the matrix $(X'X)^{-1}X'Y$ is a $p\times 1$ column vector. It is the vector of coefficients in a linear combination of the columns of $X$ that approximates $Y$ as closely as possible by a linear combination of the columns of $X$. In other words, it's the vector of regression coefficients when $Y$ is regressed on $X$. If $Y$ happens to be one of the columns of $X$---say it's the $k$th column---then $Y$ is expressed exactly as a linear combination of the columns of $X$. There's only one way to do that, since the columns are independent. That's by multiplying the $k$th column by $1$ and the others by $0$ and adding them up. If one of the columns is a column of $1$s, then that's what happens with that column. If the first column is a column of $1$s, then one gets the column vector whose first entry is $1$, and the others are $0$. That's what's happening here.
[ "stackoverflow", "0055322079.txt" ]
Q: Vue ctrl+s event listener not firing My application dialog should respond to "Ctrl+S" for a save function and cancel the default browser Save event. <div @keyup.83="doSave" @keyup.ctrl.83="doSave" @keyup.alt.83="doSave" tabindex="0"> The doSave event is fired on pressing 's' (and alt+s) but not on ctrl+s. Why is ctrl+s not fired? BONUS QUESTION: Is there a way to preventDefault without coding it? Somehow it should be possible adding .once but the docs are vague. https://codepen.io/cawoodm/pen/qvgxPL A: There are several questions packed into your question, so I am going to answer them one by one: Why is ctrl+s not fired? Several reasons. You are using the keyup event, while the browser starts to save the page on a keydown event. Your keyup event is thus never fired. For any event to be registered on your div, your div must have focus, because otherwise the event will not originate from that element, but instead from (presumably) the body. Is there a way to preventDefault without coding it? Yes. Add the prevent modifier to your event. In the same way, you can use once to unregister an event after it has triggered once, stop to use stopPropagation() and passive to explicitly not stop propagation. You would use something like: @keydown.ctrl.83.prevent="saveMe". How do I get this working? If you are find with the user having to focus the element before being able to save, and otherwise getting the default behaviour, use the following: <div id="app" tabindex="0" @keydown.ctrl.83.prevent.stop="saveInsideComponent" > <!-- --> </div> Otherwise, this is one of the few moments where registering your own event listener is useful. Just make sure to remove it before your component is destroyed, or you will have a rogue event listener throwing errors on other components + a memory leak to deal with. mounted() { document.addEventListener("keydown", this.doSave); }, beforeDestroy() { document.removeEventListener("keydown", this.doSave); }, methods: { doSave(e) { if (!(e.keyCode === 83 && e.ctrlKey)) { return; } e.preventDefault(); console.log("saving from DOM!"); }, }
[ "stackoverflow", "0038614256.txt" ]
Q: How can i show a simple instagram feed with the new api permissions I am trying to set up a instagram plugin on django cms to show my recent images on a homepage by the username set in the plugin. It seems you can no longer simply get public content from instagram. This is the current method im using with my sandbox account. user_request = requests.get("https://api.instagram.com/v1/users/search?q=" + str(instance.username) + "&access_token=" + settings.INSTAGRAM_ACCESS_TOKEN) user_id = user_request.json().values()[1][0]["id"] r = requests.get("https://api.instagram.com/v1/users/"+ user_id +"/media/recent/?access_token=" + settings.INSTAGRAM_ACCESS_TOKEN + "&count=" + str(instance.limit)) recent_media = r.json() The code above gets the username from the plugin model and makes a get request to the instagram api to get that user (i've heard this method doesn't always show the correct user as its just searching and getting the first user from a list). Is this the right way to work with the instagram api and python, I was going to use python-instagram but that is no longer supported. The only other way i can think of doing it is authenticating the user on the site and using their access token which seems silly for what i need it for. EDIT: Would removing the username field and adding access_token instead be a better method ? Then use "/users/self/media/recent" and rule out the query to search for a user by username. A: Yes, the first results is not always the match, you have loop through all the search results and compare the username to your searched username, and then get id Something like this: var user_id = 0; user_request.json().values()["data"].forEach(function(user){ if(user.username == str(instance.username)){ user_id = user["id"] } }); if(user_id){ // make api call } else { // user not found }
[ "superuser", "0000015567.txt" ]
Q: Mouse 'swipe' gestures for VMWare Fusion Is there any way to enable the 'swipe' gestures available within Mac OS X inside Fusion? I'm regularly trying to swipe around in my Windows guest machines until I realise I'm not in Kansas any more. A: Unfortunately not. The Fusion mouse driver does not include this and even the current Boot-camp drivers doesn't support this in Windows. Until Apple or VMWare produce a driver that does support this functionality it will most likely not happen. The Apple Boot-camp driver does however support right-click and 2 finger scroll.
[ "stackoverflow", "0019739393.txt" ]
Q: How do we animate a nav bar this way? Here is my code. I want to: Have the nav ul li highlighted, slid to the leftmost and also have an animated shadow to represent lifting. Have the above changes reversed as the mouse pointer leaves the nav bar. My code here has been accompanied with: jquery.min.js jquery.color-2.1.2.min.js jquery.animate-shadow-min.js This code does not work though I find nothing wrong. $(document).ready(function () { var linearOffset = $("nav li:hover").offset().left; $("nav li").mouseenter(function () { $("nav li:hover").removeClass("disappear"); $("nav li:hover").addClass("appear"); $(".disappear").css("visibility", "hidden"); $(".appear").animate({ right: linearOffset, backgroundColor: 'rgba(5, 0, 234, 0.95)', color: 'rgb(255, 255, 255)' }); $(".appear").stop(true, true); $(".appear").css("position", "absolute"); var backupOffset = linearOffset; delete linearOffset; }); $("nav").mouseleave(function () { $(".appear").stop(); $(".appear").animate({ left: linearOffset, }); $(".disappear").css("visiblity", "visible"); $(".appear").addClass("disappear"); $(".appear").removeClass("appear"); }); }); My working platform is Google Chrome 30.0.1599.101 (Official Build 227552) on Windows 8. A: CSS and HTML is too long so I just link jsFiddle. here is JQuery: $(".disappear").on('mouseenter', mEnter) $('nav>ul').on('mouseleave', function () { $('.disappear').stop(); $('.active').removeClass("active") .addClass("disappear"); $(".disappear").show(700); }); function mEnter() { $(this).addClass("active"); $(this).removeClass("disappear"); $(".disappear").hide(700); }
[ "stackoverflow", "0052504058.txt" ]
Q: Changing placeholder content not working as expected I have a placeholder in a page but am having trouble replacing the text with CSS. The input color, size, and font-style changes, but not the content? How can I replace the placeholder content? input::placeholder { color: black; font-style: italic; content:"This isn't changing"; } <input type="text" class="input-text" name="job_location" id="job_location" placeholder="e.g. &quot;London&quot;" value="" maxlength=""> A: As far as I can tell from looking at the docs you can not update the content through css for placeholder https://developer.mozilla.org/en-US/docs/Web/CSS/::placeholder You could consider using js to update the placeholder. document.getElementsByName('job_location')[0].placeholder='new text';
[ "stackoverflow", "0030782386.txt" ]
Q: Multiple Spring datasources for JUnit test I have such simple class for JUnit test: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/mysql-datasource-context.xml"}) public class EmployeeDAOTest { @Autowired EmployeeDao employeeDao; @Test public void findAllTest() { assertTrue(employeeDao.findByName("noname").size() == 0); } } The content of the mysql-datasource-context.xml looks like this: <context:component-scan base-package="my.packages.*"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/project"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="my.packages.entity"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> Now the test runs with no problem for my mysql database. The point is that I also have a postgres database and I need every test run both for the mysql and postgres databases. The only solution that comes to my mind is creating one more test class with exactly the same tests but annotate it as @ContextConfiguration(locations = {"classpath:/postgres -datasource-context.xml"}) and create one more datasource context file for it. Unfortunately this way doesn't look like a good solution. Is there a better way to solve my problem? A: I think that the simplest solution is to keep a test class as the base one: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/mysql-datasource-context.xml"}) public class EmployeeDAOTest { @Autowired EmployeeDao employeeDao; @Test public void findAllTest() { assertTrue(employeeDao.findByName("noname").size() == 0); } } and then creating one empty subclass for postgres with its own configuration: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/postgres-datasource-context.xml"}, inheritLocations=false) public class EmployeeDAOTestPostgres extends EmployeeDAOTest { } As other suggested you can alter your Spring config files in order to have only one; you can for example put the datasource in a separate context and import it or use a profile (see here for an example)
[ "sharepoint.stackexchange", "0000244839.txt" ]
Q: Get all users from azure AD group SharePoint hosted app I am currently trying to use a people picker to be able to get user properties and if a group is picked I want to be able to get all the user keys. I can get all the properties I need if I select a user and I have managed to get all the users that are in the SharePoint groups. Now I am trying to get all the users that are in the azure ad groups. Does anyone know if this is possible? A: There's no support for Azure AD groups in either the Client Object Model or the SharePoint REST API. Using the Microsoft Graph is a problem because configuring Reply URLs for a SharePoint-hosted App is a real pain. My suggestion is that you use Microsoft Flow. You can create a Flow with a HTTP Request trigger. The Flow then basically becomes a web service. You can then use the Azure AD - Get group members action to get the members from the group. Finally you can use the Response action to return the array of user object returned from the Get group members action. Once the Flow is done you can then call this Flow in pretty much the same way you would call the SharePoint REST API.
[ "stackoverflow", "0053541702.txt" ]
Q: Endless circular redirect with IdentityServer4 I'm developing multi-tenant ASP.NET MVC application using Finbuckle.Multitenant and IdentityServer4 (using standard classes and controllers from their tutorials). My app uses route strategy for tenants (https://host/tenant1/controller/action) and I use separate cookies for each tenant (cookie named auth.tenant1, auth.tenant2... etc.) Everything works fine unless I specify custom Path for auth cookie. If all of them has Path=/ everything is ok. BUT when I set Path=/tenant1 to cookie named auth.tenant1 and the same pattern for every other tenants I have a circular redirects after passing consent screen. When I click "yes" on consent screen I got 302 challenge redirect from IdentityServer middleware on client side. It redirects me back to Consent screen. After each "yes" I'm returning to consent. However it happens only during authentication process. If I open new tab and head to https://host/tenant1 I won't be redirected and will be successfully authenticated. Googled for answers for days but haven't found any solutions. Please help me! Here is my client's Startup.cs: public void ConfigureServices(IServiceCollection services) { services.AddMvc(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddMultiTenant().WithInMemoryStore(Configuration.GetSection("MultiTenant:InMemoryStore")) .WithRouteStrategy(MapRoutes) .WithRemoteAuthentication() .WithPerTenantOptions<AuthenticationOptions>((options, tenantContext) => { // Allow each tenant to have a different default challenge scheme. if (tenantContext.Items.TryGetValue("ChallengeScheme", out object challengeScheme)) { options.DefaultChallengeScheme = (string)challengeScheme; } }) .WithPerTenantOptions<CookieAuthenticationOptions>((options, tenantContext) => { options.Cookie.Name += tenantContext.Identifier; options.Cookie.Path = "/" + tenantContext.Identifier; options.LoginPath = "/" + tenantContext.Identifier + "/Home/Login"; }); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.Cookie.Name = "auth."; }) .AddOpenIdConnect("oidc", options => { options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = "https://localhost:5000"; options.RequireHttpsMetadata = true; options.ClientId = "mvc"; options.SaveTokens = true; options.ClientSecret = "secret"; //Hybrid protocols (OpenId + OAuth) options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.GetClaimsFromUserInfoEndpoint = true; //ask to allow access to testApi options.Scope.Add("testApi"); //allows requesting refresh tokens for long lived API access options.Scope.Add("offline_access"); options.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = ctx => { var tenant = ctx.HttpContext.GetMultiTenantContext()?.TenantInfo?.Identifier; ctx.ProtocolMessage.AcrValues = $"tenant:{tenant}"; return Task.FromResult(0); } }; }); } private void MapRoutes(IRouteBuilder router) { router.MapRoute("Default", "{__tenant__=tenant1}/{controller=Home}/{action=Index}/{id?}"); } Here is my client configuration on IdentityServer's side (appsettings.json): { "clientId": "mvc", "clientName": "MVC Client", "allowedGrantTypes": [ "hybrid", "client_credentials" ], "clientSecrets": [ { "value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } // Sha256("secret") ], "redirectUris": [ "https://localhost:5002/signin-oidc" ], "postLogoutRedirectUris": [ "https://localhost:5002/signout-callback-oidc" ], "allowedScopes": [ "openid", "profile", "testApi" ], "allowOfflineAccess": true }, My IdentityServer4 config: public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var identityServerBuilder = services.AddIdentityServer() .AddDeveloperSigningCredential(); if (_config.GetSection("AppSettings:UseDummyAuthentication").Get<bool>()) { identityServerBuilder .AddInMemoryIdentityResources(_config.GetSection("IdentityResources")) .AddInMemoryApiResources(_config.GetSection("ApiResources")) .AddInMemoryClients(_config.GetSection("Clients")) .AddTestUsers(_config.GetSection("TestUsers")); } services.AddAuthentication(); } Please help me, guys! How can I make Path=/tenant1 scheme work without redirects on consent screen??? A: Ok, I figured out what's wrong and post answer to those who will encounter the same problem. The problem is that when you change Path of cookie IdentityServer's middleware can't find it because it hosted on https://host/signin-oidc/. What you need to handle this is https://host/tenant1/signin-oidc for each of your tenant on client and add all those urls to clients redirectUris. To achieve it your multitenant configuration should look like this services.AddMultiTenant().WithInMemoryStore(Configuration.GetSection("MultiTenant:InMemoryStore")) .WithRouteStrategy(MapRoutes) .WithRemoteAuthentication() .WithPerTenantOptions<CookieAuthenticationOptions>((options, tenantContext) => { options.Cookie.Name = $"auth.{tenantContext.Identifier}"; options.Cookie.Path = "/" + tenantContext.Identifier; options.LoginPath = "/" + tenantContext.Identifier + "/Home/Login"; }) .WithPerTenantOptions<OpenIdConnectOptions>((opt, ctx) => { opt.CallbackPath = "/" + ctx.Identifier + "/signin-oidc"; }); Whole Startup.cs public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddMultiTenant().WithInMemoryStore(Configuration.GetSection("MultiTenant:InMemoryStore")) .WithRouteStrategy(MapRoutes) .WithRemoteAuthentication() .WithPerTenantOptions<CookieAuthenticationOptions>((options, tenantContext) => { options.Cookie.Name = $"auth.{tenantContext.Identifier}"; options.Cookie.Path = "/" + tenantContext.Identifier; options.LoginPath = "/" + tenantContext.Identifier + "/Home/Login"; }) .WithPerTenantOptions<OpenIdConnectOptions>((opt, ctx) => { opt.CallbackPath = "/" + ctx.Identifier + "/signin-oidc"; }); ; services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.Cookie.Name = "auth."; o.Cookie.IsEssential = true; }) .AddOpenIdConnect("oidc", options => { options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = "https://localhost:5000"; options.ClientId = "mvc"; options.SaveTokens = true; options.ClientSecret = "secret"; //Hybrid protocols (OpenId + OAuth) options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.GetClaimsFromUserInfoEndpoint = true; //ask to allow access to testApi options.Scope.Add("testApi"); //allows requesting refresh tokens for long lived API access options.Scope.Add("offline_access"); options.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProvider = ctx => { var tenant = ctx.HttpContext.GetMultiTenantContext()?.TenantInfo?.Identifier; ctx.ProtocolMessage.AcrValues = $"tenant:{tenant}"; return Task.FromResult(0); } }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { var errorPage = Configuration.GetValue<string>("ErrorPage"); app.UseExceptionHandler(errorPage); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseMultiTenant(); app.UseAuthentication(); app.UseMvc(MapRoutes); } private void MapRoutes(IRouteBuilder router) { router.MapRoute("Default", "{__tenant__=tenant1}/{controller=Home}/{action=Index}/{id?}"); } Don't forget to register all tenants urls in IdentityServer4 Client.RedirecUris "redirectUris": [ "https://localhost:5002/tenant1/signin-oidc", "https://localhost:5002/tenant2/signin-oidc", "https://localhost:5002/tenant3/signin-oidc" ]
[ "stackoverflow", "0039105944.txt" ]
Q: Selecting elements only if have two classes and share the same first one i have these elements in the HTML I want to parse: <td class="line"> GARBAGE </td> <td class="line text"> I WANT THAT </td> <td class="line heading"> I WANT THAT </td> <td class="line"> GARBAGE </td> How can I make a CSS selector that select elements with attributes class line and class something else (could be heading, text or anything else) BUT not attribute class line only? I have tried: td[class=line.*] td.line.* td[class^=line.] EDIT I am using Python and BeautifulSoup: url = 'http://www.somewebsite' res = requests.get(url) res.raise_for_status() DicoSoup = bs4.BeautifulSoup(res.text, "lxml") elems = DicoSoup.select('body div#someid tr td.line') I am looking into modifying the last piece, namely td.line to something like td.line.whateverotherclass (but not td.line alone otherwise my selector would suffice already) A: What @BoltClock suggested is generally a correct way to approach the problem with CSS selectors. The only problem is that BeautifulSoup supports a limited number of CSS selectors. For instance, not() selector is :not(.supported) at the moment. You can workaround it with a "starts-with" selector to check if a class starts with line followed by a space (it is quite fragile but works on your sample data): for td in soup.select("td[class^='line ']"): print(td.get_text(strip=True)) Or, you can solve it using the find_all() and having a searching function checking the class attribute to have line and some other class: from bs4 import BeautifulSoup data = """ <table> <tr> <td class="line"> GARBAGE </td> <td class="line text"> I WANT THAT </td> <td class="line heading"> I WANT THAT </td> <td class="line"> GARBAGE </td> </tr> </table>""" soup = BeautifulSoup(data, 'html.parser') for td in soup.find_all(lambda tag: tag and tag.name == "td" and "class" in tag.attrs and "line" in tag["class"] and len(tag["class"]) > 1): print(td.get_text(strip=True)) Prints: I WANT THAT I WANT THAT
[ "stackoverflow", "0026408193.txt" ]
Q: Excel: Better Percentage Ranges I am attempting to write up some tables which automatically populate with a percentage range based on if there are any contents, (and how many contents overall). Picture is what I am looking for, if you enter info in the blank boxes it automatically calculates the new ranges, and vice-versa by deleting any. . I already have a working code, but it feels clunky and I'm worried that if I had a whole datasheet full of this that it will more than likely crash. =IF(NOT(ISBLANK(C84)), ( TEXT(COUNTA(B84:$B84)/COUNTA($B84:$N84)+0.01,"0%") )&"-"& TEXT( COUNTA(B84:$B84)/COUNTA($B84:$N84)+1/COUNTA($B84:$N84),"0%"),"-") Any suggestions on trimming this? A: What info are you entering, and into which cells? Is the desired outcome a summary or a line by line result?
[ "puzzling.stackexchange", "0000072919.txt" ]
Q: Teapot Riddle no.29 Teapot Riddle no.29, and first of all thanks to @PerpetualJ and @Astralbee for making nice riddles. The riddles are linked in the end. Rules: I have one word which has several (2 or more) meanings. Each of the meanings is a teapot (first, second ...) You try to figure out the word with my Hints. First Hint: My first teapot is a known force, which comes in circulations Second Hint: My second teapot is a gesture which is done by cats untiringly Third Hint: My third teapot is an amount of feelings Fourth Hint: My forth teapot messes your hair until you look good Good luck and have fun (and write your own riddles :D) last riddles (Probz to the writers): no.28 no.27 no.26 no.25 A: Not 100% sure, but is it: TENSION? a known force, comes in circulations Tension is a natural force, and circular motion can create tension, eg swinging something around on a string will make the string tense a gesture which is done by cats untiringly Cats often stiffen, or tense an amount of feelings Feeling "tension" can be a build-up of emotion messes your hair until you look good Apparently some hair-straightening techniques involve applying tension. A: Is it: WAVE a known force, comes in circulations Forces of nature travel in waves. a gesture which is done by cats untiringly Cats seem to "wave" their paws in the air, and perhaps by "untiringly" you are referring to those Maneki-nekos, or perpetually waving cats. an amount of feelings You can experience a "wave" of emotion. messes your hair until you look good You can have a permanent wave put in your hair
[ "stackoverflow", "0060836757.txt" ]
Q: How to debug for TLS/SSL connection Ar first I made three files with these. $ openssl genrsa 2048 > server.key $ openssl req -new -key server.key > server.csr $ openssl x509 -days 3650 -req -signkey server.key < server.csr > server.crt Then,I made registry container by docker-compose which including server.key server.crt and port 5000 is open. version: '3' services: registry: container_name: registry image: registry:2 restart: always ports: - '5000:5000' volumes: - /home/ubuntu/docker/data:/var/lib/registry - /home/ubuntu/docker/certs:/certs - /etc/localtime:/etc/localtime environment: REGISTRY_HTTP_TLS_CERTIFICATE: /certs/server.crt REGISTRY_HTTP_TLS_KEY: /certs/server.key then in the localhost I rename server.crt to ca.crt and put the key /etc/docker/certs.d/docker.mysite.jp\:5000/ca.crt. Then I try to curl but in vain. $curl https://docker.mysite.jp:5000/v2/ --cacert /etc/docker/certs.d/docker.mysite.jp\:5000/ca.crt /etc/docker/certs.d/docker.mysite.jp\:5000/ca.crt curl: (60) SSL: unable to obtain common name from peer certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. OK I see there is something wrong with tls/ssl However how can I debug where to start?? $curl https://docker.mysite.jp:5000/v2/ --cacert /etc/docker/certs.d/docker.mysite.jp\:5000/ca.crt -vvv here is the log * TCP_NODELAY set * Expire in 200 ms for 4 (transfer 0x7f89b4800000) * Connected to docker.mysite.jp (135.132.179.73) port 5000 (#0) * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/docker/certs.d/docker.mysite.jp:5000/ca.crt CApath: none * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: C=AU; ST=Some-State; O=Internet Widgits Pty Ltd * start date: Mar 24 16:55:37 2020 GMT * expire date: Feb 29 16:55:37 2120 GMT * SSL: unable to obtain common name from peer certificate * Closing connection 0 curl: (60) SSL: unable to obtain common name from peer certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. I set the SQDN for crt file. then error message changed. * TCP_NODELAY set * Expire in 200 ms for 4 (transfer 0x7fb4de806c00) * Connected to docker.mysite.jp (135.132.179.73) port 5000 (#0) * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/docker/certs.d/docker.mysite.jp:5000/ca.crt CApath: none * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (OUT), TLS alert, unknown CA (560): * SSL certificate problem: self signed certificate * Closing connection 0 curl: (60) SSL certificate problem: self signed certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. but ,Then I restart with docker-compose down & docker-compose up, it fixed!!! A: execute curl with -vvv option to see all steps. Also, you can try tcpdump and wireshark to see every network action at including network level 4.
[ "stackoverflow", "0029010542.txt" ]
Q: Python - regex to keep only words with textual characters I want to have a regex in my Python program to keep only words that contain alphabetical text characters (i.e. no special characters such as dots, commas, :, ! etc.) I am using this code to get the words from a text file: find_words = re.compile(r'\w+').findall The problem with this regular expression is that for input like this: -----BEGIN PRIVACY-ENHANCED MESSAGE----- Proc-Type: 2001,MIC-CLEAR Originator-Name: [email protected] Originator-Key-Asymmetric: MFgwCgYEVQgBAQICAf8DSgAwRwJAW2sNKK9AVtBzYZmr6aGjlWyK3XmZv3dTINen TWSM7vrzLADbmYQaionwg5sDW3P6oaM5D3tdezXMm7z1T+B+twIDAQAB MIC-Info: RSA-MD5,RSA, U6u1HjX9A2VnveGmx3CbhhgTr7o+NJWodWNJQjg1aSLDkLnJwruLq9hBBcqxouFq NY7xtb92dCTfvEjdmkDrUw== 0001393311-11-000011.txt : 20110301 0001393311-11-000011.hdr.sgml : 20110301 20110301164350 ACCESSION NUMBER: 0001393311-11-000011 CONFORMED SUBMISSION TYPE: 10-K PUBLIC DOCUMENT COUNT: 16 CONFORMED PERIOD OF REPORT: 20101231 FILED AS OF DATE: 20110301 DATE AS OF CHANGE: 20110301 FILER: I get output like this: begin privacy enhanced message proc type 2001 mic clear originator name webmaster www sec gov originator key asymmetric mfgwcgyevqgbaqicaf8dsgawrwjaw2snkk9avtbzyzmr6agjlwyk3xmzv3dtinen twsm7vrzladbmyqaionwg5sdw3p6oam5d3tdezxmm7z1t b twidaqab mic info rsa md5 rsa u6u1hjx9a2vnvegmx3cbhhgtr7o njwodwnjqjg1asldklnjwrulq9hbbcqxoufq ny7xtb92dctfvejdmkdruw 0001393311 11 000011 txt 20110301 0001393311 11 000011 hdr sgml which is not what I want because A) it does not keep words that I want it to keep such as "Accession", "Number" etc., and it also keeps stuff like mfgwcgyevqgbaqicaf8dsgawrwjaw2snkk9avtbzyzmr6agjlwyk3xmzv3dtinen which I don't want to keep because of the numbers in the word, and it also keeps 0001393311 etc. which I don't want to keep. Any ideas on how to get the words that I want ? (i.e. to contain only alphabetical characters). A: Here you actually need to use a negative look-behind assertion. (?<!\S)[A-Za-z]+(?!\S)|(?<!\S)[A-Za-z]+(?=:(?!\S)) (?<!\S)[A-Za-z]+(?!\S) matches the exact word which must contain alphabets. | OR (?<!\S)[A-Za-z]+(?=:(?!\S)) One or more word characters which must be followed by a colon which in-turn not followed by a non-space character. You could use (?=:\s) pattern instead of (?=:(?!\S)) also. DEMO
[ "stackoverflow", "0062197128.txt" ]
Q: IE11: web requests not working from sandboxed iframe I'm trying to make a HTTP GET request in javascript to a rest API from within an iframe. The iframe is sandboxed, but it has the allow-scripts attribute set, and the API I'm calling is enabled to allow all origins, so CORS shouldn't be a problem. I've recreated the scenario with a minimal code sample here: http://plnkr.co/edit/jrchvxFXQQDqs2Fv If you go to that page and preview the page with any modern browser (Chrome, Edge, etc.) it works correctly. But if you do that with Internet Explorer 11, the call fails. On the javascript console, we get this generic network error: but the weird thing is: the call is actually running correctly. In fact, if we check the network tab, we can see it being performed and returming 200: Am I doing something wrong here, or is this just the usual IE being IE? A: I found that we need to add allow-same-origin to make it work in IE. By default sandbox forces the “different origin” policy for the iframe. In other words, it makes the browser to treat the iframe as coming from another origin, even if its src points to the same site. allow-same-origin removes this feature. So I think it fails in IE at first because it doesn't meet the same-origin policy. As for the difference between IE and other browsers, I think that's due to the different policy design in different browsers. I also find a thread about the issue and there's some useful information, you could also refer to it for more information.
[ "math.stackexchange", "0001986462.txt" ]
Q: How to compute a prime gap from all previous prime gaps? In prime numbers, one has the sieve of Eratosthenes, which is a method of computing the next prime, once you have all previous primes: You just cross out the multiples of the previous primes on the number line, and the first remaining number is the next prime. I wonder whether there is such a method for prime gaps. Of course, one could add up the prime gaps and then apply the sieve of Eratosthenes, get the next prime, and then compute the next prime gap from it, but I wonder whether there is a more "direct" way. A: A "more direct way" to apply a sieve process to prime gaps is described in the paper by Fred Holt and Helgi Rudd "Eratosthenes sieve and the gaps between primes"; see arXiv:1408.6002.
[ "superuser", "0001064048.txt" ]
Q: How do I turn off the sound Windows 10 makes when I plug in headphones? I usually wear headphones at my computer. Every time I plug them in, however, a deafening sound plays through them. How can I remove this sound? p.s. This is less important, and if you don't know don't bother. Whenever I reboot my PC the sound level gets reset to 100. Is it possible to get it to save? A: To turn off the notifications, access Win 10 Settings - click the notifications icon in the taskbar’s system tray area, then click “All settings”. In “Sound” click on the “Sounds” tab and you can either remove system sounds completely, or configure them individually. Find "Notifications", click the scrolling menu at the bottom of the control panel next to the “Test” button, scroll to the top and select “None”, and click “Apply” or “OK”.
[ "math.stackexchange", "0000866778.txt" ]
Q: probability of winning a dice game We have a two player game with this rules: First player throws two dice and the bigger number will be his number. Second player throws only one die. If the number of first player was bigger than that of the second player, the first player wins; if not, the first player loses. For example if first one have 2 and 4 and second have 4,first one loses and second one wins. Please help me finding probability of winning of first player. A: You care most about the maximum of the first roll. This will be 1 with probability 1/36. It will be 2 with probability 3/36 etc. (it will be n with probability (2n-1)/36) The first player will win if the second player throws less than his max. $\large P=\frac{1}{36}\frac{0}{6}+\frac{3}{36}\frac{1}{6}+\frac{5}{36}\frac{2}{6}+\frac{7}{36}\frac{3}{6}+\frac{9}{36}\frac{4}{6}+\frac{11}{36}\frac{5}{6}=\frac{125}{216}$ A: We find the probability that the second player B wins. If B tosses a $6$, she wins with probability $1$. If B tosses a $5$, she wins with probability $\left(\frac{5}{6}\right)^2$. For then B wins precisely if the first player A gets $\le 5$ twice in a row. If B tosses a $4$, she wins with probability $\left(\frac{4}{6}\right)^2$. And so on. So the probability B wins is $$\frac{1}{6^3}\left(6^2+5^2+4^2+3^2+2^2+1^2\right)=\frac{91}{216}.$$ Thus our required probability is $1-\frac{91}{216}$.
[ "drupal.stackexchange", "0000049398.txt" ]
Q: How to change Views field settings programmatically? I would like to change some field settings in a given view created with Views programmatically. For example, I would like to change the "Formatter" and "Image style" settings of an Image field. This is what the settings of this field look like when I export this view: /* Field: Taxonomy term: Natural images */ $handler->display->display_options['fields']['field_gallery_natural_images']['id'] = 'field_gallery_natural_images'; $handler->display->display_options['fields']['field_gallery_natural_images']['table'] = 'field_data_field_gallery_natural_images'; $handler->display->display_options['fields']['field_gallery_natural_images']['field'] = 'field_gallery_natural_images'; $handler->display->display_options['fields']['field_gallery_natural_images']['click_sort_column'] = 'fid'; $handler->display->display_options['fields']['field_gallery_natural_images']['type'] = 'colorbox'; $handler->display->display_options['fields']['field_gallery_natural_images']['settings'] = array( 'colorbox_node_style' => '', 'colorbox_image_style' => '', 'colorbox_gallery' => 'post', 'colorbox_gallery_custom' => '', 'colorbox_caption' => 'auto', 'colorbox_caption_custom' => '', 'display_empty' => '', 'custom_text' => '', 'empty_callback' => 'mymodule_empty_fields_no_data', ); I would like to change the "Image style" of the Colorbox formatter somehow like this: $handler->display->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail'; and save that. How should I do that? Like here: EDIT 1. Maybe I should use views_save_view(): http://api.drupal.org/api/views/views.module/function/views_save_view/7 It saves a view - so maybe I should query the whole view, change that, and use this function. But how exactly? EDIT 2. I found in views/includes/admin.inc that the given view gets saved like this: $form_state['view']->save(); in views_ui_edit_view_form_submit(). I already know how to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear), but now I would be happy if I could do something similar with a given view. A: UPDATED: You can use this code snippet to change a view without views_alter: $view = views_get_view($view_name, TRUE); $view->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail'; views_save_view($view); Change default display ID if you want to use display other than the default. If you have exported the view to code using hook_views_default_views() or the Features module, there is a hook to alter the views programmatically: /** * Alter default views defined by other modules. * * This hook is called right before all default views are cached to the * database. It takes a keyed array of views by reference. * * Example usage to add a field to a view: * @code * $handler =& $view->display['DISPLAY_ID']->handler; * // Add the user name field to the view. * $handler->display->display_options['fields']['name']['id'] = 'name'; * $handler->display->display_options['fields']['name']['table'] = 'users'; * $handler->display->display_options['fields']['name']['field'] = 'name'; * $handler->display->display_options['fields']['name']['label'] = 'Author'; * $handler->display->display_options['fields']['name']['link_to_user'] = 1; * @endcode */ function hook_views_default_views_alter(&$views) { if (isset($views['taxonomy_term'])) { $views['taxonomy_term']->display['default']->display_options['title'] = 'Categories'; } } For example: /** * Implements hook_views_default_views_alter() */ function MYMODULE_views_default_views_alter(&$views) { if (isset($views['VIEW_NAME'])) { $views['VIEW_NAME']->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail'; } } Remember to clear the cache and do revert of the view to apply changes.
[ "apple.stackexchange", "0000307416.txt" ]
Q: macOS not allowing me to reallocate free space! I had two partitions on my mac, both had macOS installed on it as a result both had a recovery partiton, now I deleted one pratition cause it got corrupted due to some script which I ran. Now mac has only one partition which is the startup volume. The problem is the previous partition created a free space upon removing it and it is not allocated to anyone, now when I try to delete the free space, Disk Utility fails to carry out the opertaion! Both the partitons also created a public folder, which I don't know much about cause I never created it, now the problem is what should I do with this public folder should I remove it from my system preferences or should I keep it, I don't know what might happen/get deleted if I remove it from my iMac! So basically two issues have arised as a consequence of the corruption and running a custom script for tweaking your mac! I went through this https://www.reddit.com/r/osx/comments/305lik/help_removing_the_free_space_partition/ post but it doesn't seems to be linked with my issue as I don't have any (No CoreStorage logical volume groups found - Terminal output for diskutil cs list; diskutil list) And when I try to resize the disk via Terminal I get this error: Sayans-iMac:~ sayanhussain$ diskutil resizeVolume disk0s2 R Resizing to full size (fit to fill) Started partitioning on disk0s2 macOS Error: -69742: The requested size change for the target disk or a related disk is too small; please try a different disk or partition, or make a larger change Sayans-iMac:~ sayanhussain$ A: Ok so the error is now solved. What I did! First I ran diskutil list to view all the active partitions, now I had only on partiton so added a new partiton via DiskUtility Then I once again ran diskutil list, now I was able to see the newly added partiton Now what I did ti remove the free space is that I merged both the partitions together To merge two partitons I simply ran this command in terminal Sayans-iMac:~ sayanhussain$ diskutil mergePartitions Usage: diskutil mergePartitions [force] format name DiskIdentifier|DeviceNode DiskIdentifier|DeviceNode Merge two or more pre-existing partitions into one. The first disk parameter is the starting partition; the second disk parameter is the ending partition; this given range of two or more partitions will be merged into one. All partitions in the range, except for the first one, must be unmountable. All data on merged partitions other than the first will be lost; data on the first partition will be lost as well if the "force" argument is given. If "force" is not given, and the first partition has a resizable file system (e.g. JHFS+), it will be grown in a data-preserving manner, even if a different file system is specified (in fact, your file system and volume name parameters are both ignored in this case). If "force" is not given, and the first partition is not resizable, you will be prompted if you want to erase. If "force" is given, the first partition is always formatted. You should do this if you wish to reformat to a new file system type. Merged partitions are required to be ordered sequentially on disk. See diskutil list for the actual on-disk ordering; BSD slice identifiers may in certain circumstances not always be in numerical order but the top-to-bottom order given by diskutil list is always the on-disk order. Ownership of the affected disk is required. Example: diskutil mergePartitions JHFS+ NewName disk3s4 disk3s7 This example will merge all partitions *BETWEEN* disk3s4 and disk3s7, preserving data on disk3s4 but destroying data on disk3s5, disk3s6, disk3s7 and any invisible free space partitions between those disks; disk3s4 will be grown to cover the full space if possible. Sayans-iMac:~ sayanhussain$
[ "stackoverflow", "0050077767.txt" ]
Q: Using variable as 'id' attribute in javascript I have following jaggery code for UI where I am fetching values from user via UI. <% for (i = 0; i < applicationAttributes.length; i++) { %> <div> <label>data:</label> <div> <input type="text" id = "attribute_<%= i%>" > </div> </div> <% } %> when reading the values respective to each ids, var data = $("#attribute_1").val(); But it is not returning the value, Can someone specify the proper method to assign 'id' A: There should be no space between id and its value <input type="text" id = "attribute_<%= i%>" > <!- _________________^_^ --> It should be <input type="text" id="attribute_<%= i%>" /> And it's a good practice to have / closing void elements.
[ "stackoverflow", "0003796839.txt" ]
Q: how to optimise this code? I have a solution to the below problem in PHP. But it is taking too much time to execute for 10 digit numbers. I want to know where am I going wrong ? I am new to dynamic programming .Can someone have a look at this ? Problem In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? ======================================================== <?php $maxA=array(); function exchange($money) { if($money == 0) { return $money; } if(isset($maxA[$money])) { $temp = $maxA[$money]; // gets the maximum dollars for N } else { $temp = 0; } if($temp == 0) { $m = $money/2; $m = floor($m); $o = $money/3; $o = floor($o); $n = $money/4; $n = floor($n); $total = $m+$n+$o; if(isset($maxA[$m])) { $m = $maxA[$m]; } else { $m = exchange($m); } if(isset($maxA[$n])) { $n = $maxA[$n]; } else { $n = exchange($n); } if(isset($maxA[$o])) { $o = $maxA[$o]; } else { $o = exchange($o); } $temp = max($total,$m+$n+$o,$money); $maxA[$money]=$temp; //store the value } return $temp; } $A=array(); while(1) { $handle = fopen ("php://stdin","r"); $line = fgets($handle); if(feof($handle)) { break; } array_push($A,trim($line)); } $count =count($A); for($i=0;$i<$count;$i++) { $val = exchange($A[$i]); print "$val \n"; } ?> A: Here a reformatted version of the code for the ones (like I) who could understand the above. It doesn't improve anything. function exchange($money) { static $maxA = array(0 => 0); if (isset($maxA[$money])) { return $money; } $m = floor($money/2); $o = floor($money/3); $n = floor($money/4); $total = $m+$n+$o; if (isset($maxA[$m])) { $m = $maxA[$m]; } else { $m = exchange($m); } if (isset($maxA[$n])) { $n = $maxA[$n]; } else { $n = exchange($n); } if (isset($maxA[$o])) { $o = $maxA[$o]; } else { $o = exchange($o); } return $maxA[$money] = max($total, $m + $n + $o, $money); }
[ "serverfault", "0000434591.txt" ]
Q: Linux service --status-all shows "Firewall is stopped." what service does firewall refer to? I have a development server with the lamp stack running CentOS: [Prompt]# cat /etc/redhat-release CentOS release 5.8 (Final) [Prompt]# cat /proc/version Linux version 2.6.18-308.16.1.el5xen ([email protected]) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-52)) #1 SMP Tue Oct 2 22:50:05 EDT 2012 [Prompt]# yum info iptables Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirror.anl.gov * extras: centos.mirrors.tds.net * rpmfusion-free-updates: mirror.us.leaseweb.net * rpmfusion-nonfree-updates: mirror.us.leaseweb.net * updates: mirror.steadfast.net Installed Packages Name : iptables Arch : x86_64 Version : 1.3.5 Release : 9.1.el5 Size : 661 k Repo : installed .... Snip.... When I run: service --status-all Part of the output looks like this: .... Snip.... httpd (pid xxxxx) is running... Firewall is stopped. Table: filter Chain INPUT (policy DROP) num target prot opt source destination 1 RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 Chain FORWARD (policy DROP) num target prot opt source destination 1 RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 Chain OUTPUT (policy ACCEPT) num target prot opt source destination Chain RH-Firewall-1-INPUT (2 references) ....Snip.... iptables has been loaded to the kernel and is active as represented by the rules being displayed. Checking just the iptables returns the rules just like status all does: [Prompt]# service iptables status Table: filter Chain INPUT (policy DROP) num target prot opt source destination 1 RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 Chain FORWARD (policy DROP) num target prot opt source destination 1 RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 Chain OUTPUT (policy ACCEPT) num target prot opt source destination Chain RH-Firewall-1-INPUT (2 references) .... Snip.... Starting or restarting iptables indicates that the iptables have been loaded to the kernel successfully: [Prompt]# service iptables restart Flushing firewall rules: [ OK ] Setting chains to policy ACCEPT: filter [ OK ] Unloading iptables modules: [ OK ] Applying iptables firewall rules: [ OK ] Loading additional iptables modules: ip_conntrack_netbios_n[ OK ] [Prompt]# service iptables start Flushing firewall rules: [ OK ] Setting chains to policy ACCEPT: filter [ OK ] Unloading iptables modules: [ OK ] Applying iptables firewall rules: [ OK ] Loading additional iptables modules: ip_conntrack_netbios_n[ OK ] I've googled "Firewall is stopped." and read a number of iptables guides as well as the RHEL documentation, but no luck. As far as I can tell, there isn't a "Firewall" service, so what is the line "Firewall is stopped." referring to? EDIT - Here's some additional info. iptables is working in spite of the "Firewall is stopped." output from service status. I added a rule to iptables that restricted ssh access to only one IP address (not my IP address) and after restarting iptables, I couldn't log in. I have an idea that the two items are output one after another in service --status-all is because the services are output alphabetically (just a guess). So, can anyone explain why I see the "Firewall is stopped." is my service status output even though the iptables rules are in effect and working correctly? Solution The "Firewall is stopped." message appears if either iptables or ip6tables is turned off. If both are off, the (same exact) message will appear twice (wouldn't it be nice if the message for ip6 indicated that it was referring to ip6). You will also see the error message if the service is on, but you have an empty rules table (as happened in my case for ip6). Information provided by @Alexander Janssen . See the answer for a link to the CentOS 5.8 default ip6 rule set. A: Edit: After having a chat with the OP we can state the following facts: It refers to the services iptables and ip6tables. The errormessage appears when the service ip6tables is on (by chkconfig), but doesn't have any rules. I advice to set up default IPv6 rules as are given in the stock CentOS 5.8 installation. You may take this as a reference. This was taken from a stock 5.8 installation. Hope everything is sorted out now :)
[ "stackoverflow", "0020926979.txt" ]
Q: Web API 2 OWIN Bearer Token purpose of cookie? I am trying to understand the new OWIN Bearer Token authentication process in the Single Page App template in MVC 5. Please correct me if I'm wrong, for the OAuth password client authentication flow, Bearer Token authentication works by checking the http authorization request header for the Bearer access token code to see if a request is authenticated, it doesn't rely on cookie to check if a particular request is authenticated. According to this post: OWIN Bearer Token Authentication with Web API Sample public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager()) { if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName); IEnumerable<Claim> claims = await GetClaimsAsync(identityManager, userId); ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims, _cookieOptions.AuthenticationType); AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } } The GrantReourceOwnerCredentials function not only compose the ticket with this line: context.Validated(ticket); but it also compose a cookie identity and set it to the cookie with this line: context.Request.Context.Authentication.SignIn(cookiesIdentity); So my questions are, what is the exact purpose of the cookie in this function? Shouldn't the AuthenticationTicket be good enough for authentication purpose? A: In the SPA template there are actually two separate authentication mechanisms enabled- cookie authentication and token authentication. This enables authentication of both MVC and Web API controller actions, but requires some additional setup. If you look in the WebApiConfig.Register method you'll see this line of code: config.SuppressDefaultHostAuthentication(); That tells Web API to ignore cookie authentication, which avoids a host of problems which are explained in the link you posted in your question: "...the SPA template enables application cookie middleware as active mode as well in order to enable other scenarios like MVC authentication. So Web API will still be authenticated if the request has session cookie but without a bearer token. That’s probably not what you want as you would be venerable to CSRF attacks for your APIs. Another negative impact is that if request is unauthorized, both middleware components will apply challenges to it. The cookie middleware will alter the 401 response to a 302 to redirect to the login page. That is also not what you want in a Web API request." So now with the call to config.SuppressDefaultHostAuthentication() Web API calls that require authorization will ignore the cookie that is automatically sent along with the request and look for an Authorization header that begins with "Bearer". MVC controllers will continue to use cookie authentication and are ignorant of the token authentication mechanism as it's not a very good fit for web page authentication to begin with. A: The existence of the cookie also left me puzzled, since it clearly is not necessary in a bearer token authentication scenario... In this post the author dissects the individual accounts template, and has the following to say about the cookie: The method also sets an application cookie. I don’t see a good reason for that. My guess is that the authors of the template wanted to show examples of different kinds of authentication logic, and in this particular case they wanted to show how the authentication information could be stored in both the bearer token authentication JSON payload, as well as in a standard authentication cookie. The fact that the JSON authentication payload is set to also include an additional (unnecessary) unencrypted property (the user id), in addition to the encrypted ticket, seems to support this theory: var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties); It seems that the authors of the template wanted to provide some useful examples, rather than the bare minimum needed to achieve bearer token authentication. This is also mentioned in the linked post above.
[ "stackoverflow", "0020748986.txt" ]
Q: How to check if a possible path exist? I'm working on an experimental javascript-based game. Player has to travel to exit on a 2-dimensional tiled map. Feel free to check this fiddle and play I'm just randomly placing obstacles, but sometimes obstacles block the way between player and exit, and level becomes impossible to beat. The code below which showing how obstacles being placed in the map is not a part of actual code, I've just simplified and translated this part to English to improve intelligibility: var arrayCoordinates; var targetSquare; var obstacleAmount = 30; for (var i = 1; i <= obstacleAmount; i++) { arrayCoordinates= randomCoordinates(); targetSquare = document.getElementById(arrayCoordinates[0] + '-' + arrayCoordinates[1]); targetSquare.className = 'obstacle'; } I'm just searching for a path-finding algorithm or an idea for me to write one. A: Had a question like this in an interview the other day. What your problem boils down to is finding the shortest path from point A to point B, given that all the steps in between are valid (according to your set of rules). So lets say we have a grid of X by Y spaces. If we start in space (x,y) then we are required to find where to move next on the board. This involves calculating all the potential squares we can make a move to from our current position. Imagine first that this problem is a spiderweb, with our starting square in it's epicentre. If we start in the middle of the spiderweb, we do not wish to pick a random direction and start walking until we hit the edge- we could be walking in the wrong direction entirely. This is the naive method of calculating the path and takes far longer than it's alternative. Better then is to walk breadthwise through the web, and only halt our exploration when we hit our goal. About to update with the code. EDIT: Working javascript code, just look for -1 to detect impossible games. LINK
[ "stackoverflow", "0004883304.txt" ]
Q: adding software components to eclipse I have an eclipse installation from the "Eclipse for PHP Developers" package and I want to "extend" it to have in addition to the PHP components all the components of "Eclipse IDE for Java EE Developers". but the Feature Lists in the above links do not match the items I am presented when I choose "Install new software..." from the eclipse help menu. Is there anything I can do about this? A: the result of copying plugins/features into that folder is not that predictable and hence not safe. Eclipse adviced to install plugins via "Install new Software" - it will tell you about conflicts (like different plugins use different version of another plugin" etc; or you need to install another plugin etc.) Otherwise I had situations when it didn't work and I got no idea why (had to read logs to figure it out). Well, to install new plugin you have few possibilities: 1) "Install new Software" - you already tried it. Take into account that the list of plugins by default is limited here. But below the button "Add..." you can see "Available Software Sites" - this list is enhanced, and some of plugins you can find here". UPDATE: the process of installation is described here 2) With new Eclipse (Helios) you got new way to add plugins, so called Eclipse Marketplace (Help/Eclipse Marketplace...). This is recommended way to look and install new plugins. Back to your problem - I think it is much more easier to download Java IDE for Java EE Developers, and install PHP Development Tools there. In Marketplace I selected Yoxos as source, typed "pdt" and found plugins related to PDTs (although I'm not sure there are all parts of it)
[ "stackoverflow", "0028281178.txt" ]
Q: PHP file not working properly on web hosting site When I run my website on localhost everything works fine, but when I host with atspace.com, simple_html_dom.php doesn't work properly. I can give the code if you need it but does anyone know what the problem may be. Also atspace.com has PHP enabled so I am pretty sure it's not that. localhost http://i.stack.imgur.com/xjJvA.png atspace.com http://i.stack.imgur.com/fXkaR.png EDIT: Turns out as I was on a free hosting plan, they didn't allow outgoing http connections or something but hostinger allows it so I am just hosting with them instead now A: file_get_contents() may have been disabled in your web hosts PHP config. You need to contact your host. Can your provide a link to a page on the server that contains only the following: <?php phpinfo(); ?> This will help to confirm it's been disabled. EDIT: Just ran the following and it worked. Are you using the function like this? <?php $test = file_get_contents("http://www.blade-edge.com/images/KSA/Flights/craft.asp?r=true&db=dunai"); echo $test;
[ "ux.meta.stackexchange", "0000003192.txt" ]
Q: What is the benefit of the 2 day bounty delay? I've quite often started a question that I find very important, to where I'm sure I'd like to reward a bounty on it. I would also like users to know that I value the question highly and that I will hold answers to a higher standard, so if I start a high bounty on it users would be more inclined to spent more time answering it. However, when you start a question you have to wait two days to start the bounty. I've never really seen the benefit of delaying bounties, in fact they seem detrimental as I often see as soon as a bounty is posted more quality answers come in and previous answers are rewritten to be better. So if more bounties were offered quicker, users would answer with those "good answers" right away, and it would improve the overall community. What is the purpose of the two day wait period? A: This has come up a few times network-wide. For instance: "Question eligible for bounty in 2 days". Why? I would say that a delay is still beneficial, mostly because I really don't want people posting questions and immediately putting a bounty on it of the 'PLEASE GIVE ME AN ANSWER IT IS URGENT' variety. There isn't really any good reason to give a question a bounty early. It's already there on the front page, and in the active questions list, so it doesn't need the bump in attention that a bounty gives questions. The reason for bounty-ing a question is usually because it's not received the attention the OP thinks it should have. Well, how do we know it's not received the attention it should if it gets bountied straight away? It might have been fine and got the answers anyway. Also, questions aren't always well written initially. They need to go through revisions (both by OP and the community) to get them to a position where they can be answered. We need time for this process to happen, otherwise a badly-written question will get a bounty on it when it shouldn't even be open in the first place! So yes, the reason for the delay is: It doesn't need the bump in attention because it is already on the front page The question hasn't been judged as a 'good' one until it's been live and vetted for a while It would open up the opportunity for people to use the site as a way of getting immediate answers to their urgent question. (We're not an emergency service; we're a repository for the solution to particular problems)
[ "stackoverflow", "0002709657.txt" ]
Q: How do I align ReSharpers "cleanup code" with Visual Studio's "format document" I'm a big fan of ReSharpers "cleanup code" feature. Especially the Solution wide clean up. But I use Visual Studio's Ctrl+K+D (Format document), it formats the code slightly differed than ReSharper. I'm on a quest to align ReSharper with Visual Studio (not the other way... because you can not share Visual Studio settings in the solution/source control system). So I'm after something like this: <Configuration> <CodeStyleSettings> <Sharing>SOLUTION</Sharing> <CSharp> <FormatSettings> <SPACE_AROUND_MULTIPLICATIVE_OP>True</SPACE_AROUND_MULTIPLICATIVE_OP> <SPACE_BEFORE_TYPEOF_PARENTHESES>False</SPACE_BEFORE_TYPEOF_PARENTHESES> </FormatSettings> </CSharp> </CodeStyleSettings> </Configuration> Which other settings will help ReSharper format code like Visual Studio? A: The solution we use is to remap Visual Studio's shortcut for "Format Document Ctrl+K, Ctrl+D" to ReSharper's Code Cleanup. We also use a plugin to manage sharing ReSharper settings through source control. The built in ReSharper shared settings functionality does not share all settings e.g. Inspection Severities and custom Code Cleanup profiles. I have a blog article that describes sorting the keyboard mapping out, and setting up the "manage settings" plugin:
[ "stackoverflow", "0044567013.txt" ]
Q: Property does not exist on type using typescript App.ts import { $, WebElement } from 'protractor'; export class App { public appName: WebElement; constructor() { this.appName = $('#appName'); } } app.e2e.test.ts import { browser, $ } from 'protractor'; import { App } from '../pageobjects/App' const BASE_URL = 'http://localhost:1344'; describe('App', () => { beforeEach(() => { browser.get(BASE_URL); }); it('should load the Sites UI homepage', () => { console.log(App.appName); }); }); Any idea why I cannot access the properties defined in App.ts? Error: > tsc -p tsconfig.test.json && protractor dist/protractor.config.js test/e2e/app.e2e.test.ts(15,28): error TS2339: Property 'appName' does not exist on type 'typeof App'. A: in your exception its pretty clear what's wrong: property 'appName' does not exist on type 'typeof App'. for this to work you need the declare a new instance of App like so: describe('App', () => { app: App; beforeEach(() => { browser.get(BASE_URL); app = new App(); }); it('should load the Sites UI homepage', () => { console.log(app.appName); }); });
[ "ux.stackexchange", "0000076267.txt" ]
Q: Allowing Users to Create Unions, Intersections, and Subtractions of Group Contents I have a design challenge for allowing users to create unions, intersections, and subtractions of groups. The end goal of this is to create a subset of the different group contents, which can be cumbersome for a user to decipher without a strong understanding of the system. As challenging as it is for the user to read these strings, I have found it equally (if not more so) challenging to find a pattern that makes the interaction of a union, an intersection and/or a subtraction clear to the user. Take, for example, the following. The user "allows" two groups. The end result is a boolean "or" state: "allow the contents of P1 or P2". The user "requires" a third, which is interpreted as a boolean "and": "allow the contents that are part of P1+P2 and P3". There could be any number of groups added to either "allow" or "require", and one could be left blank as well. Another option to the user is to "exclude" the contents of another group. Combing the example above with a 4th group, we end up with: "allow the contents that are part of P1+P2 and P3, minus those items in P4". The combinations could be much simpler, or could group more complicated depending on the desired results. The interactions between the groups is not building up a boolean logic set to a final "true" or "false" statement. The result of these interactions is a subset of P1, P2, P3 and P4 -- this could be nothing, something or a lot of somethings. How can represent the construction of this complex interaction to users, allowing them to understand the final subset of items which results? List Examples: Some original wireframes I put together for discussion show the items in a list form. Language next to each grouping would need to indicate how the different items interact with each other. An alternative to the above was to combine the "allow" and "require" lists, to make the the "require" a subset of the complete set. A: The examples you give are all achievable using first order set logic without the need for nested operations. They can be described using a form with 3 simple fields: Using this interface, the set operations you describe can be created as follows (click image to expand): If you also need nested operations, this is also doable...leave a comment and I can sketch it out.
[ "stackoverflow", "0042949653.txt" ]
Q: how to get data from array in json format in javascript I have faced a problem. When I use http://headers.jsontest.com/ then I get value. Here is my code <div id="ip"></div> <script type="text/javascript"> var getJSON = function(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.responseType = 'json'; xhr.onload = function() { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(status); } }; xhr.send(); }); }; getJSON('http://headers.jsontest.com/').then(function(data) { for(x in data){ ip.innerText = data.Host; } }, function(status) { alert('Something went wrong.'); }); </script> But when I use this link I don't get any value My Link. Why it's not working getJSON('http://67.225.137.209/index.php/queue_manage_api/queue/doc_id/3536/loc_id/4696/username/9791a47fef07649b1c3e70749e898153/password/2d593e25d0560b19fd84704f0bd24049/format/json').then(function(data) { for(x in data){ ip.innerText = data.id; } }, function(status) { alert('Something went wrong.'); }); If a default data format {data} then I get default value But when data format like [{data}] then I don't get any value also. And my data format like [{data}] this. So how to get my data A: I have edited my code below and It works fine. It gives me desired output. <script type="text/javascript"> $.ajax({ xhrFields: {cors: false}, url: "http://67.225.137.209/index.php/queue_manage_api/queue/doc_id/3536/loc_id/4696/username/9791a47fef07649b1c3e70749e898153/password/2d593e25d0560b19fd84704f0bd24049/format/json", type: "GET", crossDomain: true, dataType: "jsonp", success: function (response) { var resp = response; //JSON.parse(response); //alert(resp); //.status); for(x in resp){ document.getElementById("ip").innerHTML += resp[x].name+" "+resp[x].id+" "; } }, error: function (xhr, status) { alert("error"); } }); </script>
[ "stackoverflow", "0030191251.txt" ]
Q: Access SharePoint expanded properties I'm accessing a SharePoint lists has an associated stakeholder entity--I'm having difficultly accessing the stakeholder's properties. The 'primary' content's properties are located on xpath /feed/entry/content/properties/*. The stakeholder's properties are located on xpath /feed/entry/link/inline/entry/content/properties/*. Assuming that I include the stakeholder's name in the odata query: http://server/list/_vti_bin/listdata.svc/TheList?$select=Id,Title,Stakeholder/Name&$expand=Stakeholder How do I reference the stakeholder's properties when enumeration the feed's properties? Using this code, the Stakeholder.Name property is not populated: (Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredentials).entry.content.properties | Foreach { [PsCustomObject]@{ Id=$_.Id."#text"; Title=$_.Title; StakholderName=$_.Stakeholder.Name; } } Do I need to populate a second PsCustomObject for the stakeholder, then merge the 'primary' data? A: The query is malformed since $ symbol have to be escaped using single-quoted string literals, for example: $url = "http://contoso.intranet.com/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder" Then Stakeholder value could retrieved as demonstrated below: $StakeholderValue = $data.link | where { $_.title -eq "Stakeholder" } | select -Property @{name="Name";expression={$($_.inline.entry.content.properties.Name)}} Modified example $url = "http://contoso.intranet.com/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder" $data = Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredentials -ContentType "application/json;odata=verbose" $data | Foreach { [PsCustomObject]@{ Id = $_.content.properties.Id."#text"; Title = $_.content.properties.Title; Stakeholder = $_.link | where { $_.title -eq "Stakeholder" } | select -Property @{name="Name";expression={$($_.inline.entry.content.properties.Name)}} } } Alternatively i would propose to consider another approach. By default SharePoint 2010 REST service returns results in xml format. The idea is to return results in json format instead. Unfortunately neither Invoke-RestMethod nor Invoke-WebRequest could not be utilized for that purpose since both of them contain a bug in PowerShell 3.0 according to Microsoft Connect. This particular bug prevents us to consume SharePoint REST services since since Accept header could not be specified and therefore results could not be returned in json format Having said that, i would recommend to leverage WebClient Class. Below is demonstrated the same example that returns results in JSON format. Note that getting of List Item properties become a way easier compared to the original example : Function Execute-RequestJson() { Param( [Parameter(Mandatory=$True)] [string]$Url, [Parameter(Mandatory=$False)] [System.Net.ICredentials]$Credentials, [Parameter(Mandatory=$False)] [bool]$UseDefaultCredentials = $True, [Parameter(Mandatory=$False)] [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get ) $client = New-Object System.Net.WebClient if($Credentials) { $client.Credentials = $Credentials } elseif($UseDefaultCredentials){ $client.Credentials = [System.Net.CredentialCache]::DefaultCredentials } $client.Headers.Add("Content-Type", "application/json;odata=verbose") $client.Headers.Add("Accept", "application/json;odata=verbose") $data = $client.DownloadString($Url) $client.Dispose() return $data | ConvertFrom-Json } $url = "http://contoso.intranet.dev/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder" $data = Execute-RequestJson -Url $url -UseDefaultCredentials $true $data.d.results | Foreach { [PsCustomObject]@{ Id = $_.Id; Title = $_.Title; Stakeholder = $_.Stakeholder.Name } }
[ "softwareengineering.stackexchange", "0000199659.txt" ]
Q: How to store an object state/data for later processing? What do you think would be the most effective solution to maintain an object status through a life cycle? The goal to be able to be continue from any state any time. During the life cycle likely to have human interactions over a variety of interface. For example, an order which needs to be approved by a few people. Or a data supply process that can requires many people to approve or edit? In my mind some solutions: When called a function serializes the object and saves it in a database. All steps of the process would be saved to somewhere (database, csv, xml, etc.), so it can always be recreated based on this. Possibly a mixture of the two methods? Any good methods for the problem? A: It sounds for me that you are mixing two problems into one here. In order to implement an object that can “continue” from any state, you probably need to implement a state machine. As for serializing the object in case you need fault tolerance or some kind of persistence, you can use a lot of things — a database like SQL, No-SQL, Berkeley DB, or maybe a simple binary file, shared memory, or something like that. Which one to use depends on what exactly you need or what you already have. In terms of what design patterns you may use, check these out: Design Patterns for Data Persistence State Pattern
[ "stackoverflow", "0008329173.txt" ]
Q: Combining routes in Compojure I have two different web applications in Clojure developed with Compojure. Each use defroutes to create its handler. How can I combine the two different definitions of defroutes into one defroute? I want to reuse the routes of the first app into the second. A: You can use compojure.core/routes to combine routes: (def my-handler (routes some-handler some-other-handler))
[ "stackoverflow", "0052391131.txt" ]
Q: image width to fit browser width I would just like to know how to resize an image width to fit the browser width, The image is basically my header image that i want to fit the screen width. I would thereafter need to place a div on the image. I have the following at the moment but nothing seems to work. #container { position: relative; } #divWithin { position: relative; top: 20%; left: 20%; padding: 5px; background-color: white; } #imgWithin{ width: 100vw; height: 100vh; left: 0; } <div id="container"> <img id="imgWithin" src="~/images/image(2).png" style="height:325px; margin-top: 75px;" /> <div id="divWithin">Testing</div> </div> Any help or ideas would be gladly appreciated What I am trying to achieve is displayed in an image below: With 1 being : The image that I want displayed across the screen width (fit screen width) and with 2 being : The div that I would want to place upon the image A: To make a image responsive You need to use a class like this: .responsive { width: 100%; height: auto; } If you need more details about responsive images this link should help https://www.w3schools.com/howto/howto_css_image_responsive.asp
[ "stackoverflow", "0062049682.txt" ]
Q: Implementing chat in Django application I am a beginner in Django and I am trying to implement chatting in my Django app. I got 3 questions on how to approach this. 1. I see that people recommend to do this using Django Channels but what are the downsides to just using a database? 2. The tutorials on Channels seem to be on how to create a chat room. However I actually want the chat to be not in rooms but rather between users (I am using the default User model btw). Can anyone recommend a tutorial on how to do that? 3. In the official Django documentation JS is used too but I am not too familiar with it. So how much JS do I need to know to implement the chat? A: The downside of using a database is that you would need to constantly ask the database to see if there is a new message if you're concerned with real-time chat. If it's something like an email where the sent messages are checked by the other user by refreshing page or sending a request, using a database based system would work I think even better.
[ "stackoverflow", "0031827386.txt" ]
Q: How to pass the NSTimer as parameter in function in SpriteKit swift I have a simple function to move my sprite for predefine time duration. I want that the time duration which i pass in to function as time duration is passing in function parameter as NSTimer. My function is as below! func moveGooses(){ let path = UIBezierPath() path.moveToPoint(CGPoint(x:self.parentScene.frame.width*0.99 , y: self.parentScene.frame.height*0.90)) path.addCurveToPoint(CGPoint( x:self.parentScene.frame.width*0.01 , y: self.parentScene.frame.height*0.90), controlPoint1: CGPoint(x: self.parentScene.frame.width*0.01, y: self.parentScene.frame.height*0.90) , controlPoint2: CGPoint(x: self.parentScene.frame.width*0.01 , y: self.parentScene.frame.height*0.90)) let anim = SKAction.followPath(path.CGPath, asOffset: false, orientToPath: false, duration: 3.0) let seq = SKAction.sequence([anim]) let removeAction = SKAction.runBlock{ let myGameScene = self.parentScene as GameScene self.removeFromParent() } self.runAction(SKAction.sequence([seq,removeAction])) } A: Your question is vague but I believe this is what you're trying to do according to question title: func timerAsParam(timer: NSTimer) { //timer is a local nstimer }
[ "serverfault", "0000217512.txt" ]
Q: Anonymous access to SMB share hosted on Server 2008 R2 Enterprise First off, I have read through this post and a whole slew of non-SF posts which seem to address the same or a similar problem, however I was still unable to fix my problem. I've got three machines in this situation: a domain-joined server that runs Server 2008 R2 Enterprise ("share server") a domain-unjoined test server running Server 2003 R2 SP2 ("test server") a domain-joined workstation running XP Pro SP3 ("workstation") The share server is exposing a share on the network that the test server must access--it's a Source/Symbol Server share for our debugging purposes. I believe visual studio simply accesses the the share with its own credentials in this case, meaning that the share must be accessible anonymously since the test server isn't joined to the domain and there's no opportunity to supply domain authentication. I've attempted a lot of things to avoid the authentication window when accessing the share: I've enabled the Guest account on the share server and given Guest full sharing/NTFS permissions for the share. I've given ANONYMOUS LOGON full sharing/NTFS permissions for the share. I've added my share to “Network Access: Shares that can be accessed anonymously” in LSP. I've disabled “Network access: Restrict anonymous access to Named Pipes and Shares” in LSP. I've enabled “Network access: Let Everyone permissions apply to anonymous users” in LSP. Added ANONYMOUS LOGON to “Access this computer from the network” in LSP. Added the Guest account to “Access this computer from the network” in LSP. Attempted to provision the share using the Share and Storage Management MMC snap-in. Unfortunately when I attempt to access the share from the test server, I still see the prompt and I'm forced to enter "Guest" manually. I also tried this workflow using the local administrator account on a workstation, and the same thing happens both with and without XP Simple File Sharing enabled. Any idea why I'm getting these results, or what I should have done differently? A: You did everything correct with the exception of the local account accessing the share cannot be on both systems. Essentially, if the non-domain account running your application is called "administrator" then you must not have a local account on the domain server named "administrator".
[ "gamedev.stackexchange", "0000006862.txt" ]
Q: Are there benefits to stage selections where only the appearance changes (i.e. Street fighter, King of fighters etc.)? I'm not really sure if it's a good value add seeing as it would entail asset generation. The only value I see in it would be for variance but even that would wear thin really quickly. Clarification: i.e. Backgrounds that don't add game play related features, just appearance changes. A: Playing against the same background repeatedly would get boring quick. Also in single player the stage selection generally meant who you fought against. I remember always wanting to play on the air force base level in street fighter 2, and a friend always wanted to play Ryu's level, so there is some preference. So yes it is entirely cosmetic, as with so much in games the visual element provides a great deal. However fighting games don't have much in the way of assets anyway, so variation in backgrounds isn't so much to ask. A: This post about de Blob is cited in the first chapter of Game Feel: When the ball bounces or moves very fast, it slightly deforms, and while rolling it slightly sags. On screenshots this is quite a subtle effect, but when seen in action, it really looks fun. An interesting detail about this, is that it changes the feel of the gameplay entirely. Without the squash-shader, the game feels like playing with a ball made of stone. Then with no changes to the physics at all, the squash-shader makes it feel much more like a ball of paint. In other words, yes. Appearance alone can significantly affect perception of the game mechanics, which in turn affects how players play. Swink calls this "interactions emphasized by polish", and it's the earliest working definition of "game feel" provided in the book. A: Not only fighting games do this. It's a technique used in most games & genres. To name a few: Mario, Sonic, Zelda, Contra, R-type, Ghost-n-goblins, Out-run, Starcraft 2. All those have several "tilesets" and "backgrounds". The first reason, as PhilCK has mentioned, is that players get bored really when they get presented with the same art again and again. The other reason is that art (even on non-interactive elements, such as backgrounds) adds another layer of meaning to the levels it is used in. Take Super Mario's Ghost House, for example. The shadowy black tiles & closed windows in the background (and that music!) really do transmit something completely different from the ones in Yoshi's Island.
[ "askubuntu", "0000657209.txt" ]
Q: How do I compile KanColleTool? I have downloaded the KanColleTool repository from GitHub with this command: git clone --recursive https://github.com/KanColleTool/KanColleTool.git KanColleTool.git However when I run: cmake -DCMAKE_INSTALL_PREFIX=/usr ...this happens: CMake Error at viewer/src/CMakeLists.txt:28 (find_package): By not providing "FindQt5WebKitWidgets.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "Qt5WebKitWidgets", but CMake did not find one. Could not find a package configuration file provided by "Qt5WebKitWidgets" with any of the following names: Qt5WebKitWidgetsConfig.cmake qt5webkitwidgets-config.cmake Add the installation prefix of "Qt5WebKitWidgets" to CMAKE_PREFIX_PATH or set "Qt5WebKitWidgets_DIR" to a directory containing one of the above files. If "Qt5WebKitWidgets" provides a separate development package or SDK, be sure it has been installed. -- Configuring incomplete, errors occurred! See also "/home/zmaj/KanColleTool.git/CMakeFiles/CMakeOutput.log". A: Install the development libraries using sudo apt-get install libqt5webkit5-dev to get Qt5WebKitWidgetsConfig.cmake qt5webkitwidgets-config.cmake and start cmake -DCMAKE_INSTALL_PREFIX=/usr again Sample output ~/tmp/KanColleTool.git] master ± cmake -DCMAKE_INSTALL_PREFIX=/usr -- The C compiler identification is GNU 4.9.2 -- The CXX compiler identification is GNU 4.9.2 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Configuring done -- Generating done -- Build files have been written to: /home/aboettger/tmp/KanColleTool.git
[ "rus.stackexchange", "0000010271.txt" ]
Q: Где тут сказуемое? Подскажите, пожалуйста, где сказуемое в предложении "Иду курю"? A: Это предложение разговорное, разговорный язык не всегда следует строгим литературным нормам, поэтому синтаксический разбор бывает затруднителен. Скорее всего в данном варианте "иду" приобретает модальное значение, которого оно не имеет в литературном языке, либо значение обстоятельства цели (ср.: "сижу пишу" - сижу с целью писать). В этом случае "иду курю" - главный член предложения. Но повторяю, это не более чем грамматические окказионализмы разговорного языка. Нормативным вариантом было бы писать через запятую: "иду, курю" и рассматривать "иду" и "курю" как однородные главные члены (сказуемые) односоставного предложения.
[ "stackoverflow", "0001102900.txt" ]
Q: How would you encode a Map using Protocol Buffers? I'm trying to use Protocol Buffers for message serialization. My message format should contain Map< String, Object > entries ... but how do I write the .proto definition? As far as I know, Protocol Buffers does not have a build-in Map type. I could model around that using repeating fields. But the big problem I have is, that you need to define all your types. I want my message to be flexible, so I can't specify the types. Any ideas? A: I'd model a tuple with a key and a value (probably one value field per type that the value could be). Then just have a repeated list of that tuple type. You'd need to build the map itself in code. When you say you can't specify the types - what sort of types are you talking about? If you have an optional field of each type in the tuple, then that would cope for all the primitives - and you could map messages by serializing them into a byte string. It sounds like the level of "unstructure" you have may not be a good fit for PB though.
[ "stackoverflow", "0039613779.txt" ]
Q: Google charts extra rect tag inside bar I use google-chartAPI bar style but when I click on a bar, white rectangle is added into bar as you can see on picture. I couldn't find the option in API Documents to not to add. I have found a solution in css way thanks to Dr. Molle but it would be better to know to stop it in options. rect[fill-opacity]{ stroke-width:0 !important; } Googlechart bar A: the white rectangle is to show visually that the bar is selected the only option that will prevent this is --> enableInteractivity: false see following working snippet... google.charts.load('current', { callback: function () { var container = document.getElementById('chart_div'); var chart = new google.visualization.BarChart(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({type: 'string', label: 'Year'}); dataTable.addColumn({type: 'number', label: 'Category A'}); dataTable.addColumn({type: 'number', label: 'Category B'}); dataTable.addRows([ ['2014', 1000, 2000], ['2015', 2000, 4000], ['2016', 3000, 6000], ]); chart.draw(dataTable, { enableInteractivity: false, height: 600, legend: { position: 'bottom' }, pointSize: 4, tooltip: { isHtml: true } }); }, packages: ['corechart'] }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> if you would like to keep some interactivity and only lose the selection, you can cancel the selection by using the 'select' event listener when 'select' fires, pass an empty array ([]) to the chart's setSelection method see following working snippet... google.charts.load('current', { callback: function () { var container = document.getElementById('chart_div'); var chart = new google.visualization.BarChart(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({type: 'string', label: 'Year'}); dataTable.addColumn({type: 'number', label: 'Category A'}); dataTable.addColumn({type: 'number', label: 'Category B'}); dataTable.addRows([ ['2014', 1000, 2000], ['2015', 2000, 4000], ['2016', 3000, 6000], ]); // use 'select' listener to disable selection google.visualization.events.addListener(chart, 'select', function () { chart.setSelection([]); }); chart.draw(dataTable, { height: 600, legend: { position: 'bottom' }, pointSize: 4, tooltip: { isHtml: true } }); }, packages: ['corechart'] }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>