INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Speculative execution Mapreduce/Spark I know Hadoop/Spark framework will detect failed or slow machines and execute the same tasks on different machine. How will (On what basis) framework identifies the slow running machines. Is there any kind of stats for the framework to decide? Can someone shed light some light here?
The MapReduce model is to break jobs into tasks and run the tasks in parallel to make the overall job execution time smaller than it would be if the tasks ran sequentially. `yarn.app.mapreduce.am.job.task.estimator.class`\- When MapReduce model lunch a new job this property and implementation is being used to estimate the task completion time at runtime. The estimated completion time for a task should be less than a minute. If a task is running beyond this estimated time it can mark as slow running task. `yarn.app.mapreduce.am.job.speculator.class` \- This property is being used to implementing the speculative execution policy.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "apache spark, mapreduce, speculative execution" }
Why doesn't the brightness of a bulb change with time? Household bulbs get alternating current, which means that the voltage of source and current in circuit keep changing with time, which implies that the power supply isn't constant. However, we don't see any changes in brightness of the bulb. Why is that ?
Two reasons: * An incandescent bulb glows not (directly) because it has electricity going through it, but because it is _hot_. Even when the power going through the bulb decreases, it takes some time for the filament to cool down. Even once the bulb is turned off, it takes some time (a fraction of a second) for the light to fade. * What variation there is in the light is too fast for our eyes to see. You can see the AC flicker in slow motion videos if the camera has a sufficient frame rate, for instance this one.
stackexchange-physics
{ "answer_score": 96, "question_score": 44, "tags": "electricity, thermal radiation" }
sort a txt file, find duplicates, but also print the lines they were found in Given a txt file, that has the following values: 123 123 234 234 123 345 I use sort FILE | uniq -cd in order to get the number of counts each value is found. But how I could output also the row it was found? Output: 123 3 0;1;4 234 2 2;3 The row count is zero based, thus the above numbers.
awk ' { frequency[$1]++ if (line[$1]=="") { line[$1]=NR-1 } else { line[$1]=line[$1]";"NR-1 } } END{ for (j in frequency) if (frequency[j]>1) print j, frequency[j], line[j] }' file > `$1`: content of first column > > `NR`: current line number Output: 234 2 2;3 123 3 0;1;4
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "linux, shell, awk, sed" }
SIP Sever on Amazon EC2 Server I am making a voice call Android application and trying to use Amazon EC2 as SIP server. Amazon EC2 server is slightly slow where I live. It makes about 0.05 ~ 0.1 second delay compare to local server. I know that SIP server helps to register SIP address and let users know the SIP address. It looks like speed of Internet broadband makes delay when users make a call. The question is that does SIP voice chat quality matter on speed of SIP server network?
No the latency of the SIP connections will not affect the media quality provided you build your application so that the SIP signalling and RTP media are separate and the RTP media is transmitted directly between the call end points. SIP was designed with the intention of having the media be transmitted directly between the call end points but because of NAT most SIP servers will proxy the media. If you are using a SIP server like OpenSIPS or Kamailio WITHOUT the rtpproxy then the media will be direct and the network delay to your SIP server will not affect the call media.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sip" }
Commutative addition on the ordinals It is well known that ordinal addition is not commutative (for example $\omega+1\neq 1+\omega$), but it is associative. My question regards a new kind of addition defined as: $$a\oplus b = \text{max}\\{a+b,b+a\\}$$ This addition is obviously commutative, but is it associative? I can't find a counterexample, but I also can't prove that it is. Thank you very much.
This is not associative. $$\begin{align}a\oplus(b\oplus c)&=\max\\{a+(b\oplus c),(b\oplus c)+a\\}\\\ &=\max\\{a+\max\\{b+c,c+b\\},\max\\{b+c,c+b\\}+a\\}\\\ &=\max\\{a+b+c,a+c+b,b+c+a,c+b+a\\} \end{align}$$ and $$\begin{align}(a\oplus b)\oplus c&=\max\\{(a\oplus b)+c,c+(a\oplus b)\\}\\\ &=\max\\{\max\\{a+b,b+a\\}+c,c+\max\\{a+b,b+a\\}\\}\\\ &=\max\\{a+b+c,b+a+c,c+a+b,c+b+a\\} \end{align}$$ Thus for example $$ \omega^2\oplus(1\oplus\omega)=\omega^2+\omega+1$$ and $$ (\omega^2\oplus1)\oplus\omega=\omega^2+\omega$$
stackexchange-math
{ "answer_score": 9, "question_score": 9, "tags": "ordinals" }
Python equivalent of perl timestamp I have a function in perl: sub print_ts { return ::strftime( '%Y%m%d %H:%M:%S', localtime); } What would be python equivalent of that?
I believe this would be the equivalent in python: from datetime import datetime def print_ts(): return datetime.now().strftime('%Y%m%d %H:%M:%S')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, perl, time" }
Fadein all Elements with jQuery Waypoints I want to fadein all elements on scroll with jQuery waypoints. When i scroll to the image i add a certain class to fade them in. For this i use jQuery Waypoints. When i scroll to the image the console.log is showing "Scrolled to image" but it cant add the class with "this" to the image. $( document ).ready(function() { $('img').waypoint(function() { console.log("Scrolled to Image"); $(this).addClass("Test"); }, { offset: '50%', triggerOnce: true }); });
`this` in the callback refers to the waypoint object. Try `this.element` instead (see < \- there's a special section discussion this exact issue) $( document ).ready(function() { $('img').waypoint(function() { console.log("Scrolled to Image"); $(this.element).addClass("Test"); }, { offset: '50%', triggerOnce: true }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery waypoints" }
C Pointer Arithmetic sizeof(struct) Here is the code in question #include <stdio.h> struct test { unsigned char t; unsigned short u; unsigned char v; }; int main () { struct test * a = (void *) 0x1000; printf("%x %p %p\n", sizeof(struct test), a + sizeof(struct test), a - sizeof(struct test)); return 0; } The sizeof(struct test) prints 6, so I would _expect_ to see: `6 0xffa 0x1006` Instead I get 6 0x1024 0xfdc Last time I checked, 0x24, or 36, was not equal to 6. It's not even aligned to anything that I can tell. I am at a complete loss. Can someone please explain to me why I'm getting these values?
The problem is that when you do pointer arithmetic, it increments by a **multiple** of the size of the datatype. So what you're effectively doing is adding by the square of `sizeof(struct test)`. Since `sizeof(struct test) = 6`, you are incrementing the address by `6 * 6 = 36`. Hence why you get `0x1024` and `0xfdc` instead of `0x1006` and `0xffa`. (You also switched the `+` and `-`, but that's a small thing.) Instead, just do this: printf("%x %p %p\n", sizeof(struct test), a + 1, a - 1);
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 7, "tags": "c, struct, sizeof" }
Google Cloud Function - read the CONTENT of a new file created a bucket using NodeJS In GCP (not firebase) I have a bucket and a function which will be called when a new file was created in the bucket. Works great. /** * Triggered from a change to a Cloud Storage bucket. */ exports.mycompany_upload_file = (event, context) => { const gcsEvent = event; const filename = gcsEvent.name; const bucketName = event.bucket; console.log(`=====================================================`); console.log(`Event Type: ${context.eventType}`); console.log(`Bucket: ${bucketName}`); console.log(`Datei: ${filename}`); console.log(`=====================================================`); // now I would like to open that file and read it line-by-line How do I address that file? What's the path of that file? Can I use standard node libraries like 'fs'
I found this post that might help you, but looks like basically the answer is as follows: Note that it will store the result in a ramdisk, so you'll need enough RAM available to your function to download the file. var storage = require('@google-cloud/storage'); const gcs = storage({projectId: "<your_project>"}); const bucket = gcs.bucket("<your_bucket>"); const file = bucket.file("<path/to/your_file>") exports.gcstest = (event, callback) => { file.download({destination:"/tmp/test"}, function(err, file) { if (err) {console.log(err)} else{callback();} }) }; For more information you can check the documentation for Google Cloud Storage: Node.js Client
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "node.js, function, google cloud functions, google cloud storage, bucket" }
Numpy slicing: all entries except these ones I have a numpy array a. I would like to select a random sample of this array as a test and training set for cross-validation. As a training set, I use slicing by selecting the entries idx. Is there a way to select a compliment of these entries? i.e. all entries that are NOT in idx. # N: size of numpy array a. idx = random.sample(np.arange(N),N/10) # select random sample train(a[idx]) # train on this random sample test(a[ NOT idx]) # test on the rest. How to call the rest of the entries in a compact way for the last line? Thanks.
If you make `idx` a boolean array, then you can select the complement with `~idx`: import numpy as np N = len(a) idx = np.zeros(N, dtype='bool') idx[np.random.choice(np.arange(N), size=N/10, replace=False)] = True train(a[idx]) # train on this random sample test(a[~idx]) # test on the rest.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "numpy" }
Linux Server HDD Corrupted Today I put my forum offline just before scheduled Cpanel backup. An hour later when I checked it says DATABASE error occured(or whatever the database error was) I logged into SSH and perform reboot. The server will not reboot sucessfully. I contacted my host and they are saying: " Looks like the drive is corrupt, it is failing to boot and BIOS hangs when detecting the drive. We will have to replace the drive and install the OS again. " I do have Secondary HDD where I used to save all the backups. What should my next step be? I have other websites and a lot of data on that server... If I loose everything that means all attachments and everything is gone. They have OnePortal thing where HOST is suggesting me to check what do I have on my secondaryHDD... Can someone please suggest next steps
You have the failed drive replaced, and then restore your backups. Pretty straightforward, if annoying.
stackexchange-serverfault
{ "answer_score": 3, "question_score": -2, "tags": "linux, hard drive, centos5, corruption" }
:after doesn't scope by relative of parent I have :after for my animation, as you can see it isn't scoped by the relative. What I want is the bar should start from the width of the bar itself, now it's from the far left. What's the issue here? .loading { position: relative; background-color: #E2E2E2; &::after { display: block; content: ''; position: absolute; width: 100%; height: 100%; transform: translateX(-100%); background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .4), transparent); animation: loading 1s infinite; } } < try to inspect the :after DOM in this demo <
do not use `transform: translateX(-100%)`, it will start from outside left of your `.loading`, and add `left: 0` .loading { position: relative; background-color: #E2E2E2; overflow: hidden; &::after { display: block; content: ''; position: absolute; width: 100%; left: 0; height: 100%; /* transform: translateX(-100%); */ background: linear-gradient(90deg, transparent, rgba(100, 255, 255, .4), transparent); animation: loading 1s infinite; } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css" }
What is the function of the “for” in the sentence “For him to say that means a lot”? In the sentence “For him to say that means a lot”, I can’t figure out how to explain what part of speech the “for” is, and how it can start off a noun phrase, but the sentence seems right to me. It seems to mean basically the same thing as “His saying that means a lot”. Does anyone have any insight on how the “for” is being used in this case?
> [ _For him to say that_ ] _means a lot._ "For" belongs here to the category (POS) subordinator, and its function is that of 'marker', where it is introducing the bracketed infinitival clause. Note that "for" introduces only those infinitivals that have a subject; in this case the subject is "him".
stackexchange-ell
{ "answer_score": 2, "question_score": 1, "tags": "noun phrases, for" }
Passing a variable from created in function a to function b when function b is inside function a I have a function for the class .myclassA, inside this function I capture the id of the particular element chose and I put it inside a variable inputid. This function also brings another function for another class(.myclassB), which is inside the first function. Do you guys have any idea how I can pass the variable inputid from the first function to the function inside it? Thanks for all your help $('.myclassA').click(function(){ var inputid = $(this).attr('id'); $('.myclassB').click(function(inputid){ var thisid = $(this).attr('id'); $(inputid).val(thisid); }); //$('seqa').click(); }); //$('#empcriddi').focus();
You don't need to "pass" it, just don't name the local variable with the same name, like this: $('.myclassA').click(function(){ var inputid = $(this).attr('id'); $('.myclassB').click(function(){ var thisid = $(this).attr('id'); $(inputid).val(thisid); }); }); Though this won't quite work either, and there's no reason to go a lookup of an element you already have so just maintain a reference, for example: $('.myclassA').click(function(){ var input = $(this); $('.myclassB').click(function(){ //you may want to also .unbind('click') here input.val(this.id); }); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery" }
Django query using mysql date functions I was wondering can you perform the following query in Django using models and queryset? SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created_at/1000), '%Y-%m-%d') FROM users GROUP BY YEAR(FROM_UNIXTIME(created_at/1000)), MONTH(FROM_UNIXTIME(created_at/1000)), DAY(FROM_UNIXTIME(created_at/1000)) ORDER BY created_at ASC;
Not really no.. see < \- would just use a raw SQL query
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, mysql, django" }
Get real user IP behind two reverse proxies This is my environment setup: * Server A hosts the site (Nginx + PHP-FPM + Wordpress) * Server B is Nginx reverse proxy for server A * Cloudflare reverse proxy is on top of all. Therefore, user request first go to Cloudflare, then server B and then server A. I've set: proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; on server B. I've also installed Cloudflare wordpress plugin, but Wordpress still gets server B IP address instead of user IP address, detecting Cloudflare IP addresses as originating IPs. :( Installing Proxy Real IP changes Server B IP addresses to Cloudflare IP addresses, not real user IP. Any help to get real user IP address at Wordpress end?
When multiple proxies are involved and they all support `X-Forwarded-For`, they each append a value to it. Cloudflare states this in its documentation. To get this behavior from nginx it looks like you need to set the real_ip_recursive option. So on the WordPress side the real IP address of the user will usually be the first IP address in the comma separated value list of the `X-Forwarded-For` header. Your WordPress header states that it uses "a regular expression" to match the IP address from that field, but it doesn't state that it can deal with multiple values in that field. You may need to update the code of the plugin to work properly when there are multiple values.
stackexchange-webmasters
{ "answer_score": 1, "question_score": 1, "tags": "wordpress, nginx, cloudflare, reverse proxy" }
ImportError: No module named winreg - Odoo10 I installed Odoo 10 CE on windows 7. In one custom module, I use `import winreg` but it gives me the error: ImportError: No module named winreg How can I resolve this?
if you are using python 2 try: `import _winreg as winreg`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, odoo" }
I would like to see for what I was rewarded reputation points When viewing my reputation history I would love to know why I was awarded that particular amount. Was it for answering the question, up votes, etc.? Maybe a tool tip when you mouse over the amount awarded.
Are you talking about the reputation audit `/reputation` page? Jeff's answer on the reputation audit FAQ details the different vote types that you see on that page. > * 1 = accepted answer (to or from you) > * 2 = upvote (to you) > * 3 = downvote (to or from you) > * 4 = penalty for post flagged as offensive > * 9 = bounty award (to you) > * 8 = bounty grant (from you) > * 12 = penalty for post flagged as spam > Alternatively, you can grab the userscript I created here, which adds the vote type description behind each vote.
stackexchange-meta
{ "answer_score": 4, "question_score": 2, "tags": "feature request, reputation" }
jQuery: click function is not catching the click event on hyperlink I have the following piece of code <html> <head> <script src=" <script> $('body').on('click', 'a.wishlist_item', function(){ alert('asas'); return false; }) </script> </head> <body> <a class="wishlist_item" id="wishlist_item" href="#" >Add to wishlist</a> </body> </html> The code is supposed to alert when I click on the hyperlink with wishlist_item class. but its not working.. is there anything that I may be doing wrong in this code ?
You have to bind the event after the element exists. Use the `ready` event to run the code when all the page is loaded: $(document).ready(function(){ $('body').on('click', 'a.wishlist_item', function(e){ alert('asas'); e.preventDefault(); }); });
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "jquery, click" }
How do I get the correct time in C# I've been using `Datetime.UtcNow` to get the date. However, this date is 6 hours ahead of my time (I'm in central time). Is there a more correct way for me to get the exact date in C#? Or if not, how would I change the existing date?
`DateTime.Now` would give you current time for your time zone. `DateTime.UtcNow` gives you current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": -6, "tags": "c#, date, datetime" }
Set macro to value, iff empty Essentially I got four cases in existing code: 1. macro ABC is unset 2. macro ABC is set, but empty: `#define ABC` or `-DABC` 3. macro ABC is set, and evaluates to true: `#define ABC 1` or `-DABC=1` 4. macro ABC is set, and evaluates to false: `#define ABC 0` or `-DABC=0` I want the 1st and 4th, and 2nd and 3rd case to be the same: #if defined(ABC) && IS_EMPTY(ABC) # undef ABC # define ABC 1 #endif #if !defined(ABC) || !(ABC) # undef ABC # define ABC 0 #endif How do I do `IS_EMPTY(X)`?
If you know that only the values `0`, `1` or empty can occur you could use something like #define some_impossible_macro 1 #define some_impossible_macro0 0 #define some_impossible_macro1 0 #define IS_EMPTY(X) some_impossible_macro ## X Otherwise, for the general case this is a bit more complicated but doable. You could use `P99_IS_EMPTY` from P99.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c++, c, c preprocessor" }
How to get maximum memory used by java program Is there a way to get the peak memory used at any given point during a java program run? So far I've only seen solutions that give total memory consumed.
You can try this JDK tools for **heap** analyzis: * `VisualVM` * `jstat` (console tool) **RSS mem** usage can be found on unix by comman line tools `ps` or `top`, or by JDK tool: * `jcmd <pid> VM.native_memory detail.diff` (java process should be run with `-XX:NativeMemoryTracking=summary` JAVA_OPTS) **RSS Peak** usage can be found on linux in `/proc/<pid>/status` file in `VmHWM` field (man).
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "java, memory, memory management, jvm, runtime" }
index.html file recreation If someone deleted index.html file and unable to test the local host then how can be recreate that file to test the local host
Go to your terminal ( Command line ). type sudo nano /var/www/html/index.html When your are in there, type <h1>It Works!!</h1> hit Ctrl+o, and exit the terminal. Take your browser. Type in Voila, you have your localhost back, alive.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "apache, localhost, ubuntu 14.04" }
exporting name of last but one directory As explained in this question, we can get name of current working directory. But how to get last but one directory name? Scenario: # working directory /etc/usr/abc/xyz.txt printf '%s\n' "${PWD##*/}" #prints abc #i want to print usr printf '%s\n' "%{PWD##*/-1}" #prints me whole path Suggest me how to do this. Thanks in advance.
The classic way would be: echo $(basename $(dirname "$PWD")) The `dirname` removes the last component of the path; the `basename` returns the last component of what's left. This has the additional merit of working near the root directory, where variable editing with `${PWD##…}` etc does not necessarily work.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "linux, bash, pwd" }
Save excel file from internet I am trying to download Excel file from site using Selenium. The way I'm doing it: WebElement excelList = driver.findElement(By.xpath("...")); excelList.click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); String pageSource = driver.getPageSource(); FileOutputStream fos = new FileOutputStream("d:/load.xls"); for (int i = 0; i < pageSource.length(); i++) { char c = pageSource.charAt(i); fos.write((byte) c); } fos.close(); The page source string length is equal to the file size that I downloaded manually from this site. The problem is that I'm saving data incorrectly and MS Excel cannot open the saved file. How can I save the file properly?
I figured it out. All I need was to get input stream right from last page after clicking on load file button. But method for getting page object 'lastPage()' has protected access. Here is the way: private static void saveExcelFile(HtmlUnitDriver driver) { Method m = driver.getClass().getDeclaredMethod("lastPage", null); m.setAccessible(true); Object obj = m.invoke(driver, null); Page page = (Page) obj; InputStream stream = page.getWebResponse().getContentAsStream(); FileOutputStream fos = new FileOutputStream("d:/load.xls"); int c; while ((c = stream.read()) != -1) { fos.write(c); } fos.close(); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, excel, encoding, selenium, utf 8" }
"Annotated" lambda expression instead of interface with single apply method instead of using anonymous classes like so register(new EventListener() { @Override public void apply(Event e) { // do your work } }); with java 8 I can use lambda expressions: register(e -> (// do your work)); But what if the method in my interface is annotated? interface EventListener { @Annotation void apply; } Is it possible to annotate a lambda expression? (Specifically, I want to use Guava's EventBus.register() method with lambda expressions)
See this: Annotating the functional interface of a Lambda Expression Basically, you can't directly annotate in a lambda expression, but you can use the extending interface or class and access the annotation by calling `Class#getAnnotatedInterfaces()`. I believe that should answer your question. Hope this helps, Santiago
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 6, "tags": "java, lambda, java 8" }
Search a Column of Data & Enter a Specific Value based on 2 criteria I have a sheet, where I will enter a bunch of data with skus into 1 column, and have search terms somewhere else. What I want is to automatically, look at the SKU **AND** the search term, and then bring up the relevant meal customization. Below is what my search sheet would look like & I have also entered my dream result in red, but I understand that it could be a bit too much, so just the importing of the customizations is fine. ![enter image description here]( **There is also another sheet where I would enter the customizations. The customization tab, it is where the data will be stored. So what should happen is, when I enter the items into col A & the search terms Into the first row of the SEARCH tab it should crosscheck with the customizations tab and bring in those results.** Here is my sample sheet (with editing access): <
Use `filter()` with `mmult()` and `regexmatch()`, like this: =iferror( filter( Customization!A2:E, not( mmult( sign(not(iferror(regexmatch(Customization!B2:E, "(?i)" & B1:E1), B1:E1 = ""))), transpose(sign(column(B1:E1))) ) ) ), "(no matching data)" ) This lets you search for multiple alternative terms at once, in every data column separately. The search terms are regular expressions like `no dairy|vegan`. To format the results as a comma-separated list, use this: =arrayformula( textjoin(", ", true, if(len(A1:E1), A3:E3, iferror(1/0))) ) See the new Solution sheet in your sample spreadsheet. To learn the exact regular expression syntax used by Google Sheets, see RE2.
stackexchange-webapps
{ "answer_score": 1, "question_score": 0, "tags": "google sheets, formulas, google sheets query, search, import" }
serve js files from meteor app to other server I trying to make a service like google analytics, where the user put a script in their html. the problem is when my sever serve the script it have to make some operations and send different script depending from the requesting domain. sorry for my english and thanks so much for help
I, found the solution, really easy in server folder: Router.route("metric", { where: "server", path: "/dinamic.js", action: function () { //here all your acctions ponse.writeHead(200, { "Content-Type": "application/javascript" }); this.response.end( "console.log('in this line your dynamic " + "js" + " code')" ); } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, meteor" }
how to get different styles inside textview in ios? How do I set multiple styles for different pieces of text inside a TextView? I have searched it out and found it is possible in Android, but is it possible in iOS? If Yes then how do I proceed? Thanks in advance!
UITextView has an attribute called attributedText that you can call upon, see: Accessing the Text Attributes You can also set some of the attributes in the Attributes Inspector in Interface Builder.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, objective c, xcode" }
Why is it customary to bow at certain points when saying kaddish? It is customary to bow at certain points when saying kaddish. The link is to a chabad site and I have seen bowing in other communities as well. At first sight (excuse pun) it appears to be a visual cue for the response. Why is it done? What is the source?
Sefer HaKadish page 213 note 2 brings in the name of the Pardes HaGodol in the name of the Rokeach that we bow 4 times in Kadish in connection with the 4 names in Malachi 1:11 (3 times Shemi and once Hashem Tzevakos)
stackexchange-judaism
{ "answer_score": 1, "question_score": 4, "tags": "kaddish, bowing kneeling" }
python3.6, difference between async with and await newbie developer coming from python 3.4 here. my naive understanding is only to use the keyword `async with` when I see that the coroutine is a context manager?
From PEP 492: > A new statement for asynchronous context managers is proposed: > > > async with EXPR as VAR: > BLOCK > > > which is semantically equivalent to: > > > mgr = (EXPR) > aexit = type(mgr).__aexit__ > aenter = type(mgr).__aenter__(mgr) > > VAR = await aenter > try: > BLOCK > except: > if not await aexit(mgr, *sys.exc_info()): > raise > else: > await aexit(mgr, None, None, None) > So yes -- it yields into the coroutine returned from the `__aenter__` method of the given context manager, runs your block once it returns, then yields into the `__aexit__` coroutine.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 12, "tags": "python 3.x, python 3.6, python asyncio" }
2 Sample Kolmogorov-Smirnov vs. Anderson-Darling vs Cramer-von-Mises I was wondering what are the criteria to use Kolmogorov-Smirnov, Cramer-von-Mises, and Anderson-Darling when comparing 2 ECDFS. I know the mathematics of how each differ, but if I have some ECDF data, how would I know which test is appropriate to use?
To cut a long story short: Anderson-Darling test is assumed to be more powerful than Kolmogorov-Smirnov test. Have a glance on this article comparing various tests (of normality, but the results hold for comparing two distribudions) Power Comparisons of Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling Tests by _Nornadiah Mohd Razali & Yap Bee Wah._ Anderson-Darling test is much more sensitive to the tails of distribution, whereas Kolmogorov-Smirnov test is more aware of the center of distribution. To sum up, I would recommend you to use Anderson-Darling or eventually Cramer-von Misses test, to get much more powerful test.
stackexchange-stats
{ "answer_score": 15, "question_score": 22, "tags": "kolmogorov smirnov test, anderson darling test, two sample" }
Third Heaven what is it In 2 Corinthians 12:2 talks about being caught up to the third heaven. What is the third heaven? What does it mean by being caught up to the third heaven?
The 'formal distinction' is a bit of a synthetic one. Remember why it's "God created the heaven [not 'heavens'] and the earth' --and then subdivided the firmament a bit later... you have multiple 'heavens' at different points. The distinction as I understand it: First heaven is the domain of the clouds, birds, air and so forth. Second heaven is the stars and planets Third heaven is where God is Someone will improve the theology, but this is a framework to give you the sense of what he meant by the expression.
stackexchange-hermeneutics
{ "answer_score": 0, "question_score": 0, "tags": "2 corinthians" }
Continuous functions quotient derivative at $0$ This problem was on an exam I took (I have tried to remember it how it was but I don't have the original transcript). * * * Let $X$ be a metric space and let $f_1,f_2:X\rightarrow \mathbb{R}$ be two continuous differentiable functions. Suppose at some point $x_0$, $f_1(x_0)=0=f_2(x_0)$ and $f'_1(x_0)=C_1$ and $f'_2(x_0)=C_2$ for some non-zero finite constants $C_1$ and $C_2$. Prove that: $$\lim_{x\rightarrow x_0}\frac{f_1(x)}{f_2(x)}=K$$ for some finite constant $K$. * * * The exam is over and I got my mark but they don't give us the answers and it has bugged me since. Noone I know seems to have been able to answer it. Could anyone help me with this?
Directly applying the limit $x \rightarrow x_0$ yields the indeterminate form $\frac{0}{0}$. Thus (and since your functions are continuous and differentiable) you may then apply L'Hopital's Rule to obtain a quotient of the derivatives. Applying the limit now yields a constant (no longer an indeterminate form): $$\lim_{x\rightarrow x_0}\frac{f_1(x)}{f_2(x)}=\lim_{x\rightarrow x_0}\frac{f'_1(x)}{f'_2(x)}=\frac{f'_1(x_0)}{f'_2(x_0)}=\frac{C_1}{C_2} \equiv K$$ where the first equality is obtained by L'Hopital's Rule.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "limits, derivatives, continuity, asymptotics" }
Select input from in memory html in jQuery I am trying to run jQuery selector on an in memory representation of some html. If I have: var html = $('<input id="testBox" type="text" value="test" />'); var result = $('#testBox', html); console.log(result.val()); I will get back `undefined` as result will hold a `prevObject` How can I return the actual input directly from the selector here?
In your case, `html` is the jQuery wrapped `<input />`. For example: console.log( html.attr('id'); ); // testBox Your code would work if you wrapped the input in some other tag, for example: var html = $('<div><input id="testBox" type="text" value="test" /></div>'); var result = $('#testBox', html); console.log(result.val()); // test
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, jquery selectors" }
How to iterate Arraylist<HashMap<String,String>>? I have an ArrayList object like this: ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); How to iterate through the list? I want to display the value in a TextView which comes from the data of ArrayList object.
Simplest is to iterate over all the `HashMap`s in the `ArrayList` and then iterate over all the keys in the `Map`: TextView view = (TextView) view.findViewById(R.id.view); for (HashMap<String, String> map : data) for (Entry<String, String> entry : map.entrySet()) view.append(entry.getKey() + " => " + entry.getValue());
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 7, "tags": "java, android, arraylist, hashmap" }
App crashes when tapped on two buttons simultaneously (save / cancel) what should be the severity & priority WHile performing a random test, i have tapped on both Save and Cancel buttons at a time present at the two corners of the ipad in a application. Now what should be the Priority and Severity for this particular sceanrio. Note: The app crashes when tapped on both the buttons simultaneously.
This is a common issue of unintended concurrency. I think the priority should be moderate or low as not many people are going to press both buttons simultaneously. So, there is a likelihood of someone doing accidentally yet not intentionally (except if they test the software). The severity is different. It depends on the function of the application. Here are some examples: 1. have spend 10 hours on work and you loose it due to this bug (HIGH Severity) 2. app crashes, you started up again and everything is back to normal (severity low) 3. you have capture the one in the life time photo and... crash! (bloody high severity) So, in summary, severity is how bad the damage is after the effect and priority is usually based on the likelihood of someone going down this scenario (perhaps stats of how many times people have done that will be another indicator here).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "testing" }
Is it possible to have f.lux (software that adjusts display's color temperature) on Ubuntu 14.04? f.lux is software which adjusts temperature of your display according to time of the day. Is it possible to make f.lux work in Ubuntu 14.04? If so, maybe you can share your knowledge or point me to a guide.
Here is another way I just found. I had to do this way because company firewall won't let me add apt repository no matter what I tried. 1. download source code from author's github git clone 2. install cd xflux-gui sudo python setup.py install 3. run from command line fluxgui [update as of Feb 23 2017] repo is changed
stackexchange-askubuntu
{ "answer_score": 37, "question_score": 68, "tags": "display, color management" }
How to get Last post Id of custom post type in wordpress I want to get the last post id of a custom post type in WordPress. For this, I tried this code- $args = array( 'post_type' =>'soto_property', 'posts_per_page' => 1, 'orderby'=>'post_date', 'order' => 'DESC', ); $image_posts = get_posts($args); foreach ( $image_posts as $post ) { echo $post->ID; } But It always returns me the First post id of this custom post type. I have tried `'order'=>'ASC'` also but it gives me the same result. How can I achieve the last post id of this CPT?
I have got my last inserted Post id using `$wpdb` query as below- global $wpdb; $lastrowId=$wpdb->get_col( "SELECT ID FROM wp_posts where post_type='soto_property' ORDER BY post_date DESC " ); $lastPropertyId=$lastrowId[0];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "wordpress, post, custom post type" }
Identify salvaged parts I took apart an old printer and found two components that look like relays. ![enter image description here]( But they have no markings of any kind, save for a small sticker each that I think may be serial numbers. They are 4335xit3 and 5345xft4. I would love to find some data sheets to know what they can do, but I don't know how to identify them without markings.
That is the flyback transformer used to generate the high voltage charge in a laser printer. The comparable circuits in a CRT-based television can remain hazardous for substantial time after power is removed, unless the tube capacitance is carefully drained by someone knowledgeable in the appropriate procedure. I can't tell you off the top of my head what associated capacitance would be found in a laser printer or what voltage it would charge to, but until you know for certain, you probably don't want to be working on or disassembling the machine - if something is still charged the results could range from surprising through painful to truly hazardous, **even when unplugged from the wall**. Such hazards are not necessarily confined to televisions or large objects - in childhood I got a rather unique burn from discharging the capacitor in a small camera flash through my finger.
stackexchange-electronics
{ "answer_score": 3, "question_score": 0, "tags": "relay, components" }
ExtJS populate store from multiple proxy sources I have a distributed database system and I want my EXTJS app to request data from multiple sources and put it into a single store. Is there a way to define multiple proxy urls for a single store? Is the best way to accomplish this to make multiple stores and merge them before the data is needed?
In my opinion best way to aggregate data from multiple sources is aggregate it on your backend and return with help one endpoint. Extjs does not support multiple proxy. But you can create as many stores as you have sources, and collect all data in one memory store. But in this case you lose many features, where help you work with remote proxy store
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, database, extjs, extjs4, extjs4.2" }
Short story where the protagonist is unknowingly the demon Beelzebub. I read a short story in the 80s (as in a read it in the 80s, not that it was written in the 80s) about a protagonist that was bothered by flies, and was unknowingly the demon Beelzebub. Any ideas?
That would be Flies), by Isaac Asimov. Available at the Internet Archive. It wasn't the protagonist who was bothered by flies, as it happens, but one of his old friends. The story was set at a college reunion. > Winthrop would never know. Polen was sure of that. He wondered if Casey knew. It would be the supreme joke if Casey did not. > > He _had_ run Casey's flies, of course, not that once alone, but many times. Always the same answer! Always the same unpublishable answer. > > With a cold shiver he could not quite control, Polen was suddenly conscious of a single fly loose in the room, veering aimlessly for a moment, then beating strongly and reverently toward Beezlebub.
stackexchange-scifi
{ "answer_score": 25, "question_score": 15, "tags": "story identification, short stories" }
MYSQL: update a row without mentioning fields name I there a way to update a row without mentioning fields name ? I mean something like: UPDATE table SET VALUES(1, 'name', 'family') instead of: UPDATE table SET id=1, name='name', family='family' **update** I'm using `INSERT ON DUPLICATE KEY UPDATE` and don't want to use `REPLACE` function because `REPLACE` function will cause a record to be removed, and inserted at the end, which will cause the indexing to get broken apart, decreasing the efficiency of the table.
You cannot do like that with mysql, as set clause indicates which columns to modify and the values they should be given FYI: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, sql" }
Where is the importHref function? I'm having such a hard time trying to use the Polymer.importHref function... ![enter image description here]( What am I missing?
If you're only importing `polymer-element.html`, make sure to also import `import-href.html`: <link rel="import" href="polymer/lib/utils/import-href.html"> codepen
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "polymer, polymer 2.x" }
Where can I find a list of questions I've asked on Stack Overflow? I can't seem to find the navigation to the questions that I have posted to Stack Overflow. As well as comments that I would have made on other questions. Is there an area of the interface for this?
Click on your profile icon, and about half way down the page on the left there is a 'questions' link.
stackexchange-meta_stackoverflow
{ "answer_score": 3, "question_score": -4, "tags": "discussion, user interface" }
Pass data to child component that can be called multiple times I have a parent component and use ViewChild to call the method in child component. However, when I load the data and use that method to pass data, It show the error my method is undefined. Where did I get it wrong? **Flow:** At first: After NgOnInit() method, I load the data and pass It to the child component Second try: I use NgAfterViewInit() to load the data end then pass it to the child component but it has the same error **Note:** The parent has a variable that can create child component multiple times Sample Code with further description:
You can pass data to the child using the `@Input` decorator. The theory: 1. Pass data through this `input` 2. Fire change detection to handle those changes Parent TS: @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; } Parent HTML : <app-child [name]="name"></app-child> Child TS: import { Component } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './app-child.component.html', styleUrls: [ './app-child.component.css' ] }) export class AppChildComponent { @Input() name = ''; ngOnChanges(changes: SimpleChanges): void { if (changes.name) { this.setup(); } } setup() { ... } } Inside setup of the child you can then handle the data as expected.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "angular, angular material" }
How to get notified (trigger a lambda) when user registers with an authentication provider like fb My goal is to create a user in my user table with the data from the fresh facebook auth. The closest thing I found is within Identity Pool settings: ![enter image description here]( But it's not the event I had in mind. I want a trigger only when a new user comes in.
Once I didn't found such trigger and it looks that there were no changes since. And you don't know on a client side is it a registration or login. You can only make _workaround_ like create a dataset and store some information there (e.g. first_login), based on which you could do your stuff. There is a similar thread you could check.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "amazon web services, aws lambda, amazon cognito" }
Given step size, starting point, and a modulus, how many steps does it take to reach b mod m? Let's start with a modulus $m=5$ (this could be any integer) a step size $s=2$ (this must be relatively prime with $m$), and an initial starting value modulo $m$ of $i=1$. In this particular case, we have: m: 0 1 2 3 4 x When we advance by one step, we have: m: 0 1 2 3 4 x If we advance 1 more step, we have: m: 0 1 2 3 4 x We can easily work it out that it will take 4 steps total to reach $4 \bmod 5$. Is there a formula for calculating the number of steps it will take to reach an arbitrary remainder modulo $m$ from an arbitrary starting point modulo $m$ given a step size $s$ that is relatively prime with $m$ (Note that $s$ may be larger than $m$)?
Let $n$ be the number of steps, starting at zero, let $a$ be the starting number, and $b$ be the ending number. Then we want to know $n$, depending on $a$, $b$, $s$, and $m$ such that $a+ns \cong b \pmod{m}$. That is we want $n$ such that $$ n s \cong b - a \pmod{m} \text{.} $$ By Bezout's lemma, since you assume $\gcd(s,m) = 1$, there are integers $x, y$ such that $xs+ym = 1$. Given $s$ and $m$, $x$ and $y$ can be explicitly computed using the extended Euclidean algorithm. Then $$ (b-a)(xs+ym) = (b-a) $$ Reducing modulo $m$, this says $$ (b-a)xs \cong b-a \pmod{m} \text{.} $$ So $n \cong (b-a)x \pmod{m}$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "modular arithmetic" }
How to know first line or not of text file using vba I would like to know first line or not when reading a text file to edit its data. Because I don't want to update that data at other lines. I want to branch my code at the position marked using a . What is the best way of doing this? Set file = FSO.OpenTextFile(filepath) Do Until file.AtEndOfStream line = file.ReadLine If Then 'edit data of first line ElseIf ... Then 'other lines' condition 'update data of other lines End If 'Write line to text file Loop
This is rather trivial, but you'll have to do this check before reading the first line. If you always open the file yourself, you can be sure that your first iteration is at the beginning of the file: Set file = FSO.OpenTextFile(filepath) Set firstline = True Do Until file.AtEndOfStream line = file.ReadLine If firstline Then firstline = False 'Do first line stuff ElseIf ... End If Loop If you don't know for sure that the file will indeed be at the beginning (i.e. you're not opening it yourself in that part of code): Set file = FSO.OpenTextFile(filepath) Do Until file.AtEndOfStream line = file.ReadLine If file.Line == 2 Then ' we are actually at the second line now (after reading) 'Do first line stuff ElseIf ... End If Loop
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "microsoft excel 2010, vba" }
How grip files based on words from a file? I have this text file: l=c("ced","nad") h=c("SAF","EYR") res=cbind(l,h) and this list of files: dirf<- list.files ("path", "*.txt", full.names = TRUE) example of files ced_SAF_jkh_2020.txt ced_EYR_jkh_2001.txt nad_SAF_jkh_200.txt nad_EYR_jkh_200.txt I want to grip files that contain both words in the two columns, so the files i need ced_SAF_jkh_2020.txt nad_EYR_jkh_200.txt
You can construct the name from the matrix and use that, i.e. do.call(paste, c(data.frame(res), sep = '_')) #[1] "ced_SAF" "nad_EYR" To grep them you can do, ptrn <- do.call(paste, c(data.frame(res), sep = '_')) grep(paste(ptrn, collapse = '|'), x, value = TRUE) #[1] "ced_SAF_jkh_2020.txt" "nad_EYR_jkh_200.txt" where `x`, dput(x) c("ced_SAF_jkh_2020.txt", "ced_EYR_jkh_2001.txt", "nad_SAF_jkh_200.txt", "nad_EYR_jkh_200.txt")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r" }
Ajax + servlet GET request issue I want to create a simple AJAX call, based on How to use Servlets and Ajax? answer. The servlet processes the request (it can print on console in the doGet() function), but nothing happens on the client side. Chrome error message is: XMLHttpRequest cannot load Origin null is not allowed by Access-Control-Allow-Origin. Thanks!
> _I run the html from the local storage (C:). Is that a problem? How should I run it?_ That is definitely a problem. You should request the HTML over HTTP instead. Your target endusers also won't run HTML from the local disk file system, right? Open < in your browser.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ajax, web applications, servlets, xmlhttprequest, cors" }
python function in function call on variable this is the assignment Write a function partial that takes another function and a value as in data. Partial should return a new function with the same function as the given function but there the first argument to the given functuin is bound to a value that was given as second argument to partial run example: >>> def add(n, m): return n + m ... >>> add_five = partial(add, 5) >>> add_five(3) 8 >>> add_five(16) 21 * * * i dont quite understand the assignment and i am new to function in function but ive done this so far and i think im on the right way? def add(n,m): return n+m def partial(func,number): def add_n(number): return func(0,number)+number return add_n
So first of all : * What does partial should do ? It allows You to incremantaly build new function from another with some arguments already applied. Like In your case you always add something to number 5. Good answer can be found here : Currying in Python So answer for your question about how implemnt own partial function will be : def add(n,m): return n+m def partial(func,number): def add_n(arg): return func(number,arg) return add_n
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "function, python 3.x, in function" }
Drag drop link into textbox with text only For example I have a link (or any other control that can be drag and drop) like below: <a href="something.xxx" onclick="something">Text Link</a> If I drag and drop this link into a textbox, it paste the link location into the textbox, but, I only want "Text Link", how can I do that? Note that it needn't to be a link, I only need a web control that can be drag and drop.
with jQuery and jQuery UI: $('a').draggable({revert: true}); $("#textbox").droppable({ hoverClass: 'active', drop: function (event, ui) { this.value = $(ui.draggable).text(); } }); Demo : <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, asp.net, hyperlink, drag and drop" }
How do I open Google Maps App with loaded address onclick of TextView? I have a very simle TextView as shown below. > > <TextView > android:layout_width="wrap_content" > android:layout_height="wrap_content" > android:text="Adress:" > android:textAppearance="?android:attr/textAppearanceLarge" > android:id="@+id/textView3" > android:layout_alignTop="@+id/To" /> > > > Now this TextView will show an address and when the users clicks on the TextView I'd like it to open google maps app with the address loaded. Can anyone shed some light on this subject
You can use Common Intent on Android < public void showMap(Uri geoLocation) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData("geo:0,0?q=my+street+address"); //lat lng or address query if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, google maps" }
Hide/Show Values Inside TD tags How can I hide or show the value contained inside a TD tag? E.g: <td id="dateCell<%= i %>"> <%= Html.Encode(row.ActionOn.HasValue ? Html.FormatDateTime(row.ActionOn.Value) : Html.Encode("")) %> </td> How can I get the encoded value and hide or show it depending on a condition?
$('#myDropDown').change(function() { if($(this).val() == 4) { $('#dateCell').hide(); } else if($(this).val() == 3) { $('#dateCell').show(); } }); although this will hide the entire td, which isn't necessarily a good practice
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, html table, hide, show" }
Neutral pions and chromodynamics $\pi^0$ particles are either up-antiup or down-antidown (or strange-antistrange?) They must be opposite colors to preserve neutrality. Why don't the opposite quarks annihilate?
Pions in general and the neutral pion is not an stable particle, its mean lifetime is $\tau=8.4 \cdot10^{-18}$ s Pion - Wikipedia ")
stackexchange-physics
{ "answer_score": 3, "question_score": 5, "tags": "quantum mechanics, quantum chromodynamics" }
azure ad users to combobox without azure sql database wpf I am trying to show all users from the azure AD of the company i work for. I don't have a lot of experience using Azure. This company doesn't have an account with azure sql database so that is off the table. Now i am wondering if it is possible to fetch all the users from azure and put them into a combobox in my wpf app.
You could use the Microsoft Graph SDK. This API contains an endpoint for listing all users.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, wpf, azure, entity framework" }
android how to make gridview item corner round I will add a image to show it. < you can see the detail in the image.
For each grid item use the background below :- (save the below code in drawable folder) <layer-list xmlns:android=" <item android:bottom="1dp" android:left="1dp" android:right="1dp" android:top="1dp"> <shape android:shape="rectangle"> <solid android:color="@color/black_transparent"/> <corners android:bottomRightRadius="12dp" android:bottomLeftRadius="12dp" android:topLeftRadius="12dp" android:topRightRadius="12dp"/> </shape> </item> </layer-list>
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "android, gridview, rounding" }
1920x1080 Image don't fit to 1920x1080 screen I'm making a game with pygame and I wanted to add a background for my game. I'm trying to add a 1920x1080 background to a 1920x1080 screen, but part of the background is not visible. My code: import pygame import sys pygame.init() screen = pygame.display.set_mode((1920, 1080)) bg_img = pygame.image.load("wp.jpg").convert() clock = pygame.time.Clock() while True: screen.blit(bg_img, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) pygame.display.update() clock.tick(60) wp.jpg: ![enter image description here]( Result: ![enter image description here](
I fixed the problem by changing my code to: import pygame import sys pygame.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN|pygame.NOFRAME) bg_img = pygame.image.load("wp.jpg").convert() clock = pygame.time.Clock() while True: screen.blit(bg_img, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) pygame.display.update() clock.tick(60)
stackexchange-gamedev
{ "answer_score": 0, "question_score": 0, "tags": "python, pygame, image" }
Is there a DesignMode property in WPF? In Winforms you can say if ( DesignMode ) { // Do something that only happens on Design mode } is there something like this in WPF?
**Indeed there is** : **System.ComponentModel.DesignerProperties.GetIsInDesignMode** Example: using System.ComponentModel; using System.Windows; using System.Windows.Controls; public class MyUserControl : UserControl { public MyUserControl() { if (DesignerProperties.GetIsInDesignMode(this)) { // Design-mode specific functionality } } }
stackexchange-stackoverflow
{ "answer_score": 164, "question_score": 107, "tags": "wpf, .net 3.5" }
Single quotes changed to double quotes I have this problem that when using single quotes in my javascript those single quotes will be changed to double quotes from the browser var divs = $(".new_spezial > .contentContainer"); for(var i = 0; i < divs.length; i+=3) { divs.slice(i, i+3).wrapAll("<div class='spezial_row'></div>"); } even escaping the single quotes does not help. var divs = $(".new_spezial > .contentContainer"); for(var i = 0; i < divs.length; i+=3) { divs.slice(i, i+3).wrapAll("<div class=\'spezial_row\'></div>"); } It will always be changed to this in the browser: var divs = $(".new_spezial > .contentContainer"); for(var i = 0; i < divs.length; i+=3) { divs.slice(i, i+3).wrapAll("<div class="spezial_row"></div>"); } How would I fix this?
I found the Problem it was that in my CMS (Typo3) I had xhtml_cleaning = all activated. Therefore the single quotes were replaced...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html" }
Smartphone: java not supported What means that android smartphone (let's say Samsung J3) does not support Java? I searched on google but I didn't find explanation what it means, what is the difference between smartphones which support Java and smartphones which does not support Java? Is anybody know? Thanks!
Quoting the documentation for the site that you linked to: > Often stands for "Java ME" (the new name of J2ME, Java 2 Platform, Micro Edition). Java ME is a platform for applications running on mobile phones. These, mainly small, applications (e.g. games) can be downloaded from the Internet directly to the phone using its built-in web-browser. What that site is referring to by "Java" is not Android apps, but old Java ME applets. Few, if any, Android devices support Java ME. Most Android devices support Android apps, and those apps can be written in the Java programming language.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, smartphone" }
python solution for feed provider I want to build a site same as : < , and post all my google reader subscriptions(100+) to my gmail, (in separate mails) so I need create a feed fetcher server, get all the feeds, post new ones to my gmail. are there any python based feed fetcher library? I know there is some feed parser, I think there is a all-in-one solution somewhere..
OK, I got a great tool to do this: < maybe I can port it on gae..(oh, email quota cost more then I can afford..)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, feed" }
how to dynamc import img I try to change dynamically the img for a react hangman project. So I tried with a state but an error occured saying `Cannot convert object to primitive value` So I've tried to passed directly the function that import dynamically to my img but that makes an infinite loop. This is the function loadHangmanSvg() { const { attempts } = this.state const svgName = `hangman_${attempts}` import(`./assets/${svgName}.svg`).then(svgName => { this.setState({ svgName }); }); }; and this is the prop svgHangman={this.loadHangmanSvg()} **Thanks for your help :D**
loadHangmanSvg() { const { attempts } = this.state const svgName = `hangman_${attempts}` import(`./assets/${svgName}.svg`).then(svgName => { // only when svgName is undefined, change the state of component if (!this.state.svgName) { this.setState({ svgName }); } }); };
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs, create react app, dynamic import" }
Is there a RegExp.escape function in JavaScript? I just want to create a regular expression out of any possible string. var usersString = "Hello?!*`~World()[]"; var expression = new RegExp(RegExp.escape(usersString)) var matches = "Hello".match(expression); Is there a built-in method for that? If not, what do people use? Ruby has `RegExp.escape`. I don't feel like I'd need to write my own, there have got to be something standard out there.
The function linked in another answer is insufficient. It fails to escape `^` or `$` (start and end of string), or `-`, which in a character group is used for ranges. Use this function: function escapeRegex(string) { return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&'); } While it may seem unnecessary at first glance, escaping `-` (as well as `^`) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex. Escaping `/` makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation. As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases. And yes, it is a disappointing failing that this is not part of standard JavaScript.
stackexchange-stackoverflow
{ "answer_score": 758, "question_score": 585, "tags": "javascript, regex" }
Decryption of hashed passwords I am working on a website's framework translation. I have translate it from Yii php framework to Laravel. I have got an existing database and I have to provide login access to existing users to the new website. The problem is now I am using Laravel and Laravel does not recognizes the hashed values of the previous framework. i.e the values that are stored in the database hashed by some method in Yii framework. Is there any way to resolve this. I am using Auth::attempt() method in Laravel.
You can't... plain and simple... hashing isn't encryption. hashing is one way, you can prove this to yourself by taking an md5 or shasum of a large file, since the file's size is larger than the hashes output, by pigeonhole principle hashes can't be restored... you could try to rainbow table them with password lists, don't, because this is compromising users security. you will probably have to figure out a way to mash Yii's auth module into Laravel, or use some sort of middle man auth bit... or just make everyone change passwords.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "laravel, yii, passwords" }
Cardinal sine envelop I am looking for an envelope of the function $t\mapsto \mbox{sinc}^2(t)$, or at least an approximation of such an envelope. Is there a known envelope function? Here's an illustration of $\mbox{sinc}^2(t) = \frac{\sin^2(\pi t)}{(\pi t)^2}$ (blue), and of one of its envelopes (red), which I drew by hand. ![sinc2 function and envelope]( More generally, I was wondering, how does one calculate an envelope?
An envelope is defined for a parametric family of functions and not for a single member. It is obtained by eliminating the parameter between the function equation and that obtained by differentiating over the parameter. For example, consider the family $$y=\frac{\sin^2\lambda t}{t^2}.$$ The aformentioned derivative is $$0=\frac2t\sin\lambda t\cos\lambda t,$$ which implies $\sin^2\lambda t=0$ or $1$. Hence the two envelopes $$y=\frac1{t^2},\\\y=0.$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "trigonometry, differential geometry, curves" }
Rel canonical link tag pointing to the same page I'm implementing the canonical tag in my page to avoid be penalized with duplicate content flag by search engines. My doubt are the following: * If I have a page COPY with the canonical tag pointing to ORIGINAL, and in this ORIGINAL page I have the canonical tag pointing to ORIGINAL again, what are the consequences? The thing is, that for me is more easy to generate the tag in all pages, and not only in the copies. * Can i put the `<link rel="canonical" href="ORIGINAL" />` in anyplace, or should be in the `<head>` tag.
You can have a `<link rel="canonical">` on the original page. There's no harm in doing so. It's just redundant but that's not a problem. `<link rel="canonical">` belongs in the `<head>` section only. If it is outside of the `<head>` it is invalid HTML and may not be honored.
stackexchange-webmasters
{ "answer_score": 5, "question_score": 3, "tags": "seo, canonical url, rel canonical" }
Delta-equal to symbol and matrix with dashed lines How do i write this in latex plz ![enter image description here](
You can use \begin{equation*} w \overset{\Delta}{=} \begin{bmatrix} w^1\\ \verb!---!\\ w^2 \end{bmatrix} \overset{\Delta}{=} \begin{bmatrix} p\\ \verb!-------------!\\ [exp(q_n/\pi)]r^3 \end{bmatrix} \end{equation*} to render ![enter image description here]( `\overset` places the first argument over the second argument and `\verb` renders out exactly what its argument is in code form (kind of like the difference between code and text in Stack Exchange!). Please note that both `overset` and the `bmatrix` environment are provided by the `amsmath` package, so make sure to add `\usepackage{amsmath}` to your preamble.
stackexchange-tex
{ "answer_score": 1, "question_score": 1, "tags": "matrices" }
How can I use multi properties in one field using EditorFor? I have a `Customer` class: public class Customer { public int Id { get; set; } public string Name { get; set; } string Surname { get; set; } } How can I use `Name` and `Surname` together in **one field** using `Html.EditoFor` ? @Html.EditorFor(model => model.Customer.Name + Surename???? , new { htmlAttributes = new { @class = "form-control" } })
You can try to add `NameWithSurname` property to connected `Name`and `Surname` value. public class Customer { public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } private string _NameWithSurname; public string NameWithSurname { get { _NameWithSurname = Name + Surname; return _NameWithSurname; } set { _NameWithSurname = value; } } } @Html.EditorFor(model => model.Customer.NameWithSurname , new { htmlAttributes = new { @class = "form-control" } }) **NOTE** Your `Surname` property might be `public`, otherwise it only can use in `Customer` class.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, asp.net mvc, view, editorfor" }
How to sort a list of dictionary for datetime key which also contains empty string and get the large value first? The list of dictionary - data = [{'key1':'','key2':'111'},{'key1':12,'key2':'1'},{'key1':1,'key2':'1'}] Sorted is - sorted(data, key=lambda k: (k['key1'] is None, k['key1'] == "", k['key1']),reverse=True) Response - [{'key1': '', 'key2': '111'}, {'key1': 12, 'key2': '1'}, {'key1': 1, 'key2': '1'}] How do we get the large value first and move the empty string last?
You can try: >>> sorted(data, key=lambda x : x['key1'] if x['key1'] else float('-inf'), reverse=True) [{'key1': 12, 'key2': '1'}, {'key1': 1, 'key2': '1'}, {'key1': '', 'key2': '111'}] >>> # OR >>> sorted(data, key=lambda x : x['key1'] if isinstance(x['key1'], int) else float('-inf'), reverse=True) [{'key1': 12, 'key2': '1'}, {'key1': 1, 'key2': '1'}, {'key1': '', 'key2': '111'}]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x" }
excel rows function: increase numbers sequentially in the same cell I am using the ROWS function in an excel spreadsheet to auto increase numbers within text. the formula i am using at the moment is this: ="text"&ROWS(A$1:A1)&"text"&ROWS(A$1:A1)&"text"&ROWS(A$1:A1)&"text"&ROWS(A$1:A1)&"text"&ROWS(A$1:A1)&"text" which produces the following output: (CELL A:1) text1text1text1text1text1text The numbers increase by 1 as i copy the cells down ie: (CELL A:2) text2text2text2text2text2text The output i actually need is to increase the numbers sequentially by 1: (CELL A:1) text1text2text3text4text5text (CELL A:2) text6text7text8text9text10text ...etc Many thanks in advance
Try this version `="text"&(ROWS(A$1:A1)-1)*5+1&"text"&(ROWS(A$1:A1)-1)*5+2&"text"&(ROWS(A$1:A1)-1)*5+3&"text"&(ROWS(A$1:A1)-1)*5+4&"text"&(ROWS(A$1:A1)-1)*5+5&"text"` *5 is based on 5 text values per cell
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, function, excel formula, rows, worksheet" }
Accessing two sides of a user-user relationship in rails Basically, I have a users model in my rails app, and a fanship model, to facilitate the ability for users to become 'fans' of each other. In my user model, I have: has_many :fanships has_many :fanofs, :through => :fanships In my fanship model, I have: belongs_to :user belongs_to :fanof, :class_name => "User", :foreign_key => "fanof_id" My fanship table basically consists of :id, :user_id and :fanof_id. This all works fine, and I can see what users a specific user is a fan of like: <% @user.fanofs.each do |fan| %> #things <% end %> My question is, how can I get a list of the users that are a fan of this specific user? I'd like it if I could just have something like @user.fans, but if that isn't possible what is the most efficient way of going about this? Thanks!
Add in User model: has_many :my_fanclubs, :class_name => 'Fanship', :foreign_key => 'fanof_id' has_many :fans, :through => :my_fanclubs, :source => :user, :class_name => 'User' (not tested)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby on rails, activerecord, model, orm, relationship" }
multiplying letter of string by digits of number I want to multiply letter of string by digits of number. For example for a word "number" and number "123" output would be "nuummmbeerrr". How do I create a function that does this? My code is not usefull, because it doesn't work. I have only this def new_word(s): b="" for i in range(len(s)): if i % 2 == 0: b = b + s[i] * int(s[i+1]) return b for new_word('a3n5z1') output is _aaannnnnz_ .
This will solve your issue, feel free to modify it to fit your needs. from itertools import cycle numbers = cycle("123") word = "number" output = [] for letter in word: output += [letter for _ in range(int(next(numbers)))] string_output = ''.join(output) **EDIT:** Since you're a beginner This will be easier to understand for you, even though I suggest reading up on the itertools module since its the right tool for this kind of stuff. number = "123" word = "number" output = [] i = 0 for letter in word: if(i == len(number)): i = 0 output += [letter for _ in range(int(number[i]))] i += 1 string_output = ''.join(output) print(string_output)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x" }
What does "correctly noded" mean? I've never seen this term, and I'm wondering what it means, with regard to `ST_Polygonize` > NOTE: Input linework must be _correctly noded_ for this function to work properly
this page helpfully shows some of the edge cases where this function would fail and return NULL. To summarise some examples... * two linestring geometries which touch/cross at one point. but don't loop back on each other to touch/cross at another point * two disjoint lines * a single linestring which does't form a complete loop or any case where the set/array of geometries doesn't form one or more polygons. Also, rounding/precision errors might come into play, and it may be that linestrings need to align in a consistent direction. there may be other definitions of 'incorrectly noded' :)
stackexchange-gis
{ "answer_score": 8, "question_score": 8, "tags": "postgis, terminology" }
A difficulty in understanding the solution of Exam GRE 0568 Q31. The question and its answer is given in the following picture:![enter image description here]( The question was asking about "the graph of a **solution** to the differential equation", so why in the solution he is speaking about $dy/dx$ and not speaking about $y$? could anyone explain this for me please? Also I do not understand why our selection is narrowed to only (A) and (B) and not to (A)(B)(D) and (E), why the author exclude (D) and (E)? could anyone explain this for me? Finally, it is not clear for me why he exclude (B), could anyone explain this for me please?
See $\frac {dy}{dx} $ is the slope of the curve at that point. Now as $y\ to \pm \infty $ the slope goes to $\infty $ according to the equation. So the slope of graph at both the infinities should be $\infty $. This is true only for $A,B$. Now see graphs around $0$ we have slope as $1$ around $0$ according to the equation. But in $B$ the sope around $x=0$ is almost $0$ thus the correct graph is $A$ as its increasing around $0$.
stackexchange-math
{ "answer_score": 0, "question_score": 3, "tags": "calculus, ordinary differential equations, gre exam" }
No colon after property name in object declaration, is it valid? I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript: var x = { a (b) {} }; console.log(x); `x` is then set to an object with the property "a" containing a function called "a" with an argument identifier "b". How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand). With ES6: const obj = { a(b) { // Shorthand method // `this` context is `obj` }, c }; is equal to var obj = { a: function a(b) { }, c: c };
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 25, "tags": "javascript" }
Does glUniform*fv retains passed buffer? What really happens when I call `glUniform2fv`? Does it synchronously copy the passed buffer or is it just accepts the pointer and use that data later? Does it retain the buffer? In the other words: is it safe to pass locally-created or non-retained buffers in function or it is up to me to keep that buffer alive? I'm using OpenGL on iOS/Mac using objective-c and/or Swift, I'm afraid GC (ARC) can eat my buffer before it will be send to GPU.
It is safe, but the documentation is not clear on this, at least the version found at < > They retain the values assigned to them by a call to glUniform until the next successful link operation occurs on the program object
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, objective c, swift, opengl es" }
Definition of singly-connected set please - help - what does mean singly-connected set? this is set without holes and which has one bounded contour? the sample < means that this is set of another structure or this docs has mistake?
At least in the Straight skeleton package it means that if you strip off the boundary of the polygon, any two points of the open polygon can be connected with a curve inside the open polygon.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "math, cgal" }
excel/vba: count number of unique male and female students in list I have a database of students with names and their gender, however the list contains repeats of students on different dates. How do I count the number of unique male students and unique female students on my list? Here is a sample database: Name Date Gender A 8/1/2013 M B 8/2/2013 F C 8/2/2013 F A 9/2/2013 M A 9/3/2013 M C 8/31/2013 F B 8/15/2013 F D 10/5/2013 M The total count for unique males should be 2, and unique females should be 2. I tried to play around with the sum(if(frequency)) variation formula but without luck. I'm not sure how to tie it to using the names. I don't mind using VBA code either. Any suggestions would be appreciated. Thanks!
Assuming that each name will always have the same gender if repeated (!) you can use a formula like this to count different males in the list: `=SUMPRODUCT((C2:C100="M")/COUNTIF(A2:A100,A2:A100&""))` obviously change M to F for female count
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "list, vba, excel" }
Why am I not receiving email notifications from Stack Overflow? When people comment or answer, I no longer receive email notifications. Why?
You only receive email notifications if: 1. You have **first enabled email notifications in the global inbox:** [![][1]][1] (source: stackoverflow.com) 2. And you have **not clicked on the global inbox for the specified time period**. In other words, if you specified "daily" then you must not have clicked on the inbox with your mouse for at least 24 hours to begin getting email notifications. In other words, every single click on the global inbox resets this timer to zero. See < [1]: <
stackexchange-meta
{ "answer_score": 4, "question_score": 4, "tags": "support, email notification" }
how to make our app to start automatically? I have an apk which runs only on background. I want it to start itself every X seconds. I can do it from terminal with sh command: #!/bin/bash while true do am start --user 0 -a android.intent.action.MAIN -n com.xxxxxxx/.MainActivity sleep 20 done But after reboot it stops running itself automatically. Besides, I don't want to use sh command everytime. So I decompiled the apk with apktool. What do I need to add to make our app start it self every x seconds? p.s. I know that if I save the commands as sh file into etc/init.d/ it'll be persistent but I'm trying to learn how can we add it to source.
> What do I need to add to make our app start it self every x seconds? You need to schedule it with the AlarmManager. You can find more about that here. > But after reboot it stops running itself automatically. You need to register a receiver for `android.intent.action.BOOT_COMPLETED` for you app to be invoked after boot. You can find an answer for that here. When your receiver is invoked, you can then again schedule your app for restarting.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, android activity" }
Web3 empty response when geth not synced I am running my own geth node and doing some test transactions. When making a transaction trough web3 I get an response of transaction information. But sometimes it happens that my node is not fully in sync so when I make a transaction from geth I get an empty response. Since I want to save all the transaction hashes in my databas this is a problem. How should I handle this kind of situation? Is there a way to get transaction hash from web3 anyway if this happens? I know geth shows it but it is not returned by web3..
If you are using web3 1.0 and trying to send a transaction to a contract. For example to make a tokens transfer and obtain the transaction hash you can do this: token.methods.transfer(recipient, amount) .send({ from: owner }) .on('transactionHash', function(hash){ console.log(hash); });
stackexchange-ethereum
{ "answer_score": 1, "question_score": 0, "tags": "go ethereum, web3js, transactions, synchronization" }
Not able to login via specified user in localhost SQL Server connection string I am new to SQL Server and I am trying to connect a localhost SQL Server. And I am having the following exception: > Cannot open database "MyDatabase" requested by the login. > The Login failed Login failed for user "MyCodingPC\Cyborg". And also I don't understand why it is getting logged in via that username when I have specified another user in the connection string. My connection string Data Source=xxx.xxx.xx.xxx,1433\(localdb)\MSSQLLocalDB;Network Library=DBMSSOCN;Initial Catalog=MyDatabase;User Id=MyNewUser;Password=pass@#$word;Integrated Security=True
LocalDB cannot be used over TCP. So to accomplish my requirements I used SQLExpress instead. LocalDB is supposed to work only for local access; remote access is not possible here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql server, visual studio, ssms" }
Echelon Form and Reduced Row Echelon Form differences and when to use I have a quick question regarding the difference between echelon form and reduced row echelon form (rref). According to my googling these seem to be the same, but to me it seems that the difference between the two is that echelon form only requires the first value of the first row to be 1. The first non-zero value of each row after the first one can be any value as long as it's not 0. As for reduced row echelon form every first non-zero value of a row has to be 1. Am I correct with this or am I completely mixing things up? If I'm correct, when would the echelon form be fine and when do I have to use RREF? Thanks :)
Row-echelon form (REF): (i) Leading nonzero entry of each row is 1. (ii) The leading 1 of a row is strictly to the right of the leading 1 of the row above it. (iii) Any all-zero rows are at the bottom of the matrix. $ $ Reduced row-echelon form (RREF): (i) REF. (ii) The column of any row-leading 1 is cleared (all other entries are 0). $ $ Note: A given matrix (generally) has more than one row-echelon form; however, for any matrix, the reduced row-echelon form is unique. This uniqueness allows one to determine if two matrices are row equivalent (can one be transformed to the other by a sequence of elementary row operation).
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "linear algebra, matrices" }
Using the Product Rule I have to calculate the derivative for $f(x) = (\sqrt{x} + 102)(\sqrt{x} - 101)$. I think I have to use the product rule for this, but am not sure how to go about it.
Sure you can use the product rule. $$\frac{df}{dx}=u'v+v'u$$ In this case let $u=\sqrt x-101$ and $v=\sqrt x +102$ Then $$\frac{df(u,v)}{dx}=1+x^{\frac{-1}{2}}$$ after simplifying. Alternatively you can expand the brackets and don't worry about the product $-101 \cdot 102$ because it will disappear when you differentiate.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "calculus" }
Segmentation fault while trying to access empty vector So I made a 2D array of chars but Every time I try to access it I get a segmentation fault and I cannot figure out why. std::vector<std::vector<char>> matrix_; //Filling it with space ' ' characters std::vector<char> aRow; matrix_.resize(height_, aRow); for (std::vector<char> row : matrix_) { row.resize(width_, ' '); } std::cout << matrix_[0][0]; //Segmentation fault here
Use `auto&& row : matrix_` (note the reference added), in the `for` to get the reference to each row you are looking for. As you have it, it creates a copy, resizes it and discards the result. Without being too pessimistic about it, you could also look to resize each column with the right sized row. The `for` loop is not needed. std::vector<char> aRow(width_, ‘ ‘); matrix_.resize(height_, aRow);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, segmentation fault, stdvector" }
How to access pdf files without having the .pdf using htaccess? I want to access the pdf files but without the `filename.pdf` only `filename` How can I do this using htaccess?
You can use the following Rule in `root/.htaccess` : RewriteEngine on RewriteCond %{REQUEST_FILENAME}.pdf -f RewriteRule ^(.*?)/?$ /$1.pdf [L] This will internally redirect `/filename` to `/filename.pdf`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "apache, .htaccess, mod rewrite" }
Python: How to use MFdataset in netCDF4 I am trying to read multiple NetCDF files and my code returns the error: > ValueError: MFNetCDF4 only works with NETCDF3_* and NETCDF4_CLASSIC formatted files, not NETCDF4. I looked up the documentation and MFdataset is not supported by NetCDF4, so I'm confused where to go from here.
I think the error is pretty clear, but there are ways to avoid it. 1/ You could convert the NetCDF files from NetCDF4 to the classic format using e.g. nccopy: nccopy -k classic nc4_file.nc ncclassic_file.nc 2/ xarray has a similar method (called `open_mfdataset`) which is able to handle NetCDF4 files. A quick test: import netCDF4 as nc4 test = nc4.MFDataset(['test0.nc','test1.nc']) This gives me the same error as you get ( _"MFNetCDF4 only works with..."_ ), the same with xarray works without any problems: import xarray as xr test = xr.open_mfdataset(['test0.nc', 'test1.nc'])
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, netcdf, netcdf4" }
Как управлять объектом из другого класса? Суть вот такая. Есть библиотека плеера, который я создаю и запускаю при создании активности: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); player = new MODPlayer(getApplicationContext()); player.play(this, 1); player.onVol(Volum); } Запускается это дело в потоке, потом хочу из другой класса активности/класса диалога, скажем прибавить громкость или поставить на паузу, но ведь один экземпляр уже создан! Создать еще один путем player = new MODPlayer(getApplicationContext()) мне кажется будет криво, может можно как то объект передать другому классу?
Вообще-то в андроиде уже есть свой встроенный синглтон и называется он Application, нужно унаследовать от этого класса и хранить там все экземпляры, которые должны быть одиночками, а также добавить геттеры и сеттеры. Особенность этого класса заключается в том, что во-первых есть полная гарантия того, что он будет жить на протяжении всей жизни приложения, в отличии от обычных статических данных, а во-вторых он будет единственны и доступен, если есть контекст приложения. Работать с ним так: player = new MODPlayer();//один раз создаёте свой плеер getContextApplication().setPlayer(player);//кладём его в аппликейшен ... context.getPlayer();//а когда нужно просто его от туда достаёте, главное, чтобы был экзепляр контекста
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "android, java" }
C++ what’s the proper way to handle temporary object and array Recently I read a lot about sort algorithm, and I found the strange which made me feel confused. In the function, it needs to create a temporary array in the for loop. And the sample code is for(;;)//ignore the condition { int *b = new int[N]; //some code delete b[]; } The question is : Why not just create it directly without new operator, for the compiler will destroy it automatically and release the memory after each iteration. Like write this in the loop int b[N]; And in the previous, I always use this method to create the temporary type/object. Am I totally wrong or something like array is different from built in type? So, kind Stack Overflowers, can anyone give me some advice?
> Why not just create it directly without new operator, for the compiler will destroy it automatically and release the memory after each iteration. Indeed, why not? If `N` is known at compile time, then go on and use `int b[N]`. If `N` is not known at compile time, then `std::vector<int>` should be used instead: for(;;)//ignore the condition { std::vector<int> b(N); //some code } You should ask the author of the code why he or she uses `new[]` and `delete[]`, but chances are it's simply lack of experience.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c++" }
Connecting multiple wireless devices to one main device using bluetooth What I want to do is connect to bluetooth enabled devices to one main device. For example two bluetooth speakers to connect to my iPhone and play music. Do speaker A needs to connect to Speaker B through bluetooth and then connect to the iPhone? IS this even possible?
iPhones music app can only output to one bluetooth speaker at a time. Either the software would need to support multiple outputs or the speakers would need to have a feature to pair with each other. So it is technically possible, but not supported by iOS' music app, nor do I personally know of a speaker that does that.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ios, iphone, bluetooth" }
How to create a application that works both on Google App Engine and Local tomcat server? I am creating a java based application and i want to use google app engine for its deployment. But i want this application to be movable to other servers like tomcat etc on my local or other machines. So i though want to use google app engine. But want to keep my application independent of any Google specific things. Can somebody summarize the points i must take care of. I want to keep it independent both from application and database layer perspective.
Though I am not master in google app engine however the thumb rule to make your webapp portable is to use standard specification APIs instead of vendor specific APIs. For example if your app is using google app engine UserServive (com.google.appengine.api.users.UserService) or data store com.google.appengine.api.datastore.DatastoreService , if is tightly bound with Google app engine and can not be migrated to standalone tomcat engine. To loose couple your database for further migration you should consider using MySQl schema in google app engine. Because in future you can host your database anywhere by just taking a dump. Also, you should use JDBC apis/JPA for database operations from your application using MySQL JDBC JAR To summarize, you should avoid any API call which has com.google.appengine* import in your source. Also, you should have your own mysql schema running in google app engine cloud.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, google app engine" }
How do I find what npm package has a particular dependency? My webpack project has a new error: > Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist` Which I haven't solved yet, but the underlying problem is: I don't have **caniuse-lite** in my package.json - so where is it? _btw: running that command makes no difference._ It's obviously a dependency or a dependency of a dependency, ad infinitum... npmjs caniuse-lite lists 80 dependent packages. Is there a way to search the dependency graph of packages to easily find what package in my package.json file is the parent that somewhere along the line depends on caniuse-lite?
You can easily check that by following way. Checkout more here : < `npm ls contextify` [email protected] /home/zorbash/some-project [email protected] [email protected] [email protected]
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "npm, package.json" }
How to categorize SQL Server data access for papers? We are writing this paper about database access in a web app and have to distinguish between the different categories of the database access layer. All books and PDF's given us provide only information to JDBC or OLEDB. Researching on the web brought me to the point that access to a Microsoft SQL Server trough `linq-to-entities` or `linq-to-sql` through ADO.Net can't be put under the same category as **JDBC** or **OLEDB** (`middleware`). What would be the exact definition/category for Microsoft SQL Server-access through the .NET facilities such as LINQ2Entities or LINQ2SQL?
ADO.NET is the next step after OleDB - and it's definitely in the same category as OleDB or ODBC / JDBC. Linq-to-SQL and Linq-to-Entities are more high-level - they don't solve low-level data access problems, they're more about OR-mapping and providing models to work against. I would put those in a similar category as Hibernate in the Java world. Marc
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, linq to sql, linq to entities, categories" }
Exclude search paths from dproj when building with msbuild I'm trying to build some Delphi XE projects using msbuild. While most work without a problem, some projects which have a lot of (and long) search paths, fail to build with this error message: MSB6003: The specified task executable could not be run. The filename or extension is too long I found the reason for this: I add differing search paths via /p:DCC_UnitSearchPath= some of which are not in the dproj file. This makes the command very long and msbuild fails. So basiacally what I want to do here is just use the unit search paths I am setting via DCC_UnitSearchPath but exclude / ignore the search paths from the dproj file. Is there a way to achieve this? Thanks, Greg
Move parts of your search path to environment variables to access Spring4D, DSharp and VirtualTreeView: DSharp=C:\Users\Developer\Versioned\DSharp Spring4D=C:\Users\Developer\Versioned\Spring4D VirtualTreeView=C:\Users\Developer\Versioned\VirtualTreeView Then in your configuration specify them like this: $(DSharp)\Source\Aspects;$(DSharp)\Source\Bindings;$(DSharp)\Source\Collections;$(DSharp)\Source\ComponentModel;$(DSharp)\Source\Core;$(DSharp)\Source\Logging;$(DSharp)\Source\PresentationModel;$(DSharp)\Source\Validation;$(DSharp)\Source\Windows;$(Spring4D)\Source\Base;$(Spring4D)\Source\Base\Collections;$(Spring4D)\Source\Core\Container;$(Spring4D)\Source\Base\Reflection;$(Spring4D)\Source\Core\Services
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "delphi, msbuild" }
How can we convert regular expression to ANTLR 4 Expression I was searching for a way or tool to convert the regular expression into the ANTLR 4 expression but could not find anything suitable. Now i'm curious "Can we actually convert it or not." If not, then i assume ANTLR 4 expression and regular expression looks same look-wise but are totally different. Please correct if I'm wrong.
ANTLR lexer rules are actually regular expressions, in the formal sense. This means you won't get pattern matching features like lookahead/lookbehind/captures etc out of the box. You can insert custom code in the rules if you need more control over the matching process. As for the syntax, it's a bit different from the standard regex syntax. For instance, in ANTLR you write `~[a-z]` instead of `[^a-z]`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "regex, antlr, antlr4, antlrworks, antlrworks2" }
S.L. Weiss - Ciacona Suit 10. How to play this note on guitar? ![enter image description here]( (From S.L. Weiss - Ciacona Suit 10, arranged for guitar) As shown in the red circle. I found it very hard to place my fingers on guitar to play this. Especially the D4 note. transcribed to tablature, would be like this: almost impossible for me to play... --4-- --5-- --7-- ----- --2-- -----
The 6 in a circle says that the B will be played on the 7th fret, bottom string. Just as the C prior is on the 8th fret. Leaving the other three notes as you show. Still not an easy fretting position, but just about doable. It's an E dominant 7th chord inversion, and since it's a transcription, the transcriber has attempted to get it played verbatim to the original. Which often is near impossible on guitar.
stackexchange-music
{ "answer_score": 3, "question_score": 0, "tags": "guitar, classical guitar" }
CAN (Controller Area Network) on Android I am trying to connect control multiple device on the network centrally via a tablet/android device and have some issues trying to find the right protocol for secure communication. Is there a api available for coding/utilizing CAN network on android over Ethernet/Bluetooth/Wifi ? Or is there another protocol that is more suitable for my application? Thank you.
What you are able to use will be determined by what protocol your devices support. However, the use of a CAN bus is meant primarily to reduce wiring between the components, so implementing it over a wireless protocol is pretty much nonsense. Considering you have the alternatives you mentioned (Ethernet/Bluetooth/Wifi), assuming some kind of TCP/IP network between your devices **HTTPS** would be a reasonable protocol to use.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "android, can bus, communication protocol" }
Testing for Java SDK I am writing an application in Java. Does a Java SDK have to be installed to run the application from the command line? If so, can I package the SDK with the application to be installed when installing the application?
From Java 9 onwards you can use `jlink` to produce a custom JRE for your application. The JRE includes a copy of the `java` command and (only) the libraries / classes that your application needs. It will be platform specific. From Java 14 onwards, you can use `jpackage` to produce (platform specific) native executables for Java applications. There are also 3rd-party tools that can generate executables, and third party installer generators that (in some cases) can install Java for the end user. Note: if you take the approach of distributing your application as a self-contained JRE or native executable, the user no longer has the option of updating their Java to address security related issues. It becomes your problem / responsibility ... as the supplier of the software ... to make available in a timely fashion application updates that incorporate the new Java releases with important security patches.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java" }