INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What is the proper way to comment code in Python? I was reading PEP8 and some questions on Stack Overflow, but I was wondering about spaces between comments: Let’s say I have this code: class MyBrowser(QWebPage): ''' Settings for the browser.''' def __init__(self): QWebPage.__init__(self) # Specifies whether images are automatically loaded in web pages. self.settings().setAttribute(QWebSettings.AutoLoadImages, True) def userAgentForUrl(self, url): ''' Returns a User Agent that will be seen by the website. ''' return "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15" What is the most Pythonic way of putting blank lines between comments and the actual code? I want to show my program to some experts. And want my code to look more professional.
I don't know if this represents the "community standard" but here are Google's Python style guides (as they relate to comments). Specifically classes: class SampleClass(object): """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """ def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" self.likes_spam = likes_spam self.eggs = 0 def public_method(self): """Performs operation blah."""
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 5, "tags": "python, comments" }
Simple Python Regex not matching Very simply, I am trying to replace a string that contains the substring XX. import re def replace_bogus(original, replacement): bogus = re.compile('[.]*[X][X][.]*') if bogus.match(original) != None: original = replacement return original if __name__ == "__main__": teststr = replace_bogus('ABXX0123', '') print teststr This code prints out ABXX0123. Why is this regex wrong and what should I use instead?
Because the dot (`.`) has no special meaning when it's inside a character class (i.e. `[.]`). The regex doesn't match the text and it returns `None`. As has been said in the comments, the `re` module has its own method for replacing, i.e. the `sub` method. You can simply use it like so: import re p = re.compile(r'XX') result = re.sub(p, '', 'ABXX0123') print result // => AB0123
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, regex" }
How to transform a dataframe in an ordered matrix? Please, input the following code: A <- matrix(11, nrow = 4, ncol = 3) A[,2] <- seq(119, 122, 1) A[,3] <- seq(45, 42) B <- matrix(39, nrow = 4, ncol = 3) B[,2] <- seq(119, 122, 1) B[,3] <- seq(35, 32) C <- matrix(67, nrow = 4, ncol = 3) C[,2] <- seq(119, 122, 1) C[,3] <- seq(27, 24) D <- rbind(A, B, C) You will get `D` which is a 12 x 3 matrix; I would like to know the most efficient way to obtain `Mat` starting from `D`. > Mat 11 39 67 119 45 35 27 120 44 34 26 121 43 33 25 122 42 32 24 In fact, `Mat` is the last column of `D` indexed by the first and the second column of `D`; e.g. consider `Mat[1,1]` which is equal to 45: it comes from the only row of `D` which is identified by 11 and 119. How may I obatin it? Thanks,
You can use `xtabs`: xtabs(D[,3]~D[,2]+D[,1]) D[, 1] D[, 2] 11 39 67 119 45 35 27 120 44 34 26 121 43 33 25 122 42 32 24
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "r" }
Deleting "child" records on delete (reverse foreign key constraint?) To illustrate my problem, I have 3 tables. `Table A` **AND** `Table B` both individually have FK `C_ID` that reference `Table C`'s PK. I want `Table C`'s rows to be deleted if their related rows in `Table A` or `Table B` is deleted. **FK constraints seem to only work one way. How do I deal with this?** _To clarify, A and B has a 1:1 relationship with C. To be more precise it's a (A,B)parent-child(C) relationship where the child's existence depends on the parent's._
I would use a delete trigger to remove the records from table C when a delete occurs on table a or b. There is a question from SO where the answer gives you a nice example: < But to give you the rough idea from that answer: CREATE TRIGGER table_c_delete AFTER DELETE on table_a FOR EACH ROW BEGIN DELETE FROM table_c WHERE table_c.parent_id = old.id; END
stackexchange-dba
{ "answer_score": 2, "question_score": 2, "tags": "mysql, mysql 5.7" }
bootstrap colorpicker change class color Trying to use Bootstrap Colorpicker (< to change the color of some text, but newbie so not able to implement it. $('.pickthecolor').colorpicker().on('changeColor.colorpicker', function(event){ $('.headingexample').css("color", "red"); }); is working as expected. Documentation suggest: $('.my-colorpicker').colorpicker().on('changeColor.colorpicker', function(event){ bodyStyle.backgroundColor = event.color.toHex(); }); How can I combine these two?
I believe this is what you're looking for: $('.pickthecolor').colorpicker().on('changeColor.colorpicker', function(event){ $('.headingexample').css("color", event.color.toHex()); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, twitter bootstrap" }
php получить число с текущего url url в таком виде < Как поместить в одну переменную 0 а в другую 2? количество знаков может менятся к примеру <
Ну на самом деле способов много, как вариант: $url = ' $param = explode('/', parse_url($url)["path"]); array_shift($param); var_dump($param); Результат: array(3) { [0]=> string(4) "news" [1]=> string(2) "20" [2]=> string(3) "232" }
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php" }
GIF Animation not working in Windows Form ## I have 2 WinForms Form2 uses Infragistics ultraTabControl. On Tab Changing im Showing Form1. ## In Form1 I have a `PictureBox` assigned with animated `GIF` ## In Form2 I am displaying Form1 like this. Form1 frmOne=new Form1(); frmOne.Show(); ## Problem `GIF` is not playing animation.
## Solved My current Thread is busy to Play GIF Animation. I tried So many ways like Application.DoEvents(); etc. But every thing can't helped me. The answer in the following Question, which uses Threading is a very great working idea. StackOverFlow: Show/Hide Splash Screen Thanks for every one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "c#, winforms, infragistics, picturebox" }
What effect does RSACryptoServiceProvider.KeySize size have? I have a byte array of size 42. I am encrypting this using an `RSACryptoServiceProvider` object: $keySize = 16384 $rsaProvider = New-Object System.Security.Cryptography.RSACryptoServiceProvider($keySize) Do you need a cray super computer to decrypt using a key size that big? Is there any benefit to using `$keySize = 2048` rather than 16384 in terms of memory etc?
Using a higher key size results in larger primes and modulus which makes it harder to factorize the modulus to get the primes out of it to then reveal the private key. RSA is based on modular arithmetic. A higher key size also means that operations exponentiations on larger numbers must be performed. Key generation and decryption will be much slower. Encryption will be a little slower. 2048 is the minimal recommendation today. You might want to use 4096, but 16384 is almost certainly too much for your use case. But this depends on the attack model and the capabilities of the attacker.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "powershell, encryption, rsa" }
Random Access to Array Is the array-object in Salesforce really an array, or is it a list "disguised" as an array? Specifically: Is the access of myArray[3] really random (="quick") or does the runtime need to iterate over the first 3 elements to finally find myArray[3] like it would in a normal list? So is the access of the n-th element of an array faster than the access of the n-th element of a list? Or is the access time equal for arrays and lists? More specifically: Is the array in Salesforce implemented as a linked list? That would mean that the complexity of myArray[3] is O(n), which would be not typical for an array. Therefore I don't believe that this is not the case, but as of yet I didn't find an exact definition. (I'm a newbie though, and I may have missed out important documentation)
It is very likely - a test would confirm - that Apex uses an array-backed list for its lists and a quick check of the typical source code or typical documentation: > The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. indicates that access speed at the various indexes is constant for such a list.
stackexchange-salesforce
{ "answer_score": 2, "question_score": 1, "tags": "list, array" }
How can I make zsh completion behave like Bash completion? I switched to zsh, but I dislike the completion. If I have 20 files, each with a shared prefix, on pressing tab, zsh will fully complete the first file, then continue going through the list with each press of tab. If I want one near the end, I would have to press tab many times. In bash, this was simple - press tab and I would get the prefix. If I continued typing (and pressing tab), bash would complete as far as it could be certain of. I find this behavior to be much more intuitive but prefer the other features of zsh to bash. Is there a way to get this style of completion? Google suggested `setopt bash_autolist`, but this had no effect for me (and no error message was printed upon starting my shell). Thanks.
Try: setopt autolist unsetopt menucomplete
stackexchange-superuser
{ "answer_score": 8, "question_score": 14, "tags": "linux, command line, zsh" }
Compare and Edit Branches in Git with a Mergetool I have 2 branches that I can compare/diff using my difftool (Beyond Compare). However, the files used for the diff are temporary copies and not the actual files from the current branch. This means that if I want to make a change to an existing file, I cannot do it via the difftool. I would need to make a copy of the files of one branch, checkout the other branch and use a regular diff between the actual files. Is there a way to get the difftool to use the actual files of the current branch (at least on one side)? **UPDATE and SOLUTION** : The command I used was `git difftool branch1 branch2`. This diffs 2 branches regardless of the current branch. The command `git difftool branch` works as desired, with one "side" as the currently checked-out branch.
The command `git difftool branch` works as desired, with one "side" as the currently checked-out branch.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 14, "tags": "git, diff, branch, beyondcompare, difftool" }
Resizing adds on the stroke width I have a graphic in illustrator CC that I need to resize. The original size is about 3.5, when I go to resize it to 10.5 it bumps itself up to 10.6 adding the dimensions of the outer most stroke.
From _Preferences -> General_ check _"Use Preview Bounds"_ : ![enter image description here]( This will use the visual appearance of objects to create their bounding box, rather than the paths themselves so resizing will take in to account the width of strokes or any effects etc. _Mostly copied frommy answer here._
stackexchange-graphicdesign
{ "answer_score": 1, "question_score": 0, "tags": "adobe illustrator, resize, stroke" }
How to append filename to current directory in Batch file? I want to search a file in the current directory from which the batch is running, append the filename to the directory and include that entire directory as part of command that. So..... Directory: C:\tempfiles\batch Files in C:\tempfiles\batch tmp1.txt tmp2.txt tmp3.txt anyname.exe I want the batch file, run from the directory, to find any .exe file and append it to the directory name, and use that new string as part of a command to copy the .exe file over to another directory. The command will eventually read like this (the FILETRANSFERSW.exe is the file transfer software that is also in the directory): C:\tempfiled\batch> FILETRANSFERSW.exe "%CD%\tmp4.exe" X:\dest The .exe file name will be changing so i need to dynamically add the new filename into the above command everytime i run the batch file. Any ideas??
If I read your problem correctly, is it sufficient to use the "for" keyword? `for %a in (*.exe) do FILETRANSFERSW.exe %a X:\dest` You can test the output with something innocuous like: `for %a in (*.exe) do echo [[%a]]` %a ends up iterating over *.exe in the current directory, returning the full file name for each one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "batch file, directory, append" }
Ubuntu Server NON system HDD transfer rate I am using samba for file sharing, but transfer rates are very strange. When I am moving files to a NON system HDD, the transfer rate is ~25MB/s. But when moving files to the HDD, where my system is installed, transfer rate is ~60MB/s (Max speed of the HDD) It seems off that non-system HDDs are performing better than the system HDD. Is there any reason for this, e.g. caching to the system drive and than copying to the non-system drive?
I accidentally found the answer to my question. The problem was the filesystem of the second drive. Looks like Linux doesnt like NTFS very much. I reformated to EXT4 and all is OK now ... Can copy with max drive speed :)
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "networking, server, samba" }
What's the difference between poweroff.target, halt.target, reboot.target, shutdown.target and a bunch of others? Systemd defines a bunch of special targets that all relate to shutting down a system, like the ones listed in the title of this post. There seem to be more. `man systemd.special` gives definitions for them, but does not attempt to differentiate between them. Just under which circumstances am I supposed to use which of those targets?
The `shutdown.target` can't be called explicitly, it contains the line `RefuseManualStart=yes`. It is the common part of the other ones, responsible for stopping processes and so on. `reboot.target` means after shutdown, reboot the system. `poweroff.target` means after shutdown, power off the system. `halt.target` means after shutdown, don't do anything (no reboot, no poweroff). The system will just wait in a shutdown state.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 5, "tags": "systemd" }
Client-Side Rendering: How to leverage server/client side templates? I'm currently implementing a ruby/sinatra application using erb as the rendering engine using client-side rendering using handlebars/mustache templates as well. I'm implementing a certain list view in which the list elements will be rendered using the client side solution when javascript is present and fallback to server side when not (targeting crawlers this way). But I'm left with the folliowing issue: I basically have two templates written in two different markups which produce the same html. I'd love to "write once, run everywhere". How are other projects leveraging this issue?
I've found the answer to be using your favorite templating flavor on the server-side but using some other templating engine for the cases where the template is going to be shared on the client side. So, I'm using erb most of the time, the rest of the time using poirot (for Rails). This integrates Mustache templates on action pack, which handles multiple templating engines anyway. Poirot comes ready with helpers to write the templates on the document and also client side rendering libraries. It also integrates handlebars and hogan templates, which are mustache extensions. As for Sinatra, I try using the same approach using erb and < , but the nice integration from poirot on rails has to be done by hand.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "erb, template engine, mustache" }
Поиск элемента в бинарном дереве Например, есть бинарное дерево, глубиной n-этажей. Не сортированное. Первый вариант, что пришел мне в голову, это найти нужный элемент используя рекурсивный вывод функции, т.е.: struct Tree{ Tree * left; Tree * right; int value; }; bool ElemSearch(Tree *root, int search_elem) { if(root->value==search_elem) return true; else if(root->left->value==search_elem) return true; else if(root->right->value==search_elem) return true; else ElemSearch(root->left, search_val); //и так пока не будет найден искомый элемент } В-общем, задача, избавиться от рекурсии. Как это сделать? Если для этого нужно прочитать все дерево в какой-нибудь вектор или массив, подскажите, как это лучше сделать. Спасибо.
Попробую "псевдокод" bool Search (Tree *root, int elem) { Tree *p; if (!root) return false; initqueue(); inqueue(root); while (p = getqueue()) { if (p->value == elem) { delqueue(); return true; } if (p->left) inqueue(p->left); if (p->right) inqueue(p->right); } delqueue(); return false; } Функции inqueue() - положить указатель в конец очереди и getqueue() - взять указатель из головы очереди или вернуть NULL, если очередь пуста, initqueue() и delqueue() IMHO сами напишите. Что непонятно, спрашивайте. На собеседовании можете сказать "типичная задача с очередью или обход дерева в ширину".
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, python, структуры, java, c++" }
DNS Nameserver change I want to change the nameservers for a particular domain. I control the DNS server that is currently set as the nameserver for the domain in question. This server is also listed in the SOA. I want to move the DNS to Amazon Route53, I have created duplicate records for the zone there. My question is, what will happen if I change the nameserver entries (to point to Route53) on the current DNS server? Will the whole internet be updated with the new nameserver values and everybody rejoice in happiness? Or... will nothing happen - i.e. does the nameserver change need to occur at a higher level; i.e. done by the current registrar? Or will something even worse happen? p.s. I am a developer that is playing with forces that are beyond his comprehension, please go easy on me
Changing the name servers needs to be done at the registrar, not at the current name servers.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "domain name system" }
if-else does not work to clear a list or to alert if list is already clear [BEGINNER] I want to clear my list after clicking a button (which I managed to do) and I want to create an IF statement. IF the UL has LI's then clear list. If UL does not have LI's then I want to alert('List is already clear'). The code below doesnt work, I'm not sure what I'm doing wrong. Thank you for you help. const clearBtn = document.querySelector('.clear-btn'); const list = document.querySelector('.list'); clearBtn.addEventListener('click', clearList); function clearList() { if (list.hasChildNodes = true) { list.innerHTML = '' } else { alert('List is already clear'); } }
Did you try in your condition to make a double equal , because it's a logical statement not a arithmetique one. it will be like `if(list.hasChildNodes == true){...}`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, if statement, alert" }
A good Report Design tool/Library I have to produce multiple reports on a regular basis; same reports are produced for the whole customer base. My problem is that designing the layout of the reports is long and tedious job. What I need is a GUI tool for designing the layout of the reports. The output of the tool should be xsl file that will used for creating reports in batch. Additional option is that the toll will provide a library that will allow build a customized batch process for report creation based on GUI layout definitions. Thanks
If you are looking for an open source tool give BIRT (< a try.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "reporting, report designer" }
Have two different libraries with same properties - Swing I want to have two libraries **import java.awt.Font;** and **import com.itextpdf.text.Font;** one for GUI and second one for pdf generator, I get an error as soon as I import the second library. ![\[error\]]( If I comment the first library I get an error, ![\[an error\]]( and if I comment the second library I get an error ![ \[error,\]]( How to resolve this, thanks.
Just forget about imports, and refer to the fully qualified class names instead, like: `java.awt.Font myFont = new java.awt.Font();`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java, user interface" }
Is there an Android equivalent to iOS's "CallKit"? This actually seems like a very Android-like feature. When I heard about it, I thought there might be an Android equivalent. It lets VoIP apps use the standard phone app to call/receive calls, integrating with the phone's contacts and recent calls list. Basically, it turns VoIP calls into regular phone calls (at least for apps that support it). If there is nothing like this on Android, is there any indication that Google will add something like this to a future version?
Android does, but it's not very well documented. The ConnectionService class was introduced in Marshmallow and allows an app to register itself as a voice service, the user needs to manually enable the voice service through the phone settings (same place you would enable/disable SIP accounts). Once this is done you can choose between registered voice services when placing a call using the native dialer, or set one as the default. Incoming calls to your voice service should also trigger the native dialer. Side note, but also interesting, Marshmallow also introduced the ability to register your app as the default dialer too.
stackexchange-android
{ "answer_score": 9, "question_score": 11, "tags": "calls, hardware, voip" }
Lookahead regex pattern in javascript I'm trying to match from the following string: [[NOTE]]This is my note.[[NOTE]] the following pattern: This is my note. As I can't use lookaheads, this is my current attempt: [^\[\[NOTE\]\]](.*)[^\[\[NOTE\]\]] But it still doesn't work.
You need to escape the opening `[` bracket in your regex and also you have to remove the `^` symbol from the character class. \[\[NOTE]]((?:(?!\[\[NOTE]]).)*)\[\[NOTE]] DEMO > var re = /\[\[NOTE]]((?:(?!\[\[NOTE]]).)*)\[\[NOTE]]/g; undefined > var str = '[[NOTE]]This is my note.[[NOTE]]'; undefined > var m; undefined > while ((m = re.exec(str)) != null) { ... console.log(m[1]); ... } This is my note.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, regex" }
How can I specify the color of the line='s' or line=45 line drawn in a qq plot using statsmodels import statsmodels.api as sm sm.qqplot(residuals, line ='s',dist='norm',color='g',fmt='.g') plt.grid() ![qqplot]( I am unable to change the color of the "red line" to a color of my choice by using arguments like `linecolor` and such.
I could not find any answer which could change the color from `sm.qqplot` directly. So I tried by storing the plot in a subplot and then changing the color of the line from there. fig, ax = plt.subplots(1, figsize=(7,4.5)) sm.qqplot(data, line ='45',dist='norm',color='g',fmt='.g', ax=ax) ax.grid() ax.set_title('data_qq',fontsize=15) ax.xaxis.get_label().set_fontsize(12) ax.yaxis.get_label().set_fontsize(12) ax.get_lines()[1].set_color("black") ax.get_lines()[1].set_linewidth("2") ![Expected plot with linecolor changed]( * I am still interested to know if there is a way to do this from within `sm.qqplot` command.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, colors, statsmodels" }
Alternative for fetchAllAssociative()` and execute in doctrine I am calling a stored procedure using native sql via doctrine. `fetchAllAssociative()` and `execute` are deprecated. What are the alternatives? $sql = 'CALL spWithParams(:param)'; $stmt = $this->getEntityManager()->getConnection()->prepare($sql); $stmt->execute([":param"=>"test"]); print_r($stmt->fetchAllAssociative()); I am not planning to map the response to entity using `ResultSetMapping()` as mentioned here as I will add my custom wrapper on it.
The right way of doing this is to use a ResultSetMapping with scalar results to select arbitrary fields. You can then execute the query with `getArrayResult()` to achieve the same behaviour as in the provided code. As an example: $rsm = new ResultSetMapping(); $rsm->addScalarResult('my_database_column', 'myField'); $query = $this->getEntityManager()->createNativeQuery( 'CALL spWithParams(:param)', $rsm ); $query->setParameters([":param"=>"test"]); $results = $query->getArrayResult(); /* [ ['myField' => 'foo'], ['myField' => 'bar'] ] */
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, zend framework, doctrine" }
How to make module (such as bcrypt) available globally in Express? I have several "routes" files where I import modules like this: var bcrypt = require('bcryptjs'); I have attempted to make bcrypt available globally by importing it into my main app js and then using an app.use() something like this: var bcrypt = require('bcryptjs'); app.use(bcrypt); // clearly not right, app crashes I've tried a variety of things here. Should I just stick with importing this into every file separately or is there a good way to make this module available globally?
`app.use` will only work with an Express middleware, which `bcrypt` is not, it's just a regular Node.js module. As was pointed out in the comments, there is not really any reason why you shouldn't just use `require` to make `bcrypt` available in any module that needs it. For what it's worth, you can use the globally available variable global to create a global variable in Node.js. In your example, it would be used like this (but again, this is **NOT RECOMMENDED** ): var bcrypt = require('bcryptjs'); global.bcrypt = bcrypt;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, node.js, express" }
$L^p$ Convergence I need to show that if $\\{u_n\\}\subset L^p(\Omega)$ converges to some $u\in L^p(\Omega)$ and $G\in C^1(\mathbb R)$ with $G(0)=0$ and $|G'(s)|\le M$ then $G(u_n)$ converges to $G(u)$ in $L^p(\Omega)$. I tried it but fails to solve it. Any type of help will be appreciated. Thanks in advance.
By the mean value theorem, $|G(x)-G(y)|\leq M|x-y|$. Then, $$\int_\Omega|G(u_k(x))-G(u(x))|^pdx\leq M^p\int_\Omega|u_k(x)-u(x)|^pdx=M^p\|u_k-u\|_{L^p}^p$$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "functional analysis, sobolev spaces, lp spaces" }
How to properly assign values to lists within lists python? As part of a program to make nice tables to save in txt files, I had some code like this: data=[[1,2,3],[4,5],[6,7,8]] output=[['']*len(data)]*3 rowNum=0 for row in data: for subColNum in range(3): if subColNum >= len(row): output[subColNum][rowNum]='' else: output[subColNum][rowNum]=row[subColNum] rowNum+=1 print(output) I wanted this to output: `[[1,4,6],[2,5,7],[3,'',8]]` but instead got `[[3, '', 8], [3, '', 8], [3, '', 8]]` the problem seems to be with the line: 'output[subColNum][rowNum]=row[subColNum]' which somehow seems to be assigning multiple items at once, as opposed to one per iteration as I expected.
This problem comes up when using the multiplication symbol to give the list a certain length. Your code should work when you create the list at runtime: output = [] for row in date: output.append([]) for ColNum in range(3): output[ColNum].append(valueYouWantHere)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, list" }
Different Screens/Functionality after login There is an app with screens such as `products`, `events`, `news`; all accessible from bottom navigation. However after logging in the bottom navigation changes and a different set of features are provided e.g. `tasks`, `documents`, and `settings`. My question: What will be the best way for a users to access the functionality that was available before login without having to first log out?
Allowing members, registered users, access to different functions than people who didn't sign up is common, but those are functions that are appended to the normal set of functions. Eliminating functions after log in is a definite no-go! I would suggest to add member functions like tasks, documents and settings to the regular set of functions like products, events and news; keeping all of them in the same navigation.
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "mobile, navigation, login" }
Can I wrap the linux shutdown command to make additional checks? So we have a 3rd party process running intermittently which needs to shutdown gracefully. This process has a file present (lets call it /tmp/process1) when running. Is there anyway I can modify the standard linux shutdown process so that if this file is present the shutdown will be aborted (or delayed)? Thanks
Just create a wrapper script named `shutdown`, and make sure it invokes the original `which shutdown` by its full path and that it's in a directory that overrides the directory of the original shutdown in `$PATH` (e.g., in `/usr/local/sbin`; see `echo $PATH`).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "linux" }
Dynamically disabling / enabling the links in a Bootstrap dropdown menu on-click I understand that bootstrap allows a user to disable links within its dropdown menu component simply by adding a `class="disabled"` into the corresponding `<li>` tag. What I'd like to do is write some javascript so that when a user selects the dropdown menu and clicks on a link within it, that link will become disabled. It's in the nature of the dropdown menu to close immediately when a valid link is selected, or when the user clicks outside of the dropdown box. Therefore when the user opens the menu on any subsequent visit, he or she should see all of their previously selected items appearing as disabled. I've already tried to use the solutions posted in this link: disable a hyperlink using jQuery, but none of them are working for me.
Using Nagra's above javascript solution in this modified form: `$('#my_link').click(function(){$(this).addClass('disabled');});` I am able to add the `disabled` class to each of the `<li>` elements whenever a user clicks on the `<a>` embedded within the `<li>` parent. Thank you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, html, css, twitter bootstrap" }
How to add Android and iOS configurations after creating a Flutter project? I created a Flutter project in Android Studio. In the steps, I just selected 'Web' and now I also want Android and iOS in my project, but I don't know how to add those directories.
Open the project in your ide and in terminal enter `flutter create .` note that after create there is a period (full stop) which will create android, ios and web whichever isnt present in the project. Or if you want to add specific platforms use flutter create --platforms=android .
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flutter, android studio, dart, flutter web" }
C# The attempted operation is not supported for the type of object referenced I got this error when I tried to parse an IP address that was in string form. I was using a public dns ip address (4.2.2.2) while testing this (using the System.Net's IPAddress.Parse method). It does the parsing correctly and returns an IPAddress object. However, if I try to access the ScopeId property of this object, a SocketException is thrown with the message given in the title. I really am not able to figure out whats the problem here. When I checked the documentation of IPAddress.ScopeId property, it says an exception is thrown when AddressFamily=InterNetwork which is the case with my example. Could someone please explain the reason for this.
`ScopeID` is an IPv6 specific field. You have an IPv4 address. Therefore, an exception is raised. _InterNetwork_ in this case means IPv4.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "c#, ip address, socketexception, system.net" }
Passing Arugments to NCron Job I have an NCron service that is running on a set interval. I want to pass a variable to the job, but I haven't been able to figure out how. I also didn't see any information in the NCon Wiki. Is it possible to pass any arguments to the NCron service? If your not familiar with NCron or need more information: < service.At(setting.Interval).Run(setting.ClassInfo);
Assuming the value you want to pass to the job is something you have available while registering the jobs with the scheduler (eg command line parameters), you could do something like this: static void ServiceSetup(SchedulingService service) { service.Hourly().Run(() => new MyJob("literal")); service.Daily().Run(() => new MyJob(_field)); } Using sexy lambda syntax, you have just defined two one-line functions each instantiating the same class of job using different constructor parameters. Alternatively, you could let an IoC container instantiate your jobs with whatever constructor arguments and/or services they require. If you have no idea what I am talking about now, you probably want to stick to the first suggestion, though :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, service, scheduled tasks, parameter passing, ncron" }
Question about images of R under injective homomorphisms. I'm studying for my topology comp and I'm at a bit of a loss on this question. (My experience with Algebra is very limited and my experience with topological groups in particular is almost non-existent.) Let $G$ be a topological group and $f: R \to G$ be an injective homomorphism of topological groups. (i.e. a continuous injective homomorphism). Is it true that $f(R) < G$ is necessarily a closed subgroup? If you could provide a prod in the right direction I'd be quite grateful! Thank you.
It is not true that $f(R)$ is necessarily closed under the induced topology. The classic counterexample here is that of "shredding the torus". In particular, we take $G = S^1 \times S^1$ (where $S^1$ denotes the unit circle in $\Bbb C$ under multiplication), and take $R = \Bbb R$. For some $a \in \Bbb R \setminus \Bbb Q$, define $f$ by $$ f(t) = (e^{it},e^{ait}) $$ Show that $f$ is not surjective, but $\overline{f(R)} = G$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "topological groups" }
Convex Polyhedron: How many corners maximum? How many corners can a $n$-dimensinal convex polyhedron have at tops? Is it the same as the number of corners a $n$-dimensional simplex has? EDIT: By polyhedron $P$, I mean, that for some matrix $A \in \mathbb{R}^{m,n}$, $P = \\{ x\in \mathbb{R}^n \mid A x \leq b\\}$ where $Ax \leq b$ is meant as $a_i^T x \leq b$. An alternative charakterization would be $P = \cap_{H \text{ is hyperplane}} H_{+}$, where $H_{+}$ is the half-room $\\{x \in \mathbb{R}^n \mid \langle x, u \rangle \geq b\\}$. ADDED convex
A vertex of the polyhedron $P = \\{x \in {\mathbb R}^n: Ax \le b\\}$ is defined by the solution of $n$ of the equations $(A x)_i = b_i$ corresponding to linearly independent rows of $A$. In general, not all of those will be vertices, because they may violate other constraints. But the number of vertices is at most $m \choose n$. EDIT: P. McMullen improved the upper bound to $${{m - \lfloor (n+1)/2 \rfloor} \choose {m-n}} + {{m - \lfloor (n+2)/2 \rfloor} \choose {m-n}}$$ which turns out to be best possible. See P. McMullen, "The maximum number of faces of a convex polytope", Mathematika 17 (1970), pp. 179–184, and D. Gale, "Neighborly and cyclic polytopes", in Proc. Sympos. Pure Math., Vol. VII, Amer. Math. Soc., Providence, R.I., 1963, pp. 225–232,
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "combinatorics, geometry, polytopes" }
How does the sharpness of telephoto primes compare to telephoto zoom? **Context** I've looked at longer primes from Nikon 200mm/2, 400mm/2.8, etc but I've also seen Telezooms such as the Sigma 150-500 and Tamron 150-600. I know that primes are usually sharper than their zoom counterparts and in many cases more expensive. I've used my 24mm/1.8 over my 16-50 kit zoom and in these focal lengths it is usually not hard to walk backwards or forward to compose the shot. **Question** Are telezooms worth their price in terms of sharpness given their inability to zoom in the telephoto range? (I don't know if it's possible to walk back or forward shooting at this range.) Related do people usually use primes more so than zooms when they are shooting birds or other animals far away? I'm guessing people prefer zooms?
I really think this depends on what your are using it for. Generally, most people would get the prime because they have better aptures than their zoom counterparts. Also, for things like birding, most people usually just get a 600mm prime or something along the lines. The reason to not get the zoom is that they can usually just crop the photo if they didn't get close enough. so generally, most people do prefer zooms because of how convenient they are, but in the ranges of 400-800, i assume most people opt for the primes due to their better performance.
stackexchange-photo
{ "answer_score": 0, "question_score": 2, "tags": "lens, sharpness, telephoto, prime" }
Can't run Android Demo - No Resource Identifier Found I am trying to run the AnimationsDemo from the android developers website: < But I can't manage to compile it. I keep getting an error with the R.java file as it is not being generated. Hence, in all the Activity classes I get an error saying "R cannot be resolved into a variable). I also have errors in the manifest file saying: > "error: No resource identifier found for attribute 'parentActivityName' in package 'android'" It seems like it cannot find the any of the activity classes found in R.Layout. I did NOT import the "android.R" file so I know that's not the issue. I haven't really touched the code, so I can't figure out why it's complaining.
> error: No resource identifier found for attribute 'parentActivityName' in package 'android' This usually means that your build target (e.g., Project > Properties > Android in Eclipse) is set too low. Try raising it to a higher API level -- 14 or higher should work. You may need to download additional API levels through the SDK Manager depending upon what you have installed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "android" }
Illegal assignment: Cannot assign an unpacked type to a packed type In SystemVerilog I wrote: module mult32x32_arith ( input logic clk, // Clock input logic reset, // Reset output logic [63:0] product // Miltiplication product ); logic left_decoder, right_decoder, product_FF[63:0]={64{1'b0}}; always_ff @(posedge clk, posedge reset) begin if (reset==1'b1)begin product <= product_FF; end else begin end end But, I'm getting errors on this line: product <= product_FF; It says: > Error: mult32x32_arith.sv(19): Illegal assignment to type 'reg[63:0]' from type 'reg $[63:0]': Cannot assign an unpacked type to a packed type. But, I don't understand what the problem is.
You declared `product` as packed and `product_FF` as unpacked. Refer to IEEE Std 1800-2017, section 7.4 _Packed and unpacked arrays_ : > The term _packed array_ is used to refer to the dimensions declared before the data identifier name. The term _unpacked array_ is used to refer to the dimensions declared after the data identifier name You need to declare them as the same data type. For example, to make them both packed, change: logic left_decoder, right_decoder, product_FF[63:0]={64{1'b0}}; to: logic left_decoder, right_decoder; logic [63:0] product_FF = {64{1'b0}};
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "verilog, system verilog, modelsim" }
Как получить подряд идущие цифры в списке Есть список с цифрами. Если есть 2 и более подряд идущие цифры, то нужно из них оставить одну, при этом увеличив ее на число убранных. Т.е. есть `[1, 2, 2, 5, 8, 8, 8]`. Из него должно получится `[1, 3, 5, 10]`. Возможно ли реализовать такое?
Можно используя соответствующую функцию. from itertools import groupby a = [1, 2, 2, 5, 8, 8, 8, 7, 7, 1, 1, 1] result = [k + len(list(g))-1 for k,g in groupby(a)] print('>>>', result) >>> [1, 3, 5, 10, 8, 3] Если список считать закольцованным, то результат можно скорректировать: if len(result) > 1 and a[0] == a[-1]: result[0] += result.pop() - a[0] + 1 >>> [4, 3, 5, 10, 8] * * * Вариант через генератор. a = [1, 2, 2, 5, 8, 8, 8] def get_compressed(lst): if lst: si = 0 for i, el in enumerate(lst): if el != lst[si]: yield lst[si] + i-si-1 si = i yield lst[si] + i-si result = list(get_compressed(a)) print('>>>', result) >>> [1, 3, 5, 10]
stackexchange-ru_stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "python" }
What is the proper form of "In the beginning" for this sentence? Okay, so I fixed my first problem. Now, I have to find the proper form of "in the beginning." Should it be (hajime ni, sunaodatta,) or (hajime wa, sunaodatta?)
In your sentence ("at first", "in the beginning") is correct. This is contrastive, and can be used with another subject marked with (e.g., ). means "first (of all)", "at the beginning (of a month, etc)", "Introduction/Preface (chapter title)" and so on.
stackexchange-japanese
{ "answer_score": 3, "question_score": 1, "tags": "syntax, transcription" }
What is the purpose of a switch routed port? From my Cisco CCNA documentation: > Routed ports are used for point-to-point links. Connecting WAN routers and security devices are examples of the use of routed ports. In a switched network, routed ports are mostly configured between switches in the core and distribution layer. The figure illustrates an example of routed ports in a campus switched network. ![enter image description here]( I don't understand what are the benefit of having a routed port between the distribution and access, and more generally, the purpose of routed ports except for inter-VLAN routing like with the router-on-a-stick method (and even there, it seems that SVI are a better approach).
Routed Interface means it is a Layer3 physical Ports which is not supported to Layer 2 communications such as STP. > All Ethernet ports are routed interfaces by default.(in router) You can change this default behavior with the CLI setup script or through the `system default switchport` command. Routed ports are supported to all routing protocols. But don't misunderstand, SVI and routed interface. SVI is a virtual or logical interface which assigned to one VLAN. But Routed port is a Physical interface. IP address assigning, enable routing and layer 3 functions can be done on Routed Interface. Reference cisco
stackexchange-networkengineering
{ "answer_score": 4, "question_score": 2, "tags": "cisco, router, interface" }
Obter valor da div Quero obter o valor da `div` quando clico. O problema é que cria uma `div` no `foreach`. Quero obter o `id`, para depois passar essa valor para outra página e utilizar para fazer um SELECT na base de dados SQLite. $array_resultadoss = array(); //array $array_resultadoss=select($dir, $base, $i); $titless = ""; //variable inicialize foreach($array_resultadoss as $key =>$value){ $titless .= "<div class=dois>".$value['id']."</div>";//save in variable value } echo" <td class='td_today'> <div class=divday style='cursor:pointer' onclick='popup(\"_popup_cal.php?jour=$i&moisEcris=$months[$moisaff]&annee=$year&mois=$month&txttitle=$txttitle&txtstart=$txtstart&txtend=$txtend&txtdescription=$txtdescription&maj=$maj&clean=1&numevent=$numevent\",400,300)';> ".$titless."</div> </td>"; }
Em primeiro lugar, aconselho que você refatore o seu código, a lógica não está legal. Mas mantendo o que você já fez, acredito que a forma de conseguir o que você espera é gerando a função `popup()` do Javascript para cada `<div>`. Fiz os ajustes no código e ficou assim: $array_resultadoss = array(); $array_resultadoss = select($dir, $base, $i); $titless = ''; foreach ($array_resultadoss as $key => $value) { $titless .= "<div class=dois onclick='popup(\"_popup_cal.php?jour=$i&moisEcris=$months[$moisaff]&annee=$year&mois=$month&txttitle=$txttitle&txtstart=$txtstart&txtend=$txtend&txtdescription=$txtdescription&maj=$maj&clean=1&numevent=$numevent&num_div={$value['id']}\",400,300)';>" . $value['id'] . '</div>'; } echo "<td class='td_today'> <div class=divday style='cursor:pointer'> " . $titless . " </div> </td>"; Então em `_popup_cal.php` você terá `$_GET['num_div']`
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php" }
How to avoid axis inversion by DataRange when used in Arrayplot? Working on Mathematica 11.3, I find that the vertical axis (more precisely its ticks) is reversed by `DataRange` which should not happen, e.g. nmax = 100; ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic] ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic, DataRange -> {{0, nmax}, {0, nmax}}] Resulting in ![ArrayPlot w/o manual DataRange]( ![ArrayPlot w/ manual DataRange]( I want a plot like in the first picture but with arbitrarily chosen `DataRange` and do not want to have the data reversed along the vertical direction (as in `ListDensityPlot`). Both axes should start at the top left corner. I found a workaround using manual setting of frame ticks but that is not nice. Is their a simple solution?
This is a non-intuitive, but expected behavior. It just comes down to how do you interpret `DataRange`. See the additional option `DataReversed` ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic, DataRange -> {{0, nmax}, {0, nmax}}, DataReversed -> True] ArrayPlot[Reverse@Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic, DataRange -> {{0, nmax}, {0, nmax}}, DataReversed -> True] ![enter image description here]( ![enter image description here]( The underling reason is, that usually matrix indexes start from top left, while plot coordinates from left bottom. The function named `ArrayPlot` has to bring these two worlds together.
stackexchange-mathematica
{ "answer_score": 5, "question_score": 5, "tags": "plotting" }
EADDRINUSE in webpack on port 8080 The command `webpack-dev-server --hot` is raising the EADDRINUSE for port 8080. How can I change the ports used by webpack?
The `webpack-dev-server` CLI supports a `--port` option. Example: webpack-dev-server --hot --port=8081
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, webpack" }
How do I test for multidimensional arrays? I am trying to test for an exists of a multidimensional array within my vbscript function, but I am having issues finding the best solution for this. In my function I'm either excepting a string value or an array of values, the array can either be a single dim or multidimensional. The problem I'm having is trying to test whether the array is single or multi dim. Is there a predefined way of doing this? Any help would be great.
No, there is no predefined way; that is: there is no build in function that will return you the amount of dimensions. However, you can build you own. ' Returns the amount of dimensions of an array. ' Returns 0 when it is no array Function GetDimensions(arr) Dim dimension, upperBound On error resume next For dimension = 1 to 255 upperBound = ubound(arr, dimension) If err.Number <> 0 Then Exit for Next On error goto 0 GetDimensions = dimension-1 End Function Dim myArray(41, 42, 43) MsgBox GetDimensions(myArray) ' Will return 3.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "arrays, testing, vbscript, multidimensional array" }
iOS device - data update What is the most relevant and best way to update data on an iOS device from a - CSV file on a remote server that receives values every second? The file receives data every second and this data is to be updated. Currently im using an NSURLRequest and NSURLConnection to read the file for every 10seconds. Instead is there any other way I can update the device on the new data? like webservices?
either your current approach and web services are pulling data from the source on repeatable manner, which is fine if it's not a time-critical solution. however, if you need a "push" feature, which means clients get called immediately after new data is available, you may consider using socket programming. You may want to check out the wonderful framework CocoaAsyncSocket on github
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ios, csv, nsurlconnection" }
Why is B always not 0 I discovered that while applying Ampere's law, For a solenoid.. B inside is calculated. But outside we say the loop encloses no net current or hence there should not be any field.. Let's say for example a conducting wire carrying current i we have, B=Something But we can always have a current with opposite direction at infinity and hence an amperian loop of infinite radius and thus B to be a zero
Ampère's law does not say that the field is zero if there is no enclosed current. It says that if you integrate $B.d\ell$ round a loop then the result will be zero if there is no enclosed current. For example consider this loop in a constant magnetic field $B$: !Ampere Even though the magnetic field is non-zero, for every $d\ell$ in the loop there is a matching $d\ell$ pointing in the other direction and the two values of $B.d\ell$ will cancel out. This means the integral round the lop is zero even though $B$ is non-zero. As Rijul says, Ampère's law only applies in some circumstances i.e. when the current density is not changing with time. However it does apply in this case.
stackexchange-physics
{ "answer_score": 2, "question_score": -2, "tags": "magnetic fields" }
Download css, js , images of website as mentioned in view page source I downloaded source code of this page using below command : wget -E -H -k -K -p **Issue** : but it downloaded all css, js, imags in one file.... **Requirement** : but i need to download all the css, js files separately as mentioned in view page source **Note** : using above link for learning purpose, not for commercial use
You need to use mirror option. Try the following: `wget -mkEpnp -e robots=off It should create a recursive offline copy, updating urls, adding extensions to extensionless urls etc.
stackexchange-superuser
{ "answer_score": 6, "question_score": 2, "tags": "wget, css" }
Changing gnome-terminal color theme depending on running app Is it possible to change color theme (or whole gnome-terminal profile) of terminal if for example Midnight Commander is started inside gnome-terminal? My aim is not to launch a new terminal window but to change color theme depending on launched app.
You can write a shell function to use `setterm` (or the equivalent on your OS) to change the colors before the program is invoked, but there is no way to change the gnome-terminal profile from the command line (the title _can_ be changed though).
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "terminal, gnome terminal" }
Html5 data-popup with .NET MVC 4 Razor EditorFor extension? I want like to create a input box with a data-popup attribute like this: `<input type="text" name="title" data-popup="test">` I tried to use `@Html.EditorFor(model => model.Name , new { data_popup = "Hashtag" })` but the data-popup attribute is not rendered. Is it possbile to add a attribute like data-popup for an editorfor?
I believe if you use `TextBoxFor` instead in the same way, you will get the results you desire. The reason being is EditorFor doesn't have a parameter for htmlAttributes, the parameter you are passing is the `additionalViewData` parameter, and therefore will not be rendered as html attributes..
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "asp.net mvc, editorfor" }
Convert single quote to separators in the url_title function in CodeIgniter In CodeIgniter, the _url_title_ function takes a "title" string as input and creates a human-friendly URL string with a "separator" (dash or underscore). Currently, the function remove single quote. In french, the single quote (apostrophe) is a word separator. For example : The expected slug for " **L'apostrophe** " is " **l-apostrophe** ", and not " **lapostrophe** " as it is currently the output of the _url_title_ function. I would like to update the following source code ( _/system/helpers/url_helper.php_ \- line 493): $trans = array( '&.+?;' => '', '[^\w\d _-]' => '', '\s+' => $separator, '('.$q_separator.')+' => $separator ); Since but I'm not familiar with RegEx, it would be nice if someone could help me to add single quote in the array `$trans` in order to convert single quotes into separators.
Modifying the CodeIgniter core is always a problem to ensure upgrade and compatibility with future versions. I would better suggest to update the array of foreign characters for transliteration | conversion used by the Text helper (in _/application/config/foreign_chars.php_ ). Add the following line at the end of the array: '/\'/' => ' ' This will convert single quotes (`'/\'/'`) to spaces (`' '`) when calling the `convert_accented_characters` function.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, codeigniter 3, slug, slugify" }
Why does "WHERE text != "something" also exclude all rows with NULL values? _Sorry, this is probably a really frequent question, but I really don't know how to phrase a google search that finds it._ **SELECT * FROM table where textfield != "Word";** 1. This ignores all rows where the textfield has the string "Word" \- but it also ignores all rows where textfield is NULL. Why? 2. What is the correct way of selecting ALL rows (even NULLS), except rows with a specific string in a text field?
Almost all comparisons with `NULL` return `NULL` (the most common excepts are `IS NULL` and `IS NOT NULL`). And in `WHERE` clauses, `NULL` is treated the same as "false" \-- that is, the rows are filtered. MySQL offers a `NULL`-safe comparison operator. You can use: where not textfield <=> 'Word' `<=>` returns `true` or `false` \-- never `NULL` \-- so it does what you expect. Let me add: The SQL Standard has a `NULL`-safe operator. So, in Standard SQL, this would be: where textfield is distinct from 'Word' However, not many databases support the standard syntax -- yet.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, sql" }
VSIX - How to include XML documentation files in package? I've found the following article that nicely describes how PDB files of project references can be included in the VSIX package: < Now I would like to do the same, but for documentation XML files that are generated by project references. I see that the XML files are already copied to the output directory of the VSIX project, but how can I make sure that they are added to the .VSIX file as well?
Answering my own question: Apparently there is also a "DocumentationProjectOutputGroup" output group. This output group can then be added to all project references in the following way: <PropertyGroup> <DefaultIncludeOutputGroupsInVSIX> BuiltProjectOutputGroup; DebugSymbolsProjectOutputGroup; GetCopyToOutputDirectoryItems; SatelliteDllsProjectOutputGroup; BuiltProjectOutputGroupDependencies; DocumentationProjectOutputGroup; SatelliteDllsProjectOutputGroupDependencies </DefaultIncludeOutputGroupsInVSIX> </PropertyGroup> <ItemDefinitionGroup> <ProjectReference> <IncludeOutputGroupsInVSIX>$(DefaultIncludeOutputGroupsInVSIX)</IncludeOutputGroupsInVSIX> </ProjectReference> </ItemDefinitionGroup>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio extensions, vsix, vsixmanifest" }
AWS Active Directory: Cannot access from another VPC I've setup an Active Directory service in AWS in 2 private subnets in a VPC. I have another VPC in the same account that I want to be able to access the AD from. However for some reason it just isn't accessible from anywhere outside it's own VPC. I've setup peering between the VPC's, and confirmed that EC2 instances in the VPC's can communicate. Is there something particular to Active Directory that prevents it from being reached from outside it's own VPC? I can't see any other configuration I can make to fix this. I've confirmed the routing tables, ACL's etc. are all correct. Any help would be greatly appreciated.
I found the issue. It was quite non-intuitive. When the Active Directory is created, AWS automatically creates an associated security group. The SG was called "d-9462#####_controllers" and had the description "AWS created security group for d-9462##### directory controllers". (d-9462##### being the ID for the directory) What makes it counter-intuitive is that this SG is not displayed anywhere (as far as I can tell) within the Directory Services console. You would have to know that it existed, and know to search for it within the VPC security groups. By default this SG grants access only to the VPC in which the Directory resides. To fix the issue you need to explicitly grant access to whatever other VPC's you need.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "amazon vpc, aws directory service, vpc peering" }
Accessing Table with synonym instead of table name with Spring JPA I have used Spring JPA in my project. Following is my POJO class: @Table (name="CustomerSys") class Customer implements Serializable { /* Fields defined here */ } In my database, there is a table exists with name Customer but to access that table we have created a synonym with name CustomerSys. Now when i execute my code it throwing an error says: > Caused by: java.sql.SQLException: ORA-00942: table or view does not exist Can you please help me to know what I am missing here?
In my application I have used two difference data sources. I debugg the the application and found that the incorrect data sources mapped due to this table or view does't exits appears. So, 1\. I correct the mapping first, then a error msg appears with name incorrect protocol found. 2\. Then I used ojdbc6 instead of ojdbc14. This made my application working.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "hibernate, jpa, spring data jpa" }
Leading behavior of an integral I need your kind help in the computation of the small-$q$ expansion of the following definite integral $\displaystyle\int_0^\infty\frac{dp}{p \left(p^2+q^2\right) \Big[(a/p)^{\eta }+1\Big]^{1/2} \Big[a^\eta/(p^2+q^2)^{\eta/2}+1\Big]^{1/2}}$, where $2>\eta>0$, $a>0$, and $q\ll a$. I can show that for $\eta=2$ the integral behaves as $\displaystyle \frac{2}{a^2}\log\left(\frac{a}{q}\right)$. However, I am not able to find its small-$q$ asymptote for other values of $\eta$.
The main contribution to the integral comes from the vicinity of $p=0$. To get the leading term, it's sufficient to replace the integrand with a simpler one that has the same behavior for small $p$ and small $q$: $$\int_0^\infty \frac 1 {p \left( p^2+q^2 \right)} \left( \left( a/p \right) ^ \eta + 1 \right) ^ {-1/2} \left( a ^ \eta / \left( p^2+q^2 \right) ^ {\eta/2} + 1 \right) ^ {-1/2} dp \sim\\\ \int_0^\infty \frac 1 {p \left( p^2+q^2 \right)} \left( \left( a/p \right) ^ \eta \right) ^ {-1/2} \left( a ^ \eta / \left( p^2+q^2 \right) ^ {\eta/2} \right) ^ {-1/2} dp =\\\ \frac {\Gamma \left( \frac \eta 4 \right) \Gamma \left( \frac 1 2 - \frac \eta 4 \right)} {2 ^ {\eta/2 + 1} \sqrt \pi a ^ \eta q ^ {2 - \eta}}.$$ The leading term for $\eta=2$ can be obtained in the same manner; it'll be $-\ln(q)/a^2$ (you have an extra factor of 2 in your result).
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "definite integrals, asymptotics" }
SOQL query for displaying leadsouce type count by month I'm trying to get the a query setup so it delivers the date for each lead in a format of just the month. Right the filter I have is working fine, but the CreatedDate format returns this rediculous format that I can't get to work in third part apps. Here's the Query: SELECT CALENDAR_MONTH(CreatedDate),LeadSource FROM Lead WHERE LeadSource AND CreatedDate = THIS_YEAR It should look in the Lead Object and find the month of the created date and the lead source and filter them by leadsource and this years created dates. Or at least that's what I want. I get an error in the Salesforce Workbence and I have no idea why. Any help would be great.
If you want to count them as the title of your question suggests you would need an aggregate query of this form: for (AggregateResult ar : SELECT CALENDAR_MONTH(CreatedDate) m, LeadSource s, COUNT(Id) c FROM Lead WHERE LeadSource != null AND CreatedDate = THIS_YEAR GROUP BY CALENDAR_MONTH(CreatedDate), LeadSource ORDER BY CALENDAR_MONTH(CreatedDate), LeadSource ) { Integer m = (Integer) ar.get('m'); String s = (String) ar.get('s'); Integer c = (Integer) ar.get('c'); ... } If you are trying to list them all, then the simplest solution might be to add a custom formula field to Lead that holds the [MONTH value of the CreatedDate and return that in your query. (Because CALENDAR_MONTH seems to behave like an aggregate function and requires GROUP BY to be used if it is included in the SELECT list.)
stackexchange-salesforce
{ "answer_score": 0, "question_score": 1, "tags": "soql" }
Ball flying towards me or me flying towards ball Suppose a ball is flying towards me at a speed of 10m/s and that, on impact, I feel "x" amount of pain. If, instead, it was me flying towards the ball at the same speed, with all other conditions being the same, would I feel the same amount of pain?
Look at it this way: Suppose you are in a train travelling at 10 m/s. Somebody inside the train throws a ball at you in the opposite direction at 10 m/s. You feel the pain belonging to your first experiment. However, somebody looking at this experiment from outside the train would say that the ball is standing still and you are travelling towards the ball at 10 m/s (= your second experiment). Since it is the same experiment, you will feel exactly the same pain.
stackexchange-physics
{ "answer_score": 34, "question_score": 10, "tags": "homework and exercises, newtonian mechanics, forces, momentum, collision" }
How to pass parameter to dataSet in IReport? When I try to create a table in my report, it asks me to create a dataset. In the dataset, I type my query that have parameter ID: select * from DepositTable where id = P{ID} When I try to continue, I get this error message > General problem: Parameter "ID" does not exist. > Check username and password; is the DBMS active ?! How to fix that?
I have resolved this problem by adding the paramters itself to the dataset by right click on dataset and add paramaters
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "jasper reports" }
add css to google maps v3 polylines? is there any way to customise google maps v3 polylines I think the only options mentioned are strokecolor, weight and opacity <
As far as I know, the only options to style Google's polyline are the ones presented in the documentation. There is no way to customize them further by default. However, what might work is creating a custom polyline class where you can define everything you want, but this is connected to a lot of work. You would have to start by inheriting the `OverlayView` class and implement all the needed features (Maybe it does also work if you inherit `Polyline` and overwrite just the drawing methods - the problem is, you don't really know how the original source code looks like). In fact, for Google Maps V2, Bill Chadwick did this. You can see a demonstration on his website (the dashed polyline example at the bottom). Maybe his implementation helps you to transfer it to Google Maps API V3.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "javascript, css, google maps api 3" }
Что такое "расплох"? Застигнуть врасплох - значит неожиданно застать человека, когда он того не ожидает. А что такое, вообще, "расплох", в котором его застигают? Спасибо
Наречие "врасплох" связано с диалектным словом полОх - испуг, также: полОх - тревога, набат, полОхало - чучело на огороде, полОхать, полОшить - мутить, волновать, тревожить. Родственные слова: всполошить, переполох. В словах "врасплох и переполох" приставки РАЗ и ПЕРЕ имеют значение высокой степени проявления признака, сравнить: раскрасавица.
stackexchange-rus
{ "answer_score": 2, "question_score": 1, "tags": "этимология" }
Something is wrong with my cockatiel - she is missing feathers I have two cockatiels and four budgies. Since I got my second cockatiel, I noticed that she doesn't have feathers under her crest. I thought that the reason for it is that she is really submissive and lets herself to be pecked all the time. This was far from true, because now she got worse (see picture). She is 4 years old. Please help me, I need some group knowledge about this topic, because I have never even encountered such issue with my parrots so far, so I really don't know what to do next. ![enter image description here]( The bald spot is reddened by her blood - others pecked the feathers out. But I noticed black base of quill (maybe blood in it?).
There seem to be basically 2 possibilities: 1. Another bird pecks her and plucks her feathers 2. She scratches or plucks herself, which can indicate anything from stress or boredom to malnutrition or parasites. The first thing to do is getting the bird examined by a vet to rule out any skin condition, malnutrition, allergy, fungal infection or parasites. Then you need to observe what or who caused the wound. If she plucks herself and the behavior started before you adopted her, she might have been very stressed by her former living conditions. Since it's gotten worse since you adopted her, the change in her environment could have intensified her plucking. Since self-plucking is unfortunately quite common in birds, you can find many resources online, like this video, this article on PetMD or this article on petco and many more. If another birds plucks her, you'll need to separate them for a while. But this honestly sounds and looks a lot like self-plucking.
stackexchange-pets
{ "answer_score": 3, "question_score": 1, "tags": "health, cockatiels" }
Find time zone from IP address Is there a way to find the time zone a user is in when all I have is their IP address? I'm looking for the time offset I need to apply to the server time in order to find the time for the user's location.
You'll need to attempt to determine the location (which is far from 100% accurate). See this question about doing just that. See this question about translating a zip code into time zone (though that, again, is not 100% fool proof). The short version is: it's complicated. You'll have to use a third-party service that maintains a database of IP masks to locations, then use the location determined there to determine the time zone. It's far more reliable to have the client simply send the time zone (or UTC offset) when it connects. If this is a web application, see one more question about using JavaScript to determine the client time zone.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "c#, .net, timezone, ip address" }
Function/macro to execute function body only when arguments changed from last call This should work similar to `memoize`, but very differently. While memoize should be used with pure functions, it is often useful to speed up IO related functions. The function/macro I'm looking for should behave like higher order function. The function it produces should: * when called for 1st time, it should call the original function, passing arguments to it * remember: arguments, return value * when called 2nd time * with the same arguments: it should return memoized return value * with different arguments: forget last arguments and return value, call the original function, remember current arguments and return value * when called nth time, always compare the arguments to the last call, and behave like described above.
It would be easy enough to modify the source of `memoize` to do this. (defn memo-one [f] (let [mem (atom {})] (fn [& args] (if-let [e (find @mem args)] (val e) (let [ret (apply f args)] (reset! mem {args ret}) ret))))) (defn foo [x] (println "called foo") x) (def memo-foo (memo-one foo)) However, there is already a flexible memoization library available that can do this. (require '[clojure.core.memoize :as memo]) (defn foo [x] (println "called foo") x) (def memo-foo (memo/lru foo :lru/threshold 1)) * * * (memo-foo 1) ; called foo ; 1 (memo-foo 1) ; 1 (memo-foo 2) ; called foo ; 2 (memo-foo 1) ; called foo ; 1
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "macros, clojure, functional programming, clojurescript" }
MFC Mouse motion OnMouseMove event nFlags value if no buttons clicked? I'm working on a project translating old Windows 95 MFC code to C++11. I was wondering, if no mouse buttons are clicked during a move, what is the value of the UINT nFlags passed into the OnMouseMove() function? I'm not very familiar with MFC and I don't have access to a Windows machine to do any tests myself, so my understanding about this functions behavior may be incorrect. I know that if it's left clicked, middle or right there are special system values that the OnMouseMove function will receive in the nFlags (like MK_LBUTTON, which is 0x0001). I was wondering what the value for nFlags will be if nothing in particular has been clicked and the mouse has move, is it just 0x0000? Thank you very much, any help with this matter is greatly appreciated!
Yes, it's 0. But I think it would be safest to test for the documented possible values so if its usage is changed in the future, the "0 assuming" code doesn't break. According to MSDN for VS2012, these are the possible values: MK_CONTROL Set if the CTRL key is down. MK_LBUTTON Set if the left mouse button is down. MK_MBUTTON Set if the middle mouse button is down. MK_RBUTTON Set if the right mouse button is down. MK_SHIFT Set if the SHIFT key is down. where they are currently defined (in Winuser.h) as: #define MK_LBUTTON 0x0001 #define MK_RBUTTON 0x0002 #define MK_SHIFT 0x0004 #define MK_CONTROL 0x0008 #define MK_MBUTTON 0x0010
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c++, c++11, mfc, onmousemove" }
Create a new folder in Drive using Google App Script Is there a way to create a google app script to create a new folder in Google Drive that is NOT IN THE ROOT FOLDER? A script to move a folder in the root to a particular folder will also do.
var parentFolder = DriveApp.getFolderById(parentFolderId); var newFolder = parentFolder.createFolder("My New Folder Name");
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 6, "tags": "google apps script, google drive api" }
what is the different between identifier id and class? id is the type of the object; the type could have been `NSArray` * or `NSString` *, for example. Class can either be `NSArray` * or `NSString` * or other object. I can use them like follow - (void)wantWriteAction:(id)sender { } - (void)wantWriteAction:(Class)sender { } I want to know the different between them.In what conditions can't use id?what condition can't use Class?
`id` represents an instance of any class. `Class` represents any class-- not an instance, but the class itself. So `id` could be a specific instance of `NSString` or `NSArray`. You can call instance methods on it-- those which are shown with a `-` in the documentation, like `-length` or `-stringByAppendingFormat`. If the `id` is an `NSString` then its value might be `@"foo"`. `Class` could be the `NSString` class or the `NSArray` class. You can call class methods on it-- those which are shown with a `+` in the documentation, like `+stringWithFormat`. If the `Class` is `NSString` (note, not **an** `NSString`, but **the** `NSString` class) then it has no string value, because it's not a string. It's a class.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "ios, objective c" }
SMART values HIGH and growing, but indicator green? After drive started to freeze up, i them plugged another drive with ubuntu to see SMART data using disk utility. Now i read that "Disk is healthy". Now i'm not familiar with SMART parameters, but looking at them, there are some insane high numbers and each time i press refresh, they grow. These 3 parameters are high as seen in picture (its really ubuntu, just with mac theme): * Read error rate * Seek error rate * Hardware ECC recovered Should i conclude that the drive has failed? Or may there be problem in controller or cable, motherbord? This is an PATA drive. Also when testing for bad blocks, the test stops ~80%, but it doesn't indicate that any bad block is found. Umm, i checked the ubuntu-drive (which performs good), and those same numbers are high (and growing) for that drive also, but it is connected to SATA controller.
The tests are done by the drive on the drive so your interface to the PC is irrelevant. These are recoverable errors probably due to overheating by the looks of it. The normalized (current rating) and worst go from 100 good to 0 bad. For those 3 items the value will always go up but it is the rate that is important. You can see that these are currently higher than the worst (which means it is better now than it was). The thresholds are set by the manufacturer so are a reliable indication of whether it is a problem or not, as you can see these are good. I think if you try to improve your cooling around the drive you will see your normalized go up, your values climb less rapidly and performance should improve.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "hard drive, smart" }
What's the point on increasing the Int or Ma stat if the MC can't use magic? Unlike Nemissa, the protagonist can’t use magic of any kind. What’s the point in increasing any of these stats then? Does any of these help magic defense, summoning time or something along those lines?
**Intelligence** The Intelligence stat causes your magic to hit enemies more often and also means you'll be taking less damage from magical attacks aimed at you. **Magic** This stat causes your Magical attacks to become stronger, but, unlike Intelligence above, Magic does not affect your Magical Defense. in soul-hackers
stackexchange-gaming
{ "answer_score": 1, "question_score": 3, "tags": "soul hackers" }
using print with a comma in python 3 Using python 3 `print()`, does not list the repeated data one after the other on the same line? Let's say you want a message to display on the same line and repeatedly. example. my_message = 'Hello' for i in range(100) : print(my_message), it IS CURRENTLY printing one below the other.(not what I want) hello hello hello..... but I read in the python book that adding a comma , after print(), should create the desired effect and would make it display side by side hello hello hello hello..(x100) why doesn't it do that in Python 3? How do you fix it?
This does not work in Python 3 because in Python 3, `print` is a function. To get the desired affect, use: myMessage = "Hello" for i in range(100): print(myMessage, end=" ") or more concisely: print(" ".join("Hello" for _ in range(100)))
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "python" }
Zend Framework SQL Injection protection I'm looking at some Zend Framework code a developer I'm working with is using, and in it I see the following: $select = new Zend_Db_Select($DB); $sql = $select->where("id ='".$id."'"); Now, $id is not sanitized anywhere, and I was under the impression that you're only protected from injection via Zend if you use placeholders -- this string is vulnerable, I thought. The author of the code claims zend takes care of it even in this case, although I can't find in the documentation where it says so. Can anyone clear up if this is, in fact, safe?
You are correct. The other developer is mistaken. If you look at the documentation here you can find comments towards the bottom of the page that discuss example #20 as being subject to SQL injection if the parameters were coming from user input. Example #20 is more-or-less doing the same thing as the code you pasted. (Although, your code has single quotes, but this of course doesn't make it any safer.) I have no idea why anyone would disregard the placeholders in favor of this unsafe and less clean way of writing it.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "sql, zend framework" }
SQL - Filter by a relationship I have 3 DB table: users: id, name posts: id, user_id, content post_likes: id, user_id, post_id I want to fetch my whole user's likes, except likes that I did on my posts. In other words: Fetch all of my likes to other people's posts. How can I filter by a relationship's column `posts.user_id` when I'm actually fetching `post_likes`?
Try this one SELECT * FROM post_likes pl LEFT JOIN posts p ON pl.post_id=p.id WHERE pl.user_id = 3 AND p.user_id != 3
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql, join, relationship" }
ActiveRecord execute raw transaction typecasting? `ActiveRecord::Base.connection.execute(sql)` The results are not typecasted so they are all strings as an example `ActiveRecord::Base.connection.execute(sql).entries` `=> [{"id" => "1", "length" => "120", "content" => "something"},{"id" => "2", "length" => "200", "content" => "blahblah"}]` Is it possible to execute raw transactions in activerecord and return typecasted results?
I think you are referring to ORM (Object relational mapping) First of all, `connection.execute` will return a Mysql adapter where you can just iterate over the rows You cant convert array of strings(the result you have) to ActiveRecord objects just like that ( I guess this is what you referred as typecasting) What you can do is use `find_by_sql`. **Ex:** Blog.find_by_sql("select * from blog") # => [#<Blog id: 1, name: "first blog", description: nil, record_status_id: 1>] Using this method you can get ActiveRecord Objects fro raw SQL
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "sql, ruby on rails, activerecord" }
Merging branch to master I have two branches: `master` and `feature`. I have made several commits in `feature` branch that makes massive directory structure changes. After doing so, I `checkout`'d the `master` branch and added a `README.md` to root directory. This is the only change I've made to `master` after creating the `feature` branch. I want to now make it such that the `master` branch is "fast-forwarded" to `feature` (i.e. all changes in `feature` are now in `master`), but I also want to include `master`'s added `README.md`. How do I accomplish this task?
You are looking for `git merge <branchname>`. This will merge changes into your current checked out branch. So: git checkout master git merge feature Since you've made a change on `master` since you started the `feature` branch (adding the README), this will be done as a "merge commit". Meaning it will automatically merge and then create a commit. If you hadn't changed `master`, your branch would simply be fast-forwarded to the current commit of `feature`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "git" }
Is there a time limit for running serverless batch job? Is there a time limit for running a serverless batch job? I followed the ETL job following this link: < I am wondering is there a limit which running the batch job?
Yes. AWS Lambda functions have time limits in their configurations and will be terminated if that is exceeded. You can change this value but only up to 15 minutes of run time (currently). The problem is that when working with large amounts of data that is not enough time to complete some actions. In these case you will want to transition to Step Functions (state machines that can run Lambdas) and Redshift Data API (run queries w/o have a live connection all the time). In this way you can launch a long running query and have the Step Function poll for completion.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "aws lambda, serverless framework, serverless, aws serverless, serverless architecture" }
Simple Javascript Help Request I'm after a little help with some JS not behaving. I would like to make it so that I can pass an some JavaScript to affect the end URL destination as below: The end destination being (`delete-page.php?id=1`) <a href ="javascript:deletemessage('id=1')">Delete Page </a> <script type="text/javascript"> function deletemessage(url) { $.msgbox("Are you Sure you would like to delete this page", { type: "confirm", buttons: [{ type: "submit", value: "No" }, { type: "submit", value: "Yes" }] }, function(result) { if (result == "Yes") { window.location.href = "delete-page.php(URL)"; } }); } </script> Any help would be very much appreciated!
Replace: `window.location.href = "delete-page.php(URL)";` with: `window.location.href = "delete-page.php?" + url;`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery" }
Tengo un renglon en sql con un caracter en forma de cuadro vacio y de tamaño pequeño tengo un pequeño pero gran problema en SQL server, tengo una tabla la cual tiene varios registros con caracteres no alfanumericos, tales como el simbolo del euro, #, @, ! ? y demas que pueden ser encontrados en una tabla ascii, < bueno, varios renglones contienen informacion que si la copias y la pegas en el editor de SQL Server, no muestra nada, pero si la copias y la pegas en el editor de notepad++ te muestra un texto con fondo negro que dice SOH y STX, entonces, en el resultado de la consulta de SQL, no me muestra mas que esos registros pero si quiero hacerles un delete no se como eliminarlos si no puedo copiar y pegar el contenido del renglon en el editor de SQL. alguien me entiende o tiene alguna idea de como resolverlo.
se me ocurre que puedes hacer es guardar en la base de datos el numero equivalente al codigo ascii en lugar de almacenar el propio código ascii y desde programacion ya desde c#, java, python o lo que use convierte dicho codigo en ascii.Por otro lado para eliminar los registros (`delete from tabla`) sin where deberia eliminarlos todos, si tiene datos importantes la tabla use like
stackexchange-es_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, servidor" }
How to make ScrollViewer automatic I tried to place a `TextBlock` inside a `ScrollViewer`, and the scroll bar shows up correctly, but I cannot seem to make it automatically scroll down when the `Text` property of the `TextBlock` is updated. Here's the relevant part of the XAML: <ScrollViewer> <TextBlock FontFamily="Consolas" Text="{Binding Current.Current.Discussion}" TextWrapping="Wrap" /> </ScrollViewer> Help would be greatly appreciated, thanks!
By default, the behavior you get is that the scroll bars will adjust to the amount of text in the textblock, but the viewer will be showing the top of the text. To refresh that properly do this: scrollViewer.UpdateLayout(); scrollViewer.ScrollToVerticalOffset(txtBlock.ActualHeight);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, wpf, xaml, scroll, scrollviewer" }
c# Regex WWPN validation Need to build regex to determine valid WWPN of the format: 10:00:00:00:c9:2e:e8:90 Here, each combination separated by colon can be alphanumeric
Here you are: ([0-9a-f]{2}:){7}[0-9a-f]{2}
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, regex" }
SQL if then statement retry: exec xxxxxxxxx if @csvfilecount < 16 begin waitfor delay '00:05:00' goto retry end else begin send email end I like to use go to retry for 2 try only and then go to send email. Not sure to how do this. Please help. Thanks
Can you use a while loop with a counter? declare @counter as int set @counter = 0 while @counter <= 2 begin @counter = @counter + 1 -- your code here -- update @csvfilecount if @csvfilecount < 16 begin waitfor delay '00:05:00' end else begin send email -- do you want to BREAK here? end end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sql" }
Easy problems with hard counting versions Wikipedia provides examples of problems where the counting version is hard, whereas the decision version is easy. Some of these are counting perfect matchings, counting the number of solutions to $2$-SAT and number of topological sortings. > Are there any other important classes (say examples in lattices, trees, number theory and so on)? Is there a compendium of such problems? There are many types of problems in $P$ which have $\\#P$-hard counting versions. > Is there a version of a natural problem in $P$ that is more completely understood or simpler than general bipartite perfect matching (please include details on why simpler such as being _provably_ in the lowest classes of the $NC$-hierarchy and so on) in some other area (such as number theory, lattices) or at least for particular simple bipartite graphs, whose counting version is $\\#P$-hard? _Examples from lattices, polytopes, point counting, number theory will be appreciated_.
Here's a truly excellent example (I may be biased). Given a partially ordered set: a) does it have a linear extension (i.e., a total order compatible with the partial order)? Trivial: All posets have at least one linear extension b) How many does it have? #P-complete to determine this (Brightwell and Winkler, Counting Linear Extensions, Order, 1991) c) Can we generate them all quickly? Yes, in constant amortized time (Pruesse and Ruskey, Generating Linear Extensions Fast, SIAM J Comp 1994)
stackexchange-cstheory
{ "answer_score": 9, "question_score": 21, "tags": "reference request, counting complexity, nt.number theory, permanent, decision trees" }
How to convert bytes body to string using http header charset definition in camel RouteBuilder? In a camel instance I would like to convert the body of a rest message to a string using the specified encoding of the HTTP header. The route definition I came up with so far looks like the following: from("cxfrs:bean:rsServer") .convertBodyTo(String.class, header(Exchange.HTTP_CHARACTER_ENCODING).evaluate(refToCurrentExchange, String.class)) .inOnly("activemq:jms:foo"); However I don't know how to evaluate the `Exchange.HTTP_CHARACTER_ENCODING` header in order to use its value as the target charset for `convertBodyTo`. If the body isn't converted, the message send to the jms queue will be a jms bytes message, but I would like it to be a jms text message. How can I use the `Exchange.HTTP_CHARACTER_ENCODING` value as an argument to `convertBodyTo`?
I implemented a new processor to do the job: public static final class ConvertBodyToStringProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { // NOPMD new ConvertBodyProcessor(String.class, (String) new HeaderExpression(Exchange.HTTP_CHARACTER_ENCODING).evaluate(exchange)).process(exchange); } } now the definition of the route looks like this: from("cxfrs:bean:rsServer") .process(new ConvertBodyToStringProcessor()) .inOnly("activemq:jms:foo");
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "java, apache camel" }
replace value in column with value from the column that has the value I'd like to replace the values in `valcol` with the values in the column which is the value. Suppose you have df looking something like below: col1 col2 col3 valcol 0 a d g col1 1 b e h col1 2 c f i col2 I'd like the `valcol_new` to become this: col1 col2 col3 valcol valcol_new 0 a d g col1 a 1 b e h col1 b 2 c f i col2 f How would one do this? df for testing: df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': ['d', 'e', 'f'], 'col3': ['g', 'h', 'i'], 'valcol': ['col1', 'col1', 'col2']})
You can do this by `enumerate()` method and list comprehension and `loc[]` accessor: df['valcol']=[df.loc[x,y] for x,y in enumerate(df['valcol'])] Now if you print df you will get your desired output: col1 col2 col3 valcol 0 a d g a 1 b e h b 2 c f i f
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas" }
Proving the dimension of basis of given subspace Prove or disprove the following statement : If $B = {(b_1 , b_2 , b_3 , b_4 , b_5) }$ is a basis for $\mathbb{R}^5$ and $V$ is a two-dimensional subspace of $\mathbb{R}^5$ , then $V$ has a basis made of just two members of $B$. As it is given that dimensions of $V$ is 2, so the basis must have two elements. also, it must be a subset of $B$. But how do i connect these to prove ?
We know that $$\\{(1,0,0,0,0),(0,1,0,0,0),(0,0,1,0,0),(0,0,0,1,0),(0,0,0,0,1)\\}$$ is a basis for $\mathbb{R}^5$. If we take the span of any two vectors from this basis, the vectors in it all have three or more zero coordinates. So, if we can find a two dimensional subspace containing $(1,1,1,0,0)$ say, then it's a counterexample. * * * Here's a counting proof: There are $\binom{5}{2}=10$ subsets of $\\{b_1,b_2,\ldots,b_5\\}$ of size $2$. Hence, if the statement were true, $\mathbb{R}^5$ would have only $10$ two-dimensional subspaces. In fact, there are infinitely many two-dimensional subspace of $\mathbb{R}^5$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "linear algebra" }
Why can't an intermediary Lightning node take (nearly) all fees? Consider a Lightning payment: Alice wants to pay 100 sat to Dave via two intermediary hops: Alice - Bob - Charlie - Dave. Both Bob and Charlie advertise a fee of 2 sat. Alice sends 104 sat to Bob, expecting him to forward 102 sat to Charlie. But Bob only forwards 101 sat. Then Charlie has a choice: either to fail the payment and get nothing, or forward it for just 1 sat. It seems that the economically rational choice is to forward anyway. If this is true, why first hops not always take nearly all fees for themselves? Of course, due to onion routing, Bob doesn't know whether Charlie is the last hop. If Charlie is the ultimate recipient and he won't get the sum he expected, he won't reveal the preimage, and Bob will get nothing. But can such strategies be profitable on average, over many attempts?
Summarizing what I've read in other answers and elsewhere: yes, a node can technically do so, but this would probably not be economically viable, as current implementations fail a payment is the difference between "incoming" and "outgoing" amounts is less than their announced fee. So assuming that the majority of the network runs non-malicious software, the payment with modified fees with likely fail. The precise economic analysis of this attack (and the related DoS attack) has not been done though (AFAIK).
stackexchange-bitcoin
{ "answer_score": 0, "question_score": 2, "tags": "lightning network, lightning routing" }
Oracle - Materialized View still accessible during complete refresh. How does this work? In one of our applications, we have a massive Materialized View that refreshes three times a day, and takes seven hours to refresh. (Not ideal, I know). This perplexed me, because I surely thought that users and sessions could not access this materialized view while it was being refreshed, but apparently they can!. (The type of refresh is a _complete_ refresh) During a complete refresh, to my understanding, the existing dataset is dropped and the query is then re-executed. If this is true, then **how are users/other sessions able to access the materialized view while the materialized view is being refreshed**?
There are two different ways that a complete refresh can happen-- an atomic refresh or a non-atomic refresh. An atomic refresh simply issues a DELETE to delete all the rows in the materialized view and then does an INSERT to insert the new data. This is all within a single transaction so Oracle's standard multi-version read consistency architecture lets Oracle show other sessions the old data until the refresh completes. In a non-atomic refresh, Oracle does a TRUNCATE on the materialized view and then a direct-path INSERT to insert the new data. This is substantially more efficient but since TRUNCATE is DDL, it means that the old data is not visible to other sessions during the refresh.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 12, "tags": "oracle, oracle10g, materialized views" }
Direct inequality proof of $f(x) = \frac{x}{1+x}$ For $$f(x) = \frac{x}{1+x},$$ I need to show, without using calculus, that this function obeys the property $$x,y>0 \implies f(x+y) <f(x)+f(y).$$ It was fairly easy to do with calculus, but I don't know where to start here. Any suggestions are appreciated.
it is pretty strait forward: $f(x+y)=\frac{x+y}{1+x+y}=\frac{x}{1+x+y}+\frac{y}{1+x+y}\leq\frac{x}{1+x}+\frac{y}{1+y}=f(x)+f(y)$ notice that the inequality is valid only because $x,y>0$.
stackexchange-math
{ "answer_score": 8, "question_score": 4, "tags": "real analysis" }
How do I get LaunchBar to open the enclosing folder for a selected file? After selecting a file or application in LaunchBar, how do I get it to show it in the Finder? (I'd like the equivalent of right-clicking on a file in a Spotlight search and selecting "Open Enclosing Folder" in the pop-up menu.)
Command-Return Hold the Command key and tap the Return key This will bring you to a Finder window, where the file/app is selected within the enclosing folder.
stackexchange-apple
{ "answer_score": 2, "question_score": 1, "tags": "finder, launchbar" }
PHP URL QUERY to array I have a problem with this: <?php $url = 'aa=bb&cc=dd&ee=ff'; For something like this: <?php $url = array('aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff'); My code: <?php $url = 'aa=bb&cc=dd&ee=ff'; preg_match_all('[(\w+)=(\w+)]', $url, $matches); var_export($matches); Result: array ( 0 => array ( 0 => 'aa=bb', 1 => 'cc=dd', 2 => 'ee=ff', ), 1 => array ( 0 => 'aa', 1 => 'cc', 2 => 'ee', ), 2 => array ( 0 => 'bb', 1 => 'dd', 2 => 'ff', ), ) It's almost okay, I just want to get rid of this first key. Thank you for your help.
Actually you can get associative array by many different ways e.g with **regex** , using **explode** by `&` and so on. But **If I were you** , I'll use `parse_str()` <?php $url = 'aa=bb&cc=dd&ee=ff'; parse_str($url, $query); print_r($query); ?> **Output:** Array ( [aa] => bb [cc] => dd [ee] => ff ) **DEMO:** <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, url, preg match all" }
Find the exact value of $\sin (\theta)$ and $\cos (\theta)$ when $\tan (\theta)=\frac{12}{5}$ So I've been asked to find $\sin(\theta)$ and $\cos(\theta)$ when $\tan(\theta)=\cfrac{12}{5}$; my question is if $\tan (\theta)=\cfrac{\sin (\theta) }{\cos (\theta)}$ does this mean that because $\tan (\theta)=\cfrac{12}{5}$ then $\sin (\theta) =12$ and $\cos(\theta)=5$? It doesn't seem to be the case in this example, because $\sin (\theta)\ne 12 $ and $\cos (\theta)\ne 12 $. Can someone tell me where the error is in my thinking?
Just because $\frac{a}{b}=\frac{c}{d},$ it does **not** necessarily follow that $a=c$ or that $b=d.$ e.g. $\frac{2}{3}=\frac{4}{6}$, but $2 \neq 4$ and $3 \neq 6$. * * * In your case, since $\tan(\theta)=\frac{12}{5},$ we have that $$\frac{\sin(\theta)}{\cos(\theta)}=\frac{12}{5} \iff \boxed{5 \sin(\theta)=12\cos(\theta)},$$ which is _not_ the same thing as saying that $\color{red}{\sin(\theta)=12 \ \rm{and} \ \cos(\theta)=5 \ (\rm{wrong})}.$
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "algebra precalculus, trigonometry" }
Multiple conditions on a particular column in a sql query Example Table (Person_data) Name | Area | Id =============================== Jack | A_102 | 102 Roy | Abc-34 | 109 tom | ABC6778 | 107 Aly | hj23 | 122 Saly | dsfds | 342 I need a query such that it returns all the rows where Area column doesn't contain `_` or `-` or `Abc` or `ABC`. My query Select * from Person_data where area not like '%-%' or area not like '%_%' or area not like '%Abc%' or area not like '%ABC%';
> returns all the rows where Area column doesn't contain '_' or '-' or 'Abc' or 'ABC' You need to combine these search conditions with `AND`'s, but the problem is the `_` which is a a reserved wildcard in the `LIKE` predicate. You have to escape it in the `LIKE` predicate using `[]` or you can determine any escape character to use to escape it using the `ESCAPE` keyword something like `LIKE '%\_%' ESCAPE '\'`, therefore it will treated like a literal, and it is the standard way to that like so: SELECT * FROM PersonData WHERE area NOT LIKE '%-%' AND area NOT LIKE '%\_%' ESCAPE '\' AND area NOT LIKE '%Abc%' AND area NOT LIKE '%ABC%'; ## Here is a SQL Fiddle demo
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, special characters, sql like" }
Decorating a JFreeChart I would like to decorate all my generated JFreeCharts with a timestamp in the corner. Is there a way within the JFreeChart framework to draw on the image after the chart has been generated? EDIT: Note that these charts are being generated in a background thread and distributed via a servlet, so there is no GUI and I can't just display the timestamp on a separate component.
After dinking around with it some more, I found a solution that lets you draw arbitrarily on the image after JFreeChart is done with it, so I'll post it here for posterity. In my case, I was writing the chart to an OutputStream, so my code looked something like this: BufferedImage chartImage = chart.createBufferedImage(width, height, null); Graphics2D g = (Graphics2D) chartImage.getGraphics(); /* arbitrary drawing happens here */ EncoderUtil.writeBufferedImage(chartImage, ImageFormat.PNG, outputStream);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "java, jfreechart, graphics2d" }
TypeScript add Object to array with push I would just like to add an object of an class (Pixel) to an array. export class Pixel { constructor(x: number, y: number) {} } The class has the following attribute: pixels: Pixel[] = []; The following code looks logical for me, but does not push the actual objects to my array pixels. this.pixels.push(new Pixel(x, y)); Only this works: var p = {x:x, y:y}; this.pixels.push(p); Could anybody explain me why the above statement does not work?
If your example represents your real code, the problem is not in the `push`, it's that your constructor doesn't do anything. You need to declare and initialize the `x` and `y` members. Explicitly: export class Pixel { public x: number; public y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } Or implicitly: export class Pixel { constructor(public x: number, public y: number) {} }
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 35, "tags": "arrays, typescript" }
Return cells content from range Yesterday I learned here how to copy a row to a second sheet. Sub maJolieProcedure(Texte As String) With Worksheets("employes").Range("A:A") Set c = .Find(what:=Texte) If Not c Is Nothing Then firstAddress = c.Row Worksheets("employes").Rows(firstAddress).Copy _ Destination:=Worksheets("rapport").Range("A1") MsgBox "Ok" Else MsgBox "Nok" End If End With End Sub To respect the formatting of the second sheet, I want to copy and paste the contents of each cell one by one. I can identify the line number. However, I can't figure out how the Range object can return each cell one by one. For example, C3 content if `Rows = 3`. Thanks a lot.
If you don't want to paste the formatting from one range to another paste values only. Worksheets("employes").Rows(firstAddress).Copy Worksheets("rapport").Range("A1").PasteSpecial xlValues That's the same for all ranges, whether 1 cell or a million. The Copy process copies the subject to memory as one block. Any parsing must be done before the Copy instruction. An alternative is to read a range into an array. Dim Arr As Variant Arr = Worksheets("employes").Rows(firstAddress).Value This will create a 3D array of 1 row and about 16000 columns. You might decide to limit your enthusiasm to only what you need. With Worksheets("employees") Arr = .Range(.Cells(firstAddress, 1), .Cells(firstAddress, .Columns.Count).End)xlToLeft)).Value End With Pay attention to the leading periods within the With statement. Each such period stands for the object mentioned in the With statement.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel, vba" }
ajax with radio buttons Normally when I have an imput I use this syntax: ensino: $('#amount').val() But now I have a group of radio buttons: <input type="radio" id="radio1" name="radios" value="1"> <label for="radio1">Politécnico</label> <input type="radio" id="radio2" name="radios" value="2"> <label for="radio2">Universitário</label> <input type="radio" id="radio3" name="radios" value="3"> <label for="radio3">Profissional</label> <input type="radio" id="radio4" name="radios" value="4"> <label for="radio4">Outro</label> How can I do an Ajax post? In this case, I can't use the id, correct? Thanks.
I believe it would be `$('*[name=radios]:checked').val()`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery" }
Can't Open SSRS Reports I have inherited an SSRS solution that I can't seem to work with. I sat down with the previous owner briefly and he showed me where in TFS to find the solution. The also opened up a few of the RDL files and attempted to give me the gist of modifying a report. Every thing seemed straight forward to me during that session. Now the original developer is gone and I now have access to the code in TFS. Whenever I try to open one of the RDL files, it opens it up as an XML document instead of opening it in the designer. I have Visual Studio 2008 and SQL Server 2008 Management studio installed. Any thoughts on what I may be missing like service packs or hot fixes?
Re-run the SQL Server 2008 installer on your machine. You need to install the Business Intelligence Developer Studio component, or whatever it was called in '08. If you don't have access to an installer, find the SQL Server Express with Advanced Services download (whatever year you need, just make sure it's the "Advanced Services" - here's 2008: < ), and run that; it will also provide an option for BIDS.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ssrs 2008" }
Check if String array of digits contains symbol Got `String[][] arr` which contains only `digit` in `String` format. if (array[i][j].equals("[a-zA-Z]+")){ - not help How to check if this `arr` contains `symbol`?
mystring.matches("\\d+"); Returns true when all the chars are digits. This won't break even if the number is greater than the limit of `int`. You can see some other examples here Determine if a String is an Integer in Java
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, arrays, string" }
Cassandra Delete when row not exists Is there a performance impact when running delete statements on cassandra when row doesn't exist? I am not passing the IF EXISTS clause in my delete statement as it adds an overhead of checking. I haven't found anything online about this unique use-case.
Delete operation in Cassandra is just adding a marker called "tombstone" - it will be appended to the files with data to "hide" the previously existed data. It could have some performance impact on the read operations, if you have a lot of deletes inside partitions, etc. as tombstone usually kept for 10 days in the data file (configurable per table) There is a very interesting blog post on deletes and tombstones \- I recommend to read it.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "cassandra, delete row" }
Why doesn't Canon 18-200 mm lens show any visible difference from 170 to 200 mm? Not that it's very important but I'm wondering why doesn't a Canon 18-200 mm lens have visible change in framing between 170 and 200 mm? Why is it declared as a 200 mm lens if it stops zooming at 170-something millimeters? Or is it something subtle that I'm missing? 30 mm on a lens is usually not negligible so I'd also like to know is it the same throughout the focal range or is it less noticeable at telephoto end?
**The focal-length of lenses is measured while focused at infinity.** If you were inside a store you likely focused at less than infinity and got a different focal-length than 200mm at the long end. The closer you focus, the more likely you are to be off. At infinity, there should be a small (probably 7% as @mattdm computed) but noticeable difference. Otherwise the lens was most likely defective.
stackexchange-photo
{ "answer_score": 1, "question_score": 1, "tags": "lens, canon" }