qid
int64
5
74.7M
question
stringlengths
25
26.8k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
26
26.9k
response_k
stringlengths
28
12.8k
__index_level_0__
int64
54
372k
55,859,247
I am trying to dynamically populate the headers of MenuItems based on filenames the MenuItem will open when clicked. I've found that whenever a header name has one or more "\_"'s the first one is never displayed. I'm trying to determine the best workaround for this problem. I could replace the first "\_" with "\_\_" but I was wondering if there was a better solution? The following is an example of my code ``` <MenuItem x:Name="MenuTest" Header="this_is_a_Test"> </MenuItem> ``` which produces a header that looks like "thisis\_a\_test"
2019/04/26
[ "https://Stackoverflow.com/questions/55859247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10600176/" ]
Here is a working solution for the official PHP-FPM images based on Debian 10 (Buster). The following `Dockerfile` installs the Oracle Instant Client 18.5 (*basiclite* and *devel*) using the RPM packges and `alien`. As Christopher Jones wrote the files can currently be downloaded without an Oracle account. ``` FROM php:7.2.32-fpm # see https://help.ubuntu.com/community/Oracle%20Instant%20Client RUN apt-get update && apt-get install -y --no-install-recommends alien libaio1 wget && \ wget https://download.oracle.com/otn_software/linux/instantclient/185000/oracle-instantclient18.5-basiclite-18.5.0.0.0-3.x86_64.rpm && \ wget https://download.oracle.com/otn_software/linux/instantclient/185000/oracle-instantclient18.5-devel-18.5.0.0.0-3.x86_64.rpm && \ alien -i oracle-instantclient18.5-basiclite-18.5.0.0.0-3.x86_64.rpm && \ alien -i oracle-instantclient18.5-devel-18.5.0.0.0-3.x86_64.rpm ENV LD_LIBRARY_PATH="/usr/lib/oracle/18.5/client64/lib:${LD_LIBRARY_PATH}" ```
You don't want to use Alpine Linux, since you will need to hack it and it could become unstable. See <https://stackoverflow.com/a/53291026/4799035> for more comments. Also see <https://github.com/oracle/docker-images/blob/master/OracleInstantClient/dockerfiles/19/Dockerfile> which doesn't need any login. In summary, on Oracle Linux 7: ``` yum -y install oracle-release-el7 yum -y install oracle-instantclient19.3-basic && rm -rf /var/cache/yum ``` Update: Oracle has Docker images at <https://github.com/oracle/docker-images/pkgs/container/oraclelinux7-instantclient> and <https://github.com/oracle/docker-images/pkgs/container/oraclelinux8-instantclient> which can be pulled like: ``` docker pull ghcr.io/oracle/oraclelinux7-instantclient:21 ``` and ``` docker pull ghcr.io/oracle/oraclelinux8-instantclient:21 ```
270,111
2,222,569
I've run into an odd problem with this code: `legibIndex = 206.385 - 84.6 * (countSylb / countWord) - 1.015 * (countWord / countSent);` This is the calculation for the legibility index of a given text file. Since this is a homework assignment, we were told what the Index should be (80, or exactly 80.3) My syllable count, word count, and sentence count are all correct (they match up with the given numbers for the sample textfiles. Even if I hardcode the numbers in, I do not get 80, even though I do when i put it into my caclulator exactly as seen. I can't imagine what is wrong. Here is the equation we were given: `Index = 206.835 - 84.6 * (# syllables/# words) - 1.015 * (# words/# sentences)` As you can see, I just plugged in my variables (which are holding the correct values. For reference, the values are : 55 Syllables, 40 Words, 4 Sentences, as given by the instructor. The values my program produces when ran is a Legibility Index of 112. Am I missing some brackets, or what? I'm stumped!
2010/02/08
[ "https://Stackoverflow.com/questions/2222569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257906/" ]
Right off the bat, from the names (which include the word *count*) I'd guess that `countSylb`, `countSent` and `countWord` are declared as integers, and therefore your divisions are doing integer arithmetic, truncating the decimal portions. Cast them to floats and that should fix it. ``` legibIndex = 206.385 - 84.6 * ((float)countSylb / ((float)countWord) - 1.015 * (((float)countWord / ((float)countSent); ```
As pointed out above, your count variables are likely whole number integers, but your expression contains literal floating point numbers. Casting those ints into floats will give the correct value. You must also make sure that what you are storing the expression's result in (legibIndex) is also of type float.
210,233
22,340,643
I am trying to format a String into a date but getting java compiler error: The fragment of code is: ``` String value = String.valueOf(entry.getValue()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); //String dateInString = value; SimpleDateFormat parse = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); if (isFirst){ Date date = parse.parse(value); //Then I'll just put the date variable into a cell in the html table. ``` The error I am getting: **cannot find symbol** ``` [javac] symbol : constructor SimpleDateFormat(java.lang.String,java.util.Locale) [javac] location: class com.lb.base.util.extra.SimpleDateFormat [javac] SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); [javac] ^ ``` I get this for both times I am declaring new SimpleDateFormat. I have checked that import is not the issue. Quite confused to what it is then..why am I getting this 'cannot find symbol' error?
2014/03/12
[ "https://Stackoverflow.com/questions/22340643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347427/" ]
Your import seems to be off. You want to use java's SimpleDataFormat and not com.lb.base.util.extra whatever that is.
Something in your code, or the code your using, is very oddly expecting a non-standard version of a very standard class. You should search the source-code for this import statement: ``` import com.lb.base.util.extra.SimpleDateFormat; ``` or for a class/java file *named* SimpleDateFormat.java This is pretty difficult to diagnose without having direct access to your computer, but it seems like you are trying to use two classes with exactly the same name. One other thought: Instead of this ``` SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); ``` try explicit package names to bypass import statements: ``` xbn.text.SimpleDateFormat formatter = new xbn.text.SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); ``` I am assuming here that you *want* to use the standard Java versions. Here is a link with some information that may be instructive: <https://www.google.com/search?q=is+already+defined+in+a+single-type+import+%5Bjavac%5D+import>
104,716
193,409
The use of tolerance comes with varying degrees of indifference to something, with often unstated or deliberately understated degrees of disapproval for that thing. For example, *"While I'm tolerant of those that eat meat, I don't personally do it."* Enthusiasm, on the other hand, conveys endorsement. *"I'm excited that people are eating meat, though I don't personally don't do it."* *Ambivalence* immediately comes to mind, but that negates any inclination toward the subject, be it positive or negative. What word indicates *"I think that's fine, but it isn't for me"*, without the sort of negative connotation that *tolerance* lends, yet lacks implied or enthusiastic endorsement? What word exists between tolerance and enthusiasm for something?
2014/08/26
[ "https://english.stackexchange.com/questions/193409", "https://english.stackexchange.com", "https://english.stackexchange.com/users/3995/" ]
I don't know that it is possible to be fully neutral without dropping your perspective from it. As soon as you introduce yourself, you are automatically assuming a perspective against which a following statement will be compared, so absolute neutrality becomes improbable. Consider the difference between: > > 1. Some people like the color blue. > 2. I tolerate that some people like the color blue. > 3. I value that some people like the color blue. > > > That said, I think you could use *acknowledge* (or *recognize* or *understand*) in this context to express a relatively neutral opinion. > > I *acknowledge* that some people like the color blue. > > > It expresses that you are not ignorant of the existence of something and at the same time implies no value judgement apart from that you (probably) like a different color.
The following words come to mind: *Acceptable:* just good enough, but not very good *All right:* satisfactory or reasonably good *Convenient:* suitable for the purposes and needs and causing the least difficulty
193,501
43,600,361
I was looking for a way to convert something in dot notation into a string using Javascript. Basically here's what I am looking for: ``` function dotToString(dotNotation){ return something; } dotToString(this.is.just.a.test); // Would return "this.is.just.a.test" ```
2017/04/25
[ "https://Stackoverflow.com/questions/43600361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6807393/" ]
Short answer: No Long answer: When javascript passes an argument to a function, it passes in the value from the variable you are attempting to pass in. At no point does the `dotToString` function see `this.is.just.a.test` (It would see "blah", if `this.is.just.a.test = "blah"`). This is not possible.
Yes, you can do this with proxies. ```js function makeDotProxy(name) { return new Proxy({}, { get(target, prop) { if (prop === 'valueOf' || prop === 'toString') return () => name; if (typeof prop === 'symbol') return Reflect.get(target, prop); return makeDotProxy(name + '.' + prop); } }); } const This = makeDotProxy('this'); console.log(This.is.a.just.a.test.toString()); ``` But then, why would you want to?
131,736
17,359,296
I need to give user opportunity to choose phone number from address book, so I took example from apple manual. But it takes only the first number, how I can make so user can choose one of one's numbers in address book. ``` - (IBAction)adressBook:(UIButton *)sender { ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [self presentModalViewController:picker animated:YES]; } - (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker { [self dismissModalViewControllerAnimated:YES]; } - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person { [self displayPerson:person]; [self dismissModalViewControllerAnimated:YES]; return NO; } - (void)displayPerson:(ABRecordRef)person { NSString* phone = nil; ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty); if (ABMultiValueGetCount(phoneNumbers) > 0) { phone = (__bridge_transfer NSString*) ABMultiValueCopyValueAtIndex(phoneNumbers, 0); } else { phone = @"[None]"; } self.telNumber.text = phone; CFRelease(phoneNumbers); } ```
2013/06/28
[ "https://Stackoverflow.com/questions/17359296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035024/" ]
This will return Array than contain all the Number that person have. After that you can select any number from array. ``` - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person { //get the phone number ABMultiValueRef phone = (__bridge ABMultiValueRef)((__bridge NSMutableDictionary *)ABRecordCopyValue(person, kABPersonPhoneProperty)); NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phone); NSMutableString *strPhone = [NSMutableString string]; for (int i=0; i<[phoneArray count]; i++) { [strPhone appendString:[NSString stringWithFormat:@"%@,",[phoneArray objectAtIndex:i]]]; } NSLog(@"Dilip phoneArray : %@",phoneArray); NSLog(@"Dilip strPhone : %@",strPhone); phone = nil; phoneArray = nil; strPhone = nil; [peoplePicker dismissModalViewControllerAnimated:YES]; return NO; } ```
Use the `peoplePickerNavigationController:shouldContinueAfterSelectingPerson:property:identifier:` delegate method which gives you more information about the field that was selected.
177,068
15,885,522
why is ``` string date = string.Format("{0:mmddyyHHmmss}", DateTime.Now); ``` giving me 420813104204 shouldn't it be 040813... ? I am trying to match mmddyyHHmmSS
2013/04/08
[ "https://Stackoverflow.com/questions/15885522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354345/" ]
try this instead ``` string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now); ```
``` string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now); ``` would give you the required format. Check out [this link](http://www.csharp-examples.net/string-format-datetime/) for reference
239,746
44,091,397
I want a form to appear in the center of the page when a button is clicked. I found a solution at <http://jqueryui.com/dialog/#modal-form>. But can it be done in a simpler way without having to include jqueryui? Also, how i can make the background fields unaccessible? i.e, when the form is open, background fields should be visible but I shouldn't be able to interact with them.
2017/05/20
[ "https://Stackoverflow.com/questions/44091397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512700/" ]
Create a hidden form, then on click of a button toggle the form using [.show()](https://www.w3schools.com/jquery/eff_show.asp) and [.hide()](http://api.jquery.com/hide/) ```js $('#show').on('click', function () { $('.center').show(); $(this).hide(); }) $('#close').on('click', function () { $('.center').hide(); $('#show').show(); }) ``` ```css .center { margin: auto; width: 60%; padding: 20px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); } .hideform { display: none; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="center hideform"> <button id="close" style="float: right;">X</button> <form action="/action_page.php"> First name:<br> <input type="text" name="firstname" value="Mickey"> <br> Last name:<br> <input type="text" name="lastname" value="Mouse"> <br><br> <input type="submit" value="Submit"> </form> </div> <button id="show">Show form</button> ```
You can create your own dialog box and have it initially hidden with `display: none`. Then set an on click event on a button to `.show()` the dialog box. Obviously the dialogue box should be set to `position: fixed`, and centered through the use of `top`, `left`, `bottom` or `right` CSS attributes. I created pen like this <https://codepen.io/joaquintoral/pen/Vbdpqz>
27,692
8,574,241
I have a Java method that process a bitmap and returns a String. When I call this method from JNI (VS 2010) it works, but if I call this method many times, the memory of the process grown up until crash. The instruction that use a lot of memory is: ``` jbyteArray jBuff = _env->NewByteArray(b->Length); ``` My code: ``` static jobject staticArray=0; System::String^ MyClass::ExecuteJavaMethod(System::Drawing::Bitmap^ bmp) { JNIEnv *_env; System::String^ out; unsigned const char * buff; int res = jvm->AttachCurrentThread((void **)&_env, NULL); if (jvm->GetEnv((void**) &_env, JNI_VERSION_1_6) != JNI_OK) { return "GetEnv ERROR"; } //save the bitmap in the stream MemoryStream^ ms = gcnew MemoryStream(); bmp->Save(ms, ImageFormat::Bmp); //get the bitmap buffer array<unsigned char>^b = ms->GetBuffer() ; //unmanaged conversion buff = GetUnmanaged(b,b->Length); //fill the buffer jbyteArray jBuff = _env->NewByteArray(b->Length); _env->SetByteArrayRegion(jBuff, 0, b->Length, (jbyte*) buff); //call the java method jstring str = (jstring) _env->CallStaticObjectMethod ( Main, javaMethod, jBuff); // _env->ReleaseByteArrayElements(jBuff,(jbyte*)buff), 0); //NOT WORKING //staticArray= _env->NewGlobalRef(jBuff); NOT //_env->DeleteLocalRef(jBuff); WORKING //return the string result of the java method return gcnew String(env->GetStringUTFChars(str, 0)); } ```
2011/12/20
[ "https://Stackoverflow.com/questions/8574241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/898313/" ]
the answer is: `_env->DeleteLocalRef(jBuff);`
You didn't call `DetachCurrentThread()` for each `AttachCurrentThread()`, which is requested in [Java Native Interface Specification](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html). That makes the local references (`jBuff` and `str`) unable to be freed automatically. Also, the `const char*` fetched through `GetStringUTFChars()` needs to be released. The correct way is change ``` return gcnew String(env->GetStringUTFChars(str, 0)); ``` into ``` const char* cstr = env->GetStringUTFChars(str, 0); System::String^ retstr = gcnew String(cstr); env->ReleaseStringUTFChars(str, cstr); jvm->DetachCurrentThread(); return retstr; ```
260,002
1,977,741
ANY DOM element can be made resizable according to this page: <http://jqueryui.com/demos/resizable/> However, it seems that this doesn't work for the CANVAS element. Possible?
2009/12/30
[ "https://Stackoverflow.com/questions/1977741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199910/" ]
Canvas has two types of resize behavior: * Resizing where the contents are stretched to fit the canvas's new dimensions * Resizing where the contents remain static while the canvas grows or shrinks Here's a page that demonstrates the two types of "resizing": <http://xavi.co/static/so-resizable-canvas.html> If you want the first type of resizing (stretch the content) then place the canvas into a container `div` and set the `width` and `height` of the canvas to 100% using CSS. Here's what that code might look like: ``` /* The CSS */ #stretch { height: 100px; width: 200px; } #stretch canvas { width: 100%; height: 100%; } <!-- The markup --> <div id="stretch"><canvas></canvas></div> // The JavaScript $("#stretch").resizable(); ``` The second type of resizing (static content) is a two step process. First you must adjust the `width` and `height` attributes of the canvas element. Unfortunately, doing this clears the canvas, so you must then re-draw all its contents. Here's bit of code that does this: ``` /* The CSS */ #resize { height: 100px; width: 200px; } <!-- The markup --> <div id="resize"><canvas></canvas></div> // The JavaScript $("#resize").resizable({ stop: function(event, ui) { $("canvas", this).each(function() { $(this).attr({ width: ui.size.width, height: ui.size.height }); // Adjusting the width or height attribute clears the canvas of // its contents, so you are forced to redraw. reDraw(this); }); } }); ``` Currently the code above re-draws the canvas's content when the user stops resizing the widget. It's possible to re-draw the canvas on [resize](http://docs.jquery.com/UI/Resizable#event-resize), however resize events occur fairly often and re-draws are expensive operations -- approach with caution.
There's a bit of a funny quirk on the canvas co-ordinate system, with regards to using this : ``` #stretch canvas { width: 100%; height: 100%; } ``` (from the example above) You have to use these CSS rules because you can not specify % in the canvas' width/height attributes. But you'll find you get unexpected results when you try to draw objects on to it using just these rules- drawn objects appear squashed. Here's the above CSS, with a canvas border... ``` /* The CSS */ #stretch { width: 200px; height: 100px; } #stretch canvas { border:1px solid red; width: 100%; height: 100%; } ``` The canvas is drawn to the right size and the border rule is implemented correctly. The blue rectangle, added in code elsewhere, is supposed to fill the canvas with a 20px padding all around, but this has not happened: ![using just 100% css rules](https://i.stack.imgur.com/MyMQT.jpg) To fix this, make sure you **also** specify a width and height for the canvas element (either in the HTML or in javascript with setAttribute): ``` canvas.setAttribute('width', '200'); canvas.setAttribute('height', '100'); ``` or ``` <canvas width=200 height=100></canvas> ``` Now when I refresh the page I get what I expected: ![enter image description here](https://i.stack.imgur.com/pLkrq.jpg) This 'double-check' will make sure the canvas is drawn using the correct co-ordinate system and still allow it to be resized, via the CSS rules. If this is a bug, I'm sure it will be fixed in due course. This is just about providing a fix, but you can read more in to it [here](https://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties "here")
271,888
49,913,679
I often see in vavr-based code: ``` ... .map(x -> { if (someCondition(x)) { return doWith(x); } else { return x; } }) ... ``` Is there any way to eliminate this logic from `map` call using some constructs? I find this `if` condition awkward.
2018/04/19
[ "https://Stackoverflow.com/questions/49913679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542270/" ]
Using the ternary conditional expression may look better: ``` .map(x -> someCondition(x) ? doWith(x) : x) ```
How about `case-match` like the following: ``` Iterator.range(0, 10) .map(index -> Match(index).of( Case($(n -> n % 2 == 0), "even"), Case($(), "odd") )) ```
19,151
27,983,388
I want to use something similar to the following to clear errors in a form upon a resubmission attempt: ``` document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal").innerHTML= ""; ``` ...But the contents of the divs isn't cleared. What am I doing wrong?
2015/01/16
[ "https://Stackoverflow.com/questions/27983388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265915/" ]
You'll need to loop through the results ``` var errors = document.querySelectorAll( "#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal"); [].forEach.call(errors, function(error) { error.innerHTML = ''; }); ``` `querySelectorAll` doesn't return an array, but a node list, which doesn't have a `forEach` method on its prototype. The loop above is using the `forEach` method on the array object's prototype on the nodeList object.
Try this: ``` var x = document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel"); var i; for (i = 0; i < x.length; i++) { x[i].innerHTML = ""; } ``` See, if that helps.
357,775
75,126
How to check how much memory a solaris process consumes? I'd like both total address space allocated and the amount that is resident in RAM. I tried summing pmap output with some awk script, but it was an ugly hack. Is there a better way to script it?
2009/10/16
[ "https://serverfault.com/questions/75126", "https://serverfault.com", "https://serverfault.com/users/12626/" ]
1. `prstat -s rss` '-s' sorts prstat output by rss column (see man page for other columns). Also try '-a' option for a per user accumulation. 2. `ps -eo pid,pmem,vsz,rss,comm | sort -rnk2 | head` Top 10 RAM consumers. '-o pmem' displays percentage of resident memory i.e. RAM used by process. 3. `ls -lh /proc/{pid}/as` Easy way to show total address space (vsz) of a process. Useful in combination with pgrep to accumulate by user, pattern, ... e.g.: ``` for pid in `pgrep -U webserver`; do ls -lh /proc/$pid/as; done ```
I use variation of this output in scripts: ``` # prstat -Z 1 1 | tail -3 ZONEID NPROC SWAP RSS MEMORY TIME CPU ZONE 220 56 1057M 413M 0.3% 1:26:49 0.1% 820f6ce5-7e37-4455-80ab-b28c5de19b43 Total: 56 processes, 169 lwps, load averages: 0.07, 0.06, 0.06 ```
298,554
7,855,666
I am using a java program which sends email after finishing up some file transfers.I am using Eclipse to code up the program. How do I set up a cron job to execute this java program for a particular time. Also I have various jar files inside the project. Please suggest
2011/10/21
[ "https://Stackoverflow.com/questions/7855666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387093/" ]
* Write a shell script to invoke your java program with the necessary arguments. * Make sure that the classpath argument points to the jars that you need. * Make sure that the shell script has necessary unix permissions. * Schedule the script to be invoked by setting up a cron job. For more info about cronjob look here <http://en.wikipedia.org/wiki/Cron> just my 2 cents...
There is the cron4j library <http://www.sauronsoftware.it/projects/cron4j/>. I have used it before to schedule a java program to run weekly. The scheduling syntax is the same as a crontab. The thing is, it needs to be constantly running as a background process to work. I ended up just using normal cron, but it could be useful if you're not on an Unix-like system, and you don't have cron.
237,514
2,305,614
I am running a small java server through xinetd superserver. I'd like to get the originating client IP but I can't because streams are between xinetd and java (stin/stdout). Does somebody know how to get the client IP, without looking to xinetd logfile ? (seems a bad solution to me) Thanks !
2010/02/21
[ "https://Stackoverflow.com/questions/2305614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278054/" ]
Given the situation you have described, trawling the xinetd logfile is your only option. If your Java application is talking to the client via its standard input and standard output, there is no way for the application to access the underlying socket. Indeed, I don't think you could do this in any language. **EDIT** : actually, you probably could do this in C and C++ because they expose the file descriptors (fds) and have library APIs for doing socket operations using fds. But it won't work in pure Java. Even if you could drill down to the fd inside the Stream objects associated with `System.in` or `System.out`, I don't think that the Java class libraries provide an API for turning the fd into a `Socket` object. To do socket operations on the fd's 0 and 1 you would need to resort to JNI and native code. And as the commenter points out, if the real client is behind a proxy, the client IP that you get from the socket will be the IP of the proxy.
I think you can call `getpeername` on TCP sockets (but not UDP), see [Stevens chapter 4.10](http://books.google.com/books?id=ptSC4LpwGA0C&pg=PA118&lpg=PA118&dq=inetd+socket+obtaining+ip+address+getpeername&source=bl&ots=Kq8DNhcqNs&sig=zNIW-hLP8M_Y4yZHXTAfW21lBcM&hl=en&ei=2QyqTIiLHMzrOcbooKwM&sa=X&oi=book_result&ct=result&resnum=4&ved=0CB0Q6AEwAw#v=onepage&q&f=false).
171,857
40,626,815
I have problem with powerbuilder 12 build 5530. I can't to create new datawindow. After I click New->Datawindow->tabular or etc. The Window closed but after that there is not creating new datawindow. I also can't open properties of target sample. What is the problem with my installation? i've tried to re-install but the problem still same. Please help me... PS: sorry for bad english.
2016/11/16
[ "https://Stackoverflow.com/questions/40626815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4268402/" ]
I have been working on IE11 with selenium library: selenium-server-standalone-3.141.59.jar and have following finding: On Window 10 64 bit version IE 11 version 11.431.16299, updated version 11.0.65(KB4103765) It works fine with IEDriverServer.exe (64 bit version) no need extra setting on capability. Key in period is acceptable(for 6 characters within 1 sec) On Window 10 64 bit version IE 11 version 11.15.16299.0 updated version 11.0.47 KB4040685 It works very slow with IEDriverServer.exe (64 bit version) To enter a 6 characters string, every character needs 3-4 secs to completed. To solve the problem, the following coding I tested works fine for me. ``` InternetExplorerOptions options = new InternetExplorerOptions(); options.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true); ``` On Window 7 Professional 32 bit version IE 11 version 11.0.9600.18499, updated version 11.0.36(KB3191495) It works fine with IEDriverServer.exe (32 bit version). Keyin period is acceptable.(6 characters within a sec) No extra setting is needed
I changed to IEDriver 32 bit (from 64 bits) solved this problem for me. IE 11, Windows 7, Selenium 3.4.
339,428
15,959,738
I am pretty new when it comes to using JQuery. I know that what I want to do is very basic. Basically, I need to create a "caption" box that slides down when an image is clicked. **User** clicks the image, and a tiny caption box slides out the bottom to describe to him/her what he has just clicked. I have created a tiny image to further clarify what I need to do. ![enter image description here](https://i.stack.imgur.com/vbRj5.jpg)
2013/04/11
[ "https://Stackoverflow.com/questions/15959738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272234/" ]
Manually trigger the change event: ``` t.model.trigger('change', t.model); ``` or ``` t.model.trigger('change:fieldErrors', t.model, newFieldErrorsValue); ```
``` this.model.set({fieldErrors: JSONResponse}, {silent:true}); this.model.trigger('change:fieldErrors'); ``` see this conversation: > > [Can I force an update to a model's attribute to register as a change even if it isn't?](https://stackoverflow.com/questions/15931233/can-i-force-an-update-to-a-models-attribute-to-register-as-a-change-even-if-it) > > >
308,941
43,589,797
i have white listed my domain and i get a message showing it was successful > > {"result": "Successfuly updated whitelisted domains"} > > > but when i try getting the user id I get the error message > > An error occuredMessenger Extensions are not enabled - could be "messenger\_extensions" was not set on a url, the domain was not whitelisted or this is an outdated version of Messenger client > > > i am using A PC so an outdated version might not be it, and i have the messenger extension set this way ``` $get_started_display = "{ 'recipient':{ 'id': $sender_id }, 'message':{ 'attachment':{ 'type':'template', 'payload':{ 'template_type':'button', 'text':'Click a button below to continue', 'buttons':[ { 'type':'web_url', 'title':'Add Leader Profile', 'url':'https://aadb-3120.herokuapp.com/login.html', 'webview_height_ratio' : 'full', 'messenger_extensions': true }, { 'type':'postback', 'title':'Review Added Profile', 'payload':'review' }, { 'type':'postback', 'title':'Help', 'payload':'help' }, ] } } } }"; please what are my doing wrong? ```
2017/04/24
[ "https://Stackoverflow.com/questions/43589797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5048493/" ]
one of the Admins at the messenger platform community just confirmed that webviews extension don't work on PC, so the only way i can get the User ID is by adding it to the URL on the URL button or through session variables.
I don't think that is a valid json format. It should be in double quotes not single quotes. Why don't you write in php array instead and convert to json to reduce your chances of making mistakes. eg. ``` $data = [ 'recipient' => [ 'id' => $sender_id ], 'message' => [ 'attachment' => [ 'type' => 'template', 'payload' => [ 'template_type' => 'button', 'text' => 'Click a button below to continue', 'buttons' => [ [ 'type' => 'web_url', 'url' => 'https://google.com', 'title' => 'Visit Google', "webview_height_ratio" => "compact" ] ] ] ] ]]; $json = json_encode($data); ```
295,392
30,611,740
I want to replace "." in this result: "172.16.0.25" with " dot ". Here is my code: ``` #!/bin/bash connection=`netstat -tn | grep :1337 | awk '{print $5}' | cut -d: -f1` #this returns "172.16.0.25" replace=" dot " final=${connection/./$replace} echo "$final" ``` Which returns: `test.sh: 4: test.sh: Bad substitution` I tried using `tr '.' ' dot '` but that only replaced the '.' with a space (' ') I know this is a really dumb question, but I'm new to Shell Script. Also, if it changes anything, I'm on a Raspberry Pi 2 running Raspbian.
2015/06/03
[ "https://Stackoverflow.com/questions/30611740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4164196/" ]
You can do the same with `awk` alone : ``` netstat -tn | awk '/:1337/{sub(/:.*/,"",$5);gsub(/\./," dot ",$5);print $5}' ``` If pattern `:1337` is matched, take the `5th` field. Now remove the `:number` part. Also replace `.` with `dot` and print the field.
You can simply use: ``` final="${connection//./$replace}" ``` Example: ``` #!/bin/bash connection="172.16.0.25" replace=" dot " final="${connection//./$replace}" echo "$final" ``` Output: ``` 172 dot 16 dot 0 dot 25 ```
147,366
55,122,592
I installed the [react-navigation](https://github.com/react-navigation/react-navigation) package in react-native I have implemented tab navigation and one of them is implemented in webview format. My problem is that if I press the back physical button on Android, I go from the app itself to the previous tab, not back from the webview. I've already applied the back button for the webview on the internet, but I have not done that. I tried to display the onNavigationStateChange log when debugging, but it was not updated when url was moved after it was loaded at first startup. Here is the code I implemented: ``` import React from "react"; import {BackHandler} from "react-native"; import {WebView} from "react-native-webview"; class SermonScreen extends React.Component { constructor(props) { super(props); } static navigationOptions = { header: null }; componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } _onNavigationStateChange(navState) { console.log(navState); this.setState({ canGoBack: navState.canGoBack }); } handleBackButton = () => { console.log(this.state); if (this.state.canGoBack === true) { this.webView.goBack(); return true; } else { return false; } }; render() { return ( <WebView source={{uri: 'https://m.youtube.com/channel/UCw3kP3qCCF7ZpLUNzm_Q9Xw/videos' }} ref={(webView) => this.webView = webView} onNavigationStateChange={this._onNavigationStateChange.bind(this)} /> ); } } export default SermonScreen; ```
2019/03/12
[ "https://Stackoverflow.com/questions/55122592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9779596/" ]
Following the official webview documnentation you could try to do this: <https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#intercepting-hash-url-changes> In general you were almost there, however the way the YT navigation works made it impossible to be caught via the *onNavigationStateChange*, that's why we inject a JS code that intercepts these hash changes and posts a message to the parent component, we then catch it inside the *onMessage* handler and set the state variable properly. Copying the *injectedJavaScript* and *onMessage* properties to your example should solve your problem. I prepared a component for you that seems to do what is needed: ``` * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, { Fragment } from "react"; import { SafeAreaView, StyleSheet, ScrollView, View, Text, BackHandler, StatusBar } from "react-native"; import { WebView } from "react-native-webview"; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from "react-native/Libraries/NewAppScreen"; class App extends React.Component { constructor(props) { super(props); this.startingUrl = "https://m.youtube.com/channel/UCw3kP3qCCF7ZpLUNzm_Q9Xw/videos"; this.handleBackButton = this.handleBackButton.bind(this); } componentDidMount() { BackHandler.addEventListener("hardwareBackPress", this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton); } handleBackButton = () => { console.log(this.state); const { canGoBack } = this.state; if (canGoBack) { this.webView.goBack(); return true; } else { return false; } }; render() { return ( <Fragment> <WebView source={{ uri: this.startingUrl }} style={{ marginTop: 20 }} ref={webView => (this.webView = webView)} injectedJavaScript={` (function() { function wrap(fn) { return function wrapper() { var res = fn.apply(this, arguments); window.ReactNativeWebView.postMessage('navigationStateChange'); return res; } } history.pushState = wrap(history.pushState); history.replaceState = wrap(history.replaceState); window.addEventListener('popstate', function() { window.ReactNativeWebView.postMessage('navigationStateChange'); }); })(); true; `} onMessage={({ nativeEvent: state }) => { if (state.data === "navigationStateChange") { // Navigation state updated, can check state.canGoBack, etc. this.setState({ canGoBack: state.canGoBack }); } }} /> </Fragment> ); } } export default App; ```
The response above was perfect. I set the state true for `canGoBack` though; I was getting a null error, so: ```js constructor(props) { super(props); this.startingUrl = "https://app.vethorcardpag.com.br/GIF/login/0/"; this.state = { canGoBack : true } this.handleBackButton = this.handleBackButton.bind(this); } ```
363,094
3,763,103
How should I prove $$\forall n\in\mathbb{N}:\, \frac{e^{\frac{\pi i}{4}}}{\sqrt{2}}\left(1+e^{-(2n+1)\frac{\pi i}{2}}\right)-e^{\frac{n^2\pi i}{2}}=0?$$ My attempt: $$\begin{align}\frac{e^{\frac{\pi i}{4}}}{\sqrt{2}}\left(1+e^{-(2n+1)\frac{\pi i}{2}}\right)-e^{\frac{n^2\pi i}{2}}&=\frac{1}{\sqrt{2}}\left(e^{\frac{\pi i}{4}}+e^{-n\pi i-\frac{\pi i}{2}+\frac{\pi i}{4}}\right)-e^{\frac{n^2\pi i}{2}}\\&=\frac{1}{\sqrt{2}}\left(e^{\frac{\pi i}{4}}+e^{-i\left(n\pi +\frac{\pi}{4}\right)}\right)-e^{\frac{n^2\pi i}{2}}\\&=\frac{1}{\sqrt{2}}\left(\cos\frac{\pi}{4}+i\sin\frac{\pi}{4}+\frac{1}{\cos\left(n\pi +\frac{\pi}{4}\right)+i\sin\left(n\pi +\frac{\pi}{4}\right)}\right)-e^{\frac{n^2\pi i}{2}}\\&=\frac{1+i}{2}+\frac{1}{\sqrt{2}}\frac{1}{\frac{1}{\sqrt{2}}(\cos n\pi -\sin n\pi )+\frac{i}{\sqrt{2}}(\cos n\pi +\sin n\pi)}-e^{\frac{n^2\pi i}{2}}\\&=\frac{1+i}{2}+\frac{1}{\cos n\pi +i\cos n\pi}-e^{\frac{n^2\pi i}{2}}\\&=\frac{1+i}{2}+\frac{1}{i^{2n}+i^{2n+1}}-i^{n^2}\end{align}$$ How should I proceed?
2020/07/20
[ "https://math.stackexchange.com/questions/3763103", "https://math.stackexchange.com", "https://math.stackexchange.com/users/694553/" ]
**HINT:** from your last line, consider the two different cases, according with $n$ odd and even.
Let $f=\frac{e^{\frac{\pi i}{4}}}{\sqrt{2}}\left(1+e^{-(2n+1)\frac{\pi i}{2}}\right)-e^{\frac{n^2\pi i}{2}}$. Then $$\begin{align}f&=\frac{1}{\sqrt{2}}\left(e^{\frac{\pi i}{4}}+e^{-(2n+1)\frac{\pi i}{2}+\frac{\pi i}{4}}\right)-e^{\frac{n^2\pi i}{2}}\\&=\frac{1}{\sqrt{2}}\left(e^{\frac{\pi i}{4}}+e^{-i\left(n\pi +\frac{\pi}{2}-\frac{\pi}{4}\right)}\right)-e^{\frac{n^2\pi i}{2}}\end{align}$$ and $$\begin{align}\operatorname{Re}f&=\frac{1}{\sqrt{2}}\left(\cos\frac{\pi}{4}+\cos\left(n\pi +\frac{\pi}{4}\right)\right)-\cos\frac{n^2\pi}{2}\\&=\frac{1}{\sqrt{2}}\left(\frac{\sqrt{2}}{2}+\frac{1}{\sqrt{2}}\left(\cos n\pi -\sin n\pi \right)\right)-\cos \frac{n^2\pi}{2}\\&=\frac{1}{2}+\frac{1}{2}\cos n\pi -\cos\frac{n^2\pi}{2}\\&=\frac{1+(-1)^n}{2}-\cos \frac{n^2\pi}{2}.\end{align}$$ Since $\frac{1+(-1)^n}{2}=0$ for odd $n$ and $\frac{1+(-1)^n}{2}=1$ for even $n$ and $\cos\frac{n^2\pi}{2}=0$ for odd $n$ and $\cos\frac{n^2\pi}{2}=1$ for even $n$, $\operatorname{Re}f=0$ for $n\in\mathbb{N}$. Similarly for $\operatorname{Im}f$: $$\operatorname{Im}f=\frac{1-(-1)^n}{2}-\sin\frac{n^2\pi}{2}.$$ Since $\frac{1-(-1)^n}{2}=1$ for odd $n$ and $\frac{1-(-1)^n}{2}=0$ for even $n$ and $\sin\frac{n^2\pi}{2}=1$ for odd $n$ and $\sin\frac{n^2\pi}{2}=0$ for even $n$, $\operatorname{Im}f=0$ for $n\in\mathbb{N}$. Therefore $f=0$ for all $n\in\mathbb{N}$.
292,364
27,058,036
Why when I use setSelector method it returns neither Camera activities nor Gallery Activities.I have the following code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent camera= new Intent("android.media.action.IMAGE_CAPTURE"); Intent gallery = new Intent(); gallery.setAction(android.content.Intent.ACTION_VIEW); gallery.setType("image/*"); gallery.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); camera.setSelector(gallery); startActivity(camera); } ``` According to Android's reference API "*If the selector is set, it will be used when trying to find entities that can handle the Intent, instead of the main contents of the Intent.*" I thought that I will get a dialog that opens the gallery instead of camera. But, instead of these I got a dialog that returns arbitrary applications/activities, such as *Call Settings*, *Network Settings*, *SIM Toolkit*, etc. When I remove the `camera.setSelector(gallery);` method everything works like a charm, but when I use `camera.setSelector(gallery);` method it returns neither Camera activities nor Gallery Activities. Could somebody explain me why I got a dialog with these arbitrary activities instead of appropriate? I don't want to remove the `camera.setSelector(gallery);` because I am trying to understand how it works!
2014/11/21
[ "https://Stackoverflow.com/questions/27058036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1392366/" ]
It assigns the array's first element using Ruby's [multiple assignment](http://www.ruby-doc.org/core-2.1.5/doc/syntax/assignment_rdoc.html#label-Multiple+Assignment): ``` a, = [1, 2, 3] a #=> 1 ``` Or: ``` a, b = [1, 2, 3] a #=> 1 b #=> 2 ``` You can use `*` to fetch the remaining elements: ``` a, *b = [1, 2, 3] a #=> 1 b #=> [2, 3] ``` Or: ``` *a, b = [1, 2, 3] a #=> [1, 2] b #=> 3 ```
It works like this. If `lhs` has single element and `rhs` has multiple values then `lhs` gets assigned an array of values, like this. ``` a = 1,2,3 #=> a = [1,2,3] ``` Whereas if `lhs` has more elements than `rhs`, then excess elements in `lhs` are discarded ``` a,b,c = 1,2 #=> a = 1, b = 2, c = nil ``` Therefore `a, = 1,2,3 #=> a = 1`. The rest i.e. [2,3] are discarded
317,791
18,249,027
I currently have multiple projects being build using msbuild. I have a small customisation to the build that is handled by a .targets file. One solution is to add the snippet ``` <Import Project="MyTargets.targets"/> ``` to each project file. However, ideally I would like to not touch the project files, and be able to pass this information as a parameter to msbuild. That way I could easily control whether I run this customisation from the command line, *and* I don't have to touch the existing project files. Is this possible?
2013/08/15
[ "https://Stackoverflow.com/questions/18249027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382536/" ]
Starting from MSBuild 15.0, the following two files are auto-imported into your build in case they are found on the project path or in any parent folder on the path to the root directory: * Directory.Build.props * Directory.Build.targets Remark: once the props or targets file is found, MSBuild will stop looking for a parent one. Also see: <https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build>
Make sure you use an **absolute path** to the target file and it works. Source: [Sayed Ibrahim Hashimi - MSBuild how to execute a target after CoreCompile part 2](http://sedodream.com/2012/07/28/MSBuildHowToExecuteATargetAfterCoreCompilePart2.aspx). ``` msbuild.exe /p:CustomBeforeMicrosoftCSharpTargets="c:\mytargets\custom.targets" /preprocess:out.xml ``` Use `/preprocess[:filepath]` to see the result of the imports. You don't have to modify any `csproj` or `vbproj` files. Of course, it only works where you can set MSBuild Properties.
120,337
50,468,721
I have to convert texts like > > Example "Example Text" to Example "example text" > > > > EXAMPLE "EXAMPLE TEXT" to EXAMPLE "example text" > > > could you help with regex doing this?
2018/05/22
[ "https://Stackoverflow.com/questions/50468721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3625690/" ]
This isn't exactly what I'd call pretty, but it works and is relatively similar to what you described for C++; It works by calling [`get_parent_class()`](https://secure.php.net/manual/en/function.get-parent-class.php) and then abusing PHP's ability to create objects from strings. ``` <?php class Foo { public function func() { echo 'foo'; } } class Bar extends Foo { public function func() { echo 'bar'; } } $obj = new Bar(); $obj->func(); // Prints 'bar' $parentClassString = get_parent_class($obj); $newObj = new $parentClassString; // Gotta love PHP for magic like this $newObj->func(); // Prints 'foo' ``` See [this snippet](https://3v4l.org/7DLt6) to see it in action. **EDIT** It's a lot of work, but you could use so called [Late Static Binding](https://secure.php.net/manual/en/language.oop5.late-static-bindings.php), perhaps more clearly explained in [Jokerius's answer here](https://stackoverflow.com/a/20073664/4074200). This requires you to write a crapload of custom code though, which I don't think is preferential. Overall the short answer seems to be: it isn't really possible.
I don't know should it help you but try to add this function in Bar class ``` public function callParent($function){ return parent::$function(); } ``` and call ``` echo $obj->callParent("func"); ``` [UPDATED] Also you can write cast function yourself something like this ``` public function castAs($newClass) { $obj = new $newClass; foreach (get_object_vars($this) as $key => $name) { $obj->$key = $name; } return $obj; } ```
307,700
2,508,284
suppose I have a class with many explicit (statically allocated) members and few pointers that are allocated dynamically. When I declare a copy constructor in witch I make a deep copy of manually allocated members, I wouldn't like to copy each statically allocated member explicite. How can I use implicit (default) copy constructor functionality in explicit copy constructor?
2010/03/24
[ "https://Stackoverflow.com/questions/2508284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/263912/" ]
Use **containment**: ``` class outer { public: outer( const outer& other ) : members_( other_.members_ ), pmember_( deep_copy( other.pmember_ )) {} // DON'T FORGET ABOUT THESE TOO outer& operator=( const outer& ); ~outer(); private: struct inner { inner( int i, float f ) : int_( i ), float_( f ) {} int int_; float float_; }; inner members_; //< direct members something* pmember_; //< indirect member }; ```
I would declare the dynamically allocated members under a structure and then memcpy() them; ``` #define _WIN32_WINNT 0x0400 #define WIN32_LEAN_AND_MEAN #include <windows.h> class MyClass { private: static int some_static_member; public: struct DynamicallyAllocated { int x, y, z; } *dyn; public: MyClass(MyClass* copy = NULL) { this->dyn = NULL; if(copy != NULL) { if(copy->dyn != NULL) { this->dyn = new DynamicallyAllocated(); memcpy(this->dyn, copy->dyn, sizeof(*this->dyn)); } } } }; int MyClass::some_static_member = 0; void main() { MyClass mc1(NULL); mc1.dyn = new MyClass::DynamicallyAllocated(); mc1.dyn->x = 1; mc1.dyn->y = 2; mc1.dyn->z = 3; MyClass mc2(&mc1); } ``` You have to "group" the members inside a struct so when using memcpy() you won't overwrite some C++ "other data" such as virtual functions' pointers.
22,278
579,396
Edit: I think I found the issue: GNUplot adds a to the second timestamp to the top of the \*.tex file it generates, so of course latexmk thinks it has changed. `%% 2021-01-18 11:32:42 AM` I usually use `latexmk` to compile my documents as that saves a lot of manual work figuring out how many times I need to compile it. However, if I use `gnuplottex` with it, every single run it says `Changed files, or newly in use since previous run(s): 'loop-gnuplottex-fig1.tex'` Which...shouldn't be true? It might be being written every time, but it isn't changed. Is there a way around this, so that minor changes to my document don't trigger five runs of pdflatex, as that takes a very long time on my desktop, and an interminable one on my laptop. Here is a MWE that triggers this issue. It is not as easy to compile as I would like as one needs to install Gnuplot for it to work, then copy three files from GNUplot's `\share\texmf\tex` directory structure to somewhere TeX can find them. (It appears at one point this was supposed to happen automatically if you installed LaTeX after GNUplot based on the config files in GNUplot). Also, this MWE only works on Windows: You must unset the "miktex" option if compiling it on a Postix system. ``` \documentclass{article} \usepackage{shellesc} \usepackage{gnuplot-lua-tikz} %Note, you need GNUplot installed for this to compile, %and need to copy three files from GNUplot to somewhere TeX can find them! \usepackage[miktex]{gnuplottex} %MiKTeX means windows since they can't do basic testing, unset if on *nix \begin{document} \begin{gnuplot}[terminal=tikz, terminaloptions=color] plot sin(x) \end{gnuplot} \end{document} ``` I SUSPECT that this issue might be related to [this question](https://tex.stackexchange.com/questions/106512/gnuplot-in-latex-without-gnuplottex), but there is no worked examples, so I'm not exactly sure about how to set up my document to use what they are talking about, but it sounds like it bypasses this package entirely and speeds compilation a lot.
2021/01/18
[ "https://tex.stackexchange.com/questions/579396", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/7880/" ]
It would have helped if your MWE compiled without errors. However, try this: ``` % appendixprob.tex SE 579384 \documentclass[12pt,notitlepage]{article} %\DeclareCaptionLabelFormat{AppendixTables}{Table A.#2} %% causes an error \usepackage{appendix} %% could be useful but not necessary \begin{document} \section{A section} \appendix %\begin{appendices} \renewcommand{\thesection}{\arabic{section}} \renewcommand{\thesection}{\hspace{0.5em}} % no number but align with section titles \renewcommand{\thesubsection}{\Alph{section}.\arabic{subsection}} \section{Appendix} %\captionsetup{labelformat=AppendixTables} %% causes an error \setcounter{table}{0} \subsection{Subsection 1} \subsection{Subsection 2} %\end{appendices} \end{document} ``` It does what you want regarding the numbering of `\section{Appendix}` but I have no idea if the positioning is what you want. It is up to you to deal with the numbering of floats. [![enter image description here](https://i.stack.imgur.com/jp8HX.png)](https://i.stack.imgur.com/jp8HX.png)
Add manually the appendix. ``` \documentclass[12pt,letterpaper]{article} \counterwithin{table}{section} \newcommand{\singleappendix}[1]{% \appendix \section*{#1} \addcontentsline{toc}{section}{#1} \stepcounter{section} } \begin{document} \tableofcontents \section{Introduction} \begin{table}[htp] \caption{This is a table caption} \end{table} \singleappendix{Appendix} \subsection{Subsection 1} \subsection{Subsection 2} \begin{table}[htp] \caption{This is a table caption} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/1nwi6.png)](https://i.stack.imgur.com/1nwi6.png)
348,185
38,683,051
I am trying to find matches with pattern: ``` GiM 00 (1234/5678 DF) (90,00% ``` The matches need to fulfil some conditions 1. The "00" needs to be higher than 20 2. The percentage needs to be 90,00% or higher One note, the "1234/5678" can be from a two digit number up to a four digit number. Any ideas on how to achieve this?
2016/07/31
[ "https://Stackoverflow.com/questions/38683051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045512/" ]
If by the first point you mean to match 20..99, here's the regex: ``` GiM [2-9]\d \(\d{2,4}\/\d{2,4} DF\) \(((100,00)|(9\d,\d\d))% ```
> > The "00" needs to be higher than 20 > > > Use `(2[1-9]|[3-9]\d)` to match two-digit numbers strictly above 20 > > The percentage needs to be 90,00% or higher > > > Use `9\d,\d\d%` to match percentages greater than or equal to 90,00% > > the "1234/5678" can be from a two digit number up to a four digit number > > > Use `\d{2,4}` to match two-digit numbers to four-digit numbers. This will match numbers with leading zeros: for example `0003` would be matched as a four-digit number. [Demo.](https://regex101.com/r/uX9iF9/1)
220,400
36,749,119
I have a JSON-String array, where its entry has the following properties, *firstName*, *lastName*, *loginName*, *Country*, *phoneNumber*, and *status*. Here's an example ``` [ { "firstName": "Patrick", "lastName": "Smith", "loginName":"[email protected]", "Country":"US", "phoneNumber": "287 125-1434", "status": "340" }, { "firstName": "Bob", "lastName": "Williams", "loginName":"[email protected]", "Country":"US", "phoneNumber": "213 111-9943", "status": "215" }, { "firstName": "John", "lastName": "Johnson", "loginName":"[email protected]", "Country":"DE", "phoneNumber": "212 555-1234", "status": "167" }, { "firstName": "George", "lastName": "Jones", "loginName":"[email protected]", "Country":"FR", "phoneNumber": "217 987-2634", "status": "340" } ] ``` Now, I want to search for a specific entry based on the properties *loginName* and *status* For example * **loginName:** [email protected] * **status:** 167 ``` { "firstName": "John", "lastName": "Johnson", "loginName":"[email protected]", "Country":"DE", "phoneNumber": "212 555-1234", "status": "167" } ``` What would be the most optimized solution?
2016/04/20
[ "https://Stackoverflow.com/questions/36749119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930099/" ]
I use JSONObject and here is another way to parse. 1. Parse using `JSONArray` 2. Loop the array and read into UserProfile objects 3. Store it in HashMap to get using key ``` import java.util.HashMap; import java.util.Map; import org.json.*; class UserProfile{ String loginName; int status; String firstName; String key; UserProfile(){ } String getLoginName(){ return loginName; } String getFirstName(){ return firstName; } void setKey(String key){ this.key = key; } void setLoginName(String loginName){ this.loginName = loginName; } void setStatus(int status){ this.status = status; } void setFirstName(String firstName){ this.firstName = firstName; } } public class JSONObjParser { public static void main(String[] args){ Map<String, UserProfile> map = new HashMap<String, UserProfile>(); String msg ="[{ firstName: Patrick, lastName: Smith, loginName:[email protected], Country:US, phoneNumber: 287 125-1434, status: 340 }, { firstName: Bob, lastName: Williams, loginName:[email protected], Country:US, phoneNumber: 213 111-9943, status: 215 }]"; JSONArray jsonarray = new JSONArray(msg); for (int i = 0; i < jsonarray.length(); i++) { JSONObject jsonobject = jsonarray.getJSONObject(i); String loginName = jsonobject.getString("loginName"); int status = jsonobject.getInt("status"); String firstName = jsonobject.getString("firstName"); UserProfile profile = new UserProfile(); profile.setFirstName(firstName); profile.setLoginName(loginName); profile.setStatus(status); String key = loginName + Integer.toString(status); map.put(key, profile); } for (String key : map.keySet()) { UserProfile profile = map.get(key); System.out.println("Key = " + key + ", FirstName = " + profile.getFirstName()); } } } ```
Using Jackson, this is the crudest snippet I can think of: ``` private static ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws IOException { System.out.println(filterJsonArray(JSON, "loginName", "[email protected]", "status", "167")); } public static String filterJsonArray(String array, String keyOne, Object valueOne, String keyTwo, Object valueTwo) throws IOException { Map[] nodes = mapper.readValue(array, HashMap[].class); for (Map node : nodes) { if (node.containsKey(keyOne) && node.containsKey(keyTwo)) { if (node.get(keyOne).equals(valueOne) && node.get(keyTwo).equals(valueTwo)) { return mapper.writeValueAsString(node); } } } return null; } ``` Of course it will only returns the first match to the given pairs. If you need all the values, make it return a list instead and populate it inside the loop.
232,277
9,839,958
I have a huge text file in english which I have to convert to Hindi Or say any other language. I am reading each line of the text file and converting the english strings to Hindi using <http://api.microsofttranslator.com/V2/Ajax.svc/Translate>. So far there are no issues and text is translated and displayed on the screen. Now I want to save this converted text and re-use it. When I save and open the file say in Notepad I see only junk characters and If I now read this file and reverse it to English the chacters displayed on the screen are also junk and not english as expected. Please help with some source code. I am open to both .NET or JAVA. Regards
2012/03/23
[ "https://Stackoverflow.com/questions/9839958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617293/" ]
This isn't a good idea. (This is right at the borderline between an answer and a comment, but I wanted to give examples hard to cram into a comment.) The .sage file either contains Sage-specific syntax and behaviour or it doesn't. If it doesn't, you can simply rename it to .py, or make a symbolic link, or whatever. But if it does, then you're going to have to preparse it anyway before it'll work in Python. For example, if the "functions.sage" file writes: ``` x = 2/3 ``` if you load the file into sage, you get an element of QQ: ``` sage: x 2/3 sage: parent(x) Rational Field ``` but in Python 2, you'd simply get int(0). It might use Sage-style ranges: ``` sage: [1,3,..,11] [1, 3, 5, 7, 9, 11] ``` or other Sage features: ``` sage: F.<x,y> = GF(2)[] sage: F Multivariate Polynomial Ring in x, y over Finite Field of size 2 ``` and all of these are dealt with by the Sage preparser, not by Python. Behind the scenes, it's doing this: ``` sage: preparse("F.<x,y> = GF(2)[]") "F = GF(Integer(2))['x, y']; (x, y,) = F._first_ngens(2)" ``` UPDATE: Apparently I didn't make the problem clear enough. ``` sage: import imp sage: !cat functions.sage x = 2/3 sage: functions = imp.new_module("functions") sage: execfile("functions.sage", vars(functions)) sage: dir(functions) ['__builtins__', '__doc__', '__name__', '__package__', 'x'] sage: functions.x 0 sage: type(functions.x) <type 'int'> ``` One way or another, you're going to have to pass functions.sage through the preparser.
You could try using [execfile](http://docs.python.org/library/functions.html#execfile) to read the file. Not used it before myself, but looks like it reads the file contents into local scope.
248,714
5,691,336
I'd like a basic C++ STL-like container for the filesystem. e.g. ``` std::filesystem::const_iterator i = filesys.begin(); i->file_name(); i->full_path(), ``` etc.. Does something like that exist?
2011/04/17
[ "https://Stackoverflow.com/questions/5691336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504239/" ]
Another one is [STLSOFT](http://www.stlsoft.org/) platformstl::readdir\_sequence. Example provided [here](https://stackoverflow.com/questions/4794755/stlsoft-how-to-use-their-file-system-functionality)
I believe the [boost::filesystem](http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/index.htm) library has this functionality.
225,317
724,797
While using a macro in outlook to move an email into a subfolder, the receipt date is not preserved. Does anyone has an idea on how to avoid that?
2009/04/07
[ "https://Stackoverflow.com/questions/724797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88012/" ]
I found that the macro changes the ModifiedTime parameter which is actually right. What is wrong is that outlook in the folder view does -in column Receveid- not show the ReceivedTime, but the ModifiedTime. I also found that the Modified Column (normally not visible) contains the actual RecievedTime. So a remedy is to keep the macro as is, but add (right mouse button on the columns in a folder view) the Modified column to the view and optionally removed the Received column. You will find Modified in the "All Post fields" section.
Not an answer.. but here is some code that replicates the problem. Can't seem to find an answer to this anywhere. Quite a few people asking the question though. ``` Sub MoveToFolder(objFolder As Outlook.MAPIFolder) 'On Error Resume Next If objFolder Is Nothing Then MsgBox "This folder doesn't exist!", vbOKOnly + vbExclamation, "INVALID FOLDER" End If If Application.ActiveExplorer.Selection.Count = 0 Then Exit Sub End If Dim objItem As Outlook.MailItem For Each objItem In Application.ActiveExplorer.Selection If objFolder.DefaultItemType = olMailItem Then If objItem.Class = olMail Then objItem.Move objFolder End If End If Next Set objItem = Nothing Set objFolder = Nothing End Sub ```
103,108
415,403
I've used a number of different \*nix-based systems of the years, and it seems like every flavor of Bash I use has a different algorithm for deciding which startup scripts to run. For the purposes of tasks like setting up environment variables and aliases and printing startup messages (e.g. MOTDs), which startup script is the appropriate place to do these? What's the difference between putting things in `.bashrc`, `.bash_profile`, and `.environment`? I've also seen other files such as `.login`, `.bash_login`, and `.profile`; are these ever relevant? What are the differences in which ones get run when logging in physically, logging in remotely via ssh, and opening a new terminal window? Are there any significant differences across platforms (including Mac OS X (and its Terminal.app) and Cygwin Bash)?
2009/01/06
[ "https://Stackoverflow.com/questions/415403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9530/" ]
I found information about .bashrc and .bash\_profile [here](http://lists.debian.org/debian-user/1999/06/msg00062.html) to sum it up: > > .bash\_profile is executed when you > login. Stuff you put in there might be > your PATH and other important > environment variables. > > > .bashrc is used for non login shells. > I'm not sure what that means. I know > that RedHat > executes it everytime you start > another shell (su to this user or > simply calling bash again) You might > want to put aliases in there but again > I am not sure what that means. I > simply ignore it myself. > > > .profile is the equivalent of > .bash\_profile for the root. I think > the name is changed to let other > shells (csh, sh, tcsh) use it as well. > (you don't need one as a user) > > > There is also .bash\_logout wich > executes at, yeah good guess...logout. > You might want to stop deamons or even > make a little housekeeping . You can > also add "clear" there if you want to > clear the screen when you log out. > > > Also there is a complete follow up on each of the configurations files [here](http://www.thegeekstuff.com/2008/10/execution-sequence-for-bash_profile-bashrc-bash_login-profile-and-bash_logout/) These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.
A good place to look at is the man page of bash. [Here](http://linux.die.net/man/1/bash)'s an online version. Look for "INVOCATION" section.
335,692
107,523
Is it bad practice and unprofessional to complete penetration tests from distant cities, without meeting your clients in person?
2015/12/08
[ "https://security.stackexchange.com/questions/107523", "https://security.stackexchange.com", "https://security.stackexchange.com/users/93929/" ]
The most important thing for a penetration test to be successful is that the client's expectations is clearly communicated to the tester. This can be done face to face or remotely. A face to face meeting can be very helpful in this, but it is not necessary and I've seen very good penetration testing done without meeting anyone from the testing organization because the requirements were communicated effectively. This was done by documenting the requirements and then calls over the phone to answer questions. If the testers are a business rather than a single individual then you probably aren't going to meet the people who will perform the test anyway, you are more likely to meet a sales rep and sales staff while the "real work" may be done by a completely different set of people.
Please refer to below lines from <http://www.pentest-standard.org/index.php/Pre-engagement#Rules_of_Engagement> "One of the most important documents which need to be obtained for a penetration test is the Permission to Test document. This document states the scope and contains a signature which acknowledges awareness of the activities of the testers. Further, it should clearly state that testing can lead to system instability and all due care will be given by the tester to not crash systems in the process. However, because testing can lead to instability the customer shall not hold the tester liable for any system instability or crashes. It is critical that testing does not begin until this document is signed by the customer."
89,168
46,987,916
We have a query in which a list of parameter values is provided in "IN" clause of the query. Some time back this query failed to execute as the size of data in "IN" clause got quite large and hence the resulting query exceeded the 16 MB limit of the query in REDSHIFT. As a result of which we then tried processing the data in batches so as to limit the data and not breach the 16 MB limit. My question is what are the factors/pitfalls to keep in mind while supplying such large data for the "IN" clause of a query or is there any alternative way in which I can deal with such large data for the "IN" clause?
2017/10/28
[ "https://Stackoverflow.com/questions/46987916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7689836/" ]
If you have control over how you are generating your code, you could split it up as follows first code to be submitted, drop and recreate filter table: ``` drop table if exists myfilter; create table myfilter (filter_text varchar(max)); ``` Second step is to populate the filter table in parts of a suitable size, e.g. 1000 values at a time ``` insert into myfilter values({{myvalue1}},{{myvalue2}},{{myvalue3}} etc etc up to 1000 values ); ``` repeat the above step multiple times until you have all of your values inserted Then, use that filter table as follows ``` select * from master_table where some_value in (select filter_text from myfilter); drop table myfilter; ```
Large IN is not the best practice itself, it's better to use joins for large lists: 1. construct a virtual table a subquery 2. join your target table to the virtual table like this ``` with your_list as ( select 'first_value' as search_value union select 'second_value' ... ) select ... from target_table t1 join your_list t2 on t1.col=t2.search_value ```
366,839
324,434
I am working on a Spring/JSF app in which i have 1 scheduler to load user's sleep activity from fitbit. Right now what i do is that whenever the scheduler kicks in, I load `ALL` users from `mongoDB` and for each user i send a request to *fitbit* api to fetch `sleep` activity and save it in `mongoDB` one by one. As of now, its working fine however, once the user grows to million, this one scheduler could take sometime to execute. Not to mention, I am loading ALL users at once. Right now what i am trying to research is (seeking help here if i am right track or not) 1. Group users someway and fetch user sleep group by group. Or i can use `pagination` here. 2. For each user, I can spawn a separate thread and let that thread finish independently without hogging the scheduler which is being called by spring container. Am i on the right track or are there any better way to do so ? Also, right now, I am using only sleep activity, in future there will be more activities that i have to fetch from fitbit.
2016/07/10
[ "https://softwareengineering.stackexchange.com/questions/324434", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/52293/" ]
This would be a good use for a producer/consumer setup. Without going into the implementation in detail, you'd have one component whose job it is to pull the list of users from the DB and add them all to a queue. This could be triggered by your timer. Then, you'd have a component which sits there in a loop pulling an item from the queue, making the API request and saving the data. When you need to go faster you can just add more instances of that second component - so you still have a single producer (adding items to the queue) but multiple consumers (pulling from the queue and doing the work). In terms of implementation there's a bunch of ways to do it - Java has a lot of support for such things, typically based around [BlockingQueue](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html). If it were me I'd use [Akka](http://akka.io/), but that's a whole other question :)
Here is my take on this : The requirement is to find out the sleeping activity of the user ids that are stored in MongoDB which can grow till 1 Million. Later this requirement can be extended to pull other activities of the user. To build a decoupled scalable system, you can create 2 services. Service 1 : picks up the userIds from mongoDB or other datasources (if want to change it to something else tomorrow) and keep it in a Queue Service. I would suggest using a cloud-based Queue Service like SQS. Service 2 : Picks up the data from a Queue and tries to contact 3rd party services like FitBit to get the activity. Let us say if Fitbit service is down/ or your service became quite popular and if there is a surge in the users you can increase the hosts that can consume the messages. You can use Auto-Scale feature of Amazon Webservices to take care of autoscaling. Let's say tomorrow you want to fetch more activities of users from other systems like Google Fit to summarize all their fitness activities the same architecture works perfectly. The only change you need to do is to use a Simple Notification Service, instead of SQS which pushes the user ids into various SQS queues and each queue will be consumed by a different activity handler to process the data and updates your datastore.
9,244
17,258,653
I need to make an app internationalization, so I create the folder "values-zh-rCN", and copy all the files in the folder "values" to the folder "values-zh-rCN". I translate the files strings.xml and array.xml in the folder "values-zh-rCN" to chinese, but I find I need not translate anything in the files styles.xml and dimens.xml in the folder "values-zh-rCN". Can I delete the two files styles.xml and dimens.xml in the folder "values-zh-rCN"? Thanks!
2013/06/23
[ "https://Stackoverflow.com/questions/17258653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828896/" ]
Yes. Android will use the files in the default folder (values instead of values-xxx) if they are not present in a more specific folder. For example I have an app with 6 files in values but only two in values-fr (strings and string-arrays), one in values-sw600dp and values-sw720dp (dimens), one in values-v11 (styles) and two in values-v17 (styles and dimens). In each I only define the elements that are different from the default value and Android use those when appropriate and use the default when not.
Yes you can. Read this [article](http://developer.android.com/training/basics/supporting-devices/languages.html) it will help you. Best wishes.
179,639
66,514,374
I have two models like below. I'm using Django restframework. ``` class Family(models.Model): name= models.CharField(max_length=100) class Parishioner(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) family = models.ForeignKey(Family, on_delete=models.CASCADE) ``` There are my ViewSets ``` class FamilyViewSet(viewsets.ModelViewSet): queryset = Family.objects.all() serializer_class = FamilySerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ``` These are my Serializers ``` class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) class ParishionerSerializer(serializers.ModelSerializer): class Meta: model = Parishioner fields = ('id', 'first_name', 'last_name', 'family') read_only_fields = ('id',) depth = 1 ``` So basically `Parishioner` can have one `Family`. `Family` has multiple `members(Parishioners)` Currently I have to go to all `Parishioners` and select the `Family`. is it possible to add a field called `members` to `Family` model, where members would be an `Array` of `Existing Parishioners` ? or is there any other way to handle this ? [![enter image description here](https://i.stack.imgur.com/2Q82M.png)](https://i.stack.imgur.com/2Q82M.png)
2021/03/07
[ "https://Stackoverflow.com/questions/66514374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8089694/" ]
It would be a bad idea to do this at the database side, since that would mean the database does no longer check this. But you can easily do this in the serializer. We do this by adding an instance of the `ParishionerSerializer` to the `FamilySerializer`. We need to define the `ParishionerSerializer` *before* the `FamilySerializer`, since otherwise, that identifier is not yet assigned: ``` class ParishionerSerializer(serializers.ModelSerializer): class Meta: model = Parishioner fields = ('id', 'first_name', 'last_name', 'family') read_only_fields = ('id',) depth = 1 class FamilySerializer(serializers.ModelSerializer): **parishioner\_set = ParishionerSerializer(many=True, read\_only=True)** class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) ``` You can rename it to `members` at the model layer and then update the serializer accordingly, or only in the subserializer. Option 1: use `related_name=…` ============================== We can rename the relation in reverse to `memebers` by specifying a value for the [**`related_name=…`** [Django-doc]](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name): ``` class Parishioner(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) family = models.ForeignKey( Family, on_delete=models.CASCADE, **related\_name='members'** ) ``` then the serializer thus uses `member` instead: ``` class FamilySerializer(serializers.ModelSerializer): **members** = ParishionerSerializer(many=True, read_only=True) class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) ``` Option 2: rename the serializer with `source=…` =============================================== We can also only specify this at the serializer level, by specifying a [**`source=…`** parameter [drf-doc]](https://www.django-rest-framework.org/api-guide/fields/#source): ``` class FamilySerializer(serializers.ModelSerializer): **members** = ParishionerSerializer( **source='parishioner\_set'**, many=True, read_only=True ) class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) ```
Fam = Family.objects.get(id=1) Fam.parishioner\_set.all() This should do
235,380
51,619,001
I have a problem using `getElementsByClassName`. When clicking on the add button, it appears on the list with the name `undefined` and not the value `"hello"`. What am I doing wrong? CODE: ```js function addItem(){ var ul = document.getElementById("dynamic-list"); var candidate = document.getElementsByClassName("candidate"); var li = document.createElement("li"); li.setAttribute('class',candidate.value); li.appendChild(document.createTextNode(candidate.value)); ul.appendChild(li); } function removeItem(){ var ul = document.getElementById("dynamic-list"); var candidate = document.getElementsByClassName("candidate"); var item = document.getElementsByClassName(candidate.value); ul.removeChild(item); } ``` ```html <ul id="dynamic-list"></ul> <button type="submit" class="item" value="hello" onclick="addItem()">ADD</button> <button onclick="removeItem()">remove item</button> ```
2018/07/31
[ "https://Stackoverflow.com/questions/51619001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6797365/" ]
It may be a pretty heavy action but you can do like that: ``` var randomNumbers: [Int] = [] while randomNumbers.count != 30{ let number = Int(arc4random_uniform(1000) + 1) if randomNumbers.contains(number) { print("Already Exits") }else{ randomNumbers.append(number) } } ``` replace "1000" for a range of number that you need. That function generated 30 different number between 0...1000
Here is a simple solution. Start a `while` loop. Within this loop generate a random number (between 0 and 1000). And then append the number into your array if the array doesn't contains the number. ``` func generateArrayOfRandomNumbers() -> [Int] { var array: [Int] = [] while array.count < 30 { let randomInt = Int.random(in: 0...1000) guard !array.contains(randomInt) else { continue } array.append(randomInt) } return array } ```
105,377
24,449,712
I want to know is there any keyboard short cut in ubuntu to edit last sent message on skype.
2014/06/27
[ "https://Stackoverflow.com/questions/24449712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3467205/" ]
This is the closest I got with **jade** ([live playground here](http://jade-lang.com)): ``` mixin e(elt) - var a = attributes; - var cl = attributes.class;delete attributes.class - var elt = elt ? elt : 'div' // If no parameter given if cl - var cl = parent + '-' + cl else - var cl = parent #{elt}&attributes({'class': cl}, attributes) block - var parent = 'box' +e('aside')#so-special +e('h2').title Related +e('ul').list +e('li').item: +e('a')(href='#').link Item 1 +e('li').item: +e('span').link.current Item 2 and current +e('li').item#third(data-dash='fine', aria-live='polite') Item 3 not even a link | multi-line | block // - var parent = 'other' problem of scope I guess +e('li').item lorem ipsum dolor sit amet - var parent = 'footer' +e('footer')(role='contentInfo') +e.inner © Company - 2014 ``` A mixin named `e` will output an element taken as a parameter (default is `div`) with its attributes and content as is, except for the first class that'll be prefixed with the value of the variable `parent` (or will be the value of `parent` itself if it hasn't any class) I prefer using default jade syntax for attributes, including class and id than passing many parameters to a mixin (this one doesn't need any if it's a div, as with `.sth text`'d output `<div class="sth>text</div>` and `+e.sth text` will output `<div class="parent-sth>text</div>`) Mixin would be shorter if it didn't have to deal with other attributes (href, id, data-\*, role, etc) Remaining problem: changing the value of `parent` has no effect when it's indented. It had with simpler previous attempts so I guess it's related to scope of variables. You theoretically don't want to change the prefix for child elements but in practice... Maybe as a second optional parameter? Things I had problem with while playing with jade: * attributes doesn't work as expected. Now it's `&attributes(attributes)`. Thanks to [jade-book issue on GitHub](https://github.com/slang800/jade-book/issues/16) * but it'll output class untouched plus the prefixed one, so I had to remove it (`delete`) in a place it'd be executed by jade
Some thoughts from me: what's wrong with a variable? ``` - var myModule = 'module' div(class="#{myModule}") div(class="#{myModule}-child") div(class="#{myModule}-child") ``` or combine it with an each: ``` - var myModule2 = 'foobar' div(class="#{myModule2}") each idx in [0, 1, 2, 3] div(class="#{myModule2}-child") I'm child #{idx} ``` Sure, there is much more code to write, but if a change is neccessary then you must do this only at one point. Ciao Ralf
284,314
62,261
I should preface this with stating that I know basically nothing about proxies (despite having written a toy caching proxy a while back :)). I have a small cluster of servers running behind a firewall. One of these servers ("server0") can be connected to via http on port 8080, the rest are blocked off. I would like to set up a proxy on server0 so that it forwards requests to server1, server2, etc. I would also like to configure my client machines (all running Ubuntu) to use the proxy on server0:8080 , but only for urls that hit server\* , not for the rest of the traffic. So far I've only been able to find instructions for setting up a proxy for all traffic, not just that which matches some regex. Is this possible? Any hints / links / etc? Also recommendations on the appropriate choice of proxy software would be great. Thanks.
2009/09/04
[ "https://serverfault.com/questions/62261", "https://serverfault.com", "https://serverfault.com/users/19343/" ]
FoxyProxy is a Firefox extension that allows you to configure FireFox so urls that match a particular regex are sent out a particular proxy. This sounds like exactly what you want, but it may be difficult to centrally administer. It may be possible using WPAD to have a proxy pac file that says only certain URLs go out certain proxies but I'm not sure, would have to research that. This approach sounds overly complex. I would suggest that it is better to have a central proxy that everyone goes through and then that proxy can itself decide where to forward requests. I believe with Squid you can say "requests to this URL should be forwarded through this other proxy".
I think what you're looking for is something like [squid](http://www.squid-cache.org/) (a reverse proxy)
279,944
2,021,464
What kind of model, when store opening hours, durations of customer visits and the number of customers coming by car are known? I need to estimate the amount of parking space that I need. I've found that this is likely related to queueing theory, but having not background in it it seemed like the information that I'm given is not necessarily fit for models in queueing theory. Since those models seem to rely on e.g. the quantities "arrival rate" and "service rate", which I don't have.
2016/11/19
[ "https://math.stackexchange.com/questions/2021464", "https://math.stackexchange.com", "https://math.stackexchange.com/users/248602/" ]
> > Herein, we present a standard approach that relies on the definition of the limit. To that end we proceed. > > > --- If $\lim\_{n\to \infty}\frac{a\_{n+1}}{a\_n}=k>1$, then for all $\epsilon>0$, there exists a number $N(\epsilon)$ such that whenever $n>N(\epsilon)$, $$k-\epsilon<\frac{a\_{n+1}}{a\_n}<k+\epsilon$$ Take $\epsilon=\frac{k-1}{2}$. Then, for $n>N\left(\frac{k-1}{2}\right)$, we see that $$a\_{n+1}>\left(\frac12+\frac k2\right)a\_n$$ where $\left(\frac12+\frac k2\right)>1$. Proceeding recursively, we find that $$a\_{n+m}>\left(\frac12+\frac k2\right)^ma\_n$$ Letting $m\to \infty$, we obtain the coveted limit $$\lim\_{n\to \infty}a\_n=\infty$$ And we are done!
lim{a\_(n+1)}=lim {a\_(n+1)/a\_n}\*{a\_n}=lim{a\_(n+1)/a\_n}\*lim{a\_n}. This only works if lim a\_n is infinity.
357,662
27,779
I am about to reenter the MFC world after years away for a new job. What resources to people recommend for refreshing the memory? I have been doing mainly C# recently. Also any MFC centric websites or blogs that people recommend?
2008/08/26
[ "https://Stackoverflow.com/questions/27779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
I would highly recommend my all-time favorite book: [*MFC Internals: Inside the Microsoft© Foundation Class Architecture*](https://rads.stackoverflow.com/amzn/click/com/0201407213) **It is not a 'how-to' book — it is a 'how does it work' book.** [![alt text](https://i.stack.imgur.com/KWr8W.jpg)](https://rads.stackoverflow.com/amzn/click/com/0201407213)
The vital "how do I?" book is [http://www.amazon.com/gp/reader/0201185377/ref=sib\_dp\_pt#reader-link](https://rads.stackoverflow.com/amzn/click/com/0201185377) Codeproject is also invaluable, although many of the 3rd party controls there nowhave counterparts in the new MFC feature pack.
171,258
65,528,395
I have the following code snippet, where the np.roots function will provide two complext numbers and one real number. I was able to extract the real root, however the output is always Complex. How can I change to only real number. ``` Cd = 0.88 coeff = [1, -3, (3+Cd**2), (Cd**2 - 1)] roots = np.roots(coeff) X = (roots[np.isreal(roots)]); print (X) ``` The output is usually ``` [0.05944403+0.j] ``` However, how can I get only the following as output? ``` 0.059444 ``` The reason I am looking for that is, all my next calculations are also resulting complex numbers.
2021/01/01
[ "https://Stackoverflow.com/questions/65528395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463825/" ]
I want to show a solution using C++ language elements. Everything that I saw here is (except the usage of std::cout) pure **C-code**. And that is a pity, because C++ is much more powerful and has a lot of "of-the-shell" usable algorithms. So, as a first note. You should not use C-Style arrays in C++. There can be no argument, to not use a `std::array` instead. Or, for use cases with dynamic memory management, a `std::vector`. Using a `std::vector` is nearly always the better solution. Anyway. C++ will also still work with C-Style arrays. In my example below, I made heavy use of C++ functionality and can still work with C-Style arrays. Because of this programming style, I can exchange the C-Style array with modern C++ STL containers later, and, the program will still run. But let us first see the code, which I will explain later. ``` #include <iostream> #include <iterator> #include <algorithm> #include <functional> // Test data int arr[] = { 2, 3, -1, -1, -1, 4, -1, -1 }; unsigned int result[(sizeof(arr) / sizeof(arr[0]))/2]; // A predicate function that checks for 2 elements to be -1 bool twoMinusOnes(const int i, const int j) { return i == -1 && j == -1; } // Test program int main() { // Here we count, how many contiguos blocks of -1 are available unsigned int blockCounter = 0; // Some iterator to the begin and end of a -1 block in a source data decltype(std::begin(arr)) beginOfBlock{}; decltype(std::begin(arr)) endOfBlock{}; // Find all blocks with contiguos -1 in a simple for loop for ( beginOfBlock = std::adjacent_find(std::begin(arr), std::end(arr), twoMinusOnes); // Initial value. Start searching from beginning beginOfBlock != std::end(arr); // Check end condition beginOfBlock = std::adjacent_find(endOfBlock, std::end(arr), twoMinusOnes)) { // find next block // Ok. std::adjacent_found a block with at lease 2 repeating -1 for us // Now, find the position, where this block ends endOfBlock = std::adjacent_find(beginOfBlock, std::end(arr), std::not_equal_to<int>()); // Set iterator to past the end of the contiguous -1 block (if we are not at the end) if (endOfBlock != std::end(arr)) std::advance(endOfBlock, 1); // Store number of elements in this block result[blockCounter++] = std::distance(beginOfBlock, endOfBlock); } // Show result to user. Number of blocks and number of elements in each block for (unsigned int i{}; i < blockCounter; ++i) std::cout << "Block " << i + 1 << " has " << result[i] << " elements\n"; return 0; } ``` OK, what are we doing here? First, we define an array with the source data that shall be examined. Second, we also define a "result" array, with a fixed maximum size, equal to half the number of elements of the first array. This, because the there cannot be more consecutive -1 blocks. Ok, then we define a so called predicate function, which simply checks if both given elements are -1. That is what we are looking for in our source array. The predicate function can then later be used in C++ standard algorithms. In main, we initialize a blockCounter which will show us the number of contiguous -1 blocks found. Then we see: ``` decltype(std::begin(arr)) beginOfBlock{}; decltype(std::begin(arr)) endOfBlock{}; ``` This will define an iterator, regardless of the used C++ STL container. For our `int[]` array, it will be a `int*` (So, we could have also written `int *beginOfBlock;`. This is a very flexible approach and will allow us the use different containers later. --- Next we start a for loop, to find all blocks of contiguous -1s. For this we use a dedicated function that has been designed to find adjacent elements with a certain property: `std::adjacent:find`. Please see [here](https://en.cppreference.com/w/cpp/algorithm/adjacent_find) for the reference description. Standard is to find equal elements. But we use our predicate function to find 2 consecutive -1s. So, the init statement of the [for-loop](https://en.cppreference.com/w/cpp/language/for), looks for such a block, starting from the **beginning** of the container. The "condition" of the `for`, checks, if a block could be found or not. And the "iteration\_expression" looks for the next block, after the first block has been evealuated. This is a normal for loop and rather straight forward. In the loop body, we have only 3 statements: * Search for the end of the current found -1 block * Because the function will return the first element of a pair, it will point to the last -1 of the found block. We will increment the position to point to the next element after the found -1 block (but only, if we are not yet at the end of the array) * We store the resulting number of elements in one block That is all. Very simple and compact code. At the end we show the gathered results on the console. That is basically it. Only a few statements needed, because of the reuse of existing functions from the standard C++ library. And to show you, how versatile such a function is, you can `include` the header `vector` and then replace your C-Style arrays simply by: ``` // Test data std::vector arr{ 2, 3, -1, -1, -1, 4, -1, -1 }; std::vector<size_t> result(arr.size()/2); ``` And the program will work as before. --- I would strongly recommend to you to start using C++ language elements, if you want to learn C++ In case of questions, please ask.
You might do: ``` template <typename IT, typename T> std::vector<std::size_t> count_contiguous_block(IT begin, IT end, const T& value) { std::vector<std::size_t> res; auto it = begin; do { it = std::find(it, end, value); auto endBlock = std::find_if(it, end, [](const auto& e){ return e != value; }); if (it != endBlock) { res.push_back(std::distance(it, endBlock)); it = endBlock; } } while (it != end) return res; } ``` [Demo](http://coliru.stacked-crooked.com/a/5afca66b04618046)
356,919
93,917
We had the following mapping to manage the URIs for **ERC721** tokens in *OpenZeppelin* contracts until `pragma ^0.7`: ``` // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; ``` Therefore, we had a function to pass the token ID and URI in order to store the URI, so the call would be: ``` _setTokenURI(_tokenId, _tokenURI); ``` However, I see this whole functionality and associated checks to manage the URI is gone within [OpenZeppelin contracts](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol) on `pragma ^0.8`. Do you know whether it is now expected that we implement the URI management on our own? should it be OK to bring (copy & paste) those features from 0.7 into 0.8? if not, any recommendation?
2021/02/25
[ "https://ethereum.stackexchange.com/questions/93917", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/55658/" ]
You probably want to use [ERC721URIStorage](https://docs.openzeppelin.com/contracts/4.x/api/token/erc721#ERC721URIStorage), which is an extension of ERC721 that implements `_setTokenURI(tokenId, _tokenURI)`
Do you need to use a newer Solitude compiler? If not, stick with the pragma that works for you, by getting rid of the caret and specify a fixed version.
172,603
26,402,156
My issue is that I fixed a navigation bar at the top of my webpage and it includes both side margins and top one. Below this navigation bar, I want to set an scrollable container. Let me say I'm using Bootstrap 3.2.0 to lay out the site. The issue is that due to the margins of my navigation bar, the content I want to put below overlap the navigation bar and it's shown besides the navigation bar. For a better explanation of this I provide you my code, and a live example: **UPDATE:** I have noticed something that increases a little bit the difficult from my point of view, and it's that the body has a rule to hide the scroll and doesn't let scroll up/down: I would like just to scroll over the content "Hi World" and obviously that the whole content is shown from the first word: "BEGIN" to "END" word scrolling. ``` body { overflow: hidden; } ``` <http://www.bootply.com/TZebvFEl3T> (I updated the bootply code with the required restictions). ``` <nav class="navbar navbar-default navbar-fixed-top my-own-style"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="divider-vertical"></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </nav> <div> <p>BEGIN</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> ... <p>END</p> </div> ``` **UPDATE 2:** ------------- Experimenting with your answers and my own research I achieved something it's close to work for me, I have an scroll for the div with the content below the navigation menu and now the content doesn't overlap. The issue is that I also have a fixed footer at the page, if I resize the window the scroll is not completely visible and I can't reach the end of the list because is overlaped by the footer, so doesn't let me see the end of the scroll, if I remove the footer obviously this is visible. But I have to adjust my scroll to start at the bottom of the top nav menu, and end at the top of my footer as you can see in the example, the issue appears when you resize the browser. I think I'm looking for something like this for my container, please have a look to next link: **[Content with 100% between header and footer](https://stackoverflow.com/questions/11369764/content-with-100-between-header-and-footer)** And here is my code: <http://www.bootply.com/knJkGoEHWQ> ----------------------------------- HTML: ``` <nav class="navbar navbar-default navbar-fixed-top my-own-style"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="divider-vertical"></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </nav> <div class="container-fluid scroll"> <p>BEGIN</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> ... <p>END</p> </div> <div class="navbar navbar-default navbar-fixed-bottom"> <div class="navbar-header"><a class="navbar-brand" href="#">Brand</a></div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </div> ``` CSS: ``` /* CSS used here will be applied after bootstrap.css */ body, html { height: 100%; overflow: hidden; padding-top: 44px; } .my-own-style { margin-left: 37px; margin-top: 37px; } .scroll { overflow: auto; height: 80%; padding: 0; margin-left: 37px; } ``` --- UPDATE 3 (SOLUTION): -------------------- Ok regarding the update 2, the issue was so simple to sort it out, maybe I didn't see it. Basically in the same way I added a padding on the top of the body to set my main container below the top navigation menu, I have to do exactly the same but with the bottom padding of the body to set my main container above the bottom navigation menu. Moreover, I set the height to 100% for my main container in that way it expand along the whole div which contains it. Here is the solution: <http://www.bootply.com/sazMMHNCGy> ----------------------------------- HTML: ``` <nav class="navbar navbar-default navbar-fixed-top my-own-style"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="divider-vertical"></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </nav> <div class="scroll"> <p>BEGIN</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> Hi World <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> <p>Hi World</p> ... <p>END</p> </div> <div class="navbar navbar-default navbar-fixed-bottom"> <div class="navbar-header"><a class="navbar-brand" href="#">Brand</a></div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </div> ``` CSS: ``` /* CSS used here will be applied after bootstrap.css */ body, html { height: 100%; overflow: hidden; padding-top: 44px; padding-bottom: 25px; } .my-own-style { margin-left: 37px; margin-top: 37px; } .scroll { overflow: auto; height: 100%; padding: 0; margin-left: 37px; } ``` And for me this is the solution I was looking for.
2014/10/16
[ "https://Stackoverflow.com/questions/26402156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186541/" ]
I really don't like having to add elements that are just there for purposes of pushing content around. This is what positioning is designed to handle. The best way to do this is to start by adding padding to the top of your body, as @davidg stated in his answer. Further, to move your navbar into position, don't use margins. Instead using the top, left and right properties. The navbar-fixed-top class already sets the position to fixed, so you don't need to give any position property value. I also added the container-fluid class to your div (so that you get some padding inside) and a custom class scrollable to set the overflow property. [DEMO](http://www.bootply.com/LqphKJz221) ========================================= **CSS:** ``` html, body { height: 100%; /*Fixes the height to 100% of the viewport*/ } body { padding-top: 87px; /*50px for the height of the navbar + 37px for the offset*/ padding-bottom: 50px; /*50px for the height of the bottom navbar*/ } .navbar-offset { top: 37px; /*Offsets the top navbar 37px from the top of the viewport*/ } .container-fluid.scrollable { height: 100%; /*Sets the scrollable area to 100% of the viewport*/ overflow: auto; /*Allows the scrollable area to have a scrollbar based on the height of its content*/ background: #ccc; } ``` **HTML:** ``` <nav class="navbar navbar-default navbar-fixed-top navbar-offset"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="divider-vertical"></li> <li><a href="#">More</a></li> <li><a href="#">Options</a></li> </ul> </nav> <div class="container-fluid scrollable"> <p>BEGIN</p> <p>Hi World</p> ... <p>END</p> </div> <nav class="navbar navbar-inverse navbar-fixed-bottom"> <ul class="nav navbar-nav"> <li class="active"><a href="#"><span class="glyphicon glyphicon-home"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-user"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-calendar"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-comment"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-star"></span></a></li> </ul> </nav> ```
you can simply get this fixed by updating your margins to paddings.. and update the div like the below.. **HTML** ``` <div id="content">....</div> ``` **CSS** ``` #content{ position:absolute; top:100px; } ``` **[Demo](http://www.bootply.com/GNI6MhayAs)**
118,952
32,678,447
I am adding custom UIViews to my UIScrollView, and every UIView has a button that needs to open some users profile which must open in new UIViewController. But how do i create and connect a new controller with that button? Here is my code: ``` class FollowersViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() for var i = 0; i < count; i++ { view = FollowerView(frame: CGRectMake(0, scrollHeight, self.view.frame.width, 62)) scrollView.addSubview(view) scrollHeight += view.frame.height scrollView.contentSize.height += view.frame.height } } ``` If there is a button inside my CustomView that opens different (maybe dynamic) ViewControllers depending on its content how can I handle this issue?
2015/09/20
[ "https://Stackoverflow.com/questions/32678447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4929384/" ]
``` int *returnvalue; ``` This is just a *pointer* to `int`, but pointing nowhere defined, so this: ``` waitingID = waitpid(pid, returnvalue, 0); ``` will write the status code to some random memory location that probably doesn't belong to your process (in terms of [c](/questions/tagged/c "show questions tagged 'c'"), it is undefined behaviour to write through an uninitialized pointer). Simple thing to do, instead of defining a pointer, define an actual `int` variable: ``` int returnvalue; ``` and pass a pointer to that variable: ``` waitingID = waitpid(pid, &returnvalue, 0); ```
The function `waitpid` tries to write to the storage pointed to by `returnvalue`. In your code `returnvalue` hasn't been initialized and thus it's value is undefined. Since `waitpid` is trying to write to an unknown address, it is causing a crash. One way to mitigate this as suggested by others is to use `int returnvalue` and then pass its address as `&returnvalue` to `waitpid`. This way since the variable `returnvalue` is created on stack, its address is welldefined and `waitpid` can write to it as well. One other value that you can do is, although it is not very efficient is to call `malloc` and give your pointer a address(storage which will be created on the heap as opposed to the stack) so that you can then pass it to `waitpid`. But don't forget to call `free` on it afterwards. ``` returnvalue = malloc(sizeof(int)); waitingID = waitpid(pid, returnvalue, 0); printf("Return-value of %d is: %d\n", waitingID, *returnvalue); free(returnvalue); ```
78,818
49,676,862
I have sRGB numbers stored in file produced by Color.getRGB() method like this : ``` //example for RED color int num = Color.RED.getRGB(); // num is -65536 for RED // save num to a file. ``` Now I have to read the values from that file and have to convert each number to `[x,y,z]` RGB format. From `-65536` I need to get `[255,51,51]`. Can anyone tell me how to do that in java?
2018/04/05
[ "https://Stackoverflow.com/questions/49676862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9406220/" ]
Here it is ``` int num = Color.RED.getRGB(); int blue = num & 255; int green = (num >> 8) & 255; int red = (num >> 16) & 255; System.out.println("R:"+red+"\n"+"G:"+green+"\n"+"B:"+blue); ```
As mentionned in the [documentation](https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html), there is method in the Color class to obtain this ``` getRed() getGreen() getBleu() ```
19,950
618,713
I am new to Linq world and currently exploring it. I am thinking about using it in my next project that involves database interaction. From whatever I have read, I think there are 2 different ways to interact with databases: * Linq to SQL * Linq to DataSet Now the product that I am to work on, cannot rely on the type of database. For example, it might be deployed with SQL server/Oracle. Now my questions are: 1. If I use Linq to SQL, am I stuck with SQL server only? 2. I think I can use Linq to DataSet for both SQL server and oracle. But will I loose something (ease of programming, performance, reliability etc) if I use Linq to DataSet for SQL server (compared to Linq to SQL offcourse).
2009/03/06
[ "https://Stackoverflow.com/questions/618713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23671/" ]
1. Yes, it's SQL Server only. Additionally, Microsoft have frozen L2S and will not refine it further. But it's a good framework, performs really well and is easy to use. 2. Linq to DataSet accesses datasets as enumerables after data has been fetched from the DB. Linq to SQL uses an IQueriable to actually build dynamic SQL queries. In many cases, L2S will perform much better, and save you from writing the DB code at all. You should look into Linq to Entities. That's the most full-blown framework available. Right now, it's mainly for SQL Server, but you will have support for Oracle etc. in time.
When you use Linq to SQL, you'd be pretty much stuck with SQL Server, as far as I know. If you use Linq to DataSet, you'll lose a bit of ease of programming: With Linq, you can use the Linq entities directly while with DataSets, you have to keep using the DataSet name (MyDataSet.Entity = new MyDataSet.Entity()), which gets old after a while. I think that that's the only sacrifice. However, you can use it with e.g. Oracle (did that on a project). It's also pretty much drag-and-drop with a bit more control on the DataAdapter (as far as I know - I've never had to tweak Linq-to-SQL that much), you can specify (e.g.) which queries to use, etc. Since you can still define relationships between tables in DataSets, you can still use Linq well enough, so you won't really see problems there. I assume that reliability is as good with Linq-to-DataSet as with Linq-to-SQL (never had problems), performance seemed to be good enough, never could really profile it, though.
162,468
2,223,651
$$\int \frac {\rho^2}{(\rho^2+ h^2)^\frac 32} d\rho$$
2017/04/08
[ "https://math.stackexchange.com/questions/2223651", "https://math.stackexchange.com", "https://math.stackexchange.com/users/433759/" ]
Hint: Prove that $$\int\frac1{\sqrt{x^2+1}}\ dx=\ln(x+\sqrt{1+x^2})+c$$ Let $x=tu$ to see that $$\int\frac1{\sqrt{t^2u^2+1}}\ du=\frac1t\ln(tu+\sqrt{1+t^2u^2})+c$$ Then differentiate with respect to $t$ to see that $$\int\frac{u^2}{(t^2u^2+1)^{3/2}}\ du=-\frac1t\frac d{dt}\left(\frac1t\ln(tu+\sqrt{1+t^2u^2})+c\right)$$ Be careful, and notice that differentiating $c$ with respect to $t$ is still a constant of integration *with respect to $u$*. Now multiply both sides by $t^3$ to finally get $$\int\frac{u^2}{(u^2+\frac1{t^2})^{3/2}}\ du=-t^2\frac d{dt}\left(\frac1t\ln(tu+\sqrt{1+t^2u^2})\right)+c$$ and then let $t\mapsto\frac1t$ to get your final answer.
In addition to the pythagorean identities for circular trig functions, such as $$ 1 + \tan^2 x = \sec^2 x $$ and for the hyperbolic trig functions, such as $$ 1 + \sinh^2 x = \cosh^2 x $$ there is a similar identity involving rational functions: $$ 1 + \left( \frac{y^2 - 1}{2y} \right)^2 = \left( \frac{y^2 + 1}{2y} \right)^2 $$ The various forms of this identity can be computed as needed from $$ (2y)^2 + (y^2 - 1)^2 = (y^2 + 1)^2 $$ So, for example, when one has $$ \sqrt{1 + x^2} \, \mathrm{d} x$$ one could make the substitution $$x = \frac{y^2 - 1}{2y} \qquad \qquad y > 0$$ to get $$ \left( \frac{y^2 + 1}{2y} \right) \cdot \left( \frac{1}{2} \left( 1 + \frac{1}{y^2} \right) \mathrm{d} y \right) $$ With the square root eliminated, the problem can then be solved via partial fractions. Although in this example the denominator is a power of $y$, so you have the much simpler method of just expanding everything. Similarly, one could substitute $x = \frac{2y}{y^2 - 1}$ instead.
10,411
17,189
I have had enough courses on statistics during my school years and at the university. I have a fair understanding of the concepts, such as, CI, p-values, interpreting statistical significance, multiple testing, correlation, simple linear regression (with least squares) (general linear models), and all tests of hypothesis. I had been introduced to it much of the earlier days mostly mathematically. And lately, with the help of the book [Intuitive Biostatistics](http://rads.stackoverflow.com/amzn/click/0199730067) I have grasped and unprecedented understanding towards the actual conceptual theory, I believe. Now, what I find I lack is understanding of fitting models (estimating parameters to model) and the like. In particular, concepts such as maximum likelihood estimation, **generalized** linear models, bayesian approaches to inferential statistics always seem foreign to me. There aren't enough examples or tutorials or conceptually sound ones, as one would find on simple probabilistic models or on other (basic) topics on the internet. I am a bioinformatician and I work on RNA-Seq data which deals with raw read counts towards finding, lets say, gene expression (or differential gene expression). From my background, even if I am not familiar with statistical models, I am able to grasp the reason for a poisson distribution assumption and negative binomials and so on.. But some papers deal with generalized linear models and estimate a MLE etc.. which I believe I have the necessary background to understand. I guess what I am asking for is an approach some experts among you deem useful and (a) book(s) which helps me grasp these concepts in a more intuitive way (not just rigorous math, but theory backed with math). As I am mostly going to apply them, I would be satisfied (at the moment) with understanding what is what and later, I can go back to rigorous mathematical proofs... Does anyone have any recommendations? I don't mind buying more than 1 book if the topics I asked for are indeed scattered to be covered in a book. Thank you very much!
2011/10/18
[ "https://stats.stackexchange.com/questions/17189", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/4751/" ]
You will find everything non-Bayesian that you asked about it [Frank Harrell's Regression Modeling Strategies](http://rads.stackoverflow.com/amzn/click/0387952322). I would leave Bayesian recommendations to more knowledgeable folks (although I do have [Gelman, Carlin, Stern and Rubin](http://rads.stackoverflow.com/amzn/click/158488388X), as well as [Gilks, Richardson and Speigelhalter](http://rads.stackoverflow.com/amzn/click/0412055511), on my bookshelf). There should be a few Bayesian biostat books on the market. **Update:** [McCullach and Nelder (1989)](http://rads.stackoverflow.com/amzn/click/0412317605) is a classic book on GLMs, of course. It was groundbreaking for its time, but I find it rather boring, frankly. Besides, it does not cover the later additions like residual diagnostics, zero-inflated models, or multilevel/hierarchical extensions. [Hardin and Hilbe (2007)](http://rads.stackoverflow.com/amzn/click/1597180149) cover some of this newer stuff in good details with practical examples in Stata (where GLMs and extensions are very well implemented; Hardin used to work at Stata Corp. writing many of these commands, as well as contributing to the sandwich estimator).
I would recommend following two books: 1. [Statistical methods for bioinformatics](http://rads.stackoverflow.com/amzn/click/0387400826) 2. [The elements of statistical learning](http://rads.stackoverflow.com/amzn/click/0387848576)
335,962
1,197,903
If my understanding of Flex is correct, skins in Flex are just DisplayObjects that are added as children to UIComponents to create the visual representation of the object. But if my understanding of the Flash event model is correct, if there is a non-transparent DisplayObject on top of another, mouse events will go to the topmost DisplayObject. The overlapped DisplayObject won't receive any mouse input. So how is it that skinned Flex UIComponents work at all?
2009/07/29
[ "https://Stackoverflow.com/questions/1197903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45084/" ]
As the parts in the skin are added by the component this gives it the power to ensure that you can't click on the graphics, if you look in ButtonBase class which Button extends you can see the comments that explain this: ``` // DisplayObjectContainer properties. // Setting mouseChildren to false ensures that mouse events // are dispatched from the Button itself, // not from its skins, icons, or TextField. // One reason for doing this is that if you press the mouse button // while over the TextField and release the mouse button while over // a skin or icon, we want the player to dispatch a "click" event. // Another is that if mouseChildren were true and someone uses // Sprites rather than Shapes for the skins or icons, // then we we wouldn't get a click because the current skin or icon // changes between the mouseDown and the mouseUp. // (This doesn't happen even when mouseChildren is true if the skins // and icons are Shapes, because Shapes never dispatch mouse events; // they are dispatched from the Button in this case.) ```
You should still be able to add MouseEvent listeners to the host component - the best example is a skinned button. You treat it like any other button. In a more complex skinned component though you add listeners to individual skin components in the host component. These events should bubble up to the host component as well though.
147,980
60,688,617
Context ======= I would like to fetch some data from Firestore that way: ```py query = db.collection("users").where("age", ">", 20) for document in query.stream(): print("User id: {}".format(document.id)) ``` However, I cannot assert whether it will iterate over documents. Indeed, if no documents match with my `where` condition, nothing happens. I would like to raise an Exception instead. Question ======== How can we catch any empty [QuerySnapshot](https://googleapis.dev/python/firestore/latest/query.html) with the python API ? Resources: [Firebase documentation](https://firebase.google.com/docs/firestore/query-data/queries#simple_queries)
2020/03/15
[ "https://Stackoverflow.com/questions/60688617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7709964/" ]
I solve in this way: ``` documents = [d for d in db.collection("users").where("age", ">", 20).stream()] if len(documents): for document in documents: print("User id: {}".format(document.id)) else: print('empty query') ```
``` db.collection("users").where("age", ">", 20) ``` returns null if no document match with your where, please check for if query!= null : for document in quer`enter code here`y.stream(): print("User id: {}".format(document.id))
176,092
8,976,103
Im curious to know how lazy evaluation is implemented at higher levels, ie in libraries, etc. For example, how does the Django ORM or ActiveRecord defer evaluation of query until it is actually used?
2012/01/23
[ "https://Stackoverflow.com/questions/8976103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285614/" ]
Let's have a look at some methods for django's [`django.db.models.query.QuerySet`](https://code.djangoproject.com/browser/django/trunk/django/db/models/query.py) class: ``` class QuerySet(object): """ Represents a lazy database lookup for a set of objects. """ def __init__(self, model=None, query=None, using=None): ... self._result_cache = None ... def __len__(self): if self._result_cache is None: ... elif self._iter: ... return len(self._result_cache) def __iter__(self): if self._result_cache is None: ... if self._iter: ... return iter(self._result_cache) def __nonzero__(self): if self._result_cache is not None: ... def __contains__(self, val): if self._result_cache is not None: ... else: ... ... def __getitem__(self, k): ... if self._result_cache is not None: ... ... ``` The pattern that these methods follow is that no queries are executed until some method that really needs to return some result is called. At that point, the result is stored in `self._result_cache` and any subsequent call to the same method returns the cached value.
Not sure about the specifics about which library you talking about but, from an algorithm standpoint, I've always used/undertsood it as follows: (psuedo code from a python novice) ``` class Object: #... Other stuff ... _actual_property = None; def interface(): if _actual_property is None: # Execute query and load up _actual_property return _actual_property ``` Essentially because the interface and implementation are separated, you can define behaviors to execute upon request.
261,594
53,747,385
I am using the datetime module as follows to get the current time: ``` datetime.now().strftime('%I:%M:%S %p') ``` And this gives me the current time but in UTC. How can I get the current time in CST ? Can I do that without using other external libraries or is it easier to use something else? Any help is appreciated!
2018/12/12
[ "https://Stackoverflow.com/questions/53747385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It might be tricky without an external library, so i suggest you use the `pytz` package ``` pip install pytz ``` And with help from [here](https://stackoverflow.com/questions/10997577/python-timezone-conversion) you could try something like below ``` from datetime import datetime from pytz import timezone now_time = datetime.now(timezone('America/Chicago')) print(now_time.strftime('%I:%M:%S %p')) ``` I used `America/Chicago` because it's in the CDT timezone according to [this](https://www.timeanddate.com/time/zones/cdt). But if you are interested in doing it natively you will have to read up some more [here](https://docs.python.org/3.5/library/datetime.html) in the official documentation because it provide some examples on how to do it but it will leave kicking and screaming especially if you are a beginner.
Here's how to do it without an external library or hard-coding the offset ```py from zoneinfo import ZoneInfo time_stamp = datetime.now(ZoneInfo('America/Chicago')) ```
119,942
13,347,559
I simply want to create an empty 10\*3\*2 array with Python. I first thought of these one, but this is not working: ``` parameters = [ [ [] * 2 ]*3 ] * 10 ``` this gives me a vector of ten vectors, with three [] elements in it: ``` [[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]] ``` that is , if I want to access parameters[0][0][1] I am out of bounds, whereas I want a dimension 2 for the innermost vectors along the third dimension. then I thought of this ``` [ [ [[] * 2] ]*3 ] * 10 ``` I was thinking that `[[] * 2]` would now bring me the thing I want, an innermost two elements vector. I obtain ``` [[[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]]] ``` So, how to do it, or how to escape this initialization? Kd rgds.
2012/11/12
[ "https://Stackoverflow.com/questions/13347559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141493/" ]
First of all, you should insert something into the innermost list (like None). Secondly, when you use the multiplication in the outermost list it replicates **references** to the inner list, so when you change one element, you will also change this element in all the other lists: ``` >> parameters = [ [ [None] * 2 ]*3 ] * 10 >> print parameters [[[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None]]] >> parameters[0][0][1]=1 >> print parameters [[[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]], [[None, 1], [None, 1], [None, 1]]] ``` Therefore, you should rather use list comprehensions: ``` >> parameters=[[[None for i in range(2)] for j in range(3)] for k in range(10)] ``` However, I would recommend to use `numpy` as suggested in one of the other answers.
I would do something like this, using this lists created are different objects (i.e different `id()`): ``` In [96]: [ [ [ []*2] for _ in range(3)] for _ in range(10) ] Out[96]: [[[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]]] In [98]: [id(x) for x in lis] #all objects are unique Out[98]:  [151267948,  151268076,  151268492,  151269164,  151267276,  151265356,  151268140,  151269036,  151265644,  151265964] In [101]: lis1=[ [ [[] * 2] ]*3 ] * 10 In [102]: [id(x) for x in lis1] # all objects are same, changing one will change # others as well Out[102]: [151278188, 151278188, 151278188, 151278188, 151278188, 151278188, 151278188, 151278188, 151278188, 151278188] ```
39,781
203,586
I am getting the following error when attempting to install the VirtualBox kernel modules : ``` ------------------------------ Deleting module version: 4.1.18 completely from the DKMS tree. ------------------------------ Done. Loading new virtualbox-4.1.18 DKMS files... Building only for 3.5.0-17-generic Module build for the currently running kernel was skipped since the kernel source for this kernel does not seem to be installed. ``` I have tried installing the linux-source package, but I am not sure how Ubuntu handles kernel sources and headers. Any ideas on how to do this from an Ubuntu standpoint?
2012/10/20
[ "https://askubuntu.com/questions/203586", "https://askubuntu.com", "https://askubuntu.com/users/99213/" ]
An other way: ``` apt-get install linux-headers-`uname -r` dpkg-reconfigure virtualbox-dkms ``` The normal way: ``` /etc/init.d/vboxdrv setup ```
Didn't work for me. Solved it by running: ``` gksudo synaptic ``` Search for 'dkms' and (re)install the one for VirtualBox and press the 'Apply' button. The output should say that virtualbox kernel drivers are up and running.
237,168
35,099,387
We have tons of differences mentioned between elastic search and solr for search technologies. The differences mentioned are mostly of data formats, API accessibility, analytics support, adaptability, cloud integration , geo spatial search, indexing, etc, etc. Also , at all places they have mentioned that both this search technologies have been built on top of Apache Lucene. I have a fundamental question that if both have been built on top of search solution(Lucene here), there must be some differences in the way query works ? Like if I look from a text search aspect only and leave all other things behind, how is a text search performed in ES and solr. There should be some configuration / behavior change in the way the search engine searches / optimizes ? I need in depth understanding how the search works by taking a text string as example. It would be awesome if someone could explain me that :) Thanks.
2016/01/30
[ "https://Stackoverflow.com/questions/35099387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913481/" ]
Lucene is the underlying full-text search library used by both Solr and Elasticsearch, as you said. There are a few subtle differences in how Lucene is used and exposed between the two, but in terms of how text indexing and querying is performed they are almost identical. Both use the concept of tokenization and token-filters (ES: <https://www.elastic.co/guide/en/elasticsearch/reference/2.0/analysis-tokenfilters.html>, Solr: <https://cwiki.apache.org/confluence/display/solr/Understanding+Analyzers,+Tokenizers,+and+Filters>) to split up and process text, and both use the same Lucene index format to store statistics about these tokens on disk. I suspect the reason you've not been able to find out what the differences at this level are is because there aren't really any.
Both Solr and elasticsearch run using lucene, so you need that installed. <https://logz.io/blog/solr-vs-elasticsearch/> <http://solr-vs-elasticsearch.com/> <https://www.searchtechnologies.com/blog/solr-vs-elasticsearch-top-open-source-search> See the above for more of a run down.
20,606
1,665,730
Is there a Image related data type in MySQL that can be used for storing images for each recor?
2009/11/03
[ "https://Stackoverflow.com/questions/1665730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201445/" ]
You'll need to use some sort of `BLOB` type: [MySQL Reference: BLOB and TEXT types](http://dev.mysql.com/doc/refman/5.0/en/blob.html) Which type you use depends on the size of the image you wish to store.
Yes , there are some datatypes to store image into database. > > BLOB (Binary large object) > which can be specially use for Storing of image files into database. > > > The four BLOB types are `' TINYBLOB ',' BLOB ', ' MEDIUMBLOB` and `'LONGBLOB '`. These differ only in the maximum length of the values they can hold. Creating table: ``` CREATE TABLE image (imgname VARCHAR(33) , photo LONGBLOB ); ``` For inserting Values refer to [Insert Picture into SQL Server 2005 Image Field using only SQL](https://stackoverflow.com/questions/416881/insert-picture-into-sql-server-2005-image-field-using-only-sql) I have Stored one image file in database by using java jdbc, So if you want to see how image file is stored in database click the link : <https://ibb.co/frCpt37>
149,913
60,675,898
How do I write, in modern C++, something similar to this Javascript code: ``` // Example Code From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // Prints 'abc - 12345 - #$*%' ```
2020/03/13
[ "https://Stackoverflow.com/questions/60675898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8952375/" ]
``` #include<regex> #include<string> #include<iostream> std::string foo(std::string s) { static const std::regex r {R"~~(^([^\d]*)(\d*)([^\w]*)$)~~"}; return std::regex_replace(s, r, "$1 - $2 - $3"); } int main() { std::string s = "abc12345#$*%"; std::cout << foo(s); } ```
You can use the following regex to split the string at the desired locations, between consecutive characters: ``` (?<=[a-z])(?=[0-9#$*%])|(?<=[0-9])(?=[a-z#$*%])|(?<=[#$*%])(?=[a-z0-9]) ``` [Demo](https://regex101.com/r/QwDyxW/3/) The regex performs the following operations: ``` (?<=[a-z]) # match is preceded by a lc letter (?=[0-9#$*%]) # match is followed by a digit or punctuation char | # or (?<=[0-9]) # match is preceded by a lc letter (?=[a-z#$*%]) # match is followed by a lc letter or punctuation char | # or (?<=[#$*%]) # match is preceded by a lc letter (?=[a-z0-9]) # match followed by a lc letter or digit ```
129,061
22,007,482
I have implemented **Language Localization** in my iOS App. So, now user can set the Arabic Language in my iPad Application. I am getting the localized string response from the server and now I want to set this localized string to my `UILabel` in **Right To Left** format with **Right Alignment**. **Update :** My server response is already in RTL format. Now, I just wanted to set the text alignment to right when I have Arabic text in my `UILabel`. Right now I have to write code to set the alignment of `UILabel` based on the language. So, I just want to know if there is any *property* available for `UILabel` by setting which I can make the text of `UILabel` Right Aligned in case of Arabic Language.
2014/02/25
[ "https://Stackoverflow.com/questions/22007482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1603072/" ]
Display the text normally as you do in english if you are getting arabic text from server no need to align it. Just right align the text.
Make your text label the entire width of the view. Then the text will right align from the right side of the screen.
136,163
18,650
I find myself in much the same state each year before Rosh HaShono. I don't know what was wrong with my attempt at teshuva but the outcome was that despite my best intentions I have not accomplished all the change that I hoped for last year. What source material is there which can allow me to make a more permanent change as a result of the repentance process?
2012/08/21
[ "https://judaism.stackexchange.com/questions/18650", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/730/" ]
In order for change to be permanent, it has to go through a process (anything that changes overnight can revert overnight) The process of changing oneself has two parts: 1. Understanding the problem When we understand why some *midah* (trait) is bad it allows us to start the changing process (knowing the illness is half the cure). It's not good enough to understand the problem, rather we need to emotionally 'understand' why the *midah* is not appropriate. 2. Turning the problem into a solution Fixing the problem is an intense process, but if done right will be successful. First, we need to know about ourselves, so that we can motivate ourselves to change (for a small child it can be an ice cream, while for an adult it can be money or respect). After we know what makes us tick (and what motivates us), we then need to create a plan of action. First we need to address the 'action' (*ma'aseh*) of the *midah*. By controlling the action we start to see results. This needs to be done with wisdom by figuring out how to channel the bad *midah*, if possible. Then we work on the speech and thought part of the *midah* - we need to understand why we feel this way etc. **Example** Let's assume I have an anger problem, the way to fixing this is first to understand why it's a problem. For example: it affects my social life, it is not healthy, it doesn't allow me to be productive etc. Now that I know why it's bad, I need to figure out a way to control its 'action'. For example: I may do exercise, or scream inside an empty room to let out the anger in a 'healthy/non inappropriate way'. Next I work on the 'speech' part of it. For example: I may sing a song loudly to let out the anger. Notice how at this point the singing helps me (and most of the time I don't need to scream). Finally I work on the 'thought' aspect; I start appreciating how there is no need to get angry in the first place. For example: I realize that Hashem is in control of my life, so if something goes wrong it's for the best.
Small changes have a better chance of lasting. Make a small change now, and when you feel that you are ready for further improvement adopt another small change.
365,704
385,728
I have data with nice bell-shaped histogram PDF. However, the Normal distribution fitting (by calculating mean and variance) does not work as the figure below. [![normal fit Failed](https://i.stack.imgur.com/7Luv6.png)](https://i.stack.imgur.com/7Luv6.png) **My question** is that if there are other distributions I should try according to your experience. In other words, by which distribution should a *nice* bell-shaped data, which is not well fit by Normal distribution, be fit. **My ultimate goal** is to have an approximated analytic form of cummulative distribution function to analyze the according probability. Thus any advices towards solving this goal are appreciated. I include the data (space as delimiter): [Data to fit](https://www.dropbox.com/s/cfssiwloe5u2vqg/data_Z.txt?dl=0). *Update:* q-q plot [![QQ-plot](https://i.stack.imgur.com/PZHlp.png)](https://i.stack.imgur.com/PZHlp.png)
2019/01/05
[ "https://stats.stackexchange.com/questions/385728", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/233117/" ]
In short: your two plots show a big discrepancy, the smallest values shown in the histogram is about $-30$, while the qqplot shows values down to around $-900$. All those lom-tailed outliers is about 0.7% of the sample, but dominates the qqplot. So you need to ask yourself what produces those outliers! and that should guide you to what to do with your data. If I make a qqplot after eliminating that long tail, it looks much closer to normal, but not perfect. Look at these: ``` mean(Y) [1] 3.9657 mean(Y[Y>= -30]) [1] 4.414797 ``` but the effect on standard deviation is larger: ``` sd(Y) [1] 10.92237 sd(Y[Y>= -30]) [1] 8.006223 ``` and that explains the strange form of your first plot (histogram): the fitted normal curve you shows is influenced by that long tail you omitted from the plot.
You might try a Gaussian mixture, which is easy using Mclust in the mclust library of R. library(mclust) mc.fit = Mclust(data$V1) summary(mc.fit,parameters=TRUE) This gives a three-component Gaussian mixture (8 parameters total), with components 1: N(-69.269908, 6995.71627), p1 = 0.003970506 2: N( -4.314187, 171.76873), p2 = 0.115329209 3: N( 5.380137, 46.26587), p3 = 0.880700285 The log likelihood is -352620.4, which you can use to compare other possible fits such as those suggested. The long left tail is captured by the first two components, especially the first. The cumulative distribution estimate at "x" is (in R form) p1\*pnorm(x, -69.269908, sqrt(6995.71627)) + p2\*pnorm(x, -4.314187, sqrt(171.76873)) + p3\*pnorm(x, 5.380137, sqrt(46.26587)) I tried various quantiles (x) from .0001 to .9999 and the accuracy of the estimate seems reasonable to me.
254,397
48,862,206
I've two sheets in my workbook. One is actually a temporary sheet which holds lots of data of employees and there are more than 50 columns. There is another sheet which is limited to 10 columns which is actually filtered list and columns are in order for report. Few columns are formula columns also based on value from another column. So what I have to do is to copy those columns from Sheet1 `(Temp_Data)` and Paste it into Main sheet with columns been removed and also in a different order. So what I am doing is, copying it individually and paste it into corresponding columns of the final sheet. **Like this:** ``` Sheets("Temp_Data").Range(cells(2,1),cells(lastrow,1)).copy Sheets("Final_Invoice").Range("G2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Sheets("Temp_Data").Range(cells(2,7),cells(lastrow,7)).copy Sheets("Final_Invoice").Range("B2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ``` So this process repeats for all columns required from `Temp_Data` into `Final_Invoice`. But I really believe there should be some easiest way to replace this like mapping between columns. Any suggestions deeply thankful
2018/02/19
[ "https://Stackoverflow.com/questions/48862206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954093/" ]
* Use inline css in HTML and * Use file read stream as below * pass the file read stream to sendmail // { html } * Don't forget to explicitly close the file stream **Code sample** ``` var htmlstream = fs.createReadStream("index.html"); transport.sendMail({ html: htmlstream }, function(err) { if (err) { // check if htmlstream is still open and close it to clean up } }); ```
Just change your code as following : ``` var nodemailer=require('nodemailer'); var fs=require('fs'); require.extensions['.html'] = function (module, filename) { module.exports = fs.readFileSync(filename, 'utf8'); }; var data = require('index.html'); // path to your HTML template var transporter=nodemailer.createTransport( { service:'gmail', auth: { user:'[email protected]', pass:'********' } }); var a='<h1>Welcome</h1><p>That was easy!</p>'; var mailOptions={ from:'[email protected]', to:'[email protected]', subject:'Sending HTML page using Node JS', html:data }; transporter.sendMail(mailOptions,function(error,info) { if(error) { console.log(error); } else { console.log('Email Sent: '+info.response); } }); ```
102,582
33,074,609
Whenever i do this code ``` Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("D:M:Y"); System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]"); ``` It prints out ``` Date Launched: [285:10:2015] ``` How can i get it so it prints out the actual date like `[12/10/2015]`?
2015/10/12
[ "https://Stackoverflow.com/questions/33074609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345553/" ]
``` SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");//d small ``` [SimpleDateFormat doc](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)
use dd/MM/yyyy instead of D:M:Y so your code looks like ``` Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]"); ``` because D gives Day in year bt u want day in month M gives Month in year Y gives Year
243,737
52,666
My potted lemon tree has been losing leaves. The leaves exhibit a pattern of lighter blotches at the edge of the leaves, which I suspect may be due to a magnesium deficiency, but also a strange pattern of dry spots on the upper surface of the leaves, which I don't know what to attribute to. What could be causing these? I've attached a couple of images. [![enter image description here](https://i.stack.imgur.com/7XZtK.jpg)](https://i.stack.imgur.com/7XZtK.jpg) [![enter image description here](https://i.stack.imgur.com/b9RYO.jpg)](https://i.stack.imgur.com/b9RYO.jpg)
2020/06/16
[ "https://gardening.stackexchange.com/questions/52666", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/18169/" ]
If you filled the bed completely using only municipal compost with no soil, that might be the problem. Composted materials of this type are meant for mulching or digging into garden soil; they are not usually suitable for use as a planting medium, especially not in a contained area. If your raised bed is open at the bottom and sitting directly on soil,that's not quite so contained as a raised bed on legs - not sure which you've got, but even so, there is no soil in the raised bed, only the compost. You could try checking the source to see if it's been produced using a hot, aerobic method, which would mean it is suitable for use as a planting medium, but more usually, these are not produced in that way. The other possibility is there is some contamination from pesticides (usually herbicides) of some sort; this could be present in the compost, or could be caused by spray drift from you or someone else spraying some sort of pesticide nearby. Note that composted materials meant for soil conditioning purposes do not usually cause problems when mixed in with soil in open ground, though some horse manure can sometimes be contaminated with a particular herbicide.
Look into "Tomato russet mite" which also affects bell peppers. The damage from russet mite looks similar to your photos. I've had the same issue in my garden for years and could not work out what was causing it. And then one day, someone mentioned tomato russet mite in a Facebook gardening post I was following and when I looked into it, it seemed to match what was happening in my garden. It was so good to finally have an answer. Hope this helps you too.
176,304
7,662,620
In my $.ajaxSucess() function I need to find out if the response is json. Currently I am doing this: ``` $('body').ajaxSuccess(function(evt, xhr, settings) { var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/); if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){ ... ``` Is there a better way?
2011/10/05
[ "https://Stackoverflow.com/questions/7662620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26188/" ]
``` var a={"k":"v"}; var b="k"; try{ $.parseJSON(b); }catch(e){alert('Not JSON')} ```
You could probably use jQuery.parseJSON to attempt parsing it. If an exception is raised then it's not valid json. <http://api.jquery.com/jQuery.parseJSON/>
86,735
833,357
I've seen Euclid's proof of infinitely many primes, what are other approaches to proving there are infinitely many primes?
2014/06/13
[ "https://math.stackexchange.com/questions/833357", "https://math.stackexchange.com", "https://math.stackexchange.com/users/156984/" ]
$$\prod\_k \frac 1 {1-p\_k^{-2}}=\sum\_n n^{-2}=\zeta(2)=\frac {\pi^2}6,$$ and $\pi^2$ is irrational ([from my favorite math resource](https://math.stackexchange.com/a/2285/19341)) so we need infinitely many primes...
There is a topological proof: <http://en.wikipedia.org/wiki/Furstenberg%27s_proof_of_the_infinitude_of_primes> Apart from that there are almost infinitely many proofs..
16,285
2,063,568
I'm using WinApi and C#. I need to find window with variable caption. Caption contains constant part. I think that I need to enumerate all windows. How I can do this?
2010/01/14
[ "https://Stackoverflow.com/questions/2063568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150121/" ]
Yes, it is in hexadecimal, but what it means depends on the other outputs of the wav file e.g. the sample width and number of channels. Your data could be read in two ways, 2 channels and 1 byte sample width (stereo sound) or 1 channel and 2 byte sample width (mono sound). Use `x.getparams()`: the first number will be the number of channels and the second will be the sample width. [This Link](https://web.archive.org/web/20140221054954/http://home.roadrunner.com/~jgglatt/tech/wave.htm) explains it really well.
It's a two byte string: ``` >>> x='\x1e\x00' >>> map(ord, list(x)) [30, 0] >>> [ord(i) for i in x] [30, 0] ```
204,638
221,047
I'm a dev trying to deploy a new dashboard I've written at work, the old one is a mess of hacked together libraries and only about half of the codebase is still even in use (dead code everywhere that just never got deleted, but doesn't do anything)... I'm not willing to kill myself over this nonsense one more second, I am trying to get the user notes from accounts where a user (rarely) changed their password from the default. I have the default password's stored hashed string, what password it translates to, the hashing mechanism used, the encryption method used, and the hashed strings of the other passwords. There *just has* to be a simple way to use this information to decrypt the other passwords right?? If this is not possible, can someone explain to me why? I get the one-way nature of hashing, but given how much information I have about the process end to end, I essentially have the entire process known, so I'm not sure that matters in this instance... **To summarize:** Can I use the knowledge of hashing and encryption mechanisms, along with a sample hash string and its plaintext value, to crack other passwords produced by the same code? **PS:** If it helps, each default hash is identical regardless of when it was made...
2019/11/11
[ "https://security.stackexchange.com/questions/221047", "https://security.stackexchange.com", "https://security.stackexchange.com/users/215482/" ]
No, the information about known passwords will be of no help to crack the unknown passwords. Hashes are the result of one-way trapdoor functions. Hashing differs from encryption in that encryption can be reversed, whereas hashing cannot. Hashing destroys information, and there is no way to reconstruct the original password from a secure hash. If there is a slight change in the original password, the resulting hash will be entirely different. Hence you cannot even compare two hashes to see if the original passwords are similar. Many [open-source](https://en.wikipedia.org/wiki/Open_source) projects disclose how their application's passwords are hashed. This does not make the hashes any less secure. There are also databases consisting of known password-hash combinations. Those do not help to crack passwords that are unknown to the database. You are left to the conventional methods of cracking passwords, which usually involves trying possible passwords in an automatized manner to see if they match the hash. This is by no means easier or faster than 58 phone calls.
As the other answers state, recovering the passwords *directly* will not be possible. However, given that the data you want is the user notes, there are other options: ### DB Admin User Presuming you have legitimate access to the back end, you could pull the data as a admin user of the db. (see Trotski94's comment) ### MITM You could deploy the new dashboard, and only import the new data when the user *gives you* their password. This is effectively a MITM. (see comments of Conor Mancone and eckes) ### Hashcat Failing those options, run the hashes against hashcat (the password recovery tool). At the very least it might cut down the number of phone calls you need to make. ### Conclusion Unfortunately, other than the first option, its probably less effort just to make the calls.
183,853
160,445
I don't know why my function is not load, this code: ``` include_once('Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php'); class Singsys_ColorSelector_Override_Admin_Catalog_Product_AttributeController extends Mage_Adminhtml_Catalog_Product_AttributeController { public function saveAction() { Mage::log('ExampleText:', null, 'mylog.log'); } } ``` And my config.xml ``` <routers> <adminhtml> <args> <modules> <Singsys_ColorSelector_Override before="Mage_Adminhtml">Singsys_ColorSelector_Override_Admin</Singsys_ColorSelector_Override> </modules> </args> </adminhtml> </routers> ``` Any hints, why my saveAction not work? When I write log in Mage class all is ok. I have also conflict in another module, when I write this function in another module function is work. I try switch off conflicts module in admin and in code, but this is not help.
2017/02/17
[ "https://magento.stackexchange.com/questions/160445", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/48772/" ]
try this code ``` require_once('Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php'); class Singsys_ColorSelector_Override_Admin_Catalog_Product_AttributeController extends Mage_Adminhtml_Catalog_Product_AttributeController { public function saveAction() { Mage::log('ExampleText:', null, 'mylog.log'); } } ```
I find solution, I use 'depends' in the second modules and this is help me.
95,243
12,253,921
I've written a very simple service application based on this [code example](http://code.msdn.microsoft.com/windowsdesktop/CppWindowsService-cacf4948). The application as part of its normal running assumes there exists a file in the directory it is found, or in its execution path. When I 'install' the service and then subsequently 'start' the service from the service manager in control panel. The application fails because it can't find the file to open and read from (even though the file is in the same directory as the installed executable). My question is when a windows service is run, which is the expected running path supposed to be? When calling 'CreateService' there only seems to be a path parameter for the binary, not for execution. Is there someway to indicate where the binary should be executed from? I've tried this on windows vista and windows 7. Getting the same issues.
2012/09/03
[ "https://Stackoverflow.com/questions/12253921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655794/" ]
Today I solved this problem as it was needed for some software I was developing. As people above have said; you can hardcode the directory to a specific file - but that would mean whatever config files are needed to load would have to be placed there. For me, this service was being installed on > 50,000 computers. We designed it to load from directory in which the service executable is running from. Now, this is easy enough to set up and achieve as a non-system process (I did most of my testing as a non-system process). But the thing is that the system wrapper that you used (and I used as well) uses Unicode formatting (and depends on it) so traditional ways of doing it doesn't work as well. Commented parts of the code should explain this. There are some redundancies, I know, but I just wanted a working version when I wrote this. Fortunately, you can just use GetModuleFileNameA to process it in ASCII format The code I used is: ``` char buffer[MAX_PATH]; // create buffer DWORD size = GetModuleFileNameA(NULL, buffer, MAX_PATH); // Get file path in ASCII std::string configLoc; // make string for (int i = 0; i < strlen(buffer); i++) // iterate through characters of buffer { if (buffer[i] == '\\') // if buffer has a '\' in it, replace with doubles { configLoc = configLoc + "\\\\"; // doubles needed for parsing. 4 = 2(str) } else { configLoc = configLoc + buffer[i]; // else just add char as normal } } // Complete location configLoc = configLoc.substr(0, configLoc.length() - 17); //cut the .exe off the end //(change this to fit needs) configLoc += "\\\\login.cfg"; // add config file to end of string ``` From here on, you can simple parse configLoc into a new ifsteam - and then process the contents.
Use this function to adjust the working directory of the service to be the same as the working directory of the exe it's running. ``` void AdjustCurrentWorkingDir() { TCHAR szBuff[1024]; DWORD dwRet = 0; dwRet = GetModuleFileName(NULL, szBuff, 1024); //gets path of exe if (dwRet != 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { *(_tcsrchr(szBuff, '\\') + 1) = 0; //get parent directory of exe if (SetCurrentDirectory(szBuff) == 0) { //Error } } } ```
337,067
2,235,806
I am creating simple pojo webservice like TemperatureConversion. I was able to make deploy it and generate wsdl from it. The problem is that I want to change the EPR / address from "<http://172.x.x.x:8080/MyWebservice/services/TemperatureConversion>" to "<http://172.x.x.x:8080/MyWebservice/TemperatureConversion>" Is that possible? Thanks.
2010/02/10
[ "https://Stackoverflow.com/questions/2235806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270153/" ]
OpenGL ES is another possibility. Apple provide all the code to set up a rendering context. From there you just need to get your image into a texture, define some vertices (more than just four), and move each vertex on a sine wave.
Yes - you may want to look into cocos2d - <http://www.cocos2d-iphone.org> or OpenGL ES as mentioned above or Quartz It all depends on what this 'Wave' effect needs to look like, if it's what i think, you couldn't achieve that by using Core Animation, you would need to look in to these suggestions.
315,373
68,384
> > Therefore Jesus answered them and said, “My teaching is not of myself, but of the One having sent me. If anyone desires to do His (God's) will, he will know concerning the teaching, **whether it is from God, or I speak from myself**. > > > What does this passage teach us about the relationship between Jesus and God? Traditionally Christians have taught that Jesus is God, but at face value this does not seem to be the teaching of this passage.
2021/09/06
[ "https://hermeneutics.stackexchange.com/questions/68384", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/35842/" ]
> > If any man will do his will, he shall know of the doctrine, whether it > be of God, or whether I speak of myself. (John 7:17, KJV) > > > John 7:17, like many other passages in the Bible, teaches that God and Jesus were distinct entities from each other. To understand the Bible's teaching on any point, it is always important to consider all other verses on the same subject, to discover the sum and the balance of their truths, and to use the Bible to explain itself. In the table below, a number of these texts are provided that illustrate the same truth as is found in John 7:17, contrasted with the parallel truths that God and Jesus are "one," and that God (the Father) is "one." | God and Jesus Are Separate | God and Jesus Are One | God/Father Is One | | --- | --- | --- | | And yet if I judge, my judgment is true: for I am not alone, but **I and the Father** that sent me. (John 8:16, KJV) | **I and my Father are one**. (John 10:30, KJV) | **One God and Father** of all, who is above all, and through all, and in you all. (Ephesians 4:6, KJV) | | If I had not done among them the works which none other man did, they had not had sin: but now have they both seen and hated **both me and my Father**. (John 15:24, KJV) | And the glory which thou gavest me I have given them; that they may be one, even **as we are one:** (John 17:22, KJV) | That ye may with one mind and one mouth glorify **God, even the Father of our Lord Jesus Christ**. (Romans 15:6, KJV) | | Behold, the hour cometh, yea, is now come, that ye shall be scattered, every man to his own, and shall leave me alone: and yet **I am not alone, because the Father is with me**. (John 16:32, KJV) | And now I am no more in the world, but these are in the world, and I come to thee. Holy Father, keep through thine own name those whom thou hast given me, **that they may be one, as we are**. (John 17:11, KJV) | But to us **there is but one God, the Father**, of whom are all things, and we in him; and one Lord Jesus Christ, by whom are all things, and we by him. (1 Corinthians 8:6, KJV) | | That they all may be one; as **thou, Father, art in me, and I in thee**, that they also may be one **in us:** that the world may believe that **thou hast sent me.** (John 17:21, KJV) | **That they all may be one**; as thou, Father, art in me, and I in thee, **that they also may be one** in us: that the world may believe that thou hast sent me. (John 17:21, KJV) | Ye do the deeds of your father. Then said they to him, We be not born of fornication; we have **one Father, even God**. (John 8:41, KJV) | | These words spake Jesus, and lifted up his eyes to heaven, and said, **Father**, the hour is come; glorify **thy Son,** that **thy Son also may glorify thee**: (John 17:1, KJV) | Then said they unto him, Where is thy Father? Jesus answered, Ye neither know me, nor my Father: **if ye had known me, ye should have known my Father also.** (John 8:19, KJV) | And this is life eternal, that they might know **thee [Father] the only true God**, and Jesus Christ, whom thou hast sent. (John 17:3, KJV) | | For **there is one God, and one mediator** between God and men, the man Christ Jesus; (1 Timothy 2:5, KJV) | **If ye had known me, ye should have known my Father also**: and from henceforth ye know him, and have seen him. (John 14:7, KJV) | And call no man your father upon the earth: for **one is your Father**, which is in heaven. (Matthew 23:9, KJV) | Naturally, the apparent "oneness" of the Father and Jesus can be said to be a unity between them, for it is likened to the oneness Jesus desires his disciples to have with his Father. Clearly, the disciples will never be God, nor could ever be God, so their oneness does not apply to oneness of *being*. Neither were Jesus and the Father the same being. They are two, united in purpose, but divided in that God is spirit while Man is flesh. God (the Father) was *in Christ*, as Jesus taught plainly, but Christ was not the Father. Had Christ been the Father (God), why would he have addressed the Father in his prayer? The Father need not pray to Himself, nor does God pray to God. **In Conclusion:** Jesus and the Father are separate entities, yet one in spirit and in purpose. --- **Update:** *Answers to Questions* **Q:** *You say ”Jesus and the Father are separate entities, yet one in spirit and in purpose” please explain “one in spirit”.* **A:** This is an important and valid question. I had actually left it intentionally simple so as not to complicate the answer, but intending the expression to have a dual meaning. To clarify, let us consider the Bible's own usage of the expression "in spirit." | Reference | Passage with "in spirit" | | --- | --- | | Prov 29:23 | A man's pride shall bring him low: but honour shall uphold the humble **in spirit.** | | Eccl 7:8 | Better is the end of a thing than the beginning thereof: and the patient **in spirit** is better than the proud **in spirit.** | | Isa 29:24 | They also that erred **in spirit** shall come to understanding, and they that murmured shall learn doctrine. | | Mat 5:3 | Blessed are the poor **in spirit:** for theirs is the kingdom of heaven. | | Mat 22:43 | He saith unto them, How then doth David **in spirit** call him Lord, saying, | | Luk 1:80 | And the child grew, and waxed strong **in spirit,** and was in the deserts till the day of his shewing unto Israel. | | Luk 2:40 | And the child grew, and waxed strong **in spirit,** filled with wisdom: and the grace of God was upon him. | | Luk 10:21 | In that hour Jesus rejoiced **in spirit,** and said, I thank thee, O Father, Lord of heaven and earth, that thou hast hid these things from the wise and prudent, and hast revealed them unto babes: even so, Father; for so it seemed good in thy sight. | | Joh 4:23 | But the hour cometh, and now is, when the true worshippers shall worship the Father **in spirit** and in truth: for the Father seeketh such to worship him. | | Joh 4:24 | God is a Spirit: and they that worship him must worship him **in spirit** and in truth. | | Joh 13:21 | When Jesus had thus said, he was troubled **in spirit,** and testified, and said, Verily, verily, I say unto you, that one of you shall betray me. | | Rom 12:11 | Not slothful in business; fervent **in spirit;** serving the Lord; | | 1Cor 5:3 | For I verily, as absent in body, but present **in spirit,** have judged already, as though I were present, concerning him that hath so done this deed, | In these texts, the term "spirit" is used to mean one's character, ideals, or seat of emotions--alluding to one's perspective, mood, or attitude. A similar word in these cases might be "soul," but translators (at least of the KJV) were careful to differentiate between "soul" (Greek *ψυχή*/psyche) and "spirit" (Greek *πνεῦμα*/pneuma), both of which can also be translated as "breath." The Bible itself indicates how similar these words are in Hebrews 4:12 where God's word is likened to a two-edged sword that is capable of dividing between them. When speaking of Jesus and the Father being "one in spirit" in this sense, I refer to them as being in agreement, in unity, in these characteristics. They have the same perspective, character, and attitude. When using this sense of meaning, I refer to Jesus (the man) and the Father (God) as separate entities who work together in unity. But there is another sense of "spirit" which could legitimately apply. Jesus said "God is (a) spirit" (John 4:24). God is not made of flesh and blood as we are. He is a spiritual being: immortal, invisible, omnipotent, omniscient, and omnipresent. The Father, who IS spirit, was *in Christ*. Thus, Christ had his own human spirit, just as any of us has a spirit, and Christ also had the Spirit of God, the Father, dwelling in him. God is not said to have *two* spirits, but *one* (see Eph. 2:18; 4:4; 1 Cor. 12:13; cf. Deut. 6:4). Therefore, the spirit of God dwelling in Jesus was God's actual presence and Being. **Q:** *Just so I understand, are you saying that God is three personalities in one, that is that there is God the father, God the son, and God the Holy Spirit?* **A:** No. The Bible does not teach that God is three personalities. The Bible is clear that God is one single entity (see 1 Cor. 8:6; John 17:1-3; 1 Tim. 2:5; Deut. 6:4; Mal. 2:10; Eph. 4:6; Jam. 2:19). The Bible indicates, however, that God, who is omnipresent, was present in Christ (see 2Cor. 5:19). Christ, whose humanity veiled the presence of God (see Hebrews 10:20), was God's representative to mankind. Simultaneously, as flesh-and-blood man, he is man's representative and mediator to God (see 1 Timothy 2:5). Note that saying "God the Spirit" is actually *spiritualism*, as I outlined in another answer [HERE.](https://hermeneutics.stackexchange.com/questions/63286/should-we-understand-god-as-three-distinct-persons-based-on-at-least-matthew-3/63294#63294)
What does John 7:17 teach us about Jesus' relationship with God? > > Therefore Jesus answered them and said, “My teaching is not of myself, but of the One having sent me. If anyone desires to do His (God's) will, he will know concerning the teaching, whether it is from God, or I speak from myself. > > > What does this passage teach us about the relationship between Jesus and God? Traditionally Christians have taught that Jesus is God, but at face value this does not seem to be the teaching of this passage. The Relationship between God and Jesus in the Gospel of John 17 is seen as a servant to God. Jesus never initiates anything because all his actions are of God showing Him and telling him what he wants him to do. In this capacity he is seen as the servant to the circumcision. > > For I say that Christ has become a servant to the circumcision on behalf of the truth of God to confirm the promises given to the fathers, Rom 15:8 > > > The Scriptures listed below are all from John 17 from the YLT translation. The same chapter that the first question was referred to. > > Thou didst give to him authority over all flesh, that — all that Thou hast given to him — he may give to them life age-during; John 17:1-2 > > > > > that they may know Thee, the only true God, and him whom Thou didst send — Jesus Christ the work I did finish that Thou hast given me > > > > > glorify Thou Father, with Thyself > > > > > Thou hast given to me out of the world; Thine they were, and to me Thou hast given them > > > > > Now they have known that all things, as many as Thou hast given to me, are from Thee > > > > > truly, that from Thee I came forth > > > > > Thou didst send me. > > > > > that they may be one as we > > > > > I have given to them Thy word > > > --- In the Book of Hebrews a revelation of a new relationship is stated between God and His Son Jesus. This happened after he had provided purification for sins. > > After He had provided purification for sins, He sat down at the right hand of the Majesty on high. Heb 1:3 > > > He was now sitting down at the right hand of majesty on high since his work has been completed. God brings new honor and glory to His son that he has created everything through. God now calls his son God. > > And unto the Son: ‘Thy throne, O God, [is] to the age of the age; a scepter of righteousness [is] the scepter of thy reign; > Thou didst love righteousness, and didst hate lawlessness; because of this did He anoint thee — God, thy God — with oil of gladness above thy partners;’ > > > God has given His son a new title for the next two ages that are coming as he will be ruling from his throne that the Father has given him. > > Isaiah 53:12 > Therefore will I divide him a portion with the great, and he shall divide the spoil with the strong; because he hath poured out his soul unto death: and he was numbered with the transgressors; and he bare the sin of many, and made intercession for the transgressors. > > > > > He has spoken to us by His Son, whom He appointed heir of all things, and through whom He made the universe. > > > > > The Son is the radiance of God’s glory and the exact representation of His nature, upholding all things by His powerful word. > > > > > The Son is the image of the invisible God, the firstborn over all creation. Colossians 1:15 > > > God is invisible. The son is his image. The word for image is 1504 eikṓn (from 1503 /eíkō, "be like") – properly, "mirror-like representation," Image (1504 /eikṓn) then exactly reflects its source Christ is the very image of God.
277,803
2,605,450
As a starter: the auxiliary equation is given by $t^2+2t+5=0$ so $t=-1-2i$, $t=-1+2i$, so you can use this to determine the complementary function. The next step is determining the particular integral. How would you approach this?
2018/01/14
[ "https://math.stackexchange.com/questions/2605450", "https://math.stackexchange.com", "https://math.stackexchange.com/users/521179/" ]
**Hint:** With $x=\cos^22u$ then $$\int\sqrt{\frac{1-\sqrt{x}}{1+\sqrt{x}}}\,dx.=-4\int\cos2u(1-\cos2u)dx=2u+\dfrac12\sin4u-2\sin2u+C$$
An appropriate substitution would be $$u = \sqrt{\frac{1-\sqrt{x}}{1+\sqrt{x}}}, \quad x = \left(\frac{u^2-1}{u^2+1}\right)^2, \quad dx = \frac{8u(u^2-1)^2}{(u^2+1)^3} \, du.$$ This results in a straightforward partial fraction decomposition of a rational polynomial.
106,957
26,042,092
Hello I want to get json from http post request. I used this site: <http://www.hurl.it/> to test my request and it's working well ![http://i.imgur.com/qn5gK4D.png](https://i.stack.imgur.com/DbIdm.png) so I wanted to do same request in my code. Something in my code doesn't work: ``` @SuppressWarnings({ "rawtypes", "unchecked" }) public static String postHttpResponse() { Log.d("post", "Going to make a post request"); StringBuilder response = new StringBuilder(); try { Log.d("post", "Im inside :-)))))"); HttpPost post = new HttpPost(); URI uri = new URI("https://mywebsite.com/Home/GetHomeTemplates"); post.setURI(uri); List params = new ArrayList(); params.add(new BasicNameValuePair("Skip","100")); params.add(new BasicNameValuePair("Take","50")); params.add(new BasicNameValuePair("Type","-1")); params.add(new BasicNameValuePair("PluginType","-1")); params.add(new BasicNameValuePair("Proportion","-1")); params.add(new BasicNameValuePair("Sort","6")); params.add(new BasicNameValuePair("SortDirection","1")); params.add(new BasicNameValuePair("Categories","[]")); params.add(new BasicNameValuePair("Controls","[]")); params.add(new BasicNameValuePair("IsFree","true")); params.add(new BasicNameValuePair("IsSystem","true")); post.setHeader("Host","mywebsite.com"); post.setHeader("Accept","application/json, text/javascript, */*; q=0.01"); post.setHeader("Content-Type","application/json; charset=UTF-8, charset=utf-8"); post.setHeader("Referer","https://mywebsite.com/Templates"); post.setEntity(new UrlEncodedFormEntity(params)); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(post); if (httpResponse.getStatusLine().getStatusCode() == 200) { Log.d("post", "HTTP POST succeeded"); HttpEntity messageEntity = httpResponse.getEntity(); InputStream is = messageEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { response.append(line); } } else { Log.d("post", "HTTP POST status code is not 200"); } Log.d("post", "Done with HTTP posting"); Log.d("post", "Post" + response.toString()); } catch (Exception e) { Log.d("Exception: ", "Post " + e.getMessage()); } return response.toString(); ``` My logcat with post filter: ``` 09-25 19:49:05.290: D/post(26343): Going to make a post request 09-25 19:49:05.290: D/post(26343): post Im inside :-))))) 09-25 19:49:05.290: D/Exception:(26343): Post null ``` So it's supossed to be that code inside try/catch isn't running. **Edit:** There wasn't log "Im inside :-))))" because i was filtering for string "post" in logcat search. I also debugged and checked that my parameters aren't passed to my request. I've edited my params as @Almer Nakano suggested but it still doesn't see parameters. ``` List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("Skip","100")); params.add(new BasicNameValuePair("Take","50")); params.add(new BasicNameValuePair("Type","-1")); params.add(new BasicNameValuePair("PluginType","-1")); params.add(new BasicNameValuePair("Proportion","-1")); params.add(new BasicNameValuePair("Sort","6")); params.add(new BasicNameValuePair("SortDirection","1")); params.add(new BasicNameValuePair("Categories","[]")); params.add(new BasicNameValuePair("Controls","[]")); params.add(new BasicNameValuePair("IsFree","true")); params.add(new BasicNameValuePair("IsSystem","true")); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26042092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3978701/" ]
You can use `JSONArray` and `JSONObject` for this. ``` JSONArray array = new JSONArray(textResponse); ``` And use `array.getJSONObject(index)` to get `JSONObject` and `array.length()` to get the number of elements. ``` JSONObject jsonObject = array.getJSONObject(0); String bankname = jsonObject.getString(bankname); int id = jsonObject.getInt(id); ```
If you are using **Grails/Groovy**, you can use this following : ``` def resp = grails.converters.JSON.parse(response) ``` Then, access by *resp.id, resp.bankname*
70,505
30,903
Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git?
2008/08/27
[ "https://Stackoverflow.com/questions/30903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071/" ]
Try the newly released [**MacHg**](http://jasonfharris.com/machg/). It uses the native GUI toolkit for Mac and comes with its own bundled version of Mercurial. ![State after a merge in MacHg](https://i.stack.imgur.com/5S6PU.png) There are [many more screenshots](http://jasonfharris.com/machg/sceenshots/sceenshots.html) available.
> > hg: unknown command 'view' > > > (Maybe I need to install something - but it's not native, nonetheless). There is one "native" application out there, but it's not especially user-friendly. In fact, I'd go as far as saying that it's harder to use than the command line. There was some talk a year or so ago about a version of SCPlugin, which puts badges on icons in the Finder that are under SVN control, and gives you a contextual menu (very much like TortoiseSVN on windows), but that seems to have collapsed. I have been planning to create a mercurial "clone" of Versions (I asked them if they would consider doing a version of it for DVCS, and they said no).
348,924
11,008,373
I'm having an issue. I'm trying to display some images alongside some text in a menu, however each image has a larger height than the text therefore the text is centered to the image. Essentially, this is the site: <http://www.sasstraliss.org/scme2202> And, it views perfectly fine in firefox. In chrome, it displays vertically. In IE, the images are squashed. Where has my CSS gone wrong? I'm using this approach for the images... ``` #menu img { min-height: 1em; display: table-cell; vertical-align: middle; padding: 0px 0px 0px 10px; } ```
2012/06/13
[ "https://Stackoverflow.com/questions/11008373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311773/" ]
When you call `System.gc()`, you say to the garbage collector to make a clean-up. The problem is that it isn't clear when the `GC` will respond to your request. Even more, it is possible that `GC` to not run at all when you call it. **In java you cannot predict how the `GC` will work**. (That's why is considered bad practice to put your cleanup code in `Object`'s `finalize()` method). In `Java`, the out of reference objects are collected for garbage automatically. That's why you don't need to call `System.gc()`. In special cases, when you want run it if possible, you can try to make use of this method, but the behavior is not guaranteed. (as specified above).
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection. Generally an object becomes eligible for garbage collection in Java on following cases: 1) All references of that object explicitly set to null e.g. object = null 2) Object is created inside a block and reference goes out scope once control exit that block. 3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection. 4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
39,534
9,778,143
I have donation page which when the user clicks donate it posts the data to a php file named test.php I am trying this out my first trying to echo the first name and last name but this is not working ultimately I want this php page to run a MySQL query to update the total\_Donation row within a database, here is my main php page first. **Database code which sits at top of file** ``` <?php $con = mysql_connect("localhost","root","null"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("snr", $con); $names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0"; $names_query = mysql_query($names_sql)or die(mysql_error()); $rsNames= mysql_fetch_assoc($names_query); if(isset($_POST['donation']) && $_POST['donation'] != '') { $donation = mysql_real_escape_string($_GET['donation']); $fname = mysql_real_escape_string($_GET['first_Name']); $lname = mysql_real_escape_string($_GET['last_Name']); $donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname}'"; } mysql_close($con); ?> ``` Here is my form section of html ``` form method ="post" action="test.php"> <table> <tr><td><label>Runner:</label></td> <td> <select> <?php do{?> <option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option> <?php } while ( $rsNames= mysql_fetch_assoc($names_query))?> </select> </td> </tr> <tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation"/></td></tr> <tr><td><input id="submit" type="submit" value="DONATE"/></td></tr> </table> </form> ``` the option gets all the first names and last names fine when the user hits donate I want it to run the $donation\_sql but all i get are errors saying unidentified index, I'm even trying the below in the test.php to simply just echo the first\_Name this is giving the same error. ``` <?php echo $_POST['first_Name']; ?> ``` Can someone please help me with this, thanks.
2012/03/19
[ "https://Stackoverflow.com/questions/9778143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207707/" ]
Ideally, you don't want to put variables directly into your output like that because if there's just a single `'` in that string your JavaScript will screw up. Instead, avoid both problems by not using HEREDOC and using the proper method: ``` echo "<button id=\"buy\" class=\"...\" onclick=\"alert(".htmlspecialchars(json_encode($stockInfo[0]['name'])).");\">Buy</button>"; ``` [`json_encode`](http://php.net/json_encode) essentially makes any PHP variable (except resources) able to be dumped directly into JavaScript code. [`htmlspecialchars`](http://php.net/htmlspecialchars) makes the result safe to use in an HTML attribute.
``` echo <<<EOT <button id="buy" class="btn btn-primary btn-small" onclick="alert({$stockInfo[0]["name"]});">Buy</button> EOT; ?> ```
365,042
126,210
Are there any real world applications written in the [Clean](http://clean.cs.ru.nl/) programming language? Either open source or proprietary.
2008/09/24
[ "https://Stackoverflow.com/questions/126210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using Clean together with the iTasks library to build websites quite easy around workflows. But I guess another problem with Clean is the lack of documentation and examples: "the Clean book" is from quite a few years back, and a lot of new features don't get documented except for the papers they publish.
[Cloogle](https://cloogle.org), a search engine for Clean libraries, syntax, etc. (like Hoogle for Haskell) is written in Clean. Its source is on Radboud University's GitLab instance ([web frontend](https://gitlab.science.ru.nl/cloogle/cloogle-org); [engine](https://gitlab.science.ru.nl/cloogle/Cloogle)).
28,817
1,679,206
I have a file with data in the following format: ``` <user> <fname>Anthony</fname> <lname>Smith</lname> <accid>3874918</accid> </user> <user> ... </user> ``` I'm trying to parse this data and store it to MySQL database with the follwing fields: fname, lname, accid. Now the problem is how to determine `<user>` and `</user>` so I can parse the data inside of it? Thank you.
2009/11/05
[ "https://Stackoverflow.com/questions/1679206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203282/" ]
If it's valid XML, use [SimpleXML](http://php.net/manual/en/book.simplexml.php). First you will need to ensure that you have a single root element, for example `<users>`: ``` <?php $str = "<users> <user>...</user> <user>...</user> </users>"; $xml = simplexml_load_string($str>; foreach ($xml as $user) { // Make a query using $user->fname, $user->lname, $user->accid } ```
If you are using PHP5.x, SimpleXML will help you. ``` <?php $sample = <<<END <foo> <user> <fname>Anthony</fname> <lname>Smith</lname> <accid>3874918</accid> </user> <user> <fname>foo</fname> <lname>bar</lname> <accid>123</accid> </user> </foo> END; $xml = simplexml_load_string($sample); var_dump($xml); ```
9,692
7,729
I have an apex:commandButton on a visualforce page that invokes a method on the controller. There is currently no rerender value set for the button. Instead the controller method returns a PageReference to redirect the user as required. E.g. **Visualforce:** ``` <apex:commandButton value="Save" action="{!save}"/> ``` **Controller:** ``` public PageReference save() { // save body ... // return the user the a parent opportunity return new PageReference('/' + opp.Id); } ``` Users are currently able to click on the resulting save button multiple times before the controller completes and returns the PageReference to redirect the browser to an opportunity. **How can I disable the commandButton after the first click?** --- I tried wrapping the commandButton in an actionStatus and facet, but the need to define the rerender property prevented the resulting PageReference redirect. E.g. This will render nicely in the browser and prevent multiple clicks, but doesn't redirect to the Opportunity on completion. ``` <apex:actionStatus id="saveStatus"> <apex:facet name="stop"> <apex:commandButton value="Save" action="{!save}" status="saveStatus" rerender="saveParentBlock" /> </apex:facet> <apex:facet name="start"> <apex:commandButton value="Saving..." disabled="true" status="saveStatus"/> </apex:facet> </apex:actionStatus> ``` --- There is a similar question [Using jQuery to disable VF page button onclick](https://salesforce.stackexchange.com/questions/7229/using-jquery-to-disable-vf-page-button-onclick). I need to support an existing PageReference redirect, which slightly alters the requirements. Force.com Discussion Boards: [Disabling a commandButton to prevent double submission](http://boards.developerforce.com/t5/Visualforce-Development/Disabling-a-commandButton-to-prevent-double-submission/m-p/154027) Ideas: [Disable command buttons on click in visualforce as standard](https://sites.secure.force.com/success/ideaView?id=087300000007ZuS)
2013/01/27
[ "https://salesforce.stackexchange.com/questions/7729", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/102/" ]
This is one possible solution, I'm still keen to see if there is a better way of doing this, such as getting the actionStatus and facet to work with a PageReference redirect. --- If the commandButton onclick event is used to immediately disable the button the post back to the controller method won't occur. **This won't work:** ``` <apex:commandButton id="save" value="Save" action="{!save}" onclick="this.disabled='disabled';return true;" /> ``` Instead, create a JavaScript function that will disable the button after a short timeout via the commandButtons onclick event. You could inline this all into the onclick as required. I found it easier to split the functions out so I could disable other related buttons, etc. ``` <script> function disableOnSubmit(input) { setTimeout('disableAfterTimeout(\'' + input.id + '\');', 50); } function disableAfterTimeout(id) { var toDisable = document.getElementById( id ); toDisable.disabled = 'disabled'; // Use the Salesforce CSS style to make the button appear disabled toDisable.className = 'btnDisabled'; toDisable.value = "Saving..." } </script> <apex:commandButton id="save" value="Save" action="{!save}" onclick="disableOnSubmit(this);" /> ```
Try commandButton with actionFunction: ``` <commandButton onclick="disableMe" oncomplete="runActionJS();"/> <actionFunction name="runActionJS" action"{!action}"/> ```
317,369
8,469,291
I am just learning how to define a function and call it back later. I am stuck trying to define 'this' in my function without using an event. ``` function slide() { var imgAlt = $(this).find('img').attr("alt"); var imgTitle = $(this).find('a').attr("href"); var imgDesc = $(this).find('.block').html(); var imgDescHeight = $(".main_image").find('.block').height(); $(.active); $(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { $(".main_image .block").html(imgDesc).animate({ opacity: 0.85, marginBottom: "0" }, 250 ); $(".main_image img").attr({ src: imgTitle , alt: imgAlt}); } ); } }); ``` On line 6 you will see '$(.active); ' and this is where I want to select the class active and then apply the following function to it. Normally I used to setting this up on a click or something so I am unsure how to impliment it. Any help greatly appreciated! Thanks Here is a js fiddle where you can see the big picture: <http://jsfiddle.net/wzQj6/21/>
2011/12/12
[ "https://Stackoverflow.com/questions/8469291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592379/" ]
See lines 3-4 in code below for how to cache your `.active` elements for reuse (and then use that instead of `this`!): ``` function slide() { //cache all .active elements for reuse var actives = $(".active"); //use the new 'actives' variable instead of 'this' var imgAlt = actives.find('img').attr("alt"); var imgTitle = actives.find('a').attr("href"); var imgDesc = actives.find('.block').html(); var imgDescHeight = $(".main_image").find('.block').height(); //$(.active); -- not sure what you were doing with this :p $(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { $(".main_image .block").html(imgDesc).animate({ opacity: 0.85, marginBottom: "0" }, 250 ); $(".main_image img").attr({ src: imgTitle , alt: imgAlt}); } ); } }); ``` Cheers!
When you're calling a function, the `this` inside its scope (also called the context) is normally the object that owns and calls the said function. (i.e. with `foo.bar()`, inside `bar()`, `this == foo` normally.) In Javascript, if you want to call a function AND specify what the function context is, you can use the `call` method like so: ``` bar.call(foo); // inside bar, this == foo, even if foo wasn't the owner / caller of the function ``` You haven't posted the code for the function that you actually want to call, so I can't comment on whether or not this is the (most) correct way for you to do it, but from what I understand, this should work for you. ``` // take note, also, that your syntax for selecting .active is incorrect. // you should be passing in a string. var active_elements = $('.active'); some_function.call(active_elements); ```
244,789
47,776,136
I have some code that converts the elements of sequences with different functions like that: ``` someSequence map converterFunction ``` However, sometimes I have not a sequence but a single value that is to be passed to the function. For consistency with the other lines I'd like to write it like that ``` someValue applyTo converterFunction ``` So in a way it is like mapping a single value. Of course I can just call the function with the value, I'm just wondering if it is possible to write it similar to the way I proposed.
2017/12/12
[ "https://Stackoverflow.com/questions/47776136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302793/" ]
I agree with ChrisK that this idea doesn't sound as a good one to me in terms of code readability but if you really want it, you can do it using something like this: ``` implicit final class MapAnyOp[T](val value: T) extends AnyVal { def map[R](f: T => R) = f(value) } def convert(v: Int): String = Integer.toHexString(v) println(List(123, 234, 345) map convert) println(123 map convert) ```
You could wrap it in a Seq: ``` Seq(someValue) map converterFunction ``` If *someValue* is a custom type/class, you can define an operator that will do that for you instead of having this explicit wrapping. ``` someValue.seq map converterFunction ```
309,907
523,220
For a small community discussion, what are some essential Visual Studio macros you use? I just started learning about them, and want to hear what some of you can't live without.
2009/02/07
[ "https://Stackoverflow.com/questions/523220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53599/" ]
I use the following lesser-known shortcuts very often: * **Ctrl+Enter**: Insert a blank line above the current line (and place the cursor there) * **Ctrl+Shift+Enter**: Insert a blank line below the current line (and place the cursor there) * **Ctrl+Shift+V**: Cycles the [clipboard ring](http://blogs.msdn.com/zainnab/archive/2010/01/02/how-to-cycle-through-the-clipboard-ring-to-paste-different-things.aspx)
Insert GUID, great for WiX work, add to menu as button or as key shortcut. ``` Sub InsertGuid() Dim objTextSelection As TextSelection objTextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection) objTextSelection.Text = System.Guid.NewGuid.ToString.ToUpper(New System.Globalization.CultureInfo("en", False)) End Sub ``` Organise usings for all .cs files in a solution - **Original Author:** [djpark](http://blogs.msdn.com/djpark/archive/2008/08/16/organize-usings-across-your-entire-solution.aspx). ``` Sub OrganizeSolution() Dim sol As Solution = DTE.Solution For i As Integer = 1 To sol.Projects.Count OrganizeProject(sol.Projects.Item(i)) Next End Sub Private Sub OrganizeProject(ByVal proj As Project) For i As Integer = 1 To proj.ProjectItems.Count OrganizeProjectItem(proj.ProjectItems.Item(i)) Next End Sub Private Sub OrganizeProjectItem(ByVal projectItem As ProjectItem) Dim fileIsOpen As Boolean = False If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then 'If this is a c# file If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then 'Set flag to true if file is already open fileIsOpen = projectItem.IsOpen Dim window As Window = projectItem.Open(Constants.vsViewKindCode) window.Activate() projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort") 'Only close the file if it was not already open If Not fileIsOpen Then window.Close(vsSaveChanges.vsSaveChangesYes) End If End If End If 'Be sure to apply RemoveAndSort on all of the ProjectItems. If Not projectItem.ProjectItems Is Nothing Then For i As Integer = 1 To projectItem.ProjectItems.Count OrganizeProjectItem(projectItem.ProjectItems.Item(i)) Next End If 'Apply RemoveAndSort on a SubProject if it exists. If Not projectItem.SubProject Is Nothing Then OrganizeProject(projectItem.SubProject) End If End Sub ```
13,920
3,742,332
For some reason, after a user enters text into an EditText within my Android app the white-bar which contains "suggestions" remains at the bottom of my Layout! If you press the "Back" button, it disappears. How can I stop this from remaining after completing text entry? EDIT: Screenshots Editing the text, white bar appears with suggestions: ![alt text](https://i.stack.imgur.com/4JiKy.png) And after going back to the ListView activity ![alt text](https://i.stack.imgur.com/jG1r4.png)
2010/09/18
[ "https://Stackoverflow.com/questions/3742332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250022/" ]
What IME are you using? The suggestion bar is part of the IME, the app doesn't have control over it. This looks like a buggy IME.
Got the same problems running emulator with adnroid 2.1-update 1 only --- well found solution: Just press one or two times escape on your keyboard that will make it disappear
182,276
43,062,572
I want to fire validation to check entered email address is business email address or not immediately after lost focus from email field before submitting the form. I tried many filters ``` add_action('woocommerce_after_checkout_validation', 'rei_after_checkout_validation'); function rei_after_checkout_validation( $posted ) { } ``` but filter is fired after submitting the form. Please help me to solve it.
2017/03/28
[ "https://Stackoverflow.com/questions/43062572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5624058/" ]
Change `android:background="@drawable/my_bg"` to `android:src="@drawable/my_bg"`
**Try this:** ``` <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/icon_pressed" android:state_pressed="true" /> <item android:drawable="@mipmap/icon_simples" android:state_pressed="false" android:state_selected="false" /> </selector> ``` Hope this will work~
199,036
8,752,458
I want to execute 2 separated commands to return me a value from my table. the first one could be top 1, because is the first line, no problem... but how can I make something like top 2, but only showing the second line? Is there a simple way to do it? Like one simple select? 1 line: > > select top 1 Code from Products order by LastUpdate desc > > >
2012/01/06
[ "https://Stackoverflow.com/questions/8752458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281705/" ]
**Select first row:** `select ... order by some_rule limit 1;` **Select second row:** `select ... order by some_rule limit 1 offset 1;`
To get the second row from top you can use ``` SELECT c1 , c2 , c3 FROM table ORDER BY c1 OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY; ```
145,946
1,646,934
I'm getting the above message when attempting to add one of our trading partners' domain to the **Allowed Domains** list for the **Anti-Spam inbound policy** in the **[Office 365 Security & Compliance](https://protection.office.com/antispam)** portal. I'm able to get to the **Manage allowed domain** window and click the "**+**". I then enter, e.g., `newalloweddomain.com`, hit **`[ENTER]`** (or click the "tooltip" box) to have it show up below the textbox, and click the **Add domains** button at the bottom. [![Adding allowed domain](https://i.stack.imgur.com/LhXAI.png)](https://i.stack.imgur.com/LhXAI.png) Then I click **Done**. I'm able to complete all of these steps without error but, when I click the final **Save** button on the main **Allowed and blocked senders and domains** screen, I get the error mentioned above (and displayed in this screenshot): [![Client Error: Settings conflict!](https://i.stack.imgur.com/pUkOT.png)](https://i.stack.imgur.com/pUkOT.png) I've tried with a few different domains - both real and bogus - all resulting in the same error. I've tried adding a "dummy" specific address to the **Allowed Senders** list and get the same thing. I've also checked to confirm that the domain name I'm trying to add is not already in the allowed list. I've even gone through the other allowed *and* blocked lists to ensure that neither the domain nor any specific address using that domain is listed in any of them. I've added domains and individual addresses to these lists in the past without issue using this portal (although they've obviously "updated" it since the last time I was in there), so I'm not sure where else to look for potential settings conflicts. What other Office 365 administration settings might be causing this conflict?
2021/05/05
[ "https://superuser.com/questions/1646934", "https://superuser.com", "https://superuser.com/users/814039/" ]
Good Day All - I was having the same issue and what I had found in reviewing the email I was trying to add to the 'Safe' List, was already in the 'Blocked' List, thus the conflict. I tested the theory by removing the email from the blocked list and the safe list where I had added them in the Classic Exchange Admin Center, proceeded to add the same email to the safe list in the 'New' Security area and this worked, no conflict.
i got the same error this morning, I was able to edit the policy via the ECP (the old way) rather than using the protection.office.com.
89,517
46,634,343
```js $('.mark').click(function(){ var id = $(this).attr('id'); var next = (Number(id) + 1); window.scrollTo($('#'+next)); }) ``` ```css .mark { height: 500px; color: white; background: black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='marker'> <div class='mark' id='1'>Mark 1</div> <div class='mark' id='2'>Mark 2</div> <div class='mark' id='3'>Mark 3</div> <div class='mark' id='4'>Mark 4</div> <div class='mark' id='5'>Mark 5</div> </div> ``` Right here, I'm trying to make my window scroll to the next div with an `id` numbered with current `id + 1`. I've tried `window.scrollTo($('#'+next));`. But didn't work, then tried `window.scrollTo($('#'+next), 500);`. But always returns to first `div + 500px`. What is the proper way to handle that?
2017/10/08
[ "https://Stackoverflow.com/questions/46634343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8417646/" ]
`window.scrollTo(xpos, ypos)` takes two parameters. The first one is coordinate along x-axis and second is along y-axis. So you can use 0 for first parameter and `$('#'+next).offset().top` for second parameter ```js $('.mark').click(function(){ var id = $(this).attr('id'); var next = (Number(id) + 1); //window.scrollTo(0, $('#'+next).offset().top); $('html, body').animate({scrollTop : $('#'+next).offset().top}, 2000); }) ``` ```css .mark { height: 500px; color: white; background: black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='marker'> <div class='mark' id='1'>Mark 1</div> <div class='mark' id='2'>Mark 2</div> <div class='mark' id='3'>Mark 3</div> <div class='mark' id='4'>Mark 4</div> <div class='mark' id='5'>Mark 5</div> </div> ```
```js $('.mark').click(function(){ var id = $(this).attr('id'); var next = (Number(id) + 1); location.href="#"+next; }); ``` ```css .mark { height: 500px; color: white; background: black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='marker'> <div class='mark' id='1'>Mark 1</div> <div class='mark' id='2'>Mark 2</div> <div class='mark' id='3'>Mark 3</div> <div class='mark' id='4'>Mark 4</div> <div class='mark' id='5'>Mark 5</div> </div> ```
101,430
9,648,912
I am putting together a small project for school that involves rendering the periodic table. I chose to use LWJGL to do this. The problem is, however, that when I render the table, the game starts out at ~30fps(capped at 60fps), and quickly fluctuates to a single-digit fps. I believe that the problem could be a memory leak, but I am unsure. Can anybody see any glaring problems with my code? Here are the main classes involved in rendering the table: EntityPeriodicTable: In charge of holding a huge array of EntityElement objects(see below), activating their logic(tick() and updateInput()). package com.flafla2.periodicTable; ``` import org.lwjgl.opengl.GL11; public class EntityPeriodicTable extends ClickableEntity { //ClickableEntity is an abstract class in charge of the tick(), updateInput(), and render() methods, as well as positioning public EntityElement[] elements = {//This is unfinished, but you get the idea. //new EntityElement(Atomic #, State, Metal, "Symbol", "Name", new Vector2D(posx,posy), this) new EntityElement(1, 2, 2, "H", "Hydrogen", new Vector2D(1,1), this), new EntityElement(2, 2, 2, "He", "Helium", new Vector2D(18,1), this), new EntityElement(3, 0, 0, "Li", "Lithium", new Vector2D(1,2), this), new EntityElement(4, 0, 0, "Be", "Beryllium", new Vector2D(2,2), this), new EntityElement(5, 0, 1, "B", "Boron", new Vector2D(13,2), this), new EntityElement(6, 0, 2, "C", "Carbon", new Vector2D(14,2), this), new EntityElement(7, 2, 2, "N", "Nitrogen", new Vector2D(15,2), this), new EntityElement(8, 2, 2, "O", "Oxygen", new Vector2D(16,2), this), new EntityElement(9, 2, 2, "F", "Fluorine", new Vector2D(17,2), this), new EntityElement(10,2, 2, "Ne", "Neon", new Vector2D(18,2), this), new EntityElement(11, 0, 0, "Na", "Sodium", new Vector2D(1,3), this), new EntityElement(12, 0, 0, "Mg", "Magnesium", new Vector2D(2,3), this), new EntityElement(13, 0, 0, "Al", "Aluminum", new Vector2D(13,3), this), new EntityElement(14, 0, 1, "Si", "Silicon", new Vector2D(14,3), this), new EntityElement(15, 0, 2, "P", "Phosphorous", new Vector2D(15,3), this), new EntityElement(16, 0, 2, "S", "Sulfur", new Vector2D(16,3), this), new EntityElement(17, 2, 2, "Cl", "Chlorine", new Vector2D(17,3), this), new EntityElement(18, 2, 2, "Ar", "Argon", new Vector2D(18,3), this), new EntityElement(19, 0, 0, "K", "Potassium", new Vector2D(1,4), this), new EntityElement(20, 0, 0, "Ca", "Calcium", new Vector2D(2,4), this), new EntityElement(21, 0, 0, "Sc", "Scandium", new Vector2D(3,4), this), new EntityElement(22, 0, 0, "Ti", "Hydrogen", new Vector2D(4,4), this), new EntityElement(23, 0, 0, "V", "Hydrogen", new Vector2D(5,4), this), new EntityElement(24, 0, 0, "Cr", "Hydrogen", new Vector2D(6,4), this), new EntityElement(25, 0, 0, "Mn", "Hydrogen", new Vector2D(7,4), this), new EntityElement(26, 0, 0, "Fe", "Hydrogen", new Vector2D(8,4), this), new EntityElement(27, 0, 0, "Co", "Hydrogen", new Vector2D(9,4), this), new EntityElement(28, 0, 0, "Ni", "Hydrogen", new Vector2D(10,4), this), new EntityElement(29, 0, 0, "Cu", "Hydrogen", new Vector2D(11,4), this), new EntityElement(30, 0, 0, "Zn", "Hydrogen", new Vector2D(12,4), this), new EntityElement(31, 0, 0, "Ga", "Hydrogen", new Vector2D(13,4), this), new EntityElement(32, 0, 1, "Ge", "Hydrogen", new Vector2D(14,4), this), new EntityElement(33, 0, 1, "As", "Hydrogen", new Vector2D(15,4), this), new EntityElement(34, 0, 2, "Se", "Hydrogen", new Vector2D(16,4), this), new EntityElement(35, 1, 2, "Br", "Hydrogen", new Vector2D(17,4), this), new EntityElement(36, 2, 2, "Kr", "Hydrogen", new Vector2D(18,4), this), }; public final int ELEMENT_SIZE = 40; public Vector2D mousePos = new Vector2D(0,0); //Simple 2D vector struct. public double[] SOLID_RGB = {0,0,0}; public double[] LIQUID_RGB = {0,0,1}; public double[] GAS_RGB = {1,0,0}; public double[] METAL_RGB; public double[] NONMETAL_RGB; public double[] METALLOID_RGB; public double[] RECENT_RGB; public EntityPeriodicTable(Vector2D pos) { this.pos = pos; METAL_RGB = new double[3]; METAL_RGB[0] = 0.596078431; //152/255 METAL_RGB[1] = 0.984313725; //251/255 METAL_RGB[2] = 0.596078431; //152/255 NONMETAL_RGB = new double[3]; NONMETAL_RGB[0] = 1; NONMETAL_RGB[1] = 0.647058824; //165/255 NONMETAL_RGB[2] = 0; METALLOID_RGB = new double[3]; METALLOID_RGB[0] = 0.866666667; //221/255 METALLOID_RGB[1] = 0.62745098; //160/255 METALLOID_RGB[2] = 0.866666667; //221/255 RECENT_RGB = new double[3]; RECENT_RGB[0] = 0.803921569; //205/255 RECENT_RGB[1] = 0.788235294; //201/255 RECENT_RGB[2] = 0.788235294; //201/255 } @Override void render() { GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); for(int x=0;x<elements.length;x++) elements[x].render(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); for(int x=0;x<elements.length;x++) elements[x].renderWithTex(); } @Override void tick() { for(int x=0;x<elements.length;x++) elements[x].tick(); } @Override public void updateInput(Vector2D mousePos) { this.mousePos = mousePos; for(int x=0;x<elements.length;x++) { if(mousePos.isInBoundsWithDim(elements[x].pos.x, elements[x].pos.y, elements[x].dim.x, elements[x].dim.y)) elements[x].isSelected = true; else elements[x].isSelected = false; } } @Override void onEntityClicked() { for(int x=0;x<elements.length;x++) { if(mousePos.isInBoundsWithDim(elements[x].pos.x, elements[x].pos.y, elements[x].dim.x, elements[x].dim.y)) elements[x].onEntityClicked(); } } } ``` EntityElement: Holds data of a specific element on the table, and renders it(render code is unfinished) ``` package com.flafla2.periodicTable; import org.lwjgl.opengl.GL11; public class EntityElement extends ClickableEntity { String symbol; String element; int atomicNumber; EntityPeriodicTable table; int state;//0=solid, 1=liquid, 2=gas int metalState;//0=metal, 1=metalloid, 2=nonmetal, 3=discovered recently Vector2D gridPos; public EntityElement(int an, int st, int ms, String sy, String en, Vector2D gp, EntityPeriodicTable pt) { symbol = sy; element = en; atomicNumber = an; table = pt; state = st; metalState = ms; gridPos = gp; dim.x = table.ELEMENT_SIZE; dim.y = table.ELEMENT_SIZE; pos.x = table.pos.x + table.ELEMENT_SIZE*(gridPos.x-1); pos.y = table.pos.y + table.ELEMENT_SIZE*(gridPos.y-1); } public double[] getStateColor() { switch(state) { case 0: return table.SOLID_RGB; case 1: return table.LIQUID_RGB; case 2: return table.GAS_RGB; default: double[] d = {0.0d,0.0d,0.0d}; return d; } } public double[] getMetalColor() { switch(metalState) { case 0: return table.METAL_RGB; case 1: return table.METALLOID_RGB; case 2: return table.NONMETAL_RGB; case 3: return table.RECENT_RGB; default: double[] d = {0.0d,0.0d,0.0d}; return d; } } @Override void render() { GL11.glPushMatrix(); GL11.glTranslatef(pos.x, pos.y, 0); double[] d = getMetalColor(); GL11.glColor3d(d[0], d[1], d[2]); GL11.glBegin(GL11.GL_QUADS); { GL11.glVertex2f(0, 0);//topleft GL11.glVertex2f(dim.x, 0);//topright GL11.glVertex2f(dim.x, dim.y);//bottomright GL11.glVertex2f(0, dim.y);//bottomleft } GL11.glEnd(); GL11.glColor3d(1.0d, 1.0d, 1.0d); GL11.glPopMatrix(); } public void renderWithTex() { Font.drawString(symbol, new Vector2D(pos.x+dim.x/2-Font.getStringWidth(symbol,2)/2,pos.y+dim.y/2-Font.FONT_HEIGHT), 2); } @Override void tick() { if(isSelected) { dim.x = table.ELEMENT_SIZE+6; dim.y = table.ELEMENT_SIZE+6; pos.x = table.pos.x + table.ELEMENT_SIZE*(gridPos.x-1)-3; pos.y = table.pos.y + table.ELEMENT_SIZE*(gridPos.y-1)-3; } else { dim.x = table.ELEMENT_SIZE; dim.y = table.ELEMENT_SIZE; pos.x = table.pos.x + table.ELEMENT_SIZE*(gridPos.x-1); pos.y = table.pos.y + table.ELEMENT_SIZE*(gridPos.y-1); } } @Override void onEntityClicked() { } } ``` Font: Handles rendering text onscreen: ``` package com.flafla2.periodicTable; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; public class Font { public static final String fontText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:;?!\"&',-.[]#()+ "; public static final BufferedImage fontSheet = TextureLoader.loadTexture("/res/text.png"); public static final int FONT_WIDTH = 9; public static final int FONT_HEIGHT = 8; public static void drawString(String s, Vector2D pos, float dim) { drawString(s,pos,new Vector2D((int)Math.floor(dim*FONT_WIDTH),(int)Math.floor(dim*FONT_HEIGHT))); } public static void drawString(String s, Vector2D pos) { drawString(s,pos,new Vector2D(9,8)); } public static void drawString(String s, Vector2D pos, Vector2D dim) { for(int x=0;x<s.length();x++) { drawLetter(s.charAt(x),new Vector2D(pos.x+dim.x*x,pos.y),dim); } } public static int getStringWidth(String s) { return s.length()*FONT_WIDTH; } public static int getStringWidth(String s,float f) { return (int)Math.floor(s.length()*FONT_WIDTH*f); } public static Vector2D getPosOfLetterOnImg(Character c,int gridNumb) { int xOffset = 0; int yOffset = 0; if(!c.equals(' ')) { int letterNumb = fontText.indexOf(c); xOffset = (letterNumb%26)*FONT_WIDTH; if(xOffset != 0) xOffset -=1; yOffset = 0; int yGridOffset = (letterNumb < 26) ? 0 : ((letterNumb < 52) ? 1 : 2); switch(gridNumb) { case 1: yOffset = 34; break; case 2: yOffset = 69; break; default: yOffset = 0; } for(int x=0;x<yGridOffset;x++) yOffset += FONT_HEIGHT+x+3; } else { xOffset = 235; yOffset = 92; } return new Vector2D(xOffset,yOffset); } public static void drawLetter(Character c, Vector2D pos, Vector2D dim) { if(fontSheet == null) return; Vector2D letterPos = getPosOfLetterOnImg(c,2); BufferedImage letterImage = fontSheet.getSubimage(letterPos.x, letterPos.y, FONT_WIDTH, FONT_HEIGHT); int textureID = TextureLoader.loadGLTexture(letterImage); letterImage = null; GL11.glPushMatrix(); GL11.glTranslatef(pos.x, pos.y, 0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); GL11.glBegin(GL11.GL_QUADS); { GL11.glTexCoord2f(0, 0); GL11.glVertex2f(0, 0); GL11.glTexCoord2f(1, 0); GL11.glVertex2f(dim.x, 0); GL11.glTexCoord2f(1, 1); GL11.glVertex2f(dim.x, dim.y); GL11.glTexCoord2f(0, 1); GL11.glVertex2f(0, dim.y); } GL11.glEnd(); GL11.glPopMatrix(); } } ``` TextureLoader: Loads textures(duh lol) ``` package com.flafla2.periodicTable; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class TextureLoader { public static BufferedImage loadTexture(String texturePath) { try { return ImageIO.read(PeriodicTable.class.getResource(texturePath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private static final int BYTES_PER_PIXEL = 4; public static int loadGLTexture(BufferedImage image){ int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); //4 for RGBA, 3 for RGB for(int y = 0; y < image.getHeight(); y++){ for(int x = 0; x < image.getWidth(); x++){ int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component buffer.put((byte) (pixel & 0xFF)); // Blue component buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. Only for RGBA } } buffer.flip(); //FOR THE LOVE OF GOD DO NOT FORGET THIS // You now have a ByteBuffer filled with the color data of each pixel. // Now just create a texture ID and bind it. Then you can load it using // whatever OpenGL method you want, for example: int textureID = GL11.glGenTextures(); //Generate texture ID GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); //Bind texture ID //Setup wrap mode GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); //Setup texture scaling filtering GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); //Send texel data to OpenGL GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); buffer = null; //Return the texture ID so we can bind it later again return textureID; } } ``` I know, it's a lot of code, but if anyone can help me out it would be greatly appreciated. Thanks, Flafla2.
2012/03/10
[ "https://Stackoverflow.com/questions/9648912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203881/" ]
You have to apply it to body tag. Shorthand: ``` body { background: black; } ``` Single property: ``` body { background-color: black; } ``` Here's a [html: how to change background color](https://www.youtube.com/watch?v=sdypOOzHxzg) tutorial on YouTube. What other answers don't mention is that there are four ways to actually specify/change CSS: 1. External CSS (using `<link>` tag to add your CSS) 2. Internal CSS (type CSS between `<style>` tags) 3. Inline CSS (type `style` attribute directly inside HTML element. 4. With JavaScript: use `document.querySelector("#id").style.backgroundColor = 'black'` just make sure to type this code between `<script>` tags
You are using selector in CSS, I guess you only select a component of the body. So if you want to whold background to be one color, you must select the right component. In HTML, there is head body, head tag define the content shown on the tag. Body define the whole body of your HTML. The highlight part is head and body of your HTML.[![enter image description here](https://i.stack.imgur.com/5zh1O.png)](https://i.stack.imgur.com/5zh1O.png)
214,773
282,805
I decided to join 2006 and buy Oblivion. Unfortunately, in true Bethesda style, I can't even install the thing. When I plop in the DVD it doesn't appear (i.e. it isn't being recognized as a disc). **The Facts:** * Other DVDs work fine (I installed Portal 2 a few days ago) * Other drives work fine (The disc was read with no issues on my friend's computer) In other words it isn't the drive, it isn't the disc. It's some sort of combination. I'm honestly stumped. **The Details:** * Windows 7 Ultimate 64 bit * Drive is: NEC DVD\_RW ND-3550A ATA * Driver is 6.1.7600.16385 Does anyone have any ideas?
2011/05/13
[ "https://superuser.com/questions/282805", "https://superuser.com", "https://superuser.com/users/40927/" ]
Even if all DVD media are supposed to be the same, this is not always the case, especially for DVD-+RW. For this specific device (NECT ND-3550A), there is an [extensive list](http://support.necam.com/optical/downloads/3550Amedia.pdf) of supported media on NEC support website. Such compatibility problems can be overcomed sometimes with a firmware update.
Is this available for digital distribution? Maybe Steam or Direct2Drive? You'd have to buy the game again, but you wouldn't have to find a way to get the DVD to work. Maybe you can sell your copy to your friend?
45,062
23,431,354
I'd like to get the build variant during runtime, is this possible without any extra config or code?
2014/05/02
[ "https://Stackoverflow.com/questions/23431354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559850/" ]
Another option would be to create a separate build config variable for each build variant and use it in your code like this: In your build.gradle file: ``` productFlavors { production { buildConfigField "String", "BUILD_VARIANT", "\"prod\"" } dev { buildConfigField "String", "BUILD_VARIANT", "\"dev\"" } } ``` To use it in your code: ``` if (BuildConfig.BUILD_VARIANT.equals("prod")){ // do something cool } ```
Here is an example to define and get `BuildConfig` for different flavor ``` android { defaultConfig { ... buildTypes { ... } flavorDimensions "default" productFlavors { develop { applicationIdSuffix ".dev" versionNameSuffix "-dev" } staging { applicationIdSuffix ".stg" versionNameSuffix "-stg" } production { applicationIdSuffix "" versionNameSuffix "" } } applicationVariants.all { variant -> def BASE_URL = "" if (variant.getName().contains("develop")) { BASE_URL = "https://localhost:8080.com/" } else if (variant.getName().contains("staging")) { BASE_URL = "https://stagingdomain.com/" } else if (variant.getName().contains("production")) { BASE_URL = "https://productdomain.com/" } variant.buildConfigField "String", "BASE_URL", "\"${BASE_URL}\"" } } ``` **Using** `BuildConfig.BASE_URL`
259,234
35,778
I have recently started writing a fanfiction and I am posting it online as I write it. However, I often see in comments sayings 'This fanfiction gave me cancer','The writer of this crap should just kill herself.' and low ratings that accompany those comments. What I want to ask is: How can I avoid doing things that will cause people to think of similar things about my fanfiction novel?
2018/05/01
[ "https://writers.stackexchange.com/questions/35778", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/30657/" ]
Depending on the forum you post your fanfiction you will get those comments no matter what you do. It's a sad fact, but there are many people out there who just want to make others feel miserable and growing a thick skin when posting on the internet is a skill that you might need. Other than that it depends on the specifics of your fanfiction. For example quite often fanfiction involves different love stories than the original story had. Many people will not like that and this kind of comments are basically standard phrases for "This is not my style. I prefer to read something different." Maybe they didn't like that you changed the typical boy-meets-girl story to a boy-meets-boy story or a girl-meets-girl story or something like that. But this is just one topic that is often chosen, it really comes up with every topic though. Maybe you changed the villain to the hero for your perspective or made the favourite character of some reader to a supporting character with a minor role and now they don't like the story. Maybe you changed the scenery in a way they don't like or you added a story-arc that they find to be too cliché. Or they didn't like your wording. There are lots and lots of different topics that could invite such comments. The closer you are to the original the less likely such posts are. The more original you are in your writing the more such comments you will receive. The best advice I can give you is to ignore them. It's hard and it probably hurts quite a lot but these poor folks have nothing better to do than trying to make your life miserable. They are the ones that need to be consoled and you should mentally filter their "feedback" out as it doesn't involve anything useful and is only trying to hurt you. Ideally you would find a place where you can for example flag something with such vulgar language, but humans are not perfect and the internet tends to bring out the worst in some people, so be prepared for something like this - and be prepared to completely ignore it. Though, I guess, not going to a place where something like this occurs would probably be a better idea if you can find such a place. Fanfictions are often a starting point for people who want to start writing, meaning that there will be quite a few mistakes, making it thereby quite easy to pick on the weak people, which is why trolls love such places. But there will *always* be people who think similar things about your fanfiction and sometimes they will voice their opinions in such a drastic manner. You can't please everyone.
What my experience from several read fanfictions is: Most of the writers and readers only like the bad guys, and especialy, if they are gay and sleep with their siblings or the good guy. I don't see anything wrong in homosexual stuff, but incest is some other thing. The general problem in FanFictions is also, the lack of writing style. Many authors don't put any effort in the story and don't want to develop it any further. They lack the common sense. What makes a bad story out of a FanFiction? Thats in pretty every case the ignorance about good willed advice and critique. I often commented on promising FanFictions with good advise and helpful tips to improve the writing style, only to get turned down, insulted or even threatend to get sued for insulting Poorly most of the FanFiction Community is not very kind. So I would suggest you to ignore these comments and concentrate on the comments that tell you plotholes, story errors, styling helps and so on. Constructive critique is the keyword. Ignore everyone who just have to say that your story is shit, but don't explain why. You can only improve, if they say whats wrong.
106,040
15,655,167
There is a variable(e.g. int temp;) in the multi-thread environment. Some threads write to it, with write-lock protected. while others read the variable, but without any lock. My question is: If the variable is writed to be one of element in a SET(e.g. {1, 2, 3}), by some threads repeatedly. Is it always one of that SET, when I read it.
2013/03/27
[ "https://Stackoverflow.com/questions/15655167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807991/" ]
The rule is very simple: if two or more threads access the same variable and at least one of those threads writes to it, you **must** synchronize **all** of those accesses. If you do not, the behavior is undefined. `volatile` won't help here; either use a mutex or a condition variable, or make the variable itself atomic. (And "atomic" means C++11 atomic, not some selection of properties that someone thinks will act pretty well in multi-threaded applications).
If noone write value from outside of your SET, the value will remains from this SET. You can possibly need to use `volatile` in your case.
140,482
6,971
A friend insists on wearing a [moneybelt](http://en.wikipedia.org/wiki/Money_belt) while travelling. Some prefer (shudder) '[fanny-packs](http://en.wikipedia.org/wiki/Fanny_pack)' . ![enter image description here](https://i.stack.imgur.com/sBQ5M.jpg) ![Moneybelt](https://i.stack.imgur.com/H5pc0.jpg) I can't be bothered, frankly, I used to when I was 20 (have a money belt), but these days it's a wallet for me. To be fair, I was once pick-pocketed but that was at La Tomatina, I had 10 people pressed up against me and couldn't do much about it - although I admit a moneybelt would have prevented it then. However, there must be a better solution than a moneybelt? I've seen people with chains attached to their wallets, or carefully putting their wallets in a backpack, but that of course comes with its own risks. **Is there a commercially available, *socially acceptable*, safe way of securing the money you carry with you?**
2012/05/08
[ "https://travel.stackexchange.com/questions/6971", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/101/" ]
Personally I never carry much money around with me, I just get local cash from the ATM every week and split it up between my backpack, money belt and wallet. I used to have a wallet with a chain attaching it to my pants but recently I went without a wallet altogether and just had the notes in my trouser pockets. If it is just about cash, a ['real' money belt](http://www.ebags.com/product/eagle-creek/all-terrain-money-belt/220460?productid=10150389) could be an alternative, something that is just as thick as a normal trouser belt but has an opening on the inside to put your bank notes. I used one for one trip once, but the fact that is is only for cash but not for a passport or credit cards, made it less attractive to me. Protecting your travel documents and bank cards is much more important than cash. There are also [undercover leg wallets](http://www.ebags.com/product/eagle-creek/undercover-leg-wallet/220469?productid=10150409), but because they bend around your leg, they again are not good for passports and cards. The other problem it if you wear shorts a lot, they are not so undercover anymore. I personally don't like having anything hanging around my neck or under arms, so for me it comes down to the traditional money belt (as in your photo) for one passport, some credit cards and a bit of cash. The second passport and other cards are in the locked backpack. In some places I even used two money belts on top of each other, an outer one with some cash and a lower one with the important stuff. The thought was that if you get mugged and give them your first money belt, they wouldn't bother searching you any further.
I think the decline in importance of cash is your friend here. If you mostly use cards (whether debit or credit, and they make debit cards that mimic credit cards so you can use them at places that don't take debit) then if a card is stolen, you cancel it and use a different one until your replacement arrives. As long as you don't keep all the cards together, you're ok. I typically head out for a day of sightseeing with two cards (one debit and one credit) and enough cash for coffee and a snack, perhaps double that. They're in a pocket or a purse and while I've never been relieved of them, it would be far less hassle than having hundreds or thousands in cash or travelers cheques taken. (That moneybelt picture shows 500 Euros. I would never wander around with that much. Why would anyone?) I don't think the fanny pack is about security. More about quick access to things you use a lot. The only place I've ever worn one is on a portage trail, where they're just the right thing for the purpose. If anything, a bag like that is LESS secure than a pocket, since a knife to the strap behind your back lets someone run off with the whole bag.
221,417
25,711,011
I got a obstacle class and there i got this: ``` public Obstacle(final String name, final String action, final Position position) { this.name = name; this.action = action; this.position = position; } ``` In my main class i define an obstacle; ``` Obstacle trapdoor= new Obstacle("Trapdoor","Open",new Position(3097,3468,0)) ; ``` How do i retrieve the position from that obstacle? Or more in general how do i get one of those arguments?
2014/09/07
[ "https://Stackoverflow.com/questions/25711011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764582/" ]
Suppose your two classes Demo01 and Demo03 are in package `pack1.subpack` and your Demo02 is in `pack2` So the hierarchy is like * someDrive/pack1/subpack/Demo01 * someDrive/pack1/subpack/Demo03 * someDrive/pack2/Demo02 * someDrive/pack1/common/Demo04 where Demo01 is ``` package pack1.subpack; import pack2.Demo02; // need to add this if calling class of different package import pack1.common.Demo04; // if you are going to use Demo04 class in Demo01 class public class Demo01 { public void run() { System.out.println("--running Demo01-"); } public static void main(String[] args){ Demo01 demo01 = new Demo01(); demo01.run(); Demo02 demo02 = new Demo02(); demo02.run(); Demo03 demo03 = new Demo03(); demo03.run(); Demo04.run(); } } ``` Demo02 is ``` package pack2; public class Demo02 { public void run() { System.out.println("--running Demo02--"); } } ``` Demo03 is ``` package pack1.subpack; public class Demo03 { public void run() { System.out.println("--running Demo03--"); } } ``` Demo04 is ``` package pack1.common; public final class Demo04 { public void run() { System.out.println("--running Demo04--"); } } ``` Then just compile it using `javac pack1/subpack/Demo01.java` and execute it using `java pack1/subpack.Demo01`
``` sh$ cd package/subpackage sh$ javac Class1.java ``` Will lead to an error as the compiler will try to locate `Class2` in the `package/subpackage` subdirectory *of the current directory*. You have to compile that way: ``` sh$ javac package/subpackage/Class1.java ``` --- Here is a complete working example: ``` sh$ cat pkg/subpackage/Class1.java package pkg.subpackage; import pkg.commons.Class2; public class Class1 { public static void main(String args[]) { Class2.doSomething(); } } sh$ cat pkg/commons/Class2.java package pkg.commons; public class Class2 { public static void doSomething() { System.out.println("hello"); } } sh$ javac pkg/subpackage/Class1.java sh$ java pkg.subpackage.Class1 hello ```
6,910
857
Do anonymous browsers work? What principles do they use? Can I use them to test access to my web site? Can I detect if a visitor is using one? What is the different between traditional and anonymous browsing? While I am getting answers I have found something new: * some additional information about [Tor](http://en.wikipedia.org/wiki/Tor_%28anonymity_network%29) and its weaknesses. * a "nice" security issue: [css hack](http://samy.pl/csshack/) :) and [Plugging the CSS History Leak](http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/) * [evercookie](http://samy.pl/evercookie/) (javascript API available that produces extremely persistent cookies in a browser)
2010/11/28
[ "https://security.stackexchange.com/questions/857", "https://security.stackexchange.com", "https://security.stackexchange.com/users/4/" ]
I am going to assume you are talking about web browsers' *private browsing* feature. If that's not what you meant, please elaborate. Be warned that private browsing does not protect your anonymity. This is counter-intuitive, so let me explain. * **What private browsing does provide:** Private browsing is designed to protect you against so-called "browser betrayal": in other words, it prevents information about your past browsing from leaking to other people who may later be looking over your shoulder as you use your browser. For instance, it refrains from keeping logs or updating the browser history. * **Example scenario:** I regularly visit a breast cancer survivor's forum to help me deal with my breast cancer. Then one day, I'm giving a presentation, with my laptop hooked up to the projector, and I open up my browser and start typing in the address bar to go to some mundane site. If I'm unlucky, the breast cancer survivor's forum might show up as one of the URL suggestions, revealing my cancer status to an audience who I didn't want to know that about me. If I had used private browsing mode when visiting the breast cancer survivor's forum, that wouldn't have happened. Private browsing mode is designed to prevent this kind of embarassing scenario. * **What private browsing does not do:** Private browsing does **not** prevent web sites from learning your identity or tracking you. Private browsing does **not** provide anonymity. I realize this is counter-intuitive; the name "private browsing" is perhaps unfortunate. Additional reading: [An analysis of private browsing modes in modern browsers](http://crypto.stanford.edu/~dabo/pubs/abstracts/privatebrowsing.html).
If you are also referring to browser builtin "privacy" functions - e.g. * IE InPrivate * FF PrivateBrowsing * GC incognito * etc Then it works differently: Not so much anonymous, but really just seperates between that and your regular browsing. I.e. no history, no caching files, no stored cookies - also, "private" browsing will not use your existing cookies and such. This creates a sort of "sandbox" (weak though it is) around your "private" browsing, of which no trace should be left afterwards. (*should be* is the operative word...).
136,532
17,449,834
I just would like to add the 'autobuffer' attribute to my video tag using javascript. Basically: ``` var video = document.createElement('video'); video.addAttribute('autoBuffer'); ``` And I'll have: ``` <video autoBuffer></video> ``` I tried: ``` video.setAttribute('autoBuffer'); => <video autoBuffer="undefined"></video> ``` Which is wrong...
2013/07/03
[ "https://Stackoverflow.com/questions/17449834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The second parameter to [`setAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute) must be a string always - currently the `undefined` you're implicitly passing is converted to one. Use ``` video.setAttribute('autoBuffer', ''); ```
The fastest way I did it: ``` Element.prototype.addAttribute = function(strAttribute = "") { if (!this.attributes[strAttribute]) { this.toggleAttribute(strAttribute); } } ``` It only adds it if it's not present. Originally I named it "touchAttribute" but I renamed it for your case. If you are completely sure the attribute is not present in the Element you can use `video.toggleAttribute("autoBuffer");`
282,144
2,082,099
I've overloaded the global operator new/delete/new[]/delete[] but simple tests show that while my versions of new and delete are being called correctly, doing simple array allocations and deletes with new[] and delete[] causes the implementations in newaop.cpp and delete2.cpp to be called. For example, this code ``` int* a = new int[10]; ``` calls operator new[] in newaop.cpp, which in turn calls my version of operator new. So it seems they are globally overloaded but for some reason not the array versions. Is there something I'm missing? EDIT: My implementation of the operators are in a separate project which is compiled into a library and linked to statically. In retrospect, this might have been useful to include in the original post, as it probably has something to do with this. Although I still can't figure out why only the array versions are affected.
2010/01/17
[ "https://Stackoverflow.com/questions/2082099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't know how you overloaded `operator new[]` but I just tried it with MSVC2008: ``` void* operator new[](size_t size) { return 0; } int main() { int* a = new int[5]; } ``` The code above effectively calls my faulty implementation of `operator new[]`. So here is my guess: you failed at overloading `operator new[]` for some reason and your program uses the compiler's version of `operator new[]` which relies on `operator new` to allocate the memory. Since you overloaded `operator new`, your implementation gets called.
operator new allocates one object and calls its constructor. new[] allocates n objects and calls n constructors. edit: Having multiple new[] and delete[] overloads could be considered a bit of and odd one. How does the compiler know which one to link too? Any chance you could post your overloads? Also do yours get called if you don't link newaop and delete2 in (ie yours are the only implementations in the exe)?
177,165
472,048
I want every cell in each row except the last in each row. I tried: ``` $("table tr td:not(:last)") ``` but that seems to have given me every cell except the very last in the table. Not quite what I want. I'm sure this is simple but I'm still wrapping my head around the selectors.
2009/01/23
[ "https://Stackoverflow.com/questions/472048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
Try the last-child selector. This: ``` $("table tr td:not(:last-child)") ``` will select all cells in all rows except of the cells in the last column.
fwiw I found your original works just fine (maybe an enhancement to main jQ since 2009?)... ``` $("#myTable thead th:not(:last)").css("border-right","1px solid white"); ``` The header row of my table has navy background so the white border on the right made the table look snaggletoothed and not match the black 1px border of the data
130,105