INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
WPF .how can i access to fields in other Forms without get new object I have a MainWindow and a DetailedBookView . i want use Method and field from DetailedBookView in MainWindow class whit out using new object... MainWindows isn't parent of DetailedBook ... please help me to write code in MainWindow to use DataContaxt in MainWindow. public partial class MainWindow : Window { //use DataContaxt method here without using new object enter code here } public partial class DetailedBookView : UserControl { int DataContaxt = 10; }
Make Method and fields which you want to use in another class of DetailedBookView `static`. Doing so, you can use these methods and fields with the class name directly. public partial class DetailedBookView : UserControl { static int DataContaxt = 10; } Now you can use `DataContaxt` directly as: public partial class MainWindow : Window { int a = DetailedBookView.DataContaxt; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, wpf, class, partial classes, object oriented analysis" }
how validate empty controls in windowsform i create a windows form with multi controls (text box & date time picker & combo box) then use error provider to check if a control is empty or not (14 of controls must be filled), with a messy code to check (14 if statement on the save button event) it shows the errors but stores the form in database. how can i prevent save button to insert the form whiteout any of this 14 controls !red Square shows controls that needs to be saved
my problem solved by validating event . under validating event of each control that need to be filled` private void cmb_nof_Validating(object sender, CancelEventArgs e) { Validatecmb_nof(); } private bool Validatecmb_nof() { bool bstatus = true; if (string.IsNullOrEmpty(cmb_nof.Text)) { errorProvider1.SetError(cmb_nof, "item required"); bstatus = false; } else { errorProvider1.SetError(cmb_nof, ""); } return bstatus; } `and under saver button click event this code bool Valnof = Validatecmb_nof(); if ( Valnof ) { //some events } else { MessageBox.Show("Please enter valid data"); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, errorprovider" }
How to get the logged in user's download location (C:\Users\{UserName}\Downloads\)? When I ran the app in VS2010, it correctly downloads the file to `C:\Users\{UserName}\Downloads` folder using the below code. string userDownloadFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\"; But when I host the app in IIS, it goes to `C:\Users\.NET 4.0 App Pool\Downloads\` Yes the app pool is in .NET 4.0 App Pool. How I can get the logged in user's downloads folder by hosting the app in IIS?
ASP.NET runs at the server, and anything you do in code-behind refers to the server. When you were testing it locally your machine was acting as the server, which is why you were able to get the files to download to the correct location. You can't tell the client where to download a file. Access to the client's file system is intentionally restricted for security purposes. Can you imagine the security risks if a website could gain insight about your file system and choose where to download files?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, asp.net, iis 7.5, application pool" }
Bit bucket git bash issue Hi i am trying to update files from my local to bit bucket through Git Bash. When i try this commend $ git push -u origin 'master' I get an error like To ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to ' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. Please help me.I don't know why i am getting this error.I am beginner in git Bash and bit bucket.Please help me?
Your `local/master` is not update with `remote/master`. First Pull master then Push. $ git pull origin master $ git push -u origin master If not work then try to rebase origin/master. $ git pull --rebase origin master * * * As you mentioned (in comment), you have `untracked files` locally. Follow `Add -> Commit -> Rebase -> Push`. $ git add . $ git commit -m 'added all' $ git pull --rebase origin master $ git push origin master
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "git, bitbucket, git bash" }
users drop marker and get link that will open the map there I'd like my users to be able to drop a marker on my map and be able to get a url link which will go to my website and open the map and show the marker. So I think I need 3 things really 1. How to enable users to drop a marker 2. Get its link as a URL 3. Enable the link to open the site's map and show the marker. Are there any examples out there that will be of help?
Here's two that are relevant: * Random marker placement along with sidebar creation and hyperlink * Draggable markers with geolocation
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "google maps api 3, hyperlink, maps, marker" }
PHP, remove directories I want do delete some directories and i have their names stored in an array called folders. foreach ($folders as $f){ rmdir($dir); $dir=rtrim($dir,"/"); $dir=rtrim($dir,$f); } **For example:** dir: /cdf5/gfft/ and folders: gftt,cdf5 I saw that sometimes the rtrim function cut more than 4 characters and the remaining path in dir is: `/cdf`. What's the problem?
This function deletes directory with files inside function deldirectory($dir){ $tfile = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($tfile, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->isDir()){ rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } return rmdir($dir); } Then you can call this function foreach ($folders as $f){ deldirectory($f); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, string" }
LINQ Group Duplicate Rows and Delete All of Them Except The First one i have the following LINQ code which i found in a question on stackoverflow, i want to use it to delete the duplicate rows in the datatable and leave the one with the least index, here is the code and i can't figure out the code to be added in the commented line Dim duplicates = From row In GoogleResults.AsEnumerable() Let seller = row.Field(Of String)("Seller") Group row By seller Into DuplicateSellers = Group Where DuplicateSellers.Count() > 1 Select DuplicateSellers For Each DuplicateSellerRows In duplicates For Each row In DuplicateSellerRows 'remove current row, but skip the first one 'row.Delete() will remove all rows but how can i keep the first one? Next Next
You can use Skip() to skip the first row in each group of duplicates: For Each DuplicateSellerRows In duplicates For Each row In DuplicateSellerRows.Skip(1) row.Delete() Next Next
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "vb.net, linq, datatable, duplicates" }
Replicating tests for related subclasses with JUnit effeciently I saw the answers here How to test abstract class in Java with jUnit? that says not to test the parent class for your subclasses, but test each of the concrete classes. However, the tests are the same for each subclass (beyond what subclass is being used/tested). What is the most efficient/elegant way to test all of these beyond copy pasting into new test classes and replacing the subclasses being tested? I could see doing a loop, but are there better options?
Use Parameterized. Example, assuming that `Foobar` & `Barbar` both implement `Baz` interface @RunWith(Parameterized.class) public class BazTest { @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { new Foobar(), new Barbar(), } }); } private Baz baz; public BazTest(Baz baz) { this.baz= baz; } @Test public void test() { // assert something about baz } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, unit testing, testing, junit, mockito" }
Make filters sidebar disappear I would like to give users the ability to hide the filters sidebar so that it appears and disappears at the push of a button. Is this possible? Thanks.
By default, this feature is not included in the PrestaShop, but you can create it. Add the new button for example to the _themes/classic/templates/catalog/_partials/category-header.tpl_ <button class="btn" id="show_hide_filter">Show/hide filters</button> and with manipulate the DOM with jQuery document.addEventListener("DOMContentLoaded", function() { $('#show_hide_filter').click(function () { if($("#left-column").is(":visible")){ $("#left-column").hide(); $('#content-wrapper').addClass('col-lg-12'); }else{ $("#left-column").show(); $('#content-wrapper').removeClass('col-lg-12'); } }) });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "filter, prestashop" }
Solace: How to switch off the info statements sent to std err from solace java api currently seeing the following lines when running the solace client. 10-Feb-2016 11:14:13 com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call INFO: Connecting to host 'orig=myhost.com, host=solacehost.com, port=55555' (host 1 of 1, smfclient 4, attempt 1 of 1, this_host_attempt: 1 of 1) Looked into JCSMPProperties class to control this but no luck.
Found the solution the solace API uses various logging libs, my project had commons-logging. Suppressing the log output was quite straight forward after knowing that using static { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "solace" }
How to navigate to a webpage, input text and click on a button using Python? Could you please help me automate clicking a webpage button using Python and Selenium? Here's an example of a Python code that I have so far, which opens the browser using my profile, goes to the webpage. However, it never interacts with the page: from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument("user-data-dir=C:/Users/mohamed.a.eshra/AppData/Local/Google/Chrome/User Data") #Path to your chrome profile url = ' driver = webdriver.Chrome(executable_path="C:/tools/selenium/chromedriver.exe", chrome_options=options) driver.get(url) inputtext = driver.find_element_by_name("Search").sendkeys("This is a test") search = driver.find_element_by_name("btnk").click() Could you please help me improve it to be able to click on a webpage button? Thank you!
You can try following code: url = ' driver = webdriver.Chrome(executable_path="C:/tools/selenium/chromedriver.exe", chrome_options=options) driver.get(url) inputtext = driver.find_element_by_name('q') inputtext.send_keys('This is a test') inputtext.submit()
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x, selenium" }
Is there a way to parse a zipped XML file with JQuery on the fly? I was wondering if there is a way to parse a zipped xml file such as example.xml.gz with jQuery on the fly? The reason is the file is huge and effects the performance if we call a request to the unzipped file. Any tips?
You could let the browser handle the decompression. Browsers support `Content-Encoding` = `gzip`, which does the gzipping "transparently" at the server/client level. You can serve pre-gzipped data from a file (your `example.xml.gz`) as well, this just requires some configuration to make the server send the header and send the data as-is, not trying to recompress it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, xml" }
How to display the maximum and minimum digits of an integer I need to find the maximum and minimum digits of an integer. I tried this but it doesn't do anything: #include<stdio.h> int main(){ int n,max,min,i; printf("Give me a positive integer: "); scanf("%d", &n); i=1; while(n>=0){ if(i==1) {min=n%10; max=n%10;} else {if(min>(n%10)) min=(n%10); if(max<(n%10)) max=(n%10);} n=(int)n/10; } printf("max. figure:%d min. figure:%d ", max, min); return 0; }
Two issues here: First, you never change `i` inside of the loop. As a result `if(i==1)` is always true so you reset `min` and `max` on each iteration. You need to increment `i` at the end of the loop. Second, you have an infinite loop. The test `(n>=0)` will be true if `n` is positive _or zero_. You want to exit the loop once `n` becomes 0, so change the test to `n>0`. while(n>0){ if(i==1) { min=n%10; max=n%10; } else { if (min>(n%10)) min=(n%10); if(max<(n%10)) max=(n%10); } n=(int)n/10; i++; }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c" }
How to include CMS page in the phtml page in magento 2.2 I want to include the `CMS Page` in a `phtml` template. How can I achieve this? Can anyone help me over here?
If you want to show the cms page content on your phtml page then write the following code: **Method 1(by page identifier):** $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $content = $objectManager->create('\Magento\Cms\Model\PageFactory')->create(); $content->load('your-page-identifier', 'identifier'); echo $content->getContent(); **Method 2(by page ID):** $page_id = YOUR_PAGE_ID; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $content = $objectManager->create('\Magento\Cms\Model\PageFactory')->create(); $content->load($page_id); echo $content->getContent();
stackexchange-magento
{ "answer_score": 2, "question_score": 2, "tags": "magento2, magento2.2, template, cms pages" }
Rewrite rule htaaccess I have lost few hours on .htaccess rewrite I have this url: And I want change it to this
This approach is limited to _one_ parameter name: RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?xxx\.yyy\.zzz\.net RewriteCond %{QUERY_STRING} ^sub=(.*)$ RewriteRule ^html/(.*)$ [L] <--note the use of %1 The problem is (as outlined here: < _mod_rewrite_ can not directly access and manipulate query parameters, your possiblities are quite limited. If you only have one kind of parameters that manages your redirect, you're good to go. (NOTE: if you have other query parameters that you want to hand over to the target, leave out the final question mark. This effectively removes the rest of the query string. Also, the second rewrite condition had to be rewritten to end at the parameter)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": ".htaccess, subdomain" }
Using attrs to turn JSONs into Python classes I was wondering if it possible to use the attrs library to convert nested JSONs to Python class instances so that I can access attributes in that JSON via dot notation (`object.attribute.nested_attribute`). My JSONs have a fixed schema, and I would be fine with having to define the classes for that schema manually, but I'm not sure if it would be possible to turn the JSON into the nested class structure without having to instantiate every nested object individually. I'm basically looking for a `fromdict()` function that knows (based on the keys) which class to turn a JSON object into. (I also know that there are other ways to build 'DotDicts', but these seem always a bit hacky to me and would probably need thorough testing to verify that they work correctly.)
The attrs wiki currently has two serialization libraries: 1. cattrs 2. and related. With cattrs being maintained by one of attrs’ most prolific contributors. I know that some people mention integrations with other systems too. At this point it's unlikely that attrs will grow an own solution since the externally developed look pretty good.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "python, json, python attrs" }
What's the simple expression to get bigger number from two with T-SQL? Suppose I have two number, @n1, @n2, I want to get bigger one in one simple expression like Max(@n1,@n2). How to write the expression for T-SQL?
DECLARE @n1 INT = 2, @n2 INT = 3 SELECT MAX(n) FROM (VALUES(@n1), (@n2)) t(n)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "sql, tsql, sql server 2008 r2" }
C++ - Handling exceptions without losing the callstack There is a way to handling exception and then moving to the next line in the code that the exception was thrown? Example: try { cout << "Test Begin! 1... 2... 3..." << endl; throw "A text!"; throw 1; throw 2; throw 3; cout << "Yeah! Successful!!" << endl; } catch (char* text) { cout << ch << endl; ???(); //Go back to the previous line } catch (int i) { cout << "Thrown " << i << endl; ???(); //Go back to the previous line } The output'll be: Test Begin! 1... 2... 3... A text! Thrown 1 Thrown 2 Thrown 3 Yeah! Successful!!
This is not how exceptions work. An exception effectively "return"s (more like "exit"s) from the function it is thrown from, cleaning up any memory locally allocated. It's a unique event in a `try` block, no way around that. What I'm trying to say is that your design is probably not right for C++ exceptions, and you should rethink how you will solve the problem in C++, instead of making the language work in the way you want to solve your problem. The end result will definitely be cleaner code in the end. The call stack can be preserved if you surround a `throw`ing function's call with a `try`/`catch`, which then only unwinds that one function call, leaving the rest of the call stack intact.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "c++, exception" }
sortByKey() by composite key in PySpark In an RDD with composite key, is it possible to sort in ascending order with the first element and in descending order with the second order when both of them are string type? I have provided some dummy data below. z = [(('a','b'), 3), (('a','c'), -2), (('d','b'), 4), (('e','b'), 6), (('a','g'), 8)] rdd = sc.parallelize(z) rdd.sortByKey(False).collect()
Maybe there's more efficient way, but here is one: str_to_ints = lambda s, i: [ord(c) * i for c in s] rdd.sortByKey(keyfunc=lambda x: (str_to_ints(x[0], 1), str_to_ints(x[1], -1))).collect() # [(('a', 'g'), 8), (('a', 'c'), -2), (('a', 'b'), 3), (('d', 'b'), 4), (('e', 'b'), 6)] Basically convert the strings in the key to list of integers with first element multiplied by **1** and second element multiplied by **-1**.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "pyspark, rdd" }
Windows 8 installation, missing drivers I would like to install Windows 8 on a PC without DVD or CD rom, so I made a bootable stick. The Windows 8 Customer Preview was downloaded from the Microsoft's site. When the install starts, after selecting the language it tells me "No device drivers were found. Make sure that the installation media contains the correct drivers, and then click OK." I've downloaded the Windows 8 driver install kit from the MSDN site, and tried to rescan again, but it doesn't work. Could you suggest me some ideas, what to do now?
This issue appears to arise when the downloaded ISO is corrupt or incomplete. Have you tried downloading it again/double checking the file size with those on the website?
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "windows 8 preview" }
Lua os.execute empty terminal I have a program that requires me to call os.execute to run an external program, however, when I do this, the program runs with an empty terminal sitting open in the background, which is quite a pain. I was wondering if there was a way to prevent this?
Assuming you're on Windows, you can use the winapi library, specifically `winapi.execute()` which will run an application without popping up a terminal window.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "windows, command line, batch file, lua, love2d" }
Order a matrix depending on row and column of another in R Hello I need to order column and row names in a mtrix according to another matrix, here is an exemple M1 D E F A 1 2 3 B 4 5 6 C 7 8 9 M2 F D E C T F F A F T T So here I would like to 1 sort the `M2` columns in order to have the same as `M1` and then sort the rows (as you can see here there is not the `row B` as in `M1`, so I simply add a new one filled by `F` letters. New_M2 D E F A T T F B F F F C F F T I know for exemple how to sort the column using `M2[,colnames(M1)]` but that is all...
**Step 1.** Match column and row names of `M1` and `M2` M3 <- M2[match(rownames(M1), rownames(M2)), match(colnames(M1), colnames(M2))] # D E F # A TRUE TRUE FALSE # <NA> NA NA NA # C FALSE FALSE TRUE **Step 2.** Set the dimnames and replace missing values with `FALSE` dimnames(M3) <- dimnames(M1) M3[is.na(M3)] <- FALSE # D E F # A TRUE TRUE FALSE # B FALSE FALSE FALSE # C FALSE FALSE TRUE * * * _**Data**_ M1 <- matrix(1:9, 3, 3, T, dimnames = list(c("A", "B", "C"), c("D", "E", "F"))) M2 <- matrix(c(T, F, F, T, F, T), 2, 3, dimnames = list(c("C", "A"), c("F", "D", "E")))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "r, matrix, dplyr" }
Relation between a Lie group and Lie algebra representation for $W \otimes V$ We can define a representation of a Lie group and get the induced representation of the Lie algebra. Let $G$ act on $V$ and $W$, $\mathfrak{g}$ be the Lie algebra associated to $G$ and $X \in \mathfrak{g}$. Then the action on $V$ is defined as $\displaystyle X(v)=\left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)$ where $\gamma_t$ is a path in $G$ with $\gamma'_0 = X$. Then: $$ \begin{align*} X(v \otimes w) & = \left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)\otimes \gamma_t(w) \\\ & \stackrel{?}{=}\left(\left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)\right)\otimes w + v\otimes \left(\left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)\right) \\\ & = X(v)\otimes w + v \otimes x(w)\end{align*}$$ My question is: why does it split?
$$ \begin{align*} X(v \otimes w) & = \left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)\otimes \gamma_t(w) \\\ & = \lim_{t \to 0} \,\,\, \frac{\gamma_t(v)\otimes \gamma_t(w)-v \otimes w}{t} \\\ & = \lim_{t \to 0} \,\,\, \frac{\gamma_t(v)\otimes ( \gamma_t(w)-w+w)-v \otimes w}{t} \\\ & = \lim_{t \to 0} \,\,\, \frac{\gamma_t(v)\otimes (\gamma_t(w)-w)+ \gamma_t(v)\otimes w-v \otimes w}{t} \\\ & = \lim_{t \to 0} \,\,\, \frac{\gamma_t(v)\otimes (\gamma_t(w)-w)+ (\gamma_t(v)-v)\otimes w}{t} \\\ & = \lim_{t \to 0} \,\,\, \frac{v \otimes (\gamma_t(w)-w)}{t}+ \lim_{t \to 0} \,\,\, \frac{(\gamma_t(v)-v)\otimes w}{t} \\\ & =\left(\left.\frac{d}{dt}\right|_{t=0}\gamma_t(v)\right)\otimes w + v\otimes \left(\left.\frac{d}{dt}\right|_{t=0}\gamma_t(w)\right) \\\ & = X(v)\otimes w + v \otimes X(w)\end{align*}$$
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "differential geometry, representation theory, lie groups, lie algebras" }
Pass an array from PHP to JS hi i have a big problem i try 3 weaks to solve it but i didn't make anything i have or an errors or i don't take nothing from the results. i pas an array from query ST_AsGeoJSON from a php code in the javascript code. there are in the same file html this two codes i get the array from php to javascrypt with this line of code var jsonAr= <?php echo json_encode($Arresu) ?>; if i print the jsonAr i receve with `document.write(jsonAr);` it is give me this format { "type":"LineString","coordinates":[[25.9980559326738,39.2420282528175],......,,[26.0486275566016,39.2291388086281]]},{"type":"LineString","coordinates":[[26.0486275566016,39.2291388086281],......[]]} if i try to take the coordinates and pot it in an array i try this `jsonAr.coordinates[0][0]` but i did not take any result , i don't know how i take the coordinates
`jsonAr.coordinates[0]` will give you the first coordinate. `jsonAr.coordinates[0][0]` only gives you the first number of the first coordinate.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, php" }
Why cast to object before testing for NSNull? I have the following block in a project I have been moved onto after a previous developer has left NSObject *object = (NSObject *)string; if([object isEqual:[NSNull null]]) return @"none" Where `string` is an `NSString *` returned from a dictionary. While I undertand that NSNull needs to be checked for, can someone tell me why cast to NSObject first?
The cast is unnecessary, although it's usually best to keep an object as an `id` until you know it isn't an `NSNull` (e.g. if you just pulled it out of a collection). If you have an `NSString*` which might actually be `NSNull` it can be confusing. Perhaps the original author wanted to make it clear that the string actually could be something else? Also, `NSNull` is documented as a singleton, so you could (if you wanted) compare using `==`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ios, objective c, nsstring, nsnull" }
Array push with associate array If I am working with an associate array like such: Array ( [Username] => user [Email] => email ) and I want to add an element to the end, I would think to do: array_push($array, array('Password' => 'pass')); However, this leaves me with: Array ( [Username] => user [Email] => email Array ( [Password] => pass ) ) How can this be avoided so I end up with: Array ( [Username] => user [Email] => email [Password] => pass ) Much appreciated!
You are using an associative array so you just set the key/value pair like this. $array["Password"] = pass; I think you may need to review the difference between an array and an associative array. For example if I ran the same command again with a different value it would overwrite the old one: $array["Password"] = "overwritten"; Giving you this Array ( [Username] => user [Email] => email [Password] => "overwritten" ) Which judging by your question is not what your expecting
stackexchange-stackoverflow
{ "answer_score": 34, "question_score": 20, "tags": "php, arrays, array push" }
Script to disable all 3rd party services (like safe mode, but not) I have a situation where I need to boot a VM into normal mode but disable as many services as possible. Basically we are doing a virtual to virtual conversion of the VM and the fewer services running, the less likely that a file will be locked and unable to be copied. The conversion program (Citrix XenConvert) uses VSS to take a snapshot but still files are sometimes skipped because they are open. I know the obvious question is "why not boot into safe mode with networking" - unfortunately, if I do that, it messes with the virtualization tools. Ideally it would be a script that gets the vendor of every service that is running, and if the vendor is NOT microsoft, it stops the service. Even better would be an exclusion list, so that I could say "don't stop this vendor's services". Do you incredibly smart and resourceful people have any idea where that script could be found? Or cobbled together quickly? Many thanks!
Think you'll have to put together a list of services you want to stop manually, then create a batch file to stop /start them. Typing net start at a command prompt will return a list of running services. net help services will give you the basic windows services, though some of these _can_ be stopped and there will likely be others in the list from net start that you _won't_ want to stop. I suggest you experiment with a little trial and error. Once you have the list of service names you wish to stop, create a .bat file with the following line repeated for every service you want to stop enclosed in quotes: NET STOP "Service Name" Create another .bat file with each service to start again when you're through: NET START "Service Name"
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "windows, scripting, service, xenserver, safe mode" }
Putting text next to an equation without moving the equation to the side I want to write something like: \begin{equation} f(x)=y \quad \text{(This is the equation lala)} \end{equation} But this essentially moves the equation out of the center. I don't want the equation not being centered anymore. I rather want the text on the right of the centered equation. Is there an easy solution (like naming an equation and letting that appear somehow...)?
So you want to **align** something? \begin{align} f(x)&=y &&\text{tralala} \end{align} if you want to stick with equation you could simply tell latex to ignore the width of the text \begin{equation} f(x)=y \rlap{\quad \text{tralala}} \end{equation}
stackexchange-tex
{ "answer_score": 4, "question_score": 2, "tags": "equations" }
Storing latitude longitude in cassandra table How to store latitude and longitude into the Cassandra tables and how to query up the data within 5 kms radius
Your question is very broad and vague, so I will give a very broad answer. You could store each latitude and longitude as a row in a Cassandra table, like this: CREATE TABLE locations (location text PRIMARY KEY, latitude float, longitude float); Then to find all the locations within a 5 km radius of a specified latitude and longitude (let's call that location X), you'd need to check each row in the table using a client application you would create. In pure Cassandra, you would SELECT * from the table to get all the rows (using paging if there are a lot of rows), and in your client application, for each row check if the distance between X and the row is less than 5 km, and output rows that match. Or you could pair Cassandra with Apache spark and do the same calculation in parallel. But there are a lot of different approaches you could take, so that's just one way.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "cassandra, cql" }
Move a set of rows of a dataframe to the beginning I want to move a set of dataframe rows to the beginning The indexes of the corresponding rows are these ones: indexes = [2188, 2163, 37, 47, 36, 41, 61, 1009, 40, 39, 123, 121, 2151, 19, 2, 8, 117, 205, 204] So: index 204 -> index 0 index 205 -> index 1 . . index 2188 -> index 18 At the moment I have this code that allows to move only one row: def move_row(index): idx = [index] + [i for i in range(len(df)) if i != index] return df.iloc[idx].reset_index(drop=True)
Here's an approach that reindexes the DataFrame based on using sets theory to create a new set list from indexes. This partially assumes that the indexes will be unique. import pandas as pd ## sample DataFrame d = {'col1': [0, 1, 2, 3, 4], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]} df = pd.DataFrame(data=d) print(df) ## col1 col2 col3 ## 0 0 4 7 ## 1 1 5 8 ## 2 2 6 12 ## 3 3 9 1 ## 4 4 5 11 indexes = [3, 1] new_idx = indexes + list(set(range(len(df))).difference(indexes)) df = df = df.iloc[new_idx].reset_index(drop = True) print(df) ## col1 col2 col3 ## 0 3 9 1 ## 1 1 5 8 ## 2 0 4 7 ## 3 2 6 12 ## 4 4 5 11
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, pandas, dataframe" }
Get element id using the custom tag value jquery How can I get element id using the custom tag value jquery ? <div id="1" tab_id="4" class="div_focus" tabindex="1">This is label A</div> how can i get value of id where tab_id = 4 using jquery ?
## **Demo On JsFiddle** try out this selector $('div[tab_id = "4"]').attr("id") check : [Attribute Equals Selector [name="value"]](
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery, html" }
Implement email validator with android patterns I am trying to implement email validation in my app, using android patterns, but every time nothing is returned when I call my function `isEmailValid(String)`. can anyone help? //Valida conteúdo do email char_Email.setOnFocusChangeListener(new View.OnFocusChangeListener(){ @Override public void onFocusChange(View v, boolean hasFocus){ if(!hasFocus){ email = char_Email.getText().toString(); isEmailValid(email); } } private boolean isEmailValid(String email){ return Patterns.EMAIL_ADDRESS.matcher(email).matches(); } });
How about this? //Valida conteúdo do email char_Email.setOnFocusChangeListener(new View.OnFocusChangeListener(){ @Override public void onFocusChange(View v, boolean hasFocus){ if(!hasFocus){ email = char_Email.getText().toString(); boolean validEmail = isEmailValid(email); if(!validEmail) { // Do something, maybe show a Toast } } } private boolean isEmailValid(String email){ return Patterns.EMAIL_ADDRESS.matcher(email).matches(); } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, android, validation, user interface" }
Bootstrap <form> height I am attempting to have a form on my website using the Bootstrap framework, which is going fine except for the fact that Bootstrap doesn't seem to be calculating the form's height. I have a footer right after my form, in a separate div tag, but when I view the output in my browser, the footer just covers half of the form. It's like Bootstrap doesn't give the form div an automatic height. Code: `` < **The form is the last element in the wrapper and then the footer is the last of my body. Sorry about the messy CSS, I write messy and then go back and clean it. Output: < **I can't post images yet, sorry!!** Thanks!
Your sticky footer is correct. Your bootstrap columns usage is wrong... Bootstrap uses the container as just a wrapper div to control the width of you content part and also to provide a gutter around your content. Col-xs- _, col-sm-_ etc., - These are just floating elements with certain widths in percentage. Since these divs are floated, their correct heights will be calculated only when it has a "row" around it. row - has clearfix ( CSS clear) specified in it. so that col-* height can be calculated YOU MUST have a row around your columns <div class="row"> <form class="col-xs-12"></form> </div> Here is a working fiddle <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "html, css, forms, twitter bootstrap" }
Ensure string value from JSON response I have a webservice spitting out JSON responses from the database, which I intend to use in my iPad app. However, depending on the server where the webservice is run, it either casts integers to integers or returns them as string. As I cannot be sure of the type, I have to take care of either way in my app. So, I have a NSDictionary from which I obtain the value using `objectForKey:`. I then tried calling `stringValue` but apparently that only works if the value is not a string already. Is there a simple method for enforcing a string type when having either a NSString or a NSInteger instance?
You can simply do NSString *definitelyAString = [NSString stringWithFormat:@"%@", unsureString]; where `unsureString` is the value you get through `objectForKey:`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "objective c, types, casting" }
Creating Multidimenional Arrays How can I add arrays into an existing array item? For instance: $user[$user->id] = array(//values); But if that user needs another array added, I want all data to fall under that user ID in the array. I want to store orders a user has made, so I can look up all orders on the fly by user ID in the $user array above.
$user[$user->id]['orders'] = array(); Or $user[$user->id] = array( 'orders' => array( array(// data for order #1), array(// data for order #2), array(// data for order #3) ); ); // Looping over the orders foreach($user[$user->id]['orders'] as $order) { // Do something with the order }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, arrays, multidimensional array" }
Uribuilder encoding with exclamation mark I'm trying to use Uribuilder from: javax.ws.rs.core.UriBuilder; To update a URI. The issue is that the parameter name gets escaped when I use replaceQueryParam. so: UriBuilder uriBuilder = webResource.getUriBuilder(). replaceQueryParam("abcd!dcv, "wid"). replaceQueryParam("format", "json"); if there is already an existing "abcd!dcv" parameter in the Uribuilder, it will escape and add a new one. so it will become ?abcd!dcv=originalvalue&abcd%21cdv=wid instead of ?abcd!dcv=wid How should I get around this? Thanks!
`URIBuilder` is an abstract class and the implementation gets to decide which characters need special encoding and which do not. The `URIBuilder` we get from a WebResource is attempting to follow the guidelines of RFC 3986. On page 12, **!** is listed as a sub-delimiter and this is why it is getting encoded. From my reading of the RFC, I don't think we should be using ! as part of a query parameter. For instance, Vaading uses ! to distinguish between sub-windows of the same application. The simplest work around I can think of is to simply not use URIBuilder or use the fromURI method that takes a String as input. You can create the URI with everything except the part with the characters we don't want encoded, convert this to `astring`, manipulate `astring` to replace the query parameter and then call `URIBuilder.fromURI(aString)`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "java, jax rs, url encoding" }
String substring function How can i get the string within a parenthesis with a custom function? e.x. the string "GREECE (+30)" should return "+30" only
There are some different ways. Plain string methods: Dim left As Integer = str.IndexOf('(') Dim right As Integer= str.IndexOf(')') Dim content As String = str.Substring(left + 1, right - left - 1) Regular expression: Dim content As String = Regex.Match(str, "\((.+?)\)").Groups[1].Value
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "vb.net, substring" }
Pimple is always returned as an array I have this trait use Pimple\Container; trait ContainerAwareTrait { protected $container; public function setContainer(Container $container = null) { if (null !== $this->container) { $this->container = $container; } } public function getContainer() { return $this->container; } } I have this code using it (via an `App` class) $container = new Pimple\Container(); $app = new App($container); // uses ContainerAwareTrait, constructor calls `setContainer` var_dump($app->getContainer(), $container);die; What I'm seeing is that the first `var_dump` result is an `array`, and the second is an instance of `Pimple\Container`. I was expecting them both to be the same instance. Can someone tell me what is going on here?
Your setter logic is wrong: you want to set `this->container` when it hasn't been set (is `null`), not when it is already set (is `not null`).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, pimple" }
Python lazy evaluator Is there a Pythonic way to encapsulate a lazy function call, whereby on first use of the function `f()`, it calls a previously bound function `g(Z)` and on the successive calls `f()` returns a cached value? Please note that memoization might not be a perfect fit. I have: f = g(Z) if x: return 5 elif y: return f elif z: return h(f) The code works, but I want to restructure it so that `g(Z)` is only called if the value is used. I don't want to change the definition of `g(...)`, and `Z` is a bit big to cache. EDIT: I assumed that `f` would have to be a function, but that may not be the case.
I'm a bit confused whether you seek caching or lazy evaluation. For the latter, check out the module lazy.py by Alberto Bertogli.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 9, "tags": "python, caching, lazy evaluation, memoization" }
A fair die is rolled five times. Find the probability that one shows twice, three shows twice, and six shows once. I am working on the following problem: > A fair die is rolled five times. Find the probability that one shows twice, three shows twice, and six shows once. The answer in the solution is given : $$\left(\frac{5!}{1! 2! 2!}\right) \left(\frac{1}{6}\right)^6$$ But I think it should be $(1/6)^5$. What it the correct answer? (Ref: Probability, Random variables and Stochastic processes - Papulis(Ch-4/Exercise-31)
Since the die is fair, there are $6$ equally likely outcomes for each of the five rolls, so there are $6^5$ possible outcomes for the five rolls. We have a sequence of five outcomes. For the favorable cases, choose two of the five positions in the sequence for the ones and two of the remaining three positions in the sequence for the threes. The final open position in the sequence must be filled with a six. Therefore, there are $$\binom{5}{2}\binom{3}{2} = \frac{5!}{3!2!} \cdot \frac{3!}{2!1!} = \frac{5!}{2!2!1!}$$ favorable sequences. Hence, the probability that two ones, two threes, and a six are obtained when a fair die is rolled five times is $$\frac{\dbinom{5}{2}\dbinom{3}{2}}{6^5} = \left(\frac{5!}{2!2!1!}\right)\left(\frac{1}{6^5}\right)$$
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "probability, probability theory, random variables" }
How to open the link clicked in a new tab? In my page,I have a link on which i clicked it should open in a new tag but its not working for me.Can anyone please suggest help.So far I hadd tried the below <a target="_BLANK" ng-href="{{news.url}}">{{news.url}}</a>
Use href instead of ng-href <a target="_blank" href="google.co.in">google.co.in</a>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, html, angularjs, href" }
Does the sun have a notable frame-dragging effect on the planets? Frame-dragging is a general relativistic effect that can be imagined as the effect that the momentum of mass-energy has (the stress elements in the stress-energy tensor) on mass-energy in the surroundings of the moving mass-energy. For example, a large moving sheet of mass will cause particles to be dragged along in the direction of motion of the sheet (on top of gravitating towards the sheet). So I was wondering. Does the sun have a noticeable frame-dragging effect on the planets?
An effect, but not a noticeable effect. Wikipedia gives a formula for the frame-dragging in a a Kerr metric: $$\Omega = \frac{r_{s} \alpha c}{r^{3} + \alpha^{2} r + r_{s} \alpha^{2}}$$ where $\Omega$ is the angular speed that the frame of reference rotates at, $r$ is the orbital radius (70 billion metres for Mercury), $r_s$ is the Schwartzchild radius of the sun (3000 m), $c$ is the speed of light and $\alpha = \frac{J}{Mc}$ is the angular momentum of the sun divided its mass and the speed of light. For the sun $\alpha\approx 320$ metres. Plugging these values in gives $\Omega \approx 10^{-18}$ radians per second. This isn't noticeable (compared to other relativistic effects and Newtonian perturbations) Frame dragging can be detected in carefully designed experiments on Earth satellites since the effect is greater at smaller orbit radius.
stackexchange-astronomy
{ "answer_score": 2, "question_score": 1, "tags": "the sun, planet, general relativity" }
Prevent Excel to format string as date I want to insert a string of type `10/3` in a cell like this: Worksheets("Sheet1").Range("A1").Value = "10/3" But Excel automatically formats the cell as a date or a number. I want to have it as a string. How can I achieve this with VBA?
Worksheets("Sheet1").Range("A1").NumberFormat = "@" Worksheets("Sheet1").Range("A1").Value = "10/3"
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 8, "tags": "excel, vba" }
Тире в простом предложении Безусловно, данный пункт актуален для всех типов кранов – как разборных, так и цельносварных. Правильно ли я поставила тире?
Лучше использовать запятую: "Безусловно, данный пункт актуален для всех типов кранов, как разборных, так и цельносварных". Постановка тире в подобных конструкциях факультативна и обычно не применяется, например: "Компания «Хорс» осуществляет поставки насосов для перекачки всех типов жидкости, как простых так и сложных". Тире - более сильный знак, чем запятая, и для его применения при союзной связи определений нет достаточных оснований. И относить информацию на второй план не имеет смысла, так как требуется расшифровка местоимения "всех". Сравнить: Безусловно, данный пункт актуален для всех типов кранов - разборных, цельносварных и т.д. (требуется распространенный ряд при отсутствии союзов). Мы долго шли по обочине дороги – бурой, ещё не высохшей от снега, сплошь покрытой прошлогодними листьями.
stackexchange-rus
{ "answer_score": 1, "question_score": 0, "tags": "пунктуация" }
capture and retrieve image in iphone? I am new to iOS 5.0, I want to know that, Is there any method to capture the image from camera and retrieve it in application in iOS ?
Take a look at the Camera Programming Guide.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, ios, ios5" }
How to connect dual brushless motors to arduino I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back. This the motor I want to use : < !motor specs !enter image description here. !enter image description here. !enter image description here
It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed. You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.
stackexchange-arduino
{ "answer_score": 0, "question_score": 0, "tags": "arduino uno" }
4pin fan on RAMPS board - direct? The question is simple - I have a RAMPS 1.4 running Marlin 1.1.9 with the three MOSFETs being used (end, fan, bed), but I'd like to have a couple other Marlin-controlled fans. One of them would be a 4-pin, 6000RPM cooler I got from a dead graphics card. Seeing how it runs perfectly at 12V 350 mA if I keep the control pin disconnected (and ignore the sense pin too, of course), Could I connect 12V and GND directly to the PSU (or RAMPS 12V header) and the CONTROL pin to one of the pwm servo control pins like D11? Or do I need a resistor? I could add some info about the fan if needed, but it's a FirstD 4-pin, 12V 0.35A fan that can run up to 6000 RPM.
Yes, this should work. According to this 4-pin fan specification, such fans use a 5V PWM signal. You would have to make sure the PWM frequency on the pin you use satisfies that 21-28 kHz range specified in the document. According to 3.3 and 3.4 in the document, you may not be able to turn the fan off completely when using the PWM input signal.
stackexchange-3dprinting
{ "answer_score": 4, "question_score": 5, "tags": "ramps 1.4, print fan, fans" }
MongoDB Aggregation - Parse field to decimal and use this in match I have a document that has a balance field of type string. I want to rule out all of these documents where the "balance" property is `$lte: 0` but I can't manage to find the right syntax to do so. $match:{ {$toDecimal:'$balance'}: $lte:0 } It's not working. I'm wondering how to cast the field to a numeric inside a match function before making the match itself.
You should use `$expr` and the syntax should be as below: { $match: { $expr: { $lte: [ { $toDecimal: '$balance' }, 0 ] } } } Sample Mongo Playground
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mongodb, aggregation framework" }
Server configuration for referral URL I have a domain called `example.com` that takes a parameter `?ref=XXXXXX`. The referral URLs are `ex.co/XXXXXX` My question is, when a user goes to `ex.co/AhJ7z1` or any random string, how do I configure my server to forward to `example.com/?ref=AhJ7z1`. Is that something that can be done in `.htaccess` or `php.ini` or something like PHP? **EDIT :** I'd like this to be done in a PHP script if possible so that I can reserve certain URLs and restrict URLs outside of what I want. Is there an `.htaccess` script I could utilize `index.php` in root directory to do this?
In your .htaccess you can do something like this: RewriteEngine on RewriteCond %{HTTP_HOST} ^ex\.co$ RewriteRule ^(.*)$ [L,R] EDIT: to redirect to index.php RewriteEngine on RewriteCond %{HTTP_HOST} ^ex\.co$ RewriteRule ^(.*)$ /index.php?ref=$1 [L] Then it's a matter of you writing your index.php script to grab the 'ref' parameter and find what URL to redirect to.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, web services, apache, .htaccess" }
dart FFI - Pointer to a Pointer In dart using the ffi library we can create a Pointer object two ways Pointer<NativeType> foo = allocate(); Pointer<NativeType> bar = Pointer.fromAddress(int address); We can also get the Pointer objects address using `int address = foo.address();` If we want to create a Pointer from another Pointer object doing `final bar = Pointer.fromAddress(foo.address);` Will the resulting type of `bar` be `Pointer<Pointer<Double>>` or will `bar` just be a copy of foo where `foo.address == bar.address` If it simply clones the Pointer, how can we create a Pointer to another Pointer?
Here is an example: Pointer ptrToCopy; // i will assume that you have this already... Pointer<Pointer<NativeType>> _ptrToPtr = allocate(); _ptrToPtr.value = Pointer.fromAddress(ptrToCopy.adress);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "flutter, pointers, dart, ffi" }
Volume of a cube with integration. Say we wanted to derive the formula for the volume of a cube _with integration_. Each "slice" of the cube has area $x^2$, with "width" $dx$. Integrate from $0$ to $x$, and I believe you would get the following: $$\int_0^x x^2dx$$ And this equals $\frac 13x^3$, however the volume of a cube is given by $x^3$! What is wrong with this process?
The problem is that with $\int_0^x x^2dx$ you are actually calculating the volume of a kind of inverted pyramid. As @Fermat suggested, you have to maintain the side fixed (through $a^2$), otherwise it changes as the third axis does.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "integration, proof verification" }
Prove that $X_n \to c$ (in distribution) $⇒ X_n → c$ (in probability) > Show that for real random variables $\\{X_n\\}$ on a probability space, $X_n \to c$ (in distribution) $⇒ X_n → c$ (in probability) ($c$ is the RV degenerate at 0) My attempt: I wrote down the definitions of the two convergence. $P\\{\omega : |X_n (\omega)-c(\omega)|>\epsilon\\}=P\\{\omega : |X_n (\omega)-c(\omega)|>\epsilon,\omega<c\\}+P\\{c : |X_n (c)-1|>\epsilon\\}+P\\{\omega : |X_n (\omega)-c(\omega)|>\epsilon,\omega>c\\}$ But can't go further to show that the sum $\to 0$ as $n \to \infty$ Thanks in Advance for help!
$P\\{X_n >c+\epsilon\\} \to P\\{c>c+\epsilon\\}=0$ (by convergence in distribution) and (similarly) $P\\{X_n <c-\epsilon\\} \to P\\{c<c-\epsilon\\}=0$ .Then just add these two to get $P\\{|X_n-c| >\epsilon \\} \to 0$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability theory, convergence divergence" }
How to take the top 10 results of a UNION in sql? I currently have the following code in a stored procedure (see below). In an effort to return 10 results total, I take the TOP 5 of each union-half. However, I'd like to take the TOP 10 of the UNION, and not necessarily 5 of each. Any ideas? Is this possible? BEGIN SELECT TOP 5 a_object_ID as [id], a_object_name as [name], 'A_object' as [Type] FROM [database].[dbo].[table_a] WHERE a_object_name LIKE @Search + '%' UNION ALL SELECT TOP 5 b_object_ID as [id], b_object_name as [name], 'B_object' as [Type] FROM [database].[dbo].[table_b] WHERE b_object_name LIKE @Search + '%' ORDER BY [name] END
How about this? SELECT TOP 10 * FROM ( SELECT a_object_ID as [id], a_object_name as [name], 'A_object' as [Type] FROM [database].[dbo].[table_a] WHERE a_object_name LIKE @Search + '%' UNION ALL SELECT b_object_ID as [id], b_object_name as [name], 'B_object' as [Type] FROM [database].[dbo].[table_b] WHERE b_object_name LIKE @Search + '%' ) x ORDER BY [name]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "sql, stored procedures" }
Custom scrollbar on firefox I need custom scrollbar on my website but i dont know how to do it. Something like this: < I alredy tried something but nothing happend. Thanks!
The scrollbar bugs are already open in Firefox's ToDo list in BugZilla. So technically this is not possible unless you use a JavaScript based solution like `NiceScroll JS`. To use NiceScroll JS, you need to include the script: <script src="jquery.nicescroll.js"></script> And activate it: $(document).ready(function() { $("html").niceScroll(); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, php, jquery, html, css" }
Getting Object instance not set to an instance of an object error I am trying to encrypt user password CryptoWrapper wrapObj = null; UserDetails userDetails = dbContext.GetUserDetails(); if (userDetails != null) { if (userDetails.Password !=null && userDetails.Password != "") { //some code here wrapObj.Crypt(userDetails.Password); } } I am getting "Object instance not set to an instance of an object." Can someone help me here?
CryptoWrapper wrapObj = null; is null and you are trying to use it. wrapObj.Crypt(userDetails.Password); You need to create an instance of `CryptoWrapper` and assign it to `wrapObj` CryptoWrapper wrapObj = new CryptoWrapper();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, nullreferenceexception" }
SQL Server : calling a stored procedure or not I have a stored procedure that has one input parameter. However, in the stored procedure, there is a condition that needs user's input (`WHEN t.flag = 0`). Is there a way not to call a new stored procedure but does the same job? I do not want to add another input parameter in `[dbo].[UpdateTheRate]` itself because I have other processes going on in this stored procedure. ALTER PROCEDURE [dbo].[UpdateTheRate] (@PID int) AS UPDATE t SET t.rate = CASE WHEN t.flag = 1 THEN (select UnitRate from RateTable where state ='IL' and Term='20') WHEN t.flag = 0 THEN EXEC [dbo.rate_procedure] --(USER enter rate) FROM TblChargeTable t WHERE t.PID = @PID
Something along these lines? ALTER PROCEDURE [dbo].[UpdateTheRate] (@PID int) AS -- defer executing the procedure unless necessary IF EXISTS (SELECT 1 FROM TblChargeTable WHERE flag = 0 and PID = @PID) BEGIN EXEC dbo.rate_procedure; -- get @user_rate via return code or out parameters perhaps END UPDATE t SET t.rate = CASE WHEN t.flag = 1 THEN (select UnitRate from RateTable where state ='IL' and Term='20') WHEN t.flag = 0 THEN @user_rate END -- retrieved above FROM TblChargeTable t WHERE t.PID = @PID;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, sql server 2008, stored procedures" }
asp:Textbox off focus? I want to save the contents of a multline textbox when off focus - i.e. user has finished typing and clicks outside the textbox so it goes off focus. I can handle the saving- thats no problem, but is there an off focus function? I don't mind a javascript version. I must be using asp:TextBox though. I tried with onFocus, OnServerChange, onKeyUp, but it is not exactly how I want it. If any of you use Facebook, then it is like the textbox displayed right below the profile picture.
`OnBlur` :) <asp:TextBox runat="server" onblur="alert(1);" /> (I can't recall, off the top of my head, if it will write any unknown server property to the client, I think it does, but if it doesn't, you'll need to add it as an attribute, in code). \-- Edit: Confirmed that it does, indeed, happily write out unknown properties (onblur is not a property of TextBox control, but it will render in the HTML, so it works).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, javascript, visual studio 2008" }
Matching multiples I need to match the following using preg_match() cats and dogs catsAndDogs i like cats and dogs etc, so i simply stripped out the spaces and lowercased it and used that as my pattern in preg_match(); '/catsanddogs/i' But now I need to match the following too: cats+and+dogs cats_and_dogs cats+and_Dogs So is there quick and easy way to do a string replace multiple times, other than nesting it? I want to end up with the same pattern to match with. Thanks.
try this expression `'/cats([+_-])?and([+_-])?dogs/i'` edit: just saw that you don't want a + after the "and" when you already have a + before the "and". If that's right then you should use this expression: `'/cats(\+and\+|\+and_|_and_|and)dogs/i'`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, regex, preg match" }
SQL - Is it better to do a subquery here or an extended WHERE clause? The CUST table below will be joined with ~10 tables. For this subquery in particular, am I better off simply joining up directly with the Customer table and moving the subquery's 4-part WHERE clause to the main query's WHERE clause? I'm primarily wondering if it is possible to cut down on the amount of processing that SQL Server has to do if we localize portions of the master WHERE Clause by creating subqueries as below. select * From (select CKey, CID, CName from MainDB.dbo.Customer where LOC = 'ARK' and Status = 1 and CID not like 'KAN%' and CID not like 'MIS%') as CUST
Based on what you provided, there's no need for the subquery. Without the ~10 joins to the derived table `CUST`, it's extremely difficult to say what should or should not be done.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, sql server, sql server 2005, sql server 2008" }
how to calculate standard deviation from different colums in shell script I have a datafile with 10 columns as given below ifile.txt 2 4 4 2 1 2 2 4 2 1 3 3 1 5 3 3 4 5 3 3 4 3 3 2 2 1 2 3 4 2 5 3 1 3 1 2 4 5 6 8 I want to add 11th column which will show the standard deviation of each rows along 10 columns. i.e. STDEV(2 4 4 2 1 2 2 4 2 1) and so on. I am able to do by taking tranpose, then using the following command and again taking transpose awk '{x[NR]=$0; s+=$1} END{a=s/NR; for (i in x){ss += (x[i]-a)^2} sd = sqrt(ss/NR); print sd}' Can anybody suggest a simpler way so that I can do it directly along each row.
You can do the same with one pass as well. awk '{for(i=1;i<=NF;i++){s+=$i;ss+=$i*$i}m=s/NF;$(NF+1)=sqrt(ss/NF-m*m);s=ss=0}1' ifile.txt
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "linux, shell, awk, stdev" }
Simplifying the sum $\sum\limits_{i=1}^n\sum\limits_{j=1}^n x_i\cdot x_j$ How can I simplify the expression $\sum\limits_{i=1}^n\sum\limits_{j=1}^n x_i\cdot x_j$? $x$ is a vector of numbers of length $n$, and I am trying to prove that the result of the expression above is positive for any $x$ vector. Is it equal to $\sum\limits_{i=1}^n x_i\cdot \sum\limits_{j=1}^n x_j$? If it is then my problem is solved, because $\left(\sum\limits_{i=1}^n x_i\right)^2$ is non-negative (positive or zero).
Yes, $$\sum_{i=1}^n\sum_{j=1}^nx_i x_j=\left(\sum_{i=1}^ nx_i\right)^2\;.$$ To see this, let $a=\sum_{i=1}^ nx_i$; then $$\sum_{i=1}^n\sum_{j=1}^nx_i x_j=\sum_{i=1}^n\left(x_i\sum_{j=1}^nx_j\right)=\sum_{i=1}^na x_i=a^2\;.$$
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "linear algebra, algebra precalculus, matrices, summation, vectors" }
Setting up an Artifactory instance to mirror another Artifactory We would like to have two JFrog Artifactory instances, one for users inside local network of the company (with complete open access) and one that can be used from outside (with restricted accesses). So we want the second instance mirror some (or all) of repositories of the first one. Where should I start?
You would probably want to have Remote Repositories that point to the inner network instance (it has to be reachable from outside your network, but only for the credentials you specify on the remote repository's configuration though) so that they can serve whatever is in the inner instance's repositories when requested. Another option is to use Replication (which runs periodically) to sync (mirror) a repository from the outside instance with the inner one. I would probably go with the first option as you will not have to wait for replication cycles to complete to be sure the outer instance is completely synced, replication is more of a DR usecase.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "artifactory, mirror" }
Delete from table A joining on table A in Redshift I am trying to write the following MySQL query in PostgreSQL 8.0 (specifically, using Redshift): DELETE t1 FROM table t1 LEFT JOIN table t2 ON ( t1.field = t2.field AND t1.field2 = t2.field2 ) WHERE t1.field > 0 PostgreSQL 8.0 does not support `DELETE FROM table USING`. The examples in the docs say that you can reference columns in other tables in the where clause, but that doesn't work here as I'm joining on the same table I'm deleting from. The other example is a subselect query, but the primary key of the table I'm working with has four columns so I can't see a way to make that work either.
I don't understand the mysql syntax, but you probably want this: DELETE FROM mytablet1 WHERE t1.field > 0 -- don't need this self-join if {field,field2} -- are a candidate key for mytable -- (in that case, the exists-subquery would detect _exactly_ the -- same tuples as the ones to be deleted, which always succeeds) -- AND EXISTS ( -- SELECT * -- FROM mytable t2 -- WHERE t1.field = t2.field -- AND t1.field2 = t2.field2 -- ) ; * * * Note: For testing purposes, you can replace the `DELETE` keyword by `SELECT *` or `SELECT COUNT(*)`, and see which rows would be affected by the query.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "sql, amazon redshift, delete row" }
How to rate-limit Apache server on IP basis? I currently have a custom implementation in PHP/mysql that keeps track of web hits and blocks those that exceed a certain rate for the same IP. I.e. if a given source IP hits the server more than X times in the last Y seconds then it will be served a redirect to a predefined location Z and the normal request processing will be aborted. It works OK, but puts significant stress on MySQL. So I was wondering if there is a special tool for this available? Maybe an Apache module or some kind of filter?
The best * mod_evasive (Focused more on reducing DoS exposure) * mod_cband (Best featured for 'normal' bandwidth control) and the rest * mod_limitipconn * mod_bw * mod_bwshare One more option - mod_qos Not simple to configure - but powerful. <
stackexchange-serverfault
{ "answer_score": 7, "question_score": 3, "tags": "apache 2.2" }
permotation group S13 question if a = (1 2 4 8) (3 5 7 9 11 13) (6 12) ∈ S13, and b= (1 2 3 4 5 6) (7 8 9 10) (11 12) ∈ S13 ,let σ ∈ S13 a = σbσ−1 then how much σ like this are there in S13?
Hint: Prove that if $\;(i_1\;i_2\;\ldots\;i_k)\;$ is a cycle in $\;S_n\;$ and we take _any_ element $\;\sigma\in S_n\;$ , then $$\sigma(i_1\;i_2\;\ldots\;i_k)\sigma^{-1}=(\sigma(i_1)\;\sigma(i_2)\;\ldots\;\sigma(i_k))$$ Further hint: if $\;c_1,..,c_r\;$ are cycles (or, in fact, general permutations), then $$\sigma(c_1\cdot\ldots\cdot c_k)\sigma^{-1}=(\sigma c_1\sigma^{-1})(\sigma c_2\sigma^{-1})\cdot\ldots\cdot(\sigma c_r\sigma c_r^{-1})$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "abstract algebra, group theory, permutations" }
What is wrong with this number script? I'm very new to JavaScript and I want to do an input check. Here is my script: function checkInp() { var x=document.forms["myForm"]["num"].value; // Get the value if (isNaN(x)) { alert("Not a number!"); // Check if the input is a number return false; } var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment. Number(valuex); // Make the input a number if (valuex.value > 480) { alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally. return false; } else { return; } } I don't know what happens, but the script doesn't work since I added the second part (to check if the number is greater than 480). Please help me, with full example if possible.
The way I'll doing it: * Document selectorQuery is more understandable * Dont get the value multiple time * Use ParseInt to transform your var on number * Don't forget to return true if success Code: function checkInp() { var x = document.querySelector('input[name="num"]').value; if (isNaN(x)) { alert("Must be a number"); return false } else if (x > 480) { alert("Must be under 480"); return false } return true }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "javascript, html, numbers" }
Wifi Jammer SH1106Wire.h: No such file or directory Trying to upload code onto esp8266 module for a wifi jammer. I followed these instructions/ When uploading the code I keep getting the error message SH1106Wire.h: No such file or directory.
See < and < for ensuring all SDK files are available.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "arduino esp8266" }
AutoFixture setup interface property inside class How can I have AutoFixture populate properties in my object containing interface property? public class Car : ICar { public string Name { get; set; } public ICarinformation ContactInformation { get; set; } // problematic ... public CarInformation: ICarinformation { public string Make {get; set; } // I would like these to be populated as well ... fixture.Create() throws: > An exception of type 'Ploeh.AutoFixture.ObjectCreationException' occurred in Ploeh.AutoFixture.dll but was not handled in user code > > Additional information: AutoFixture was unable to create an instance from Mediachase.Commerce.Inventory.ICarInformation because it's an interface Is there a way to provide AutoFixture with Concrete type for that property?
Yes, you can just use the `TypeRelay` customization fixture.Customizations.Add( new TypeRelay( typeof(ICarInformation), typeof(CarInformation)); Alternatively, if you wanted to use a fake object using Moq, you could use either `AutoMoqCustomization` or `AutoConfiguredMoqCustomization`.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "c#, .net, autofixture" }
Unable to manually trigger pipeline - Trigger button grayed out The trigger button is grayed out and disabled. I cannot select it. Pipeline has been published and zero errors on validation. Pipeline is running on a schedule with no errors, but want to run manually as needed. Tried Edge and Chrome Pipeline-Before-Publish Pipeline-After-Publish
Didn't repro on my side. Which browser do you use? Could you share a screenshot of the disabled trigger button? It seems like a bug, here is a workaround: on top of the trigger button, right click and then left click inspect ![on top of the trigger button, right click and then left click insect]( find the trigger tag and remove disable ![find the trigger tag and remove disable]( What's your factory version? If it's preview (2018-07-01-preview), then publish/debug/trigger are all blocked. Please refresh the page and go to overview page, you will see a prompt dialog suggesting you move to GA version.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure data factory 2" }
Data modeling : Data without uniqueness I have a use case where data needs to be dumped into DB, that is not having any uniqueness. Say some random data, that can have repeated values, generated at very high speed. Now Cassandra has constraint of having partition key per table mandatory. Even though I can introduce a TimeUUID column, but again problem comes while retrieving. That again can be handled using ALLOW FILTER in Select clause. I am looking for some better approach. Anyone can suggest some other approach. Only constraint is I can only dump data in Cassandra DB, File system not available.
It seems like you just want to store your data without knowing yet how to query it. With Cassandra, you typically need to know how to query it before you design your data model. If you want to retrieve the full data set, you will have poor performance. You might want to consider hdfs instead. If you really need to store in Cassandra, try to think of a way to store it that makes sense. For example, you could store your data in timebucket. Try to size your bucket to store about 1MB worth of data. If you produce 1MB of data per minute, then a minute bucket is appropriate. You would have a partition key as the minute of the date, then a clustering column as timeUUID, then the rest of your data to store.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "cassandra, cassandra 3.0, datastax java driver" }
Parser Error: Unexpected end of expression: {{value?}} | Angular 2 Typescript I'm running into trouble with showing the variable that is initialised asynchronously. I added the `?` in the template to catch the error that it would be undefined but it says the expression end unexpected. @Component({ template: `<div>{{value?}}</div>` }) export class Component implements OnInit { value: number; constructor(private _service: Service) { } getValue() { this._service.getValue().subscribe(data => this.value = data); } ngOnInit() { this.getValue(); } }
I think that in your case you can use the variable directly without the Elvis operator: @Component({ template: `<div>{{value}}</div>` }) It's useful when you try to access property of a variable gotten asynchronously. For example: @Component({ template: `<div>{{value?.someProperty}}</div>` })
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "http, typescript, angular" }
How to reference parent node of cck referenced node in drupal I have a new content type called 'A' which has a cck reference node field that makes reference to type 'B'. I have a custom template that renders out all node types 'B' in a very specific way.. the problem is that for this template, I need to know who the current node belongs to. type B will always have a parent (of type 'A').. but I have no way to know the nid of the parent. Is this possible? So in short, when $node->type == 'B' print $node->parent->nid???????????? how can this be done?
**Old Solution:** Try using the < (Corresponding Node References) Module. This way you will be able to find out the "parent" of Node B. Basically you will get a node reference field in Node of type B that points back to a Node of type A (the "parent" node). Also you will only need to update one of the Node Reference fields -- the other will be kept in sync automatically. **Alternate and Better Solution** Try using the Node Referer Module. See <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "drupal, cck" }
Difference btw Premium + Non-Premium Accounts? What's the difference between premium and non premium account names? Is there bidding on regular account names (what is that process)? Say I want the account name "java". That would be premium, no? How about if I want "java00000000" (12 characters)? Is that a non-premium account? How can I secure that account name?
### Normal acccount names Are exactly 12 characters long and do not contain a dot. These can be created right now by sending a `newaccount` action to the eosio.system contract. ### Premium Account Names These are less than 12 characters or contain a dot. To obtain the right to create one of those with the `newaccount` action you must first win an auction for that name. When you own the premium account `x` you and only you also gain the right to create accounts of the form `name.x`. Premium account names are basically your own TLD.
stackexchange-eosio
{ "answer_score": 1, "question_score": 2, "tags": "account name, premium" }
How to put custom HTML into Yii2 GridView header? There's this `<abbr></abbr>` tag in bootstrap that will automatically shows popup of the abbreviated word. I want to insert this tag to a certain header in the gridview with attribute name `act`. Here is my code so far. [ 'attribute'=>'act', 'format'=>'raw', 'label'=>'<abbr title="Area Coordinating Team">ACT</abbr>', 'value'=>function($model){ return '<span class="fa fa-thumbs-up text-green"></span>'; } ], but the output literally shows the whole `<abbr title="Area Coordinating Team">ACT</abbr>` !enter image description here
I already answered that here. To achieve that, use `header` property instead of `label`: [ 'attribute' => 'act', 'format' => 'raw', 'header' => '<abbr title="Area Coordinating Team">ACT</abbr>', 'value' => function ($model) { return '<span class="fa fa-thumbs-up text-green"></span>'; }, ], That way HTML content won't be encoded. **Official docs:** * $header
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 7, "tags": "html, gridview, yii2, formatting, yii2 advanced app" }
Real estate agent wants a loan introduction letter I was talking to a real estate agent (USA, CA bay area) who told me that I need to not only fill out a loan app, w2, and account statements but also write a introduction letter for the lender. I've never heard of this is it common? When searching the internet I haven't seen any examples of this. I see examples of cases where people have been in financial peril or needed to explain anomalous finances but never for a simple mortgage application. I've talked to other real estate agents who have not mentioned this. Is this a red flag? Why can I not find examples on the internet. I searched mortgage application introduction and I just found bank introduction letters offering mortgages. What should these letters typical contain, who should they be addressed to, particularly if I will never / have never met the lender nor do I know who they might be.
I have never heard of that, sounds weird. What would you write in the introduction letter that would affect the lender, and is not in your financial support? Whatever that might be - chances are that lender would be breaking an anti-discrimination law. I now some real-estate agents in the area ask to write such letters to _sellers_ to convince them to accept your offer, but I don't think it actually works all that much as well. Anyway, regarding mortgage application - I would advise not writing any letter or providing any information the mortgage broker/loan officer didn't ask for. Some things are illegal for them to take into consideration and putting it in writing in the application may force them to decline just because they got exposed to that particular piece of information.
stackexchange-money
{ "answer_score": 1, "question_score": 0, "tags": "united states, mortgage, real estate, first time home buyer" }
Static Semantics meaning? What does term "static semantics" mean in programming? What is relationship between static semantics, semantics and dynamic semantics? I know that semantics stands for checking if written code (without syntax errors) has any meaning.
Semantics is about meaning. It includes: * the static semantics, which is the part that can be ascertained at compile time, including data typing, whether all variables are declared, which declaration applies to which variable in the case of scoping, what their type is, whether functions and methods are called with correct calling sequences, whether assignments are type-compatible, etc., and * dynamic semantics, which is what actually happens when the program is executed. Source: Frank de Remer, _Compiler Construction_ course, University of California, Santz Cruz, 1979.
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 15, "tags": "syntax, static, compiler construction, semantics" }
Switch case on Enum values > The feature recursive patterns is currently in preview, to use preview feature, please select preview version switch (transactionRecieved) { case TransactionType.TransactionName.ToString(): break; case TransactionType.TransactionName1.ToString(): break; } I am not using anything new. This is the general scenario and we use it all time like this for enum > `TransactionType` is a enum I also went through this post not found it useful.SO Post > I need to use enum in swith statement and I am not able to use it. could anyone help me on that part
If you're asking "why doesn't this work"? I'm not sure you do use it all the time like that because `case` expects a constant value: ![enter image description here]( Parse your string `transactionRecieved` to a TransactionType enum with `Enum.Parse` or `Enum.TryParse<T>` and then remove the `ToString()` from your case, perhaps like: var x = "Whatever"; if(Enum.TryParse<TransactionType>(x, out xEnum)){ switch(xEnum){ case TransactionType.Whatever: break; } } Notes: * `xEnum` is in scope within the if * `Enum.IsDefined` can be used in conjunction with `Enum.Parse` (but I find tryparse neater)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, enums, switch statement, visual studio 2019" }
Laravel - LeftJoin 'on' and 'orOn' at the same time I want to accomplish something like this: SELECT * FROM table1 LEFT JOIN table2 ON (table1.id=table2.id OR table1.tid=table2.tid) AND table1.x=table2.x Which in Laravel would become something like: TABLE1::leftJoin('table2', function($join){ $join->on('table1.id','table2.id')->orOn('table1.tid','table2.tid'); $join->on('table1.x','table2.x'); })->get() I'm just not sure how to bring the OR parenthesis in Eloquent's query?
Found it: TABLE1::leftJoin('table2', function($join){ $join->on(function($join2) { $join2->on('table1.id','table2.id'); $join2->orOn('table1.tid','table2.tid'); }); $join->on('table1.x','table2.x'); })->get()
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "laravel, eloquent" }
Autoloading a separate, Laravel application into Lumen I'm writing an API for an existing Laravel application using Lumen. So as to allow the API's controllers to access the Laravel app's models, I've added the Laravel app as a git submodule, and set it to autoload into the "Main" namespace via the composer.json file: "psr-4": { "App\\": "app/", "Main\\": "main/app/" } This works fine, but I wanted to ask what impact this will have on memory usage. Is the entire Laravel app being loaded into memory (thus causing a performance drop), or is the Lumen app just being told "where to look" when a Main\Model class is referenced? Thanks
As this process uses standard PHP autoloading functionality under the hood, classes are loaded ad-hoc if not already defined, rather than them each being loaded initially.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, laravel, lumen, psr 4" }
Log multiple occurences of one HTTP header with Apache With **mod_log** you can log headers sent back to the client in the access.log file with the `%{Set-Cookie}o` directive. But if there are **multiple occurences** of the same header, as is authorized by the HTTP RPC, **only one gets logged**. How can we have **all of them** logged ? For reference, the RFC states : > Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. `Set-Cookie` is such a field-name since the field-value is comma-separated. I would not mind to have them joined together as suggested in the HTTP RPC.
Actually, since version 2.0, It works out-of-the-box, except for `Content-type` : every header gets nicely concatenated with a comma as suggested in the HTTP RFC. The "Set-Cookie" response header also has a special treatment as we can see in the `log_header_out` function of `modules/loggers/mod_log_config.c` : // ... start of snippet ... if (!strcasecmp(a, "Content-type") && r->content_type) { cp = ap_field_noparam(r->pool, r->content_type); } else if (!strcasecmp(a, "Set-Cookie")) { cp = find_multiple_headers(r->pool, r->headers_out, a); } else { cp = apr_table_get(r->headers_out, a); } // ... end of snippet ...
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "apache 2.2, logging" }
Get string array from Pymongo query I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values. Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources. Right now I'm doing this: from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') headers = client['headers'] entomo = headers.entomo entomo_data = entomo.find() entomo_array = [] for data in entomo_data: entomo_array.append(data['colname']) Then I return the `entomo_array`.
If the 'colname' field has distinct values or if you do not care about duplicate values you can use distinct function. For your example: entomo_array = entomo.find().distinct('colname')
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, mongodb, mongodb query, aggregation framework, pymongo" }
Consultar NFe sem certificado Existe alguma forma de consultar a base de NFe sem certificado via programação? Hoje precisaria somente consultar quais os produtos estão na NFe para automatizar um processo interno.
Tem sim eduardo, você pode usar qualquer cliente http para consultar a página de consulta da NFe, e baixar o contéudo da mesma para uma string, daí você monta o documento traduzindo as tags html para os campos conforme o leiaute da NFe, o único chato é o captcha que ou você contorna ou exiba no seu programa para o usuário digitar, a desvantagem disso é que você codifica em função da página da sefaz, mas é bem simples de implementar.
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "nfe" }
How do I enable Git for Visual Studio/Team Server 2013 We have a Team Project we created in 2013. The web site of the project allows Git Repos to be created, but in Visual Studio 2017 the Git repos we created are always Offline and exhibiting other odd behaviors (loading TFVC's interface in Visual Studio even when connecting to a Git repo within it for example). I used Fiddler to check out the traffic and noticed that this particular project is missing the SourceControlGitEnabled = true flag. A project we created a year and a half later DOES include the SourceControlGitEnabled flag and works properly. Is there a TFS Team Project setting we can alter/enable or do I have to create a new Project with Git as the repo and migrate everything to it?
When you create a new repo in the Team Project in TFS2013, there should be a warning as below: > Note that some versions of Visual Studio will only **provide full Team Explorer integration** with a repository that has **the same name as the team project**. Users may need to manually clone this new repository to use it in Visual Studio. ![enter image description here]( This maybe the limitation of TFS2013 with GIT, either manually clone this new repository to use it in Visual Studio or create a new Project with Git as the repo and migrate everything to it, both should be work.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "tfs, visual studio 2017" }
sum column based on two matching fields using awk I can't seem find an awk solution for this simple task. I can easily sum a column ($3) based on one matching field ($1) with : awk -F, '{array[$1]+=$3} END { for (i in array) {print i"," array[i]}}' datas.csv Now, how can I do that based on two fields ? Lets say $1 and $2 ? Here is a sample datas : P1,gram,10 P1,tree,12 P1,gram,34 P2,gram,23 ... I simply need to sum column 3 if first and second fields match. Thanx for any help !
Like so awk -F, '{array[$1","$2]+=$3} END { for (i in array) {print i"," array[i]}}' datas.csv My result P1,tree,12 P1,gram,44 P2,gram,23 **EDIT** As the OP needs the commas to remain in the output, I edited the answer above using @yi_H's "comma fix".
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "awk" }
attaching the link of the article in href i am having the link like <a href=" onclick="OpenPopup(this.href); return false">Click Here to See Popup</a> for bookmarking the article clicked to twitter .. The above one just add the articles message to twitter.. But i am trying to add my article link also to twitter,.. so i am using the location.href but its not working tat is its not showing me the articles site name.. THe below is the one i tried.. <a href=" onclick="OpenPopup(this.href); return false">Click Here to See Popup</a> Thanks i advance.. Help me to get out of this...
It seems that you're using PHP, so you could use '<a href="...' . urlencode(curPageURL()) . '-' . $markme_ddesc . '...' where `curPageURL` is a custom function to get the full URL. (Or use `$_SERVER['REQUEST_URI']` if the domain is not needed.) * * * But if you really need to attach the URL from client side, you need to use Javascript. <a id="xyz" href=" … > ... // onload: var xyz = document.getElementById('xyz'); xyz.href = xyz.href.replace(/@PLACEHOLDER@/g, encodeURIComponent(location.href)); Of course this will fail if the client doesn't enable Javascript.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, html" }
Get the PHP version number only I've been using this... echo PHP_VERSION; ...to display the version of PHP running on the server, which usually displays something like... 5.4.6.1 But I've just discovered that on some servers I get more than the version number, and instead this gets displayed: 5.4.6.1ububtu1.8 Is there a way I can get just the numbers? The reason being is I need to check the version of PHP and display a message, something like... $phpversion = PHP_VERSION; if($phpversion >= "5.5") { echo "All good"; } else { echo "Your version of PHP is too old"; } ...but of course if $phpversion contains anything other than numbers then this script won't work properly. Thanks in advance.
To get full version (5.4.6.1) <?php preg_match("#^\d+(\.\d+)*#", PHP_VERSION, $match); echo $match[0]; It will return 5.4.6.1 in your example To get version as you need (5.4) preg_match("#^\d.\d#", "5.4.6.1ububtu1.8", $match); echo $match[0]; It will return 5.4 in your example Test here
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "php, server" }
fetch score from previous rank belonging to another student I'm trying to to fetch score from previous rank belonging to another student for every row in the following select statement. Now, I'd like to have the Score of previous Rank in each GroupCode for every CourseCode and StudentCode. SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank FROM Table my table data ![enter image description here](
You can use `apply` : SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank, t1.What_u_want FROM Table t OUTER APPLY ( SELECT TOP 1 t1.Score AS What_u_want FROM Table t1 WHERE t1.CourseCode = t.CourseCode AND t1.GroupCode = t.GroupCode AND t1.StudentRank < t.StudentRank ORDER BY t1.StudentRank DESC ); However, same could also achieve with _correlation_ approach : SELECT StudentCode, CourseCode,GroupCode, Score, StudentRank, (SELECT TOP 1 t1.Score AS What_u_want FROM Table t1 WHERE t1.CourseCode = t.CourseCode AND t1.GroupCode = t.GroupCode AND t1.StudentRank < t.StudentRank ORDER BY t1.StudentRank DESC ) What_u_want FROM Table t1;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "sql, sql server, rank, sql server 2005 express" }
AngularJS - Keep Checking Variable/Function I would like to know what is the best way to keep checking a variable in AngularJS. I made a simple clicker game where the user keeps gathering gold, so I need to be constantly checking the number of gold so I can perform some functions accordingly. The only thing I know is $interval, but I don't know if that's the best way since I have to write a number of seconds. Thank you in advance.
Wherever your variable is stored (controller/directive): $scope.goldAmount = 0; // or whatever initial value you so desire Set a watch function $scope.$watch('goldAmount', function(newAmount, oldAmount){ // Do something with the amount when it changes }); `$watch` allows you to 'watch' any variable within your `$scope` and run a call back when it changes. Docs can be found here: <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "javascript, angularjs" }
VS 2015 Find and replace this string but not that string I am using VS regex to try and delete the string Windows.Forms but not System.Windows.Forms I can use this to find all of the lines: ^(?!.*System.Windows.Forms). _Windows.Forms._ $ But I cant use a replace for that since it obviously deletes the whole line. Any ideas?
You just need to adjust the lookbehind to (?<!System\.)Windows\.Forms Or with word boundary to be more precise: (?<!\bSystem\.)\bWindows\.Forms\b See the regex demo%5CbWindows%5C.Forms%5Cb&i=I%20am%20using%20VS%20regex%20to%20try%20and%20delete%20the%20string%20Windows.Forms%20but%20not%20System.Windows.Forms&r=) The lookbehind is checking the text _before_ the current position meets some subpattern. So, the text you need to match and consume is `Windows.Forms`, but it should not be preceded with `System.`. Thus, the lookbehind (negative one) should only contain `System\.` (or `\bSystem\.`). Note that the dots must be escaped to match literal dots.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, regex, visual studio" }
In the movie Avatar, mountains were floating on their own but vehicles needed engines to fly, why? When Quaritch organizes a pre-emptive strike against the Tree of Souls, the mountains were floating on their own while the RDA vehicles needed engines to fly, why?
The Hallelujah mountains float because they're essentially large chunks of unobtainium, which is a room temperature superconductor, thus subject to the Meissner Effect. This causes superconductors to "levitate" in the presence of certain strong magnetic fields: !Image of a supercooled "high-temperature superconductor" levitating above a magnet. Vehicles need engines to fly because gravity and the laws of thermodynamics still exist in the Avatar universe. So vehicles still need a power source for propulsion and can't defy gravity for no apparent reason.
stackexchange-scifi
{ "answer_score": 40, "question_score": 15, "tags": "avatar" }
Can you get the benefit of Saving Inspiration without spending a healing surge? The Warlord feat Saving Inspiration reads as follows: > Benefit: When you use inspiring word, you can forgo any extra dice of healing granted by the power to instead grant the target a saving throw. If a warlord uses Inspiring Word with this power, can the target choose not to make spend a healing surge but still make a saving throw?
**No.** If they don't spend a surge, they don't get the extra healing. If they wouldn't get the extra healing, they can't take the save instead if the extra healing. On a side note, Mark of Healing (from the Eberron Player's Guide) is _vastly_ superior to Saving Inspiration if you can take it.
stackexchange-rpg
{ "answer_score": 6, "question_score": 1, "tags": "dnd 4e" }
ABC Conjecture: Simple example showing $\epsilon$ is necessary I was looking over Lang's discussion of the abc conjecture in his famous _Algebra_ tome. He says > We have to give examples such that for all $C>0$ there exist natural numbers $a$,$b$, $c$ relatively prime such that $a+b=c$ and $|a|>C N_0(abc)$. But trivially, $2^n | (3^{2^n} -1)$. We consider the relations $a_n+b_n=c_n$ given by $3^{2^n}-1 = c_n$. It is clear that these relations provide the desired examples. Well, it is not clear to me. Can someone more algebraic than I please fill me in on what he's talking about? I understand that because $2^n|(3^{2^n}-1)$, $N_0(3^{2^n}-1) \ll 3^{2^n}-1$, but I don't see which values of $a_n$ and $b_n$ will allow us to conclude anything like $|a|>C N_0(abc)$.
The $\epsilon$ is necessary in the following sense. The abc-conjecture in the first version of Oesterle says: For every $\epsilon >0$ there are only **finitely many** abc-triples with quality $P(a,b,c)>1+\epsilon$, where $P(a,b,c)=\log c/(\log rad (abc))$, and $a,b,c$ coprime integers with $a+b=c$. This is **wrong** for $\epsilon=0$, because of the above exmaples. To simplify it, let $$ (a,b,c)=(1,9^n-1,9^n) $$ for $n\ge 1$. Then $rad(abc)=3rad(b)$, and because of $8\mid (8+1)^n-1$ we have $8\mid b$ and $4\mid b/rad(b)$, so that $rad(b)\le b/4$, and $rad(abc)=3rad(b)\le 3b/4<c$, and hence $$ P(1,9^n-1,9^n)>1+\frac{\log(4/3)}{2n\log 3}>1+\frac{1}{8n}>1, $$ for **infinitely many** abc-triples.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "abstract algebra, elementary number theory" }
How to stack left-nav-bars with 3col fixed layout? How can I stack nav bars on top of eachother given the following fiddle? Fiddle: < This is photoshopped in the red but it's what I want to achieve !enter image description here I have tried wrapping two stacked in and but no go. <div class="???"> <div class="well sidebar-nav left"> <ul class="nav nav-list"> // o o o </ul> </div> <div class="well sidebar-nav left"> <ul class="nav nav-list"> // o o o </ul> </div> </div>
Would scaffolding like this work for you? < Basically the two lefthand nav blocks are in the same span, the right hand nav is in its own span, and the central block is in nested container. I'm sure you will want to customise this further, though if you use the standard bootstrap grid as much as possible everything will stack and scale well on narrow screens. Good luck!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "twitter bootstrap" }
Python get records based on date in a list Here i need two records based on the date field in the list. The two records must have the older dates: records = [['2019-02-01', 29], ['2018-12-01', 22], ['2019-01-01', 2]] Need to display two records with older date Expected Output = ['2018-12-01', 22] , ['2019-01-01', 2]
You can use `sorted`, and parse the `datetime` strings within the lists using the `key` argument so the list is sorted based on the dates. Finally slice the list to keep the first two elements: from datetime import datetime sorted(records, key=lambda x: datetime.strptime(x[0], '%Y-%m-%d'))[:2] **Output** [['2018-12-01', 22], ['2019-01-01', 2]]
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "python, python 2.7, list, sorting, python datetime" }
Strange facebook like box behaviour I have a simple yet hard problem here that is driving me nuts ... Apparantly with no code change what so ever the facebook and Google+ like boxes show as I want in one section of my site: < yet on the other they just disappear < I'm going crazy over here! Someone ?
As I was using the relative path <script src="js/scripts.js"></script> When the address changed the scripts.js file wasn't loading. Using: <script src=" It's always loaded no matter what address the user is accessing. It was a dumb mistake!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "html, facebook, facebook like" }
Nest returns zero results with MatchAll() Query and Size(100000) I have the following Nest query in C#: var results = client.Search<Question>(s => s.From(0).Size(100000).Query(q=>q.MatchAll())); When this is run I get zero results. When I adjust the Size() method to Size(10000) it works. I am basically trying to return all results in the index. What am I missing here? I have googled to find out if there is a max results settings on the Elastic server itself but have found nothing.
There is a `index.max_result_window` settings (defaults to 10000) which you can adjust. However, as described in the official documentation, if you want to retrieve all the documents, you're better off using scroll search instead. You can find an example of using scroll search with NEST here
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, elasticsearch, nest" }
Is there a Perl module to interface to Google Contacts API? I want to write a command line program to add a contact to GoogleMail. WWW::Contact::GoogleContact appears only to be able to get things from Google.
I think you want the Google Data API instead. The Contacts API is read-only.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "perl, contacts" }
PHP: How to sort an array containing inner arrays based on one of it's inner array's values? I have this array: $animals = array( '0' => array('name' => 'cat', 'order' => '2'), '1' => array('name' => 'dog', 'order' => '1'), '2' => array('name' => 'fish', 'order' => '3') ); I want to turn it into this: $animals = array( '1' => array('name' => 'dog', 'order' => '1'), '0' => array('name' => 'cat', 'order' => '2'), '2' => array('name' => 'fish', 'order' => '3') ); As you can see I want to sort based on the `order` key. How to do this?
You could use array_multisort() $animals = array( '0' => array('name' => 'cat', 'order' => '2'), '1' => array('name' => 'dog', 'order' => '1'), '2' => array('name' => 'fish', 'order' => '3') ); $tmp = array(); foreach($animals as $k=>$r){ $tmp[] = $r['order']; } array_multisort($tmp,SORT_ASC,$animals); // SORT_DESC to reverse echo '<pre>',print_r($animals),'</pre>';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "php, arrays" }
how to get nested values inside braces How to use php to get inside nested braces? example: {{ text1 {{text2 text3 {{text4}} text5}} }} should output 1- text1 {{text2 text3 {{text4}} text5}} 2- text2 text3 {{text4}} text5 3- text4
I've found the answer i was looking for and put this here so everyone could use it. Its very simple indeed, in one line only: $text1=preg_replace("/\{\{(([^{}]*|(?R))*)\}\}/",'',$text1); It will search and replace all {{text}} with whatever you want. You can also use the preg_match_all to get all of them in an array.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "php, regex" }
Does Windows 7 supports Google Email Uploader? Is `google email uploader` available in `windows 7`...... I am using `Outlook 2007` as my desktop email program.... I thought of uploading all my mails to a new gmail account which i created.. But from System requirements of google email uploader * Windows XP and Vista * Outlook 2003 and greater for Outlook support. * A Google Apps account * Microsoft .NET 2.0. If you do not have 2.0, the program will install it for you. Is it available for windows 7....
Yes, it fully supports Windows 7.
stackexchange-superuser
{ "answer_score": 2, "question_score": 3, "tags": "windows 7" }