INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is a boost thread interruptible after termination? As per How can I tell reliably if a boost thread has exited its run method?, thankfully you can join a finished thread and avoid the race condition that arises if you had to conditionally join a thread only if running. But what about `thread::interrupt()`? Can it be called after the thread exited?
Yes, it is safe to call this method. From the documentation: > **If *this refers to a thread of execution** , request that the thread will be interrupted the next time it enters one of the predefined interruption points with interruption enabled, or if it is currently blocked in a call to one of the predefined interruption points with interruption enabled. When the `boost::thread` object (`*this`) is not "a thread of execution", that means is not running, **calling this method does nothing**.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "multithreading, boost, join, interrupt" }
Is the condition "if $\phi\left(X_{n}\right)$ is integrable" redundant in this proposition? I'm reading a proposition about Martingale in my lecture note: > ![enter image description here]( From the definition of martingale, I get $X_n$ is integrable. From this thread, I get the composition of a convex function with an integrable function is integrable. As such, $\phi(X_n)$ is automatically integrable. Is the condition _if $\phi\left(X_{n}\right)$ is integrable_ redundant? Thank you so much ;)
If $X$ is integrable it does not follow that $X^{2}$ is. And $x \to x^{2}$ is convex. In the link you provided they are talking about Riemann integrability and boundedness of the function plays an important role. But an intergable random variable need not be bounded.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "stochastic processes, martingales" }
replacing wheel studs on a 92 Buick century Some of my studs are crossthreaded from the last mechanic who replaced my tires and wasn't paying attention to his impact wrench. The problem is, there is no space to get the new studs in, and I had to cut the old ones out. Is there any way to replace them without removing the whole tire assembly and potentially messing up the seal and ball bearings inside? (Brakes and everything else necessary to normally replace studs has already been removed. The problem is that there isn't enough space between the opening and the more complicated parts of the tire assembly, and there isn't a groove like there usually is for replacing studs.)
I have the service manual for the 93 Buick and you have to grind the old studs out and put a small stud in for replacement or remove the hub. You can not install the regular size stud without removing the hub!
stackexchange-mechanics
{ "answer_score": 3, "question_score": 5, "tags": "buick, century, wheel lugs" }
How do you draw text in a custom view using Objective-C? I've figured out how to use the NSBezierPath class to draw shapes in the drawRect function of my custom view class, however I can't seem to figure out how to draw text. The following code is what I have so far for drawing the text (located in the drawRect function): NSText *text = [NSText new]; [text setTextColor: [NSColor yellowColor]]; [text setText: @"Hello!"]; I'm guessing that I may need to supply an NSRect or NSPoint to tell the NSText object where to draw itself, but I can't find anything in the Cocoa documentation about how to do this.
You could try something along these lines: //note we are using the convenience method, so we don't need to autorelease the object NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:26], NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName, nil]; NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Cat" attributes: attributes]; NSSize attrSize = [currentText size]; [currentText drawAtPoint:NSMakePoint(yourX, yourY)];
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 11, "tags": "objective c, cocoa" }
What about allowing file uploads up to 100MB through PHP? Is reasonable to allow file uploads up to 100MB through PHP ? I'm currently allowing 64MB, but usually my customers only need 24MB. Can we improve that ? thanks
I assume you are talking about the php.ini directive upload_max_filesize. When you adjust this value you must also adjust post_max_size and memory_limit. The general rule is that memory_limit > post_max_size > upload_max_filesize. The problems with allowing larger file uploads are more memory (RAM) usage, greater disk space usage, and longer lived open connections to handle the uploads. You should ensure that all are in amble supply before allowing such a drastic increase in file upload size. Consider your visitors & if they are likely to be malicious (on the internet assume everyone is from 4chan /b/) then you should make certain that your solution is robust. I have done 100MB file uploads for a audio/video upload site without problems, but the servers were monsters.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "php, upload" }
AjaxEditableLabel showing Date formatted by SimpleDateFormat I have and AjaxEditableLabel with shows a date from a Date object, but when its shown in its formated likes this "08-08-07 00:00". Is there something i can add to the label so it presents its object differently? item.add(new AjaxEditableLabel("stockEntry_date") { @Override public void onSubmit(AjaxRequestTarget target) { super.onEdit(target); //Save to database } });
You can use the DateFormat class from java to get a string representation of the date in the format you want. You can use the DateFormat to convert your Date to a String for the displaying purpose and then convert it back to a Date for what you want to do with it (like saving to database) It will probably look like this (please note that I did not use any IDE to write this code so it may not be correct) DateFormat df = DateFormat.getDateInstance(desiredFormat); myString = DateFormat.getDateInstance().format(myDate); item.add(new AjaxEditableLabel("stockEntry_date", myString) { @Override public void onSubmit(AjaxRequestTarget target) { super.onEdit(target); df.parse(this.getLabel().getDefaultModelObject());//not sur if this is the correct to get the label value //Save to database } });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, wicket" }
How to make autoIncrement number start with (001....009, 011......099)? i have a challenge with my time in my work, i have feature class called "Parcel" storing many data, i generated an autoIncrement number by using field calculator, in field "parcel code" `Expression: autoIncrement() Expression Type: PYTHON_9.3 Code Block: rec=0 def autoIncrement(): global rec pStart = 1 #adjust start value, if req'd pInterval = 1 #adjust interval value, if req'd if (rec == 0): rec = pStart else: rec = rec + pInterval return rec ` that i asked here before Adding automated values to attribute field? i want to start number to 001......009, and 010.........099,
You need to use `zfill` function, like in the code below, `zfill` function fill zeros in the left of the string: Expression: autoIncrement() Expression Type: PYTHON_9.3 Code Block: rec=0 def autoIncrement(): global rec pStart = 1 #adjust start value, if req'd pInterval = 1 #adjust interval value, if req'd if (rec == 0): rec = pStart else: rec = rec + pInterval return str(rec).zfill(3)
stackexchange-gis
{ "answer_score": 3, "question_score": 5, "tags": "python, arcgis desktop, arcmap, field calculator, attribute table" }
Understanding low level initialization in C I have the following piece of code. It was generated by my IDE and I am trying to understand it. #define TRGMR (*(volatile union un_trgmr *)0xF0250).trgmr Here the timer manager is at the location 0xF0250 according to the data sheet. But what I cant understand is the syntax. union un_trgmr { unsigned char trgmr; __BITS8 BIT; }; I know about pointers. But I really cant understand what exactly is being done. Could someone please help me out?By the way BITS8 is another struct with bitfields as follows: typedef struct { unsigned char no0 :1; unsigned char no1 :1; unsigned char no2 :1; unsigned char no3 :1; unsigned char no4 :1; unsigned char no5 :1; unsigned char no6 :1; unsigned char no7 :1; } __BITS8;
It's just a way of accessing a memory-mapped register at a fixed address `0xF0250`. You can access individual bits of the registers via the `BIT` field of the union, or the whole 8 bit register via the `trmgr` field. The `#define` just gives you convenient access to the latter, so that you can write, e.g. TRMGR = 0x3f; // write 0x3f to timer manager register Note the use of `volatile` \- this is a common technique with memory-mapped I/O registers to ensure that reads/writes always occur as intended and are not optimised away (as they might be with normal memory locations).
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 5, "tags": "c" }
Where do I get Java default Library on windows? I couldn't find HttpURLConnection in my java environment, and I wonder how to get that class. How to get Java Basic Library on windows? I've searched for that for 2 hours. e.g: import java.net.HttpURLConnection; import java.net.URL;
well, you can find java default library on your system location as mentioned below C:\Program Files\Java\jre1.8.0_151\lib(follow this path)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java" }
Identifying a probability mass function In my stats class, we're given the following problem: Consider the following discrete variable $X$ which can only take the values $X \in \\{1,2,3\\}$. Some observations are recorded for this variable: $\\{1,1,1,2,1,3,1,3,1,1,3,3,3,2\\}$. (I've truncated the list here, as its quite long). Anyhow, the question is how would one form the PMF, and calculate for example, the probability of observing a $1$ or a $2$ or $3$, etc... Is there a "better" way than simply drawing the histogram?
Let $X$ be a discrete random variable and let $p$ be the probability mass function (pmf) of $X$. Write $P(X=x)$ to mean the probability of observing $x$. Then $$ p(x)= P(X=x) = \begin{cases} \dfrac{\mbox{the number of occurrences of }x}{\mbox{total number of occurrences}} &\mbox{ if } x = 1,2,3, \\\ \hspace{2cm} 0 &\mbox{ otherwise}. \end{cases} $$ So for your occurrences: $1,1,1,2,1,3,1,3,1,1,3,3,3,2$, the pmf is $$ p(x) = \begin{cases} \frac{1}{2} &\mbox{ if } x=1, \\\ \frac{1}{7} &\mbox{ if } x=2, \\\ \frac{5}{14} &\mbox{ if } x=3, \\\ 0 &\mbox{ otherwise}. \\\ \end{cases} $$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability, statistics, probability distributions" }
Is css3 -ms-flex available on non MS browsers? I am doing some videos from Microsoft Virtual Academy and stumbled upon _-ms-flex_ or so called _Flexbox_ in _css3_. I would like to implement a web app on _html5_ and _css3_ and this _-ms-flex_ would help me very much. Is this available in _webkit_ or _fennec_ based browsers on mobile devices? If this can be used, are there any limitations of use? Also are there any equivalent for those browser if that is not supported? I found that : safari has _webkit-box_ and maybe there are others for the rest of the browsers(Opera, Chrome and Mozilla or Dolphin)
Alright, extending from comment: According to can_i_use, You can use flex box on many modern browsers with proper prefix: * WebKit browsers (Chrome, Safari, Android stocked browser, Chrome for Android, iOS Safari) with `-webkit-` prefix; * Gecko/Fennec browsers (Firefox, Firefox for Android) with `-moz-` prefix; * Trident browsers (IE 10) with `-ms-` prefix; * Presto browsers (Opera desktop) without prefix. You should be able to find some tutorial/example on MDN, or (as usual) Google.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "html, css, flexbox" }
Python user input for def function How to do a number input by user first then only display the answer? a = int(raw_input("Enter number: "),twoscomp) def tobin(x, count = 8): return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) print a
I believe this is what you're trying to do? def tobin(x, count = 8): return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) a = twoscomp(raw_input("Enter number: ")) print a Things to note: * You need to define things before you use them, and that includes functions. * Indentation is important, and you should use it.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, bit manipulation, twos complement" }
Change homepage url is there any way how to achieve this? I've tried to google it, but I have no clue how to call it. `siteurl.com` \- for whole web `siteurl.com/news` \- homepage with news When I add `siteurl.com` I have to by directly redirected to `siteurl.com/new`. It's needed because some google analytics setting or so which will be more precise. Thanks a lot for your help. EDIT: `siteurl.com/news` \- needs to be "frontpage" and set as "homepage" (theme template issue, it's really complicated to change it to a custom page. Something as "fake url" or so, is it possible to achieve this?
i think this can help you: use the below code in your theme's `functions.php` function redirect_homepage() { if( ! is_home() && ! is_front_page() ) return; wp_redirect( ' 301 ); exit; } add_action( 'template_redirect', 'redirect_homepage' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, site url" }
Loop to split a String inside Array Swift 3 How do I have the follow output ["1", "2", "3", "4", ...] or ["one", "two", "three", "four", ...] from this Array ["1 one", "2 two", "3 three", "4 four", ...].
You can simply split it with a for loop. var str = ["1 one", "2 two", "3 three", "4 four"] var first: [String] = [] var second: [String] = [] var splited: [String] = [] for value in str { splited = value.components(separatedBy: " ") first.append(splited[0]) second.append(splited[1]) } thanks to @Martin R
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "arrays, swift" }
Reading environment variables with Javascript I need to read the system time from the environment variables on the client's OS. I searched on Stackoverflow and found that this isn't possible. However, those answers were from 2010 and I want to ask if anything has changed since. Is it possible with some kind of framework? or Javascript is still sandboxed and cut off from OS?
`szpic`, if Javascript were not sandboxed from the OS, any half-witted criminal could get onto your computer and take control. Allowing environmental variables is way too low level to ever be allowed. Take a look at all of your environmental variables and ask yourself if everyone on the planet should have access to all that data about your computer. * * * If you want to do this with Javascript, you'll have to use a special web browser, such as node-webkit. It isn't going to run on any normal web browser, though, so don't expect more than 0.0001% of the population to expect to run your page. * * * I don't know your intended use, but one trick, to throw in an environmental variable, is to make a shortcut to your web application, and include it in there as a URL parameter (at least on Winblows).
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 33, "tags": "javascript, environment variables" }
Issue with returning value in recursive function PHP Have some issue with returning a value in recursive function. But I can echo it. What could be wrong with this? function calculate($i,$count=1) { $str_i = (string)$i; $rslt = 1; for ($k=0; $k<strlen($str_i); $k++) { $rslt = $str_i[$k]*$rslt; } if ( strlen((string)$rslt) > 1 ) { $this->calculate($rslt,++$count); } elseif ( strlen((string)$rslt) == 1 ) { return $count; } }
In the `if` in you code the value returned in the recursive call is not used. You don't set it to a value or `return` it. Thus every call except the base case doesn't return a value. Try this: function calculate($i,$count=1) { $str_i = (string)$i; $rslt = 1; for ($k=0; $k<strlen($str_i); $k++) { $rslt = $str_i[$k]*$rslt; } if ( strlen((string)$rslt) > 1 ) { return $this->calculate($rslt,$count+1); // I changed this line } elseif ( strlen((string)$rslt) == 1 ) { return $count; } } Now we return the value returned by the recursive call. Note I changed `++$count` to `$count+1` since it's bad style to mutate when using recursion.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, recursion, return" }
How to login into a network switch using ethernet cable I have a network switch which is connected to my Ubuntu Desktop through Ethernet port. I would like to login into the network switch and execute some commands. Can I use Minicom or is there any other way? I found Ethernet to serial converters online. But is it not possible to setup serial communication using a plain ethernet cable?
Looking at some of the specifications of the Summit X440 series switches I can see both console and net management ports: Summit X440-8t * 8 x 10/100/1000BASE-T (RJ45) ports * 4 x 100/1000BASE-X (SFP) unpopulated ports * 2 x SummitStack * 1 x Serial (console port) * 1 x 10/100BASE-T out-of-band management port The last port listed is the net management port, but even in the manual I cannot see a default IP address listed. So, from my experience, to configure this switch to allow connection to the net management port for straight Ethernet you would need to connect a console connection (Serial to Ethernet) cable. Hope this helps!
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "networking, ethernet, console, serial port" }
Color a specific part of a string I am trying to color a specific part of a string, this is what I have so far: function SpecialColor(num) { const color = document.getElementById(`alignColor${num}`).value; let realnum = num - 1; const input = document.getElementById("rolealign"); const splited = input.innerHTML.split(" "); let result = input.innerHTML; let winner = splited[realnum]; result.replace(winner, `<span style="color:${color};"> ${winner} <span>`); console.log(result); input.innerHTML = result; } Let's say the string is `Miki Mouse`. Nothing happens. result - Stays as `Miki Mouse` winner - `Miki` splited - `["Miki", "Mouse"]` color - A value taken of out a color input. Can someone please explain to me why my code doesn't work, and point me out to some other soultions? Thanks.
The problem is that the line result.replace(winner, `<span style="color:${color};"> ${winner} <span>`); does nothing - it creates a new string with the HTML markup, and then that new string is not assigned to anything, so it's never used again, and soon gets garbage collected. Primitives, including strings, are immutable, so you can't `.replace` in-place - you have to explicitly assign to a new variable: function SpecialColor(num) { const color = document.getElementById(`alignColor${num}`).value; const realnum = num - 1; const input = document.getElementById("rolealign"); const splited = input.innerHTML.split(" "); const result = input.innerHTML; const winner = splited[realnum]; const htmlResult = result.replace(winner, `<span style="color:${color};"> ${winner} <span>`); console.log(htmlResult); input.innerHTML = htmlResult; }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "javascript, html" }
Boolean constant for assert in if..else block I have the following condition statement in Groovy: if ( condition_1 ) { //some actions } else if ( condition_2 ) { //some another actions } else { assert false, 'Assertion description' } Code Narc gives me a warning about using boolean `false` constant in the assertion. I'm not sure if it is real issue, so please share your thoughts about it. I thought about using exceptions in this code instead of `assert false` but it looks too heavy (exception handling is too heavy I think) for my particular case.
Throwing an assert error is probably heavier than throwing an Exception (as Groovy will parse the assert inputs to give you a pretty output string) And unless you are going to be running this hundreds of times per second, I wouldn't worry about it either way... A way of using assert that gets round the warning (and provides a nice error message) might be to do: assert condition_1 || condition_2, 'Expected at least condition_1 or condition_2 to be true'
stackexchange-codereview
{ "answer_score": 1, "question_score": 1, "tags": "groovy, constants" }
Why cout<<main; prints 1? Why does `cout<<main;` printing `1` on my computer? I thought it would print the address of main. But when I use `printf("%x",main);` I get different output. Edit: I tried `std::cout` for other functions. I'm getting `1` for every case.
It is nothing but `undefined behavior`. It is an example of a code whose behavior is unpredictable.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c++" }
PrimeFaces calendar has old value in onblur event I'm trying to copy calendar's value into inputText field (don't ask me why) in the following way: <p:calendar id="cal" widgetVar="calWidget" onblur="PF('inputWidget').val(PF('calWidget').val());"/> <p:inputText id="text" widgetVar="inputWidget" /> I've overridden PF functions, that's all working fine, the problem is that inputText gets previous selected date i.e. inputText is always one step behind with values. Is this expected behaviour and does anyone have any suggestions? Thanks. P.S. I tried simpler solution also, same thing happens: onblur="PF('inputWidget').val(this.value);"
Use `dateSelect` event: <html xmlns=" xmlns:h=" xmlns:ui=" xmlns:p=" <h:head /> <h:body> <h:form> <p:calendar value="#{myDate}"> <p:ajax event="dateSelect" update="dateOutput" /> </p:calendar> <p:inputText id="dateOutput" value="#{myDate}" /> </h:form> </h:body> </html>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, jsf, primefaces, calendar" }
Why do some of the scenes in the 5th Episode of Attack on Titan differ when it was aired in Fukuoka? The airing of the 5th episode of Attack on Titan in Fukuoka (see top in the Youtube video below) had some noticeable differences from the original airing (see bottom). Why were these changes made? Was it due to censorship or production issues? <
In the video you linked, the uploader also linked to a news post on the Attack on Titan anime's official website. This news post explains the situation. I've translated the most relevant part: > > > Although we tried our hardest to deliver the same product to each broadcasting office on the day of the airing, due to certain circumstances involving the episode as well as the broadcast office's deadline, the broadcast ended up like this. Source: Attack on Titan news post Seems like the staff were running a little too close to their deadlines and ended up not having the finished product for all stations. I think it would be safe to assume that stations that aired the unfinished version had stricter deadlines.
stackexchange-anime
{ "answer_score": 15, "question_score": 15, "tags": "anime production, attack on titan" }
ASP.NET Cache unique Is HttpRuntime Cache unique for each user in ASP.NET as well as the Sessions?
No, the HttpRuntime Cache is stored on the server side, and is valid application-wide.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "asp.net" }
Exim4 - mulitple local parts redirect to public folders - how to There has been a request to have public mailboxes such as jobs@ and sales@ for example. We have a working proof of concept as below: #Public mailbox router public_mailbox: local_part_suffix = +* local_part_suffix_optional driver = accept transport = public_delivery condition = ${if eq {${local_part}} {jobs}} #Public mailbox transport public_delivery: driver = appendfile maildir_format = true create_directory = true mode_fail_narrower = false directory = /var/mail/public/.${local_part}/ user = mail group = mail delivery_date_add = true envelope_to_add = true This works as expected for a single address. I am trying to have it lookup a list of addresses or local parts in a file as there will be multiple public folders one for each address. Any help would be much appreciated. Many thanks Daniel
In order to store the local parts in a file, create a file (e.g. `/etc/exim4/public-addresses`) with content: jobs: sales: ... and replace the `condition = ${if eq{$local_part}{jobs}}` with: local_parts = lsearch;/etc/exim4/public-addresses Remark that, if the addresses are not too many, you can use a `:` separated list: local_parts = jobs : sales : public1 : public2 : ...
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "exim" }
Remove all html in python? Is there a way to remove/escape html tags using lxml.html and not beautifulsoup which has some xss issues? I tried using cleaner, but i want to remove all html.
Try the `.text_content()` method on an element, probably best after using `lxml.html.clean` to get rid of unwanted content (script tags etc...). For example: from lxml import html from lxml.html.clean import clean_html tree = html.parse(' tree = clean_html(tree) text = tree.getroot().text_content()
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 1, "tags": "python, tags, xss, lxml" }
Number of permutations of a string > Calculate the number of permutations that is created by picking 4 letters from the string 'HARD CORD' (2 duplicates) I know that if the string had 8 distinct letters, I can use $_8$P$_4$ to get the required answer. But how do things change when there are duplicates in the given string like the one given above?
I think the easiest way to do this is to count the words with all letters different, then the other cases. The number of words with all letters different is ${}^6\mathrm P_4=360$, since there are $6$ different letters to choose from. The number of words with two Rs and other letters all different is ${}^4\mathrm C_2\times {}^5\mathrm P_2=120$, since there are ${}^4\mathrm C_2$ ways to choose the positions of the Rs and then ${}^5\mathrm P_2$ ways to pick two different letters from the remaining five, in order. Similarly there are $120$ words with two Ds and all other letters different. Finally, the number of words with two Rs and two Ds is ${}^4\mathrm C_2=6$: once we choose two places for the Rs, we know where the Ds have to go. This gives a total of $606$ words.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "combinatorics, permutations" }
Geting entities by id/key without specifying the ancestor key I use go with app engine and datastore. I have Restaurants and Owners entities. _Owner_ is parent to _Restaurant_. I show list of restaurants on main web page. When visitor clicks on a restaurant, the profile page(www.../restaurants/:id) will open. I don't have ancestor key at that point. How should I retrieve the restaurant? I could use /restaurants/:key but datastore.key is quite long string. What is the natural way of doing this? should I use unique restaurant names and query/filter by that?
You can keep your current data model (restaurants child entities of owners). All you need is to add "Owner" variable to a restaurant. When you retrieve restaurant entity, you can extract owner ID from its key - every key already includes a parent key, if any. In Java it looks like this: restaurant.setOwner(entity.getParent().getId()); When you need to get/save the restaurant entity, you can create its full key using its own identifier and a parent key, created with owner ID.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "google app engine, google cloud datastore" }
Manipulate url to return length of string/number after special characters Given a URL, I want to be able to get the number of characters (s if non digit character and d for digit character) after each special character. For example, for a URL like this: url=" I want the output to be: `'4s.4d.6s.1d.4s.2d.com/6s/6d/6s-5s-6d.'` The code I have below only generates the desired result before the domain (before '.com'). I am having issues generating the rest. How can I manipulate it to get the desired output (`'4s.4d.6s.1d.4s.2d.com/6s/6d/6s-5s-6d.'`)?
You will need to loop on every character, as in import string def mysplit(path): s=d=0 out='' for c in path: if c in string.punctuation: if s: out += f'{s}s' s=0 if d: out += f'{d}d' d=0 out += c elif c in string.digits: d+=1 else: s+=1 if s: out += f'{s}s' if d: out += f'{d}d' return out >>> mysplit('/photos/414612/pexels-photo-414612.jpeg') '/6s/6d/6s-5s-6d.4s' Apart from handling the top level domain name, the above function may be used for the first section of the url as well >>> mysplit(' '5s://4s4d.6s1d.4s2d.3s'
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x, string, urlparse" }
Why $\mathbb{Z}_p$ can't have proper subfields? From the notes I'm studying from I read that " $\mathbb{Z}_p=\mathbb{F}_p$ has no proper subfield." The rationale is: "assuming $\mathbb{K}$ is a subfield of a finite field $\mathbb{Z}_p= \mathbb{F}_p$, $p$ prime, then $\mathbb{K}$ must contain 0, and 1, and so all other elements of $\mathbb{F}_p$ by the closure of $\mathbb{K}$ under addition. Therefore, it follows that $\mathbb{Z}_p=\mathbb{F}_p$ contains no proper subfield" But thinking about $\mathbb{Z}_5 = \\{0,1,2,3,4\\}$ and $\mathbb{Z}_3 = \\{0,1,2\\}$ Isn't $\mathbb{Z}_3$ a proper subfield of $\mathbb{Z}_5$ since it contains 0, 1 and is closed under addition and multiplication?
It’s a proper sub **set** , but it’s not a sub **field** at all: for example, $2^2=1$ in $\Bbb F_3$, and $2^2=4\ne 1$ in $\Bbb F_5$, so they don’t have the same operations. Similarly, $1+2=0$ in $\Bbb F_3$, but $1+2=3\ne 0$ in $\Bbb F_5$.
stackexchange-math
{ "answer_score": 2, "question_score": -1, "tags": "field theory, finite fields" }
best engine for high-performance counts table I have a `counts` table which contains columns similar to (around 14 count columns): user_id friends_count photo_count video_count blogs_count This table gets updated whenever the user adds a photo or a friend. I am going with InnoDB Engine since it is better to have row locking, but in the meantime also there are good number of reads on this table. For every user when they see profile of other user or even the users side menu contains all these counts. Which engine is best suited for **most writes and most reads** like this?
I looked at the different articles and especially these three links < Should I use MyISAM or InnoDB Tables for my MySQL Database? < and came to conclusion it is better to go ahead with InnoDB . Any comments on this also appreciated Thanks and Regards Kiran
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, database optimization, database engine" }
Transparency iOS I have an image that I took with my iOS device that contains a few lines of words and little bit of background colour (red). I want the image to only display the words to the user (they will be doing something similar). I cannot use an UIImageView in any way so simply taking the image and putting it on the background will not work. So I was wondering if someone could tell me which of the following methods would give me the best results, if they are possible and example would be nice. I have posted code below of what I have tried to do with little luck (option 2). 1. Make the background white so only the words appear 2. Remove the color red from the image Thanks in advance UIImage *image = [UIImage imageNamed:@"pic1.jpg"]; const float colorMasking[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; image = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(image.CGImage, colorMasking)];
UIImage *image = [UIImage imageNamed:@"image1.jpg"]; UIImage *inputImage = [UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)]; const float colorMasking[6] = {225.0, 255.0, 225.0, 255.0, 225.0, 255.0}; CGImageRef imageRef = CGImageCreateWithMaskingColors(inputImage.CGImage, colorMasking); UIImage *img2 = [UIImage imageWithCGImage:imageRef]; I have removed the light gray color from the background of my image.The range of color is given between 225 and 255 for RGB. Now it appears transparent.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "objective c, ios, xcode" }
How to hide the separate error log window in DBeaver? A few weeks ago I detached the error log within the editor as a separate window; I was just seeing what was going to happen. Now I can't put it back and I get two separate error log windows. One that is the original detached window and another that's still within the editor. I can't find any option to reattach it to the single Dbeaver window/editor in attempt to revert it to what it was before. The yellow bar in the picture is the window I'm referring to. It's just a little annoying for a new window to be produced every time I get an error. I've tried to look for toggles in the preferences menu but haven't seen anything that stands out to be the problem. Nor can I just drag and drop back it into the editor. ![error windows](
Looks like after an update you can't merge it to any of the bottom windows , but can keep it as a tabbed window like this. ![See Image](
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql, dbeaver" }
Any suggestions for a nice ASP.NET Ajax tooltip? I am looking for a nice tooltip control (with delay) in ASP.NET AJAX. I know there are many nice Javascript libraries out there, but since I am already using ASP.NET AJAX, I may just as well use that.
An "oldie-but-goodie" that I have used many times for tooltips would be overlib It's quite nice, VERY flexible and can be used independent of any particular AJAX platform.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "asp.net, asp.net ajax" }
How to install .jar files into Eclipse? I have written a Eclipse plugin project and successful export the .jar files. But after i copyed .jar files into the Plugins folder (tried also the dropins folder)and restarted the Eclipse, i still can't find the plugin in the "Eclipse Installation Details". After i install a plugin from Eclipse Marketplace(Any One), i can find my plugin in the "Eclipse Installation Details".Does anyone know why?
When you export your plug-in - presumedly via the Plug-in Export Wizard - have a look at the export option (first page) "Install into host repository". Using this you can update the p2 director directly from the wizard.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "eclipse, eclipse plugin" }
jQuery change image after hovering a dynamic link So I generate a list of names that got an image linked in the database. I will put the names in an HTML list. Now I got 1 div that should contain the image linked to the name, so as soon as I hover an other link; the image should change. These links are generated by PHP and can be either 1 or 100 links. I got the following HTML code: <ul> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> </ul> <div id="divid_1"></div> As soon I hover over link 1; I want the corresponding image to be shown, same for link 2 and so on. Thanks.
You should try : $("ul li").mouseover(function() { $("#divid_1").find("img").attr("src",$(this).find("a").attr("href")); }); You must add an `<img>` in your `div#divid_1` for this to work. See jsFiddle example here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, jquery, mouseover" }
How can I find out the number of seconds since 1970 using DateTime in C# I am currently using this code: var stringSecsNow = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString(); But is there some other way. I seem to recall in another language that there was an easier way to do this?
Almost same but looks easier. DateTime PreviousDateTime = new DateTime(1970, 1, 1); var stringSecsNow = (DateTime.UtcNow - PreviousDateTime).TotalSeconds.ToString();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#" }
automatically create metadata properties in the search application I want to create a number of metadata properties in the search application in sharepoint 2010. I don't want to do this myself. I know it is possible to create a powershell script to create the metadata properties. Is this the right way to create the metadata properties or is there a better way to create the metadata properties?
I believe that a Powershell script is the simplest way, yes. That's what we do.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 2, "tags": "search, powershell, search express" }
Add a timeout to "setInterval()"? I have a setInterval function like below on a Divbox so if **I leave a divbox** , this **setInterval is triggered** : setInterval("playthis()", 1000); **What I want it to do:** If I leave the divbox and lets say within the next 2 second rehover it, the setInterval should **not** triggered. Is this possible?
You can use cousins `setTimeout` and `clearTimeout` to set a function callback that invokes your `setInterval` only after 2 uninterrupted seconds: var handle = null; function yourDivboxLeaveHandler() { handle = setTimeout(startPlay, 2000); } function yourDivboxHoverHandler() { if (handle !== null) { clearTimeout(handle); handle = null; } } function startPlay() { setInterval(playthis, 1000); // use function references please, not eval handle = null; } You will want much better variable/function names than this though.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 8, "tags": "javascript" }
Contains search on the word "after" fails Basically running the following: SELECT * FROM document WHERE contains(cachedText, 'after') returns 0 records, same with any search term with the word `after` in it. Searching for: SELECT * FROM document WHERE cachedText like '%after%' returns about 200k records in my dataset. Just wondering if there is any reason for this?
The first query matches the word "after", i.e. a _distinct word_ within other text. (If "after" is in the stopwords list then it is ignored entirely.) You can read about the details at Full-Text Search. The second query matches "afternoon", "crafters", "dafter", ..., i.e. any string containing "after" regardless of word breaks. Examine the matches that the second query returns and you'll likely find "after" embedded in longer words.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, tsql" }
reshaping a data frame in pandas Is there a simple way in pandas to reshape the following data frame: df = pd.DataFrame({'n':[1,1,2,2,1,1,2,2], 'l':['a','b','a','b','a','b','a','b'], 'v':[12,43,55,19,23,52,61,39], 'g':[0,0,0,0,1,1,1,1] }) to this format?: g a1 b1 a2 b2 0 12 43 55 19 1 23 52 61 39
In [75]: df['ln'] = df['l'] + df['n'].astype(str) In [76]: df.set_index(['g', 'ln'])['v'].unstack('ln') Out[76]: ln a1 a2 b1 b2 g 0 12 55 43 19 1 23 61 52 39 [2 rows x 4 columns] If you need that ordering then: In [77]: df.set_index(['g', 'ln'])['v'].unstack('ln')[['a1', 'b1', 'a2', 'b2']] Out[77]: ln a1 b1 a2 b2 g 0 12 43 55 19 1 23 52 61 39 [2 rows x 4 columns]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas, dataframe, reshape" }
information criteria for confusion matrices One can measure goodness of fit of a statistical model using Akaike Information Criterion (AIC), which accounts for goodness of fit and for the number of parameters that were used for model creation. AIC involves calculation of maximized value of likelihood function for that model ( _L_ ). How can one compute _L_ , given prediction results of a classification model, represented as a confusion matrix?
Information-Based Evaluation Criterion for Classifier's Performance by Kononenko and Bratko is exactly what I was looking for: > Classification accuracy is usually used as a measure of classification performance. This measure is, however, known to have several defects. A fair evaluation criterion should exclude the influence of the class probabilities which may enable a completely uninformed classifier to trivially achieve high classification accuracy. In this paper a method for evaluating the information score of a classifier''s answers is proposed. It excludes the influence of prior probabilities, deals with various types of imperfect or probabilistic answers and can be used also for comparing the performance in different domains.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "statistics, modeling, entropy" }
What is /usr/local/Cellar/coreutils/8.31/bin/g[ What is `/usr/local/Cellar/coreutils/8.31/bin/g[`? `g[` is an odd file name. It obviously appears to have been installed by the homebrew coreutils formula, but I can't find any documentation about it.
There's a remark when installing `coreutils`: Commands also provided by macOS have been installed with the prefix "g". Presumably what was once `[` is now `g[`. `[` is an odd name for a file, but it's an important shell feature. See `man \[` for details.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "homebrew, gnu coreutils" }
How to portion results in AngularJS New to AngularJS, and was wondering how I could limit results on a line, and keep spilling over onto the next row. My page has cards loading in, based on how many people are pulled from a database. For example: if someone searches "thomas" itll find x different thomas' and list x cards using Ng-repeat that have a name on them. But I want to limit 3 cards on a line, then move to the next row and repeat. I cant use "LimitTo" because it just cuts off the other results. Thanks.
Definitely smarter to use CSS as SSH suggested. Simply used this and it fixed it. ul{ width:100%; } li{ float:left; width:45%; margin-left: 5%; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, angularjs" }
How to install windows service using Inno Setup? In VS2010 I have solution with windows service project and some other 'helper' projects. So in my debug folder there is an windows service application and couple of dlls. I can install windows service by running application with parameter, so in Inno Setup I just do: Filename: {app}\MyService.exe; Parameters: "--install"; WorkingDir: {app}; Flags: skipifdoesntexist; StatusMsg: "MyService is being installed. Please wait..." My question in: It is necessary to pack all files from Release folder to my Setup file? I mean, in my Release folder are: DLLs from my other projects in app solution, Program Debug Database (.pdb) files, and XML Configuration file.. What files should be packed in my Setup.exe file?
You just need the `*.exe` files. `*.pbd` and other are not needed there. Only DLLs if nedded by your main project (service).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, windows services, inno setup" }
Get Random Days Based on the Month in R I want to be able to generate random YYYMMDD variables I tried: Day=ifelse(substr(o1$Month,6,7) %in% c(1,3,5,7,8,10,12),sample(c(paste0('0',1:9),10:31),1), ifelse(substr(o1$Month,6,7) == 2,sample(c(paste0('0',1:9),10:28),1),sample(c(paste0('0',1:9),10:30),1))) to generate a random day based on the month. Note that `o1$Month` is of YYYY-MM format. But the results are all identical days. > table(o1$Day) 25 55 Can anyone offer some advice so I can get other days as well. Thanks
To create a random date you could use the following: gsub("-", "", sample(seq(as.Date("1900-01-01"), as.Date("2000-12-31"), by = "day"), 10)) #[1] "19700214" "19910824" "19640205" "19531101" "19020116" "19360823" "19791019" "19520713" "19890408" "19220327" Here, I create a sequence of days between two dates (1900/01/01 and 2000/12/31) and then randomly sample from them 10 times. If you want unique dates, use this code. Otherwise, set `replace = TRUE` in the `sample` function. I then use `gsub` to replace the dashes with empty strings. For example, `1947-11-01` becomes `19471101`. You can change the dates to sample from if you want a specific range.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, date, sample" }
Print MySQL column names for empty result set I am running some SQL queries from command line as follows: cat my_query.sql | mysql --defaults-file=my_conf.cnf I need to print column names whether the query returns any data or not. Currently when there is no data to return, i.e when query returns an empty result set this command does not print anything. For example my query is: -- id=-1 doesn't exist SELECT col1, col2 FROM table WHERE id=-1 I need this query to return col1 col2 Instead it returns nothing. Is it possible to do that using purely mysql and standard unix commands? Thanks.
Adding a UNION ALL to a SELECT with "dummy"/blank data might work: SELECT col1, col2 FROM table WHERE id=-1 UNION ALL SELECT '', '' -- OR 0, 0 whatever is appropriate ; I don't run queries from the command line, so this is assuming it normally would give you the column names if you had at least one row in the results.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql" }
Android AVD not showing anything. only "ANDROID" in the middle of the screen I am an Android Newbie! please help. I have been following googles introduction tutorial and managed to install everything with no problems. but whenever i try to run the HelloAndroid example the avd launches but doesnt show anything. cone somebody help please?
After you create an AVD it really does take a long time to initialize. On my less than year old Core2Duo 2.8 GHz running Win7x64 and 4Gb of RAM, initializing a 2.2 version took at least 5 to 10 minutes (if not longer). Once it starts initializing you can watch the logcat in the DDMS panel of eclipse and watch it unpack and install all of the apps in the emulator.
stackexchange-stackoverflow
{ "answer_score": 48, "question_score": 37, "tags": "android, eclipse, android virtual device" }
Why is it that $ \left(\sum_{j=1}^{N}\pi_jx_j\right)^2 = \sum_{j=1}^{N}\sum_{k=1}^{N}\pi_j \pi_kx_jx_k $? In my Statistical Inference class, I came across the following: $$ \mathbb{E}(Y^2) =\Bigl(\sum_{j=1}^{N}\pi_jx_j\Bigr)^2 = \sum_{j=1}^{N}\sum_{k=1}^{N}\pi_j \pi_kx_jx_k $$ What I don't understand here is why a summation, when squared, becomes a double summation. In my head, the LHS would just be $$ \Bigl(\sum_{j=1}^{N}\pi_jx_j\Bigr)^2 = \Bigl(\sum_{j=1}^{N}\pi_jx_j\Bigr)\Bigl(\sum_{j=1}^{N}\pi_jx_j\Bigr)$$
You are just distributing one by one so we have $$ \sum_j \pi _j x_j \sum_j \pi_j x_j = \pi_1x_1(\sum_j\pi_jx_j)+...+\pi_Nx_N(\sum_j\pi_jx_j)$$ Now this is much easier to work with, so lets bring those factors inside the $N$ summations. that is why we get $ \sum_k\sum_j \pi_j\pi_kx_jx_k$.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "algebra precalculus, statistics" }
Facebook recommendation box in iframe: url is not valid I am creating Facebook recommendation box here. The domain is " For example(" I can see the proper box to my right, but when I click "Get Code" and choose "IFRAME" I get this message: "A valid url is required when using the iframe implementation." You can also try it. What is wrong here?
It still didn't work so I built the iframe tag myself: <iframe src=" site=mydomain.co.il&width=300&height=300&header= false&colorscheme=light&locale=he_IL" scrolling="no" frameborder="0" allowTransparency="true"> </iframe>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "facebook" }
How to get position of every character How to get position (left, top) of every characters in some node? I know just one method: wrap every character in it's own tag and then we can get it's coordinate. But it's bit slowly
I've found answer on my question — Range interface can present all information that I need (More info — <
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "javascript, dom" }
Create Local Javascript Array From jQuery.get() AJAX Call I'm using the jQuery Autocomplete plugin and would like to store all the autocomplete values locally in an array. I'm able to retrieve a comma separated list from a url using jQuery.load() or jQuery.get(). However, I can't load the data into an array successfully. Any suggestions on how to get this working? I realize there's probably a much better way. Any help would be appreciated. Thanks!
Are you sure that it isn't working properly, but that you're not trying to access that variable outside of the async ajax call? The only way to have immediate access outside of that ajax call is to run it async=false, or to use a timer to wait and check for that value. If this is the case, look to the docs on the ajax abstractions: < Specifically: var html = $.ajax({ url: "some.php", async: false }).responseText;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery plugins, jquery" }
how to create a new AVD in eclipse? I have a problem in creating a new android virtual device in eclipse I have a window with this information needed : AVD name , Device , Target , CPU/ABI , Keyboard , Skin , Front Camera , Back Camera , Memory Options , Internal Storge , SD Card , Emulation Options , and an OK button . Instead of the window which I see in the tutorials that needs just this info : Name , Target , CPU/ABI , SD Card , Snapshot , Skin , Hardware , and Create AVD button . And in my window I don't know what is the device option should I select + what ever I selected the OK button never be available ! what should I do ? please help me , thank you .
May be the following will help : !Window -> Android Virtual Device Manager !Device Definitions !Create new device Then start the emulator
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 16, "tags": "android, eclipse, sdk, android virtual device" }
Identifying studies on how English language reflects sexism Right now I'm looking for papers on how sexism is reflected in the English language. A lot of the literature is from the 1970's and is seen as a little out there and not empirical. Besides reading the abstract carefully, reading the actual study, and common sense, are there any general "warning signs" on what I should avoid in the literature? Also, are there any specific studies that are well known and should be avoided or are must reads? I'm focusing on semantic change and words used in relation to women.
Sexism is in general not reflected in language. Rather, changing standards about what is considered sexist are reflected in the metalinguistic discourse of commentators on gender issues. I do not know of any literature on this topic (metalinguistic discourse about sexism), but it seems like a very interesting one and I would be happy to learn that I was mistaken about its non-existence. For scholarship about how gender and sexuality are reflected in sociolinguistic variation, and about the study of gender and language in general, you might start with works by Penelope Eckert. I suppose it is possible that some sociolinguistic variables identifiable with subcommunities of people who are openly sexist could in principle be identified. A simple approach might be to use the Oxford English Dictionary, which has detailed word histories.
stackexchange-linguistics
{ "answer_score": 6, "question_score": 4, "tags": "semantics, lexical semantics, research" }
How to integrate and find the inverse of $f(x)=\frac{1}{4\sqrt{|1-x|}}, x\in[0,2]$? I need to integrate, then find the inverse. The function I am working on, $$f(x)=\frac{1}{4\sqrt{|1-x|}}, x\in[0,2]$$ I tried to solve it on wolfram. It looks pretty complicated, am I doing this right? Could I use the [0,2] bounds to make the problem easier? Thanks for any kind of help.
You could break it up into cases. Then you get $$f(x)=\begin{cases}\frac{1}{4\sqrt{1-x}}&x<1\\\\\frac{1}{4\sqrt{x-1}}&x>1\end{cases}$$ Now you can just integrate as normal and get $$F(x)=\int f(x)dx=\begin{cases}\frac{-1}{2}\sqrt{1-x}+c&x<1\\\\\frac{1}{2}\sqrt{x-1}+c&x>1\end{cases}$$ So to integrate from 0 to 2 you get $$\int_0^2f(x)dx=\int_0^1\frac{1}{4\sqrt{1-x}}dx+\int_1^2\frac{1}{4\sqrt{x-1}}dx$$ $$=\left[\frac{-1}{2}\sqrt{1-x}\right]_0^1+\left[\frac{1}{2}\sqrt{x-1}\right]_1^2=0+\frac{1}{2}+\frac{1}{2}+0=1$$ As for the inverse $$F^{-1}(x)=\begin{cases}1-4x^2&x<1\\\1+4x^2&x>1\end{cases}$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus" }
What is the size in Byte of this kind of float? I want to know what is the size in memory in bytes of this float number for example `-0,005606111`.
According to the documentation a `float` takes up 32 bits (4 bytes), a `double`.aspx) takes 64 bits (8 byteS) and a `decimal`.aspx) takes 128 bytes (16 bytes). Note, however that a `float` offers a precision of 7 digits, so it **won't** be appropriate for storing the value `-0.005606111`. Instead, you should use a `double` (15-16 digits of precision) or a `decimal` (28-29 digits).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, memory, byte" }
Meteor takes multiple times to make a successful database read Say I have a helper that needs to return an article's title. <template name="articleList"> <span>{{title}}</span> </template> Template.articleList.title = function () { return Articles.findOne({author: "Billy Bob"}).title } I often get a 'Cannot read property title of undefined' error. So when I try to debug it like this Template.articleList.title = function () { console.log(Articles.findOne({author: "Billy Bob"})) } The log will say undefined undefined Object[0] So it only works on the third time. I think it's probably bad code somewhere in my router or somewhere else, but I don't know what it is. Any suggestions?
You need to check that the document is already loaded by your subscription. Try this: <template name="articleList"> <span>{{title}}</span> </template> Template.articleList.title = function () { var doc = Articles.findOne({author: "Billy Bob"}); return doc && doc.title; }; The reason is that if the client hasn't yet received the document over DDP, the `findOne` call will return `null`. You get an error when you try to call `null.title`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "meteor" }
Does the Units of a Ring always form an Abelian Group? I know that the units of a ring form a multiplicative group because it inherits the associativity from the ring; every element has its inverse by definition; it is closed under multiplication: indeed, if you take $x,y \in U(R)$ there exists $x',y' \in U(R)$ such that $$ (x \cdot y) \cdot (y' \cdot x') = x \cdot (y \cdot y') \cdot x' = x \cdot x = 1 \implies x \cdot y, y' \cdot x' \in U(R); $$ And it has the identity element since it itself is a unit ($1 \cdot 1 = 1$). The issue I'm having is to prove that it is abelian, and I suspect that it isn't always true. Does anyone have a counter example or a proof for this statement?
No. For example multiplication in Hamilton's quaternions $\mathbb H$ is not commutative, so its group of units (which is everything except $0$) is not Abelian. You can embed whatever group you want into the units of a ring using a construction called a group ring, and in particular you could put in any nonAbelian group that you wanted.
stackexchange-math
{ "answer_score": 6, "question_score": 2, "tags": "ring theory" }
How to get records only if difference between them is 10 sec I need to be able to find all records with sql only if time between those less than 10 seconds. Let me put a little example so you can see what I need: id method db_add_date 1 5 2013-09-11 00:42:12 2 6 2013-09-11 00:42:25 3 4 2013-09-11 12:02:33 4 7 2013-09-11 12:02:35 5 1 2013-09-11 12:10:54 6 2 2013-09-11 12:10:57 And output like this: id method db_add_date 3 4 2013-09-11 12:02:33 4 7 2013-09-11 12:02:35 5 1 2013-09-11 12:10:54 6 2 2013-09-11 12:10:57 because #3 & #4 has difference 2 seconds & #5 & #6 has difference 3 seconds I am having difficulty in putting this into a SQL query form, I would appreciate any help on this!
Join the table to itself on a +/- 10 second timestamp range, making sure not to join to itself: select distinct t1.* from mytable t1 join mytable t2 on t2.db_add_date between subdate(t1.db_add_date, interval 10 second) and adddate(t1.db_add_date, interval 10 second) and t2.id != t1.id SQLFiddle demo Points: * this finds near rows by joining to itself * if rows only come in pairs within 10 seconds (not more than two within 10 seconds) you can omit the `distinct` keyword * if an index is on `db_add_date` this will perform well and scale well due to the way the look up time interval is determibant for the joined rows
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
Uniqueness of solution > 3. Solve the differential equation $\dot x=1+x^2$, with $x(0) = x_0$. Why can you be certain that the solution is unique? Show that for all values of $x_0$ the solution goes to infinity in finite time, both forwards and backwards. > I have found the solution to be $x(t)=\tan(t+\arctan x_0)$. How would I go about proving uniqueness? Is the solution the entire graph of $\tan(t+\arctan x_0)$ or only the tan wave which is defined on the interval (when $\arctan(x_0)>0$): $$-\frac{\pi}2-\arctan x_0<t<\frac{\pi}2-\arctan x_0 $$ i.e the tan wave with domain containing $t=0$ so that the tan wave intersects the $x$ axis at $x_0$
Uniqueness follows from the general Picard-Lindelöf (or if you prefer, Cauchy-Lipschitz) existence and uniqueness theorem for differential equations. Since the solution blows up as $t + \arctan(x_0)$ approaches $\pm \pi/2$, the solution is only on the interval $-\pi/2 < t + \arctan(x_0) < \pi/2$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "ordinary differential equations" }
If $f(a+b)=f(ab)$ for all a and b and $f(\frac{-1}{2})=\frac{-1}{2}$ find $f(1)$ **problem** A function $f(x)$ is defined for all real values $x$. If $f(a+b)=f(ab)$ for all a and b, and $f(\frac{-1}{2})=\frac{-1}{2}$ , compute the value of $f(1)$. **my steps** i know that I can have $f(\frac{-1}{2}+\frac{-1}{2})=f(-1)=f(\frac{1}{4})$ from there i don't know what to do
Taking $a=0$ in the functional equation (which is always a good thing to try when solving functional equations), we get that $$f(0+b) = f(0\cdot b)$$ $$f(b) = f(0)$$ and thus $f$ is constant, and $f(1) = -\frac{1}{2}$.
stackexchange-math
{ "answer_score": 10, "question_score": 0, "tags": "algebra precalculus" }
UITableView Custom Header using a UICollectionReusableView I'm currently using a UICollectionReusableView to make a custom header for a tableview. The problem I'm facing is that this header is not scrolling with the tableview as I would like. Here's how I implemented the headerview: func numberOfSections(in tableView: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = Bundle.main.loadNibNamed("StoresListHeaderView", owner: self, options: nil)?.first as! StoresListHeaderView; return headerView; } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 170; } In the UICollectionReusableView .swift file there's the default code and in the .xib just a backgroundImage. Is there any boolean option to set this up? Otherwise what would you use?
Try changing UITableView's `style` property to `.plain` if it isn't. The `.grouped` style will keep the header on screen while scrolling.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ios, swift, uitableview" }
Do I need a CPU that supports Virtuallization to do Containerization? I've read that Containerization is cheaper than virtualization; I know that containerization uses less resources than virtualization since there's only one OS involved and no virtualized hardware. But do I need a CPU that supports virtualization to run containerization such as Docker, or since it runs an app using the OS's libraries in a container, can I just run it on a CPU without virtualization?
> But do I need a CPU that supports virtualization to run containerization such as Docker, or since it runs an app using the OS's libraries in a container, can I just run it on a CPU without virtualization? No, Docker (and other container solutions like LXC) do not require any special hardware support. They are effectively an enhanced version of `chroot` that uses kernel features (primarily namespaces) to isolate process trees from your host and from each other.
stackexchange-serverfault
{ "answer_score": 10, "question_score": 8, "tags": "central processing unit, docker, lxc, containers" }
Trying to access Python through Windows Command Prompt without adding Environment Variable I am trying to access Python through a Windows command prompt, but am at an office and cannot add an Environment Variable. So, I cant follow the advice provided here. Thus, I added a User Environment Variable through User Accounts and use Variable:python and Value: C:\Python33. When I do a Windows Run check on %python% I reach the required Python33 folder. However, when I type `python -Version` in the command prompt I get the error `'python' is not recognized as an internal or external command, operable program or batch file.` I am not sure how to proceed.
Run Python from the command prompt and include the full path to python.exe. For example to get the version: C:\Python33\python.exe --version When you run a script you specify the path to the script if you're not in the directory where the script is located. For example, if your script is in `C:\scripts` and is called `my_script.py`: C:\Python33\python.exe C:\scripts\my_script.py
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, command line" }
Demagnetization field of a prism magnet I am studying some magnetism, and i am curious about bar magnets. Lets say you have an uniform prism magnet of Iron for example. How would you calculate the demagnetization field H which the bar magnet produces? As I understand, first you need the magnetization M which is the magnetic moments per volumen. But then what ? Or would you apply and external field to the bar magnet and see how it reacts, if this is the case, how does this work ?
If you know M then H is just $\frac{M}{\chi_m}$ where $\chi_m$ is the magnetic susceptibility. This only holds for paramagnets and diamagnets, however. In the case of a ferromagnetic material like iron, you would have to refer to the hysteresis curve. If you know the net (= applied+induced) magnetic field B in the material, then you can use any of these relations $$ \begin{align*} H=& \frac{B_{net}}{\mu}\\\ H=& \frac{B_{applied}}{\mu_0}\\\ H=& \frac{B_{net}}{\mu_0}-M\\\ H=& \frac{B_{applied}+\mu_0M}{\mu}\qquad{(\because B_{induced}=\mu_0M)} \end{align*} $$where $\mu=$permeability.
stackexchange-physics
{ "answer_score": 2, "question_score": 0, "tags": "magnetic fields, magnetic moment" }
How to return array from recursive function I couldn't find solution for this and I don't have much time for this. So what I want is to make function that I give category ID and it returns all ID's of categories which are it's child categories. function getID($var) { $categories = array(); function getChildren($id) { $result = mysql_query("SELECT * FROM categories WHERE parentID = '$id'"); echo "<ul>"; while ($row = mysql_fetch_array($result)) { echo "<li><a>{$row['ID']}</a>"; $categories[] = $row['ID']; getChildren($row['ID']); echo "</li>"; } echo "</ul>"; } getChildren($var); return $categories; } I wan't to store everything in $categories array. $var is category ID which I give to function. When I call this function it prints list of exactly what I want't but array is empty.
It seems you have a scope problem. Try this: function getChildren(&$categories, $id) { $result = mysql_query("SELECT * FROM categories WHERE parentID = '$id'"); echo "<ul>"; while ($row = mysql_fetch_array($result)) { echo "<li><a>{$row['ID']}</a>"; $categories[] = $row['ID']; getChildren($categories, $row['ID']); echo "</li>"; } echo "</ul>"; } function getID($var) { $categories = array(); getChildren($categories, $var); return $categories; } Here is the PHP reference page describing how to pass by reference instead of by value. Basically it says that any function parameter which has a `&` in front of it will be passed by reference instead of by value.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 5, "tags": "php, arrays, recursion" }
The hard-to-understand chain I have a chain. I can extend this chain indefinitely. For beginners, this chain is hard to understand. They call it magical, yet it is not in reality. I used to only declare. But with this chain, I can finally command. [Maybe, this chain is made from Io.] What am I and what is this chain? Subtle Hint: > Though there is only one **kind** of the chain, it comes in various **types**. Three types are mentioned in the text. Moderate Hint: > The chain can be so many things. It can be a writer, it can be a reader, it can be a parser, it can store states, and many other things. Moderate Hint 2: > There is a sugar. The chain can be **done**. Decisive Hint: > I am in seven letters. The chain is in five letters. Decisive Hint 2: > I start with 'H'. The chain starts with 'M'. Decisive Hint 3: > I end with 'l'. The chain ends with 'd'.
You are > The Haskell programming Language) And the chain is > A monad)
stackexchange-puzzling
{ "answer_score": 2, "question_score": 3, "tags": "riddle, knowledge" }
Bathroom faucet drip I had a faucet drip in my bathroom sink. I determined it was the hot water (confirmed by the warm drip and it stopped when I shut off the hot under the sink). I assumed that the stem went (which happened before, to the cold stem) but after replacing it and tightening everything, I still have the drip. Can I assume the faucet needs to go? It's an old Price Pfister. Note: The plumbing and shutoff valves are new but the faucet assembly is old.
There should have been a 'packing' in the stem assembly. This is usually a gasket or a series of gaskets that prevent water from seeping around the stem when the stem is in the off position. If the packing was in good shape (no cracks or brittleness) and was seated properly then I would say it's time to replace the whole fixture. In my past experience if the leak doesn't come from the stem or the packing around it, then the time finding the problem and the cost to fix it usually is not worth it for a cheaper fixture.
stackexchange-diy
{ "answer_score": 6, "question_score": 2, "tags": "plumbing, bathroom, faucet, sink" }
XRegExp replace I'm trying to do some string manipulation on some words that may or may not have unicode characters in them. Here's my code: var regex = XRegExp("(\\P{L}+)", "gui"); var s = 'no sea demásiado tarde'; var ret = XRegExp.replace(s, regex, "<span>$1</span>"); console.log(ret); <script src=" But the words are not getting wrapped by the span tags as expected. How come? Thank you
Because you are wrapping non-letters with `\\P{L}+` as `\P{L}` matches any character other than a Unicode letter. Use `"\\p{L}+"` pattern and replace with `<span>$&</span>` (the `$&` backreference stands for a whole match). var regex = XRegExp("\\p{L}+", "gui"); var s = 'no sea demásiado tarde'; var ret = XRegExp.replace(s, regex, "<span>$&</span>"); console.log(ret); <script src="
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, regex, xregexp" }
C parser in Javascript I'd like to parse C header files in Javascript. Is there any such library available? Otherwise, any tips to help me get started? **Update:** My ultimate goal is to automatically build interfaces for node-ffi. The parser doesn't necessarily have to be in Javascript as long as it can spit out a format understandable by Javascript. If it's very hard to develop by myself, I'll probably have to go with an off the shelf solution...?
You should check out clang. For a simple command-line invocation, you can try this: clang -cc1 -ast-dump-xml myfile.h Or you can build your own tool using `clang` reasonably-well-documented parser library, which will build an AST for you, and let you walk it as you see fit (perhaps for output in JSON).
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 11, "tags": "javascript, c, node.js, node ffi" }
Export Lat long of Line/Polyline in QGIS with start to end I have a polyline layer in QGIS, and I am trying to get the list of lat longs of each of the vertices and their path. As you can see from the image below, I have tried the steps mentioned in this answer. I have extracted the vertices of the lines and I can calculate the lat long of each of these vertices. But the only thing missing is the **trail/path/direction of the coordinates**. I need to extract, not only the lat longs of the vertices but also the direction (coord A to coord B to C to D etc., or D-C-B-A, order so far is not important yet). ![enter image description here](
When you use "Extract Vertices" tool, it gives a clue for the directions. It adds `vertex_index` column. ![enter image description here]( Then extract the vertices to CSV and set `GEOMETRY` = `AS_XY` ![enter image description here](
stackexchange-gis
{ "answer_score": 6, "question_score": 1, "tags": "qgis, coordinates" }
MongoDB: Determine index of item in array Is there a way to determine the index of a retrieved item in an array in MongoDB? * * * I have an array of object ids inside some document. { ids: [id1, id2, id3, ...] } I search the array for `id3`, and if it's found, I also want the position of the object added to the result. In this case, it's so I can insert more objects immediately after it in the array. If I can't do this, how would I go about creating an ordered list of objects for which I can retrieve and easily modify the position of elements in the ordered list (since an insert operation on the list will result in modifying the position of all elements after the insert)? * * * answer: **_Obtaining the positional index is NOT supported in mongodb_**. I will open a new question then about redesigning my application to deal with this limitation. Thanks everyone!
The way I see it, you have two choices: * Retrieve the whole array, mutate it however you wish in your language of choice, and update the array in the db with your new array. * Come up with a data structure that supports whatever it is you are ultimately trying to do.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "arrays, mongodb, position" }
Execute a console application remotely from C# web app, perfomance-wise Here's some background. The C# web application I developed employ another console application (for image resizing and several magical stuff), which is quite heavy on memory and processor. Once the application finished, the web app need to read the STDOUT result. I'm planning of moving the console application to its own server for better scalability (or maybe to more servers, later). I need a way to remotely execute the console application, quickly and effectively. The connection between the computers is strictly private, so encryption and security is really not needed, more like telnet rather than ssh. I also need connection pooling, there's no way to reconnect every single time the application need to run. Thanks in advance.
It sounds like you better decouple your web frontend from the actual processing and just use it to put data (images) into the system and present the results after processing. I implemented a similar system for calculating commissions: A web frontend for creating jobs to process communicating with a WCF service (Singleton) via MSMQ. You'll have the freedom of moving the processing service around at any time and you could even have 2 or more machines running a processing service.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": ".net, execution" }
how can I transfer files from raspberry pi 3 to windows and android via WiFi hotspot? I want to transfer different types of files from the Raspbian OS to the windows and android through a WiFi hotspot that we created already,without a internet connection we need transfer the files?please tell me the complete steps....
If both computers are attached to the same wireless hotspot, then they should be able to contact one another directly via IP address. This is the same as on a normal internet connected LAN -- hence you can also use the same kind of software to transport the files. Using SMB/CIFS is popular with Windows users, implemented by Samba) on the linux side. To that end you will find many questions tagged samba here and an order of magnitude more on our big sibling site _Unix & Linux_. Note that Raspbian is essentially a normal GNU/Linux OS distro with some cosmetic and configuration tweaks. You are not bound to use SMB/CIFS, of course. I believe there is some Windows side software around to mount SSHFS shares, which is more popular with linux users. You can also use normal FTP, a web server, etc. etc. WRT Android there look to be both Samba and SSHFS _clients_ available.
stackexchange-raspberrypi
{ "answer_score": 2, "question_score": 0, "tags": "raspbian, python, wifi, wireless, wifi direct" }
Signed java applet I am creating a socket connection with an unsigned applet to a different host and I'm getting java.security.AccessControlException: access denied If I sign this applet with either "self-cert" or "CA cert" does the applet gain the permissions to create a socket connection to a different host (not the same host it was downloaded from) and does a security message popup if its been certified by a CA? Thanks
If you don't sign the applet, the code which is accessing local resources won't be executed in any way. If you sign the applet with a self-cert, the enduser would only get a warning message which asks for permission. You however still need to wrap the call inside an `AccessController#doPrivileged()`. public void init() { AccessController.doPrivileged(new PrivilegedAction<Object> { @Override public Object run() { // Put your original init() here. return null; } }); } If you sign the applet with a $$$-cert, the enduser won't get a warning message.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, security, applet, signed applet" }
ZendFramework: Load a part of phtml per Ajax It's possible to get a part of a phtml per Ajax? The phmtl is a form and I just need to load a part of this form dynamicly. Zend Version 1.12
Phtml files are layouts and they should not be accessible directly. The best practice is create an action in a pertinent controller and render the form layout from there. After you can use jQuery.load() like this <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, ajax, zend framework" }
PHP MySQL - How do I obtain the id of the result of the last Insert statement without a second query? How do I obtain the id of the result of the last Insert statement without a second query? I am aware I could select the last row of the database to get what I'm looking for... sometimes. The issue is if two users are inserting at the same time I'm worried that they may get the wrong results. Pseudo Example Code: User 1 - Insert Record A User 1 - Select last Record User 1 - Record A Selected Pseudo Multi-user Problem: User 1 - Insert Record A User 2 - Insert Record B User 1 - Select last Record **User 1 - Record B Selected** User 2 - Select last Record User 2 - Record B Selected
The problem does not occur, when the users use different connections. That should always be the case on different requests. But even within the same script, utilizing _different_ connections, ensures the separation. Prove: $connection_for_user1 = new MySQLi('localhost', 'user', 'pass', 'test'); $connection_for_user2 = new MySQLi('localhost', 'user', 'pass', 'test'); $result_for_user1 = $connection_for_user1->query("INSERT INTO test_table (data) VALUES ('A')"); $result_for_user2 = $connection_for_user2->query("INSERT INTO test_table (data) VALUES ('B')"); $record_id_for_user1 = $connection_for_user1->insert_id; $record_id_for_user2 = $connection_for_user2->insert_id; echo "User 1: record $record_id_for_user1\n"; echo "User 2: record $record_id_for_user2\n"; Result: User 1: record 1 User 2: record 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql, networking, select" }
remove encoding from xmlserializer I am using the following code to create an xml document - XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); new XmlSerializer(typeof(docket)).Serialize(Console.Out, i, ns); this works great in creating the xml file with no namespace attributes. i would like to also have no encoding attribute in the root element, but I cannot find a way to do it. Does anyone have any idea if this can be done? Thanks
**Old answer removed and update with new solution:** Assuming that it's ok to remove the xml declaration completly, because it makes not much sense without the encoding attribute: XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (XmlWriter writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { OmitXmlDeclaration = true})) { new XmlSerializer(typeof (SomeType)).Serialize(writer, new SomeType(), ns); }
stackexchange-stackoverflow
{ "answer_score": 34, "question_score": 19, "tags": "c#, xmlserializer" }
AI bias in the sentiment analysis Using sentiment analysis API and want to know how the AI bias that gets in through the training set of data and other biases quantified. Any help would be appreciated.
There are several tools developed to deal with it: Fair Learn < Interpretability Toolkit < In Fair Learn you can see how biased a ML model is after it has been trained with the data set and choose a maybe less accurate model which performs better with biases. The explainable ML models provide different correlation of inputs with outputs and combined with Fair Learn can give an idea of the health of the ML model.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sentiment analysis, azure cognitive services, text analytics api" }
Как менять внешний вид пункта ListView при клике на него? При разработке приложения столкнулся с такой проблемой. У меня есть `ListView`. Нужно, чтобы при клике на пункт, этот пункт менял свой внешний вид (цвет текста), а при повторном клике возвращался в обычное состояние. Сложность в том, что это должно сохраняться, т.е. при перезапуске приложения, внешний вид пунктов должен быть такой же как при закрытии. P.S. Пункты списка тянутся из базы, если это чем-то поможет.
Надо примерно так: Декларируем лэйаут `TextView` (my_text_view.xml) <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android=" android:id="@+id/textView" android:textColor="@color/myColor" android:layout_width="fill_parent" android:layout_height="fill_parent"/> Заводим списочек: ListView listView = new ListView(context); String[] items = {"Item 1","Item 2", "Item 3"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,R.layout.my_text_view,items); listView.setAdapter(ad); Далее при клике на элемент: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long i) { ((TextView) view).setTextColor(anyColor); //вставляем свой цвет } });
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "android, listview, java" }
Probability of swapping elements in an array Given an array with n numbers (n>30). Perform the following steps: * Compare the first element with the second element. If the first one is greater than the second one, swap their positions in the array. * Compare the second element with the third element. If the second one is greater than the third one, swap their positions in the array. ..... Keep doing the above steps until the last element of the array is compared. What is the probability of the case that the value of the 10th element being moved to the 30th element. * * * My attempt is: In order for this case to happen, the 10th element must be the largest number of the first 10 elements AND the 10th element must also be the largest number of the next 21 elements (from 10th to 30th). However, I don't know how to present it into probability. Your help would be greatly appreciated.
There are $30$ numbers in the first $30$, so the probability the $n$th of the $30$ is the largest is $\frac{1}{30}$. So the probability the $10$th is the largest of the first $30$ is $\frac{1}{30}$. But if you want the $10$th not to move further than position $30$, then it must be smaller then the $31$st. The probability that $31$st is the largest and the $10$th is the second largest of the first $31$ numbers in the array is $\frac{1}{31} \times \frac{1}{30}=\frac{1}{930}$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "probability" }
C# winforms Несколько форм Я создал приложение, и теперь я делаю для него авторизацию но не могу понять как сделать чтобы сначала открывалась форма авторизация, помогите пожалуйста.
Создаете форму-диалог авторизации, к примеру `LoginForm`, реализуете для нее логику `DialogResult`. В главной форме в обработчике события `Form.Load` можно написать например так. private void Form1_Load(object sender, EventArgs e) { var loginForm = new LoginForm(); while (true) { switch (loginForm.ShowDialog(this)) { case DialogResult.OK: return; case DialogResult.Cancel: Application.Exit(); break; default: MessageBox.Show("Не удалось авторизоваться, попробуйте еще раз"); break; } } } Все что вам осталось сделать - это реализовать возврат правильного `DialogResult`. Саму логику авторизации можете реализовать как в логинформе, так и в главной форме, или отдельном классе. Здесь уж как вам нравится.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, winforms" }
Getting Wrong data in Salesforce Marekting Cloud Query I have written the following query in my child BU to get data from subscribers. Select EmailAddress,Status,Subscriberkey,DateUnsubscribed from ent._Subscribers I am storing this records in Data Extension. "Status" field for 4-records is "Unsubscribed" in Subscribers. but, after checking records in data extension, the Status for the Same record is Showing "active". all other fields data is correct any specific reason?
The first answer is entirely correct, BUT the solution has become much easier lately, with the introduction of the new data view businessUnitUnsubscribes, which eliminates the need for the (correct) workaround linked by Brad. Hope this helps! Edit: to clarify - BusinessUnitUnsubscribes has the current BU-wide subscription status, IF that status is unsubscribed. It does not hold the subscriber status if it is active, held or bounced. Since it does also not hold events (unlike _Unsubscribe data view), it will always only show current status (...if it's "unsubscribed", that is.).
stackexchange-salesforce
{ "answer_score": 4, "question_score": 0, "tags": "marketing cloud, query, unsubscriber" }
PyOpenGL windows OS problem So I've developed an application on Mac OS and now I'm trying to test it on a machine having windows XP. Now this doesn't work here first issue being that glGenBuffer and glGenBuffer are giving a NullFunctionException. So I tried to check the OpenGL version on that machine but glGetString(GL_VERSION) returns None. Problem is I don't know much about the machine I'm testing on. If I run a dxdiag direct X returns only n/a to all details about the video card.
You can use gpu-caps to find out details, dxdiag can only be helpful in regards to directx. You might have to update graphic card drivers.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "opengl, pyopengl" }
DataNavigateUrlFields navigating to subfolder instead of correct location. I have a datagrid that needs one of the fields to hyperlink to a document housed on another server. The path is in this format: `\\server\location\file.doc`, but when I click on the cell in the data grid it becomes: ` Is there any way that I can force this to go to the correct location? I know that you can prevent this for external websites by adding ftp:// or but this does not seem to work for opening up this server location. Any suggestions?
I believe your answer can be found here on the asp.net forums < \- accepted answer from there below for your convenience. <Columns> <asp:TemplateField> <ItemTemplate> <asp:HyperLink Text="TextField" id="myHL" runat="server" NavigateUrl='<%# "file:///" + DataBinder.Eval(Container.DataItem, "Path").ToString() %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> </Columns> I believe you need to prefix your links with `file:///` for it would be `file:///\\server\location\file.doc`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net, datagrid" }
Proof for a Limit of a Sequence converging to 0 $\frac{1}{n+1}$ \- $\frac{1}{n+2}$ \+ . . . $\frac{(-1)^{n-1}}{2n}$ converges to Zero. My guess It can be written as $\frac{1}{n}$$\sum_{k=1}^n$$\frac{1}{1+\frac{k}{n} }$ \- $\frac{2}{n}$$\sum_{k=1}^{n/2}$$\frac{1}{1+\frac{2k}{n} }$ = $\frac{1}{n}$$\sum_{k=1}^n$$\frac{1}{1+\frac{k}{n} }$ \- $\frac{1}{n/2}$$\sum_{k=1}^{n/2}$$\frac{1}{1+\frac{k}{n/2} }$ As n tends to infinity both sum converges to log2 Thus log2 - log2 = 0 Correct me if I assumed anything wrong. Or give something new , better way,
The analysis in the OP is not quite correct. Instead, we have $$\begin{align} \sum_{k=1}^n \frac{(-1)^{k-1}}{k+n}&=\sum_{k=1}^{\lfloor n/2\rfloor} \left(\frac1{2k-1+n}-\frac1{2k+n}\right)+O\left(\frac1n\right)\\\\\\\ &=\sum_{k=1}^{\lfloor n/2\rfloor} \frac1{(2k-1+n)(2k+n)}+O\left(\frac1n\right)\\\\\\\ &\le \frac{n}{2}\frac{1}{(n+1)(n+2)}+O\left(\frac1n\right) \end{align}$$ Can you finish now?
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "real analysis, sequences and series, convergence divergence" }
mktemp for TCP ports `mktemp` returns filename which is free (not associated to real file). So we can use that file. How we can do the same with tcp ports? Anybody knows `mkport` application? ( I need it from tests level. So I need just number. Then I will use it in two applications which will communicate on that tcp port. )
This python script might do what you want: #!/usr/bin/env python import socket s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.listen(0) print s.getsockname()[1]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "linux, tcp" }
How to create folder shortcut in Ubuntu 14.04? I have a folder in my Dropbox and I want to add a shortcut of that folder on my Desktop. I guess this should be extremely easy as in Windows OS :) However, I have no idea how to do it in Ubuntu 14.04. Is there anything I can do to create a simple folder shortcut on my desktop?
Click on that folder, click on make link, then move the shortcut to Desktop.
stackexchange-askubuntu
{ "answer_score": 19, "question_score": 67, "tags": "14.04, filesystem, configuration, gui, shortcuts" }
Update/change roles claim (or any other claim) in JWT I'm storing user roles inside a JWT (to restrict API endpoints). The roles can be changed by an administrator. If a role is changed. How am I supposed to reflect this inside all tokens? I've thought about a couple of solutions: * If I'd use refresh tokens, the user would have to wait until the expiration date of the access token is expired. * I could keep a record of changed user IDs and check every request, and then return a new token if the user has been changed. Is there a standard way to do this?
Refresh tokens don't seem to be the solution if you care about the changes you make being instant, you probably don't want an user to access moderation tools for some time if you revoke his permissions. What you could do is keep a version number in the jwt token relative to the user, much like how mongoose does it with it's versionKey. By doing this, you would be able to check this version against the one in the database for a given user. Each time you change the roles of this user, you would increment this version, if the version of the jwt doesn't match, just recreate a new one with the correct roles and version and send it back to the user. I don't believe there is a proper standard for this, as jwt is immutable by design, you'll have to change it entirely if you need to "update" it.
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 31, "tags": "authentication, oauth, asp.net core, jwt, asp.net core webapi" }
How to debug a connection failure between Jboss and eclipse debugger I have setup eclipse to attach to a local JVM. But when I try to do the same for a machine over the network I get "connection timed out exception". How do I go about debugging this issue? I tried: lsof -i :8787 on the remote machine, and it appears that a java process is in fact listening on that port. What else could be wrong and how to go about finding it. Please help. Thank you. Note: My JAVA_OPT looks like this on the remote machine. JAVA_OPTS=”-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS”
Servers often have multiple NICs; you might add the hostname or IP of the remote interface you're using to your debugging options, like so: `-Xrunjdwp:transport=dt_socket,address=HOSTNAME_OR_IP:8787,server=y,suspend=n`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "eclipse, jboss, debugging, jvm, lsof" }
Characteristic function and convergence in distribution I am trying to solve the following exercise: Let $X_1^{(n)},\ldots, X_n^{(n)}$ be iid r.v. such that $P(X_i^{(n)}=1)=P(X_i^{(n)}=-1)=\frac{1}{2n}, (P(X_i^{(n)}=0)=1-\frac1n$ Let $S_n = \sum_{i=1}^n X_i^{(n)}$, show that $S_n$ converges in Distribution and compute its limit. I am trying using characteristic functions. I have that $$ E(e^{itX_1^{(n)}})= \frac{e^{it}}{2n}+\frac{e^{-it}}{2n}+1-\frac1n$$ and $$ E(e^{itS_n}) = \left(E\left(e^{itX_1^{(n)}}\right)\right)^n = \bigg(1 + \frac{e^{it}+e^{-it}-2}{2n}\bigg)^n \to \exp\bigg(\frac{e^{it}+e^{-it}-2}{2}\bigg)$$ as $n$ approaches $+\infty$. Even re-writing the limiting function as $\exp(\cos(t)-1)$ I have no Idea on how to compute the limiting random variable. How do I compute the corresponding integral? $$ \int_\mathbb{R} e^{-itx+\cos(t)-1} dt$$ Did I do something wrong?
I see nothing wrong with the computations. In terms of known probability distributions, the limit is the difference of two independent Poisson distributed random variables with parameter $1/2$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "probability, complex analysis, probability distributions, characteristic functions, probability limit theorems" }
Konva - visualize custom hit area Is there an easy way to visualize a custom hit area shape? As described here < the hitFunc attribute can be set to a function that uses the supplied context to draw a custom hit area / region. Something like this: var star = new Konva.Star({ ... hitFunc: function (context) { context.beginPath() context.arc(0, 0, this.getOuterRadius() + 10, 0, Math.PI * 2, true) context.closePath() context.fillStrokeShape(this) } }) For debugging purposes, I would like an easy way to toggle visual rendering of the shape (circle in this case), eg by filling it yellow. Thanks :)
Currently, there is no public API for that. But you still can add hit canvas into the page somewhere and see how it looks: const hitCanvas = layer.hitCanvas._canvas; document.body.appendChild(hitCanvas); // disable absolute position: hitCanvas.style.position = ''; < Or you can add hit canvas on top of the stage and apply an opacity to make scene canvases visible: const hitCanvas = layer.hitCanvas._canvas; stage.getContainer().appendChild(hitCanvas); hitCanvas.style.opacity = 0.5; hitCanvas.style.pointerEvents = 'none'; <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "konvajs" }
A simple question about vectors Suppose that we have a vector $v\in\mathbb{R}^3$ whose components are $v=(v_1,v_2,v_3).$ > **Question.** It is possible to see the vector $v$ as a vector of $\mathbb{R}^2\times\mathbb{R}$? That is $v=((v_1,v_3),v_2)$, or $v=((v_2,v_3),v_1)$? Thanks!
Yes. In particular, we can identify $((v_1,v_2),v_3)\in\mathbb R^2\times \mathbb R$ with the vector $(v_1,v_2,v_3)\in\mathbb R^3$. You should check that this is an isomorphism so that the operations in the vector space work normally, and once you have done that, you can safely treat them as the same thing.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "linear algebra" }
C program freeze at fprintf ( large amounts of data ) I am attempting to write the clipboard contents to a file, but for some reason the program is freezing. FILE *fp; fp = fopen("tmp.code","w"); fprintf(fp,getclip()); /*writes*/ fclose(fp); char* getclip(){ HANDLE clip; if (OpenClipboard(NULL)){ clip = GetClipboardData(CF_TEXT); CloseClipboard(); return clip; } } What am I doing wrong ? Thanks
The function `getclip()` returns an `int`, and `fprintf` expects pointer to char. It is trying to access an invalid memory position: you're returning a `HANDLE` as `int` and then `fprintf` interprets that as a memory address to read characters from. Please look at your compiler errors and warnings and fix your code.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -4, "tags": "c" }
You can't use Airport Utility without Airport Extreme? I want to use Airport Utility to settle wireless time limits, it seems that I can't use Airport Utility. Is it because you can use Airport Utility only with Apple hardware like Airport Extreme?
Airport Utility is only for Apple's line of Airport wireless routers. This includes Airport Express, Airport Extreme, and Time Capsule. It does not support other routers.
stackexchange-apple
{ "answer_score": 4, "question_score": 0, "tags": "macos, network, macbook pro, airport" }
How to write this algorithm in a python code? I have the following code. for k in range( ( N + 1 ) * K ): if k >= 0 and k <= K-1: # do something # n = 0 elif k >= K and k <= 2*K-1: # do something # n = 1 elif k >= 2*K and k <= 3*K-1: # do something # n = 2 ... ... The 'do something' is complicated to explain but I replaced it with the affectation n = p. How can I write this explicitly? More specifically, if k is in the set {p*K,...,(p+1)*K-1} for p = 0 to N, then do something. How can I do it in a code?
for loop_id in xrange(N): for i in xrange(K): k = K * loop_id + i do_smth(loop_id, i, k)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 6, "tags": "python, algorithm" }
How to merge 2 data sets using 2 common columns in each in R I'm trying to merge two data frames based on 2 columns in each. I want to merge the Territory column and IDMate column from Data Frame 2 to Data Frame 1 based on matching ID and Year columns. Data Frame 1: ID Year 1 1 1998 2 2 2001 3 3 2005 4 4 2008 Data Frame 2: ID Year Territory IDMate 1 1 1998 A 22 2 1 1999 B 24 3 1 2000 C 25 4 2 2001 D 26 5 2 2002 E 27 6 3 2005 F 28 7 4 2008 G 29 Goal is to get this: ID Year Territory IDMate 1 1 1998 A 22 2 2 2001 D 26 3 3 2005 F 28 4 4 2008 G 29
You can use `left_join` from `dplyr`: library(dplyr) res <- left_join(df1, df2, by = c("ID", "Year")) # ID Year Territory IDMate # 1 1998 A 22 # 2 2001 D 26 # 3 2005 F 28 # 4 2008 G 29
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "r" }
Logging a PostgreSQL session in text file I am trying to log a complete session in psql into a .txt file. The command given to me was initially this: psql db_name| tee file_name.txt However, my SSH client does nothing until I quit it. That means, it does not recognize any command. More like a document, no action happens no matter what I write. So far, only `'\q'` is recognised which lets me get out of it. Any ideas what is happening? How am I to write the query if shell will not read anything. Also, I tried the following (this is before connecting to database) : script filename.txt It does show the message : `script started, file is filename.txt`, but I dont know where this file is stored and how to retrieve it. Any help with the above will be welcome and really appreciated! Thanks a lot :)
There is option to psql for log query and results: > **-L filename** > \--log-file filename > > Write all query output into file _**filename**_ , in addition to the normal output destination. Try this: psql db_name -L file_name.txt
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "postgresql, psql" }
Why does an Android app project have to include a package used by a library An Android app uses a library (aar module) that uses "com.google.gson.Gson". The library has the following in its build.gradle: compile 'com.google.code.gson:gson:2.6.2' The app builds fine, but generates the following error when it starts: Failed resolution of: Lcom/google/gson/Gson; The only way to solve it is adding the same compile line to the app's build.gradle: compile 'com.google.code.gson:gson:2.6.2' Could anyone shed some light on this? **[Edit]** The library was added with the standard procedure that created a folder under the app called "androidLibrary-release". The following line has been added to the build.gradle of the app: compile project(':androidLibrary-release')
Libraries don't include their dependencies. It is up to the developer to include them as necessary in the app modules that implement them. However, if this library comes from a Maven repo, it is possible to include the information about which dependencies the library uses and they will be fetched when your project is built.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android library" }
Python logging sending logs to standard out I am running the following code in a custom Python application: if __name__ == '__main__': logging.basicConfig(filemode='example.log', level=logging.DEBUG) logging.debug('This message should go to the log file') but the output is being written to standard out. I ran the same code from a Jupyter notebook and it creates the example.log file and writes the log message to it. I read that the order of imports may be important. Here is the order: import logging import argparse import time import os import sys import json
You made a typo in the arguments to `basicConfig`. Instead of setting `filename` to `example.log`, you set `filemode`, which is something else! It worked for me like this: import logging if __name__ == '__main__': logging.basicConfig(filename='example.log', level=logging.DEBUG) logging.debug('This message should go to the log file')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python 3.x, logging" }
google cloud platform billing account china **I can't create billing account for China.** I just want to use the Google Map Platform, before this is free and easy to use. I am happy to pay for Google Map Platform, but I'm Chinese. I don't have any visa or JCB credit card. This is a confusing question. Maybe the Google Map Platform can support paypal to create billing account? By the way, Google map is well. I like it.
Please note that according to our Maps Platform Terms of Service, section 3.2.4 (f), usage in prohibited territories is not allowed, and China is on the list of Prohibited Territories. It is not permissible to set up Maps APIs using projects associated with a billing account from a prohibited territory, or include Maps APIs with a Customer Application built for use within a prohibited territory. For further questions regarding the Maps Platform Terms of Service, please work with your legal representative for guidance.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "google maps, google maps api 3, billing" }