qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
454,414
Noise-canceling headphones can reduce a lot of ambient sound, but they are not 100% perfect. (Especially in the human vocal range.) 1. Is there any physical principle preventing the creation of perfect sound-canceling headphones? In other words, headphones that can cancel or block 100% of all external sound before it reaches my ears. (I realize that I would still hear internal body sounds, of course.) 2. Now, instead of headphones, how about a device that can cancel all the sound in the room for all the listeners in the room?
2019/01/15
[ "https://physics.stackexchange.com/questions/454414", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/134671/" ]
The scattering of light by light is a very tiny quantum effect that was first observed in 2016 with high-energy photons at the Large Hadron Collider. <https://en.wikipedia.org/wiki/Two-photon_physics> Most of the time, photons do not interact with each other. When they occasionally do, they do not do so directly but instead indirectly through virtual electrons and positrons, or, even more rarely, through other charged particle-antiparticle pairs. [![enter image description here](https://i.stack.imgur.com/0JKdE.png)](https://i.stack.imgur.com/0JKdE.png) (Picture from Wikipedia.) The cross section for this scattering process, in the zero-total-momentum frame, averaged over the polarization of the photons, can be calculated and is $$\sigma(\gamma\gamma\rightarrow\gamma\gamma)=\frac{973\alpha^4\omega^6}{10125\pi m^8}$$ where $\alpha$ is the fine-structure constant, $\omega$ is the angular frequency of each of the two photons in the zero-total-momentum frame, and $m$ is the mass of the electron. This formula applies when $\omega$ is small compared to $m$ and is in natural units where $\hbar=c=1$. <https://arxiv.org/abs/1111.6126> For example, the cross section for green light with frequency 600 THz is $1.7\times10^{-67}\;\text{m}^2$. In other words, green photons behave as if they have a "radius" of about $2\times10^{-19}$ fermi. By contrast, the radius of a proton is about 0.9 fermi, so this shows how fantastically small the cross section is and how unlikely visible photons are to scatter off of each other. The effect is only observable with very high-energy photons.
TLDR: no, photons do not normally react with each other. All of the answers above are technically correct (*the best kind of correct*), but I'm not sure they really explain what's going on if I'm reading your post correctly. I'll try using a toy model to illustrate some of the main features. Particles with electrical charge, like the electron, produce a "sea" of "virtual photon"s around them. We'll skip the details of this for now, they're ultimately not important to this discussion. What is important is this: for every virtual photon, there is, over time, the exact opposite photon. So for instance, if the electron "releases" a photon going left with energy 1, it will also release one going right with energy 1. When you sum up all of this, you get zero. That makes sense, otherwise the electron would evaporate. Now another important point is that the spectrum of these virtual photons is very specific - there is a relationship between their energy and the time before they are zeroed out again. So high-energy photons exist, but only for short times, and vice versa. When you add in this wrinkle you get something *very* interesting; the energy density of the overall "sea" (or "cloud", what have you) drops off **almost exactly like the classical electric field.** Ok, so how does this cause a force? Well consider what happens when one of these things hits another electron. It is absorbed. So that second electron has now picked up the momentum from the virtual photon, and that makes it move away from the original electron. But even more interesting: since that electron was absorbed, the original electron now has a partner virtual electron that no longer has its partner. And that one had the exact opposite momentum, so that means the original electron starts moving away from the second. **Just like classical electric force.** So what does all of this have to do with your original question? Well, photons are *not* electrically charged. That means they *don't* (normally) give off these virtual photons. That means they don't have an field, and that means, basically, **they ignore each other completely**. Now the caveat to that statement is outlined by G. Smith above - at very very high energies other things start to occur that mean that two photons may indeed recoil from each other, but I don't think that's what you're asking about.
24,904,552
I want to use BeautifulSoup to pick up the ‘Model Type’ values on company’s webpages which from codes like below: it forms 2 tables shown on the webpage, side by side. **updated source code of the webpage** ``` <TR class=tableheader> <TD width="12%">&nbsp;</TD> <TD style="TEXT-ALIGN: left" width="12%">Group </TD> <TD style="TEXT-ALIGN: left" width="15%">Model Type </TD> <TD style="TEXT-ALIGN: left" width="15%">Design Year </TD></TR> <TR class=row1> <TD width="10%">&nbsp;</TD> <TD class=row1>South West</TD> <TD>VIP QB662FG (Registered) </TD> <TD>2013 (Registered) </TD></TR></TBODY></TABLE></TD></TR> ``` I am using following however it doesn’t get the ‘VIP QB662FG’ wanted: ``` from bs4 import BeautifulSoup import urllib2 url = "http://www.thewebpage.com" page = urllib2.urlopen(url) soup = BeautifulSoup(page.read()) find_it = soup.find_all(text=re.compile("Model Type ")) the_value = find_it[0].findNext('td').contents[0] print the_value ``` in what way I can get it? I'm using Python 2.7.
2014/07/23
[ "https://Stackoverflow.com/questions/24904552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2998077/" ]
Your alert box is empty, because the variable course has no value! **Why?** Your page gets reloaded, when you click on a link. The course variable is then empty, because variable values won't be stored for the next request. HTTP is stateless! **What to do?** Your page should not get reloaded. Try something like: ``` $('li').click(function(e){ alert($(this).html()); return false; }); ```
``` course = $(this).find("a").text(); ```
24,904,552
I want to use BeautifulSoup to pick up the ‘Model Type’ values on company’s webpages which from codes like below: it forms 2 tables shown on the webpage, side by side. **updated source code of the webpage** ``` <TR class=tableheader> <TD width="12%">&nbsp;</TD> <TD style="TEXT-ALIGN: left" width="12%">Group </TD> <TD style="TEXT-ALIGN: left" width="15%">Model Type </TD> <TD style="TEXT-ALIGN: left" width="15%">Design Year </TD></TR> <TR class=row1> <TD width="10%">&nbsp;</TD> <TD class=row1>South West</TD> <TD>VIP QB662FG (Registered) </TD> <TD>2013 (Registered) </TD></TR></TBODY></TABLE></TD></TR> ``` I am using following however it doesn’t get the ‘VIP QB662FG’ wanted: ``` from bs4 import BeautifulSoup import urllib2 url = "http://www.thewebpage.com" page = urllib2.urlopen(url) soup = BeautifulSoup(page.read()) find_it = soup.find_all(text=re.compile("Model Type ")) the_value = find_it[0].findNext('td').contents[0] print the_value ``` in what way I can get it? I'm using Python 2.7.
2014/07/23
[ "https://Stackoverflow.com/questions/24904552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2998077/" ]
Your alert box is empty, because the variable course has no value! **Why?** Your page gets reloaded, when you click on a link. The course variable is then empty, because variable values won't be stored for the next request. HTTP is stateless! **What to do?** Your page should not get reloaded. Try something like: ``` $('li').click(function(e){ alert($(this).html()); return false; }); ```
You can use "this" to get the correct reference. ``` $(function(){ $('li').click(function(e){ alert($(this).text()); }); }); ``` jsfiddle: <http://jsfiddle.net/CMt9h/3/> you can also use the event argument to get the target: ``` $(function(){ $('li').click(function(e){ alert($(e.target).text()); }); }); ``` jsfiddle: <http://jsfiddle.net/CMt9h/4/>
24,904,552
I want to use BeautifulSoup to pick up the ‘Model Type’ values on company’s webpages which from codes like below: it forms 2 tables shown on the webpage, side by side. **updated source code of the webpage** ``` <TR class=tableheader> <TD width="12%">&nbsp;</TD> <TD style="TEXT-ALIGN: left" width="12%">Group </TD> <TD style="TEXT-ALIGN: left" width="15%">Model Type </TD> <TD style="TEXT-ALIGN: left" width="15%">Design Year </TD></TR> <TR class=row1> <TD width="10%">&nbsp;</TD> <TD class=row1>South West</TD> <TD>VIP QB662FG (Registered) </TD> <TD>2013 (Registered) </TD></TR></TBODY></TABLE></TD></TR> ``` I am using following however it doesn’t get the ‘VIP QB662FG’ wanted: ``` from bs4 import BeautifulSoup import urllib2 url = "http://www.thewebpage.com" page = urllib2.urlopen(url) soup = BeautifulSoup(page.read()) find_it = soup.find_all(text=re.compile("Model Type ")) the_value = find_it[0].findNext('td').contents[0] print the_value ``` in what way I can get it? I'm using Python 2.7.
2014/07/23
[ "https://Stackoverflow.com/questions/24904552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2998077/" ]
Your alert box is empty, because the variable course has no value! **Why?** Your page gets reloaded, when you click on a link. The course variable is then empty, because variable values won't be stored for the next request. HTTP is stateless! **What to do?** Your page should not get reloaded. Try something like: ``` $('li').click(function(e){ alert($(this).html()); return false; }); ```
As AndiPower said the course variable is empty due to the page reload. If you want this page reload, but still want to display the selected value on the next page you can do: * Submit the value to the server and load it in js ready * Add it as an url parameter to the `href` and read it in js ready * Store it in a cookie
35,353
I am a Windows administrator standing up an Ubuntu Server for some intranet LAMP applications. I have read through some of the Ubuntu documentation but am not clear on a good way to get backups of the system. Obviously what I would like to do is be able restore the application data (and perhaps applications) if an issue occurs to the box. I would like the schedule the backup to run daily. What are (is) the recommended way to backup up an Ubuntu server? Am I able to direct backups to a network share where they will be put to tape? What is involved in restoring the data?
2011/04/15
[ "https://askubuntu.com/questions/35353", "https://askubuntu.com", "https://askubuntu.com/users/13733/" ]
It really depends upon what your backup requirements are. Are you considering backup of entire machine, just userdata, perhaps app data, maybe mySQL data, etc? Linux admins commonly use tools like Rsync with combination or ssh, at times for added security to do file level backups. Of course, if you have a virtual environment, maybe you are backing up whole datastores. So, maybe the question is are you considering file-level, and if so entire OS, or just some data directories? For typical data directories rsync+ssh is really commonly seen. When it comes to mySQL, there are countless scripts on the internet to dump that data into a file, and then again, using rsync+ssh to transfer that data. I personally am a fan of NFS, and all data remains on NFS, which just happens to be backed by a SAN. I use what I preach. I work for Nexenta, and use our SAN solution for all data, and backups. Backups in my case are done on the SAN, simply using snapshots and cloning.
You say this is for LAMP applications (only?). In that case, you probably just need to backup the MySQL database(s), and the contents of /etc. The former should be backed up with a script specific to MySQL (backing up the MySQL data directory directly risks backing up an inconsistent database state), while for the latter, any technique can be used, even `cp -a`, because `/etc` is quite small. OK, a third thing to backup might be the applications themselves, but this is not so important because presumably you can just download them again if necessary.
114,142
I have my Stack Overflow account and [this](https://webmasters.stackexchange.com/questions/22660/how-do-i-set-starting-at-12-value-for-a-grouped-product-in-magento) question was migrated to Pro webmasters Why was this question migrated?
2011/11/30
[ "https://meta.stackexchange.com/questions/114142", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/173856/" ]
I'm a little surprised there isn't an FAQ question about this. (Maybe this could be it?) A question is migrated when it is off topic for Stack Overflow, but is on topic for the destination site. In this case, your question was migrated because it was not about programming specifically, but was about higher-level tasks involved in managing a website.
Because there are a wealth of people on that site who know about Magento - and, best I can tell, your question wasn't programming-related - and fits within the scope of the other site more aptly.
114,142
I have my Stack Overflow account and [this](https://webmasters.stackexchange.com/questions/22660/how-do-i-set-starting-at-12-value-for-a-grouped-product-in-magento) question was migrated to Pro webmasters Why was this question migrated?
2011/11/30
[ "https://meta.stackexchange.com/questions/114142", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/173856/" ]
I'm a little surprised there isn't an FAQ question about this. (Maybe this could be it?) A question is migrated when it is off topic for Stack Overflow, but is on topic for the destination site. In this case, your question was migrated because it was not about programming specifically, but was about higher-level tasks involved in managing a website.
As the migrator in question, I'll second what David has said. It was not programming related, and therefore off topic for StackOverflow. There is not much traffic for managing Magento website configurations on Webmasters, unfortunately for you, but it is on topic there. Perhaps you should check out this [Magento proposal](http://area51.stackexchange.com/proposals/25439/magento) at Area 51?
1,508,516
Prove that $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n}$ is an even integer. I'm not sure how to prove that it is an even integer. What would I do for the Inductive Step? And for the basic step, can I plug in zero and prove something from that?
2015/11/01
[ "https://math.stackexchange.com/questions/1508516", "https://math.stackexchange.com", "https://math.stackexchange.com/users/286002/" ]
**Hint:** Prove by induction on $k$ that $(1+\sqrt2)^k = a+b\sqrt2$ for some integers $a$ and $b$ such that $(1-\sqrt2)^k = a-b\sqrt2$. Then set $k=2n$. You can choose either $k=0$ or $k=1$ to be the base case. --- **Alternatively:** Use the binomial theorem on each of $(1+\sqrt2)^{2n}$ and $(1-\sqrt2)^{2n}$. Note that the terms that involve an odd power of $\sqrt2$ cancel out each other between the two sums, and that terms with an *even* power of $\sqrt2$ are (a) integers and (b) are the same in each of the two sums.
For the basic step, yes, you can plug $n=0$ (and also $n=1$, if you want) and do some computations. On the other hand, for the inductive step you can always use the following equality: $$x^{2n} + y^{2n} = (x^2+y^2)\cdot (x^{2(n-1)} + y^{2(n-1)}) - x^2y^2\cdot (x^{2(n-2)} + y^{2(n-2)})$$ and use *complete induction* (after you have observed that $(1+\sqrt{2})^2(1-\sqrt{2})^2 =1$).
1,508,516
Prove that $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n}$ is an even integer. I'm not sure how to prove that it is an even integer. What would I do for the Inductive Step? And for the basic step, can I plug in zero and prove something from that?
2015/11/01
[ "https://math.stackexchange.com/questions/1508516", "https://math.stackexchange.com", "https://math.stackexchange.com/users/286002/" ]
**Hint:** Prove by induction on $k$ that $(1+\sqrt2)^k = a+b\sqrt2$ for some integers $a$ and $b$ such that $(1-\sqrt2)^k = a-b\sqrt2$. Then set $k=2n$. You can choose either $k=0$ or $k=1$ to be the base case. --- **Alternatively:** Use the binomial theorem on each of $(1+\sqrt2)^{2n}$ and $(1-\sqrt2)^{2n}$. Note that the terms that involve an odd power of $\sqrt2$ cancel out each other between the two sums, and that terms with an *even* power of $\sqrt2$ are (a) integers and (b) are the same in each of the two sums.
Note that $(1+\sqrt2)(1-\sqrt2) =-1 $ and $(1+\sqrt2)^2 =3+2\sqrt{2} $. Therefore, if $a =3+2\sqrt{2} $, then $1/a = 3-2\sqrt{2} $, so that $a+1/a =6 $ and $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n} =a^n+1/a^n $. We now use the identity true for any $a$ that $a^{n+1}+1/a^{n+1} =(a+1/a)(a^n+1/a^n)-(a^{n-1}+a^{n-1}) $. Therefore, for this particular $a$, $a^{n+1}+1/a^{n+1} =6(a^n+1/a^n)-(a^{n-1}+a^{n-1}) $. Since $a^n+1/a^n$ is an integer for $n=0$ and $n=1$, it is an integer for all $n$. Explicitly, if $u\_n = a^n+1/a^n =(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n} $, $u\_{n+1} =6u\_n-u\_{n-1} $ with $u\_0 = 1$ and $u\_1 = 6$.
1,508,516
Prove that $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n}$ is an even integer. I'm not sure how to prove that it is an even integer. What would I do for the Inductive Step? And for the basic step, can I plug in zero and prove something from that?
2015/11/01
[ "https://math.stackexchange.com/questions/1508516", "https://math.stackexchange.com", "https://math.stackexchange.com/users/286002/" ]
Base case: $P(0)$ $$ (1 + \sqrt{2})^0 + (1 - \sqrt{2})^0 = 1 + 1 = 2 $$ which is even since $2 = 2\cdot 1$ and of course $1 \in \mathbb{Z}$. Inductive step: Assume true for $P(k)$, i.e. $$ (1 + \sqrt{2})^{2k} + (1 - \sqrt{2})^{2k} $$ is true. Show that $P(k+1)$ is true.
For the basic step, yes, you can plug $n=0$ (and also $n=1$, if you want) and do some computations. On the other hand, for the inductive step you can always use the following equality: $$x^{2n} + y^{2n} = (x^2+y^2)\cdot (x^{2(n-1)} + y^{2(n-1)}) - x^2y^2\cdot (x^{2(n-2)} + y^{2(n-2)})$$ and use *complete induction* (after you have observed that $(1+\sqrt{2})^2(1-\sqrt{2})^2 =1$).
1,508,516
Prove that $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n}$ is an even integer. I'm not sure how to prove that it is an even integer. What would I do for the Inductive Step? And for the basic step, can I plug in zero and prove something from that?
2015/11/01
[ "https://math.stackexchange.com/questions/1508516", "https://math.stackexchange.com", "https://math.stackexchange.com/users/286002/" ]
Base case: $P(0)$ $$ (1 + \sqrt{2})^0 + (1 - \sqrt{2})^0 = 1 + 1 = 2 $$ which is even since $2 = 2\cdot 1$ and of course $1 \in \mathbb{Z}$. Inductive step: Assume true for $P(k)$, i.e. $$ (1 + \sqrt{2})^{2k} + (1 - \sqrt{2})^{2k} $$ is true. Show that $P(k+1)$ is true.
Note that $(1+\sqrt2)(1-\sqrt2) =-1 $ and $(1+\sqrt2)^2 =3+2\sqrt{2} $. Therefore, if $a =3+2\sqrt{2} $, then $1/a = 3-2\sqrt{2} $, so that $a+1/a =6 $ and $(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n} =a^n+1/a^n $. We now use the identity true for any $a$ that $a^{n+1}+1/a^{n+1} =(a+1/a)(a^n+1/a^n)-(a^{n-1}+a^{n-1}) $. Therefore, for this particular $a$, $a^{n+1}+1/a^{n+1} =6(a^n+1/a^n)-(a^{n-1}+a^{n-1}) $. Since $a^n+1/a^n$ is an integer for $n=0$ and $n=1$, it is an integer for all $n$. Explicitly, if $u\_n = a^n+1/a^n =(1+\sqrt2)^{2n} + (1-\sqrt2)^{2n} $, $u\_{n+1} =6u\_n-u\_{n-1} $ with $u\_0 = 1$ and $u\_1 = 6$.
161,346
and now i stuck in using node override with content type. I followed these step. 1. Create new content type name post (machine name: post) 2. Copy node.tpl.php from module to my\_theme/templates/node/node--post.tpl.php 3. Go to admin-configuration-performance and click "Clear all caches" Well, it did not work. Sorry for create duplicated article, but when i followed from answer, it did not work too.
2015/06/10
[ "https://drupal.stackexchange.com/questions/161346", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/48129/" ]
Views comes with a (initially disabled) page that will display your taxonomy terms for you. If you look for "Taxonomy Term" in your views overview you should find it. It will display all of your taxonomy terms through a view. It is recommended that you enable the view, clone it, disable the original and work with the clone, to begin with. However, be careful as it will turn all your taxonomy terms into a views page.
You simply follow the following steps in order to make it work. ![enter image description here](https://i.stack.imgur.com/VZ6Tu.jpg) Now add your dynamic field value say i.e year and pass the argument value as shown below. ![enter image description here](https://i.stack.imgur.com/9xeHI.jpg)
48,740,493
The table has 3 fields and sample data. ``` customerid ordertype countoforders 1 APP 10 1 WEB 20 2 APP 10 3 WEB 10 4 APP 30 5 APP 40 5 WEB 10 ``` I want to retrieve only APP order customers and it counts. How can I write the query for the same? For example from above table APP only customers are 2 and 4.
2018/02/12
[ "https://Stackoverflow.com/questions/48740493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7825252/" ]
Changing the `outputMode` to `complete` solved the issue. ``` val query = theGroupedDF.writeStream .outputMode("complete") .format("console") .start() query.awaitTermination() ```
adding this would solve the problem: ``` val theGroupedDF = theDF .multiplyYieldByHundred .explodeDates .aggregateByValue //code bellow .withColumn("timestamp", current_timestamp()) .withWatermark("timestamp", "10 minutes") ```
1,004,739
***Do not ask me to read the similar questions because I already did and my question is different*** There is an idea about saving the current machine stat in a virtual machine *(virtualizing a physical machine)* and save it in an external storage then install 64 Bit system and install the virtual machine to reinstall all the programs , services , registry keys and the files . So with this way I will be able to upgrade from 32 Bit to 64 Bit without reinstalling my programs , so does anyone of you have any idea about that If it is then share it with me here please ?(I'm using windows 10)
2015/11/24
[ "https://superuser.com/questions/1004739", "https://superuser.com", "https://superuser.com/users/515264/" ]
No, that can't possibly work. The 64-bit versions of those programs and their components *aren't installed on your 32-bit system*. So you have to install them all. When you run an installer on a 32-bit operating system, it installs the 32-bit versions of the program's components in the correct locations for a 32-bit operating system. A 64-bit operating system would require different components in different places. The only way to get them there is to run the installer.
You could use [this](https://technet.microsoft.com/en-us/sysinternals/ee656415.aspx) Microsoft Sysinternals tool to capture a VHD of your Hard Drive(s), which you could then mount onto a virtualisation software ([VMWare Player](https://my.vmware.com/web/vmware/downloads), [Virtualbox](https://www.virtualbox.org/)) to use within the virtual machine. There is no way, however, to 'import' your 32-Bit applications into your 64-Bit Windows 10 install, you'll need to re-download the relevant versions to install onto the new install.
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Addition to @Matthias's answer, you can also use NSCompoundPredicate for your AND operations like this. **Obj-C - AND** ``` NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"]; NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"]; NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2]]; ``` **Swift - AND** ``` let predicate1:NSPredicate = NSPredicate(format: "X == 1") let predicate2:NSPredicate = NSPredicate(format: "Y == 2") let predicate:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2] ) ``` **Swift 3 - AND** ``` let predicate1 = NSPredicate(format: "X == 1") let predicate2 = NSPredicate(format: "Y == 2") let predicateCompound = NSCompoundPredicate(type: .and, subpredicates: [predicate1,predicate2]) ```
This is may be useful if you want to search multiple properties for anything that matches (eg UISearchControllerDelegate): ``` NSString *searchFor = @"foo"; NSArray *fields = @[@"Surname", @"FirstName", @"AKA", @"Nickname"]; // OR'd dictionary fields to search NSMutableArray *predicates = NSMutableArray.new; for (NSString *field in fields) { [predicates addObject:[NSPredicate predicateWithFormat:@"(%K BEGINSWITH[cd] %@)", field, searchFor]]; } NSPredicate *search = [NSCompoundPredicate orPredicateWithSubpredicates:predicates]; ``` You could then use this, for example, to filter an array of dictionaries: ``` NSArray *results = [bigArray filteredArrayUsingPredicate:search]; ``` (the BEGINSWITH[cd] is no magic, just means it'll match beginnings of strings and case-insensitive. Change as needed for your match criteria.)
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
You can append multiple search terms in an `NSPredicate` using the usual boolean operands such as AND/OR. Something like this should do the trick. ``` [NSPredicate predicateWithFormat:@"name contains[cd] %@ OR ssid contains[cd] %@", query, query]; ``` Hope that helps :)
To avoid the warning **Incompatible pointer types initializing 'NSCompoundPredicate \*\_strong' with an expression of type 'NSPredicate \*'**, replace the following: ``` NSCompoundPredicate * predicate = [NSCompoundPredicate orPredicateWithSubPredicates:subPredicates]; ``` with this: ``` NSPredicate * predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; ``` Source: [NSCompoundPredicate](https://stackoverflow.com/questions/13647089/nscompoundpredicate)
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Complete solution for Swift2 ``` let request = NSFetchRequest(entityName: "Location") let subPredicate1 = NSPredicate(format: "(name = %@)", searchString) let subPredicate2 = NSPredicate(format: "(street = %@)", searchString) let subPredicate3 = NSPredicate(format: "(city = %@)", searchString) request.predicate = NSCompoundPredicate(type: .or, subpredicates: [subPredicate1, subPredicate2, subPredicate3]) ```
This is may be useful if you want to search multiple properties for anything that matches (eg UISearchControllerDelegate): ``` NSString *searchFor = @"foo"; NSArray *fields = @[@"Surname", @"FirstName", @"AKA", @"Nickname"]; // OR'd dictionary fields to search NSMutableArray *predicates = NSMutableArray.new; for (NSString *field in fields) { [predicates addObject:[NSPredicate predicateWithFormat:@"(%K BEGINSWITH[cd] %@)", field, searchFor]]; } NSPredicate *search = [NSCompoundPredicate orPredicateWithSubpredicates:predicates]; ``` You could then use this, for example, to filter an array of dictionaries: ``` NSArray *results = [bigArray filteredArrayUsingPredicate:search]; ``` (the BEGINSWITH[cd] is no magic, just means it'll match beginnings of strings and case-insensitive. Change as needed for your match criteria.)
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
To avoid the warning **Incompatible pointer types initializing 'NSCompoundPredicate \*\_strong' with an expression of type 'NSPredicate \*'**, replace the following: ``` NSCompoundPredicate * predicate = [NSCompoundPredicate orPredicateWithSubPredicates:subPredicates]; ``` with this: ``` NSPredicate * predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; ``` Source: [NSCompoundPredicate](https://stackoverflow.com/questions/13647089/nscompoundpredicate)
For Swift: ``` var predicate = NSCompoundPredicate( type: .AndPredicateType, subpredicates: [predicate1, predicate2] ) ```
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Addition to @Matthias's answer, you can also use NSCompoundPredicate for your AND operations like this. **Obj-C - AND** ``` NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"]; NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"]; NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2]]; ``` **Swift - AND** ``` let predicate1:NSPredicate = NSPredicate(format: "X == 1") let predicate2:NSPredicate = NSPredicate(format: "Y == 2") let predicate:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2] ) ``` **Swift 3 - AND** ``` let predicate1 = NSPredicate(format: "X == 1") let predicate2 = NSPredicate(format: "Y == 2") let predicateCompound = NSCompoundPredicate(type: .and, subpredicates: [predicate1,predicate2]) ```
Fraser Hess over at CISMGF.com has a great search example. You can read the post at <http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/> My code based off the post is: ``` NSArray *searchTerms = [searchText componentsSeparatedByString:@" "]; if ([searchTerms count] == 1) { // Search in name and description NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", searchText, searchText]; [self.searchFetchedResultsController.fetchRequest setPredicate:predicate]; } else { // Search in name and description for multiple words NSMutableArray *subPredicates = [[NSMutableArray alloc] init]; for (NSString *term in searchTerms) { NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", term, term]; [subPredicates addObject:pred]; } NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; [self.searchFetchedResultsController.fetchRequest setPredicate:predicate]; } ```
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Complete solution for Swift2 ``` let request = NSFetchRequest(entityName: "Location") let subPredicate1 = NSPredicate(format: "(name = %@)", searchString) let subPredicate2 = NSPredicate(format: "(street = %@)", searchString) let subPredicate3 = NSPredicate(format: "(city = %@)", searchString) request.predicate = NSCompoundPredicate(type: .or, subpredicates: [subPredicate1, subPredicate2, subPredicate3]) ```
Fraser Hess over at CISMGF.com has a great search example. You can read the post at <http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/> My code based off the post is: ``` NSArray *searchTerms = [searchText componentsSeparatedByString:@" "]; if ([searchTerms count] == 1) { // Search in name and description NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", searchText, searchText]; [self.searchFetchedResultsController.fetchRequest setPredicate:predicate]; } else { // Search in name and description for multiple words NSMutableArray *subPredicates = [[NSMutableArray alloc] init]; for (NSString *term in searchTerms) { NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", term, term]; [subPredicates addObject:pred]; } NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; [self.searchFetchedResultsController.fetchRequest setPredicate:predicate]; } ```
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Complete solution for Swift2 ``` let request = NSFetchRequest(entityName: "Location") let subPredicate1 = NSPredicate(format: "(name = %@)", searchString) let subPredicate2 = NSPredicate(format: "(street = %@)", searchString) let subPredicate3 = NSPredicate(format: "(city = %@)", searchString) request.predicate = NSCompoundPredicate(type: .or, subpredicates: [subPredicate1, subPredicate2, subPredicate3]) ```
To avoid the warning **Incompatible pointer types initializing 'NSCompoundPredicate \*\_strong' with an expression of type 'NSPredicate \*'**, replace the following: ``` NSCompoundPredicate * predicate = [NSCompoundPredicate orPredicateWithSubPredicates:subPredicates]; ``` with this: ``` NSPredicate * predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; ``` Source: [NSCompoundPredicate](https://stackoverflow.com/questions/13647089/nscompoundpredicate)
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
Complete solution for Swift2 ``` let request = NSFetchRequest(entityName: "Location") let subPredicate1 = NSPredicate(format: "(name = %@)", searchString) let subPredicate2 = NSPredicate(format: "(street = %@)", searchString) let subPredicate3 = NSPredicate(format: "(city = %@)", searchString) request.predicate = NSCompoundPredicate(type: .or, subpredicates: [subPredicate1, subPredicate2, subPredicate3]) ```
For Swift: ``` var predicate = NSCompoundPredicate( type: .AndPredicateType, subpredicates: [predicate1, predicate2] ) ```
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
You can append multiple search terms in an `NSPredicate` using the usual boolean operands such as AND/OR. Something like this should do the trick. ``` [NSPredicate predicateWithFormat:@"name contains[cd] %@ OR ssid contains[cd] %@", query, query]; ``` Hope that helps :)
Complete solution for Swift2 ``` let request = NSFetchRequest(entityName: "Location") let subPredicate1 = NSPredicate(format: "(name = %@)", searchString) let subPredicate2 = NSPredicate(format: "(street = %@)", searchString) let subPredicate3 = NSPredicate(format: "(city = %@)", searchString) request.predicate = NSCompoundPredicate(type: .or, subpredicates: [subPredicate1, subPredicate2, subPredicate3]) ```
10,611,362
I am trying to use a `UISearchBar` to query multiple properties of a `NSManagedObject` I have a `NSManagedObject` called `Person`, every person has a `name` and `socialSecurity` property. Right now my code can perform a search (fetch) for one of those properties or the other, but not both at the same time. ``` - (void) performFetch { [NSFetchedResultsController deleteCacheWithName:@"Master"]; // Init a fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Apply an ascending sort for the color items //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setSortDescriptors:descriptors]; // Recover query NSString *query = self.searchDisplayController.searchBar.text; //if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query]; if(searchValue==1) { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; } else { if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; } // Init the fetched results controller NSError *error; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil]; self.fetchedResultsController.delegate = self; if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.tableView reloadData]; } ``` I don't know how to put both properties into this statement... ``` if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; ``` Any help or ideas would be greatly appreciated.
2012/05/16
[ "https://Stackoverflow.com/questions/10611362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225266/" ]
You can append multiple search terms in an `NSPredicate` using the usual boolean operands such as AND/OR. Something like this should do the trick. ``` [NSPredicate predicateWithFormat:@"name contains[cd] %@ OR ssid contains[cd] %@", query, query]; ``` Hope that helps :)
You could use a [`NSCompoundPredicate`](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCompoundPredicate_Class/Reference/Reference.html). Like this: ``` NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; NSPredicate *predicateSSID = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query]; NSArray *subPredicates = [NSArray arrayWithObjects:predicateName, predicateSSID, nil]; NSPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; request.predicate = orPredicate; ``` there is a `NSCompoundPredicate` for `AND` too: `andPredicateWithSubpredicates:`
19,994,709
I am making application related to images. I have multiple images on my screen. I had take screen shot of that. But it should not provide my whole screen. Little part of the top most & bottom most part need not be shown in that. I have navigation bar on top. And some buttons at bottom. I don't want to capture that buttons and navigation bar in my screenshot image. Below is my code for screen shot. ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, [UIScreen mainScreen].scale); [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` After taking screenshot I am using it by below code in facebook share method, ``` UIImage *image12 =[self screenshot]; [mySLComposerSheet addImage:image12]; ```
2013/11/15
[ "https://Stackoverflow.com/questions/19994709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2862205/" ]
the easiest way to achieve this would be to add a UIView which holds all the content you want to take a screenshot of and then call `drawViewHierarchyInRect` from that UIView instead of the main UIView. Something like this: ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(contentView.bounds.size, YES, [UIScreen mainScreen].scale); [contentView drawViewHierarchyInRect:contentView.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` Hope this helps!
You can use my below code to take screen shot of a view. I have put the condition to check the size of a screenshot. With this code image is saved in your documents folder and from there you can use your image to share on Facebook or anywhere you want to share. ``` CGSize size = self.view.bounds.size; CGRect cropRect; if ([self isPad]) { cropRect = CGRectMake(110 , 70 , 300 , 300); } else { if (IS_IPHONE_5) { cropRect = CGRectMake(55 , 25 , 173 , 152); } else { cropRect = CGRectMake(30 , 25 , 164 , 141); } } /* Get the entire on screen map as Image */ UIGraphicsBeginImageContext(size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * mapImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); /* Crop the desired region */ CGImageRef imageRef = CGImageCreateWithImageInRect(mapImage.CGImage, cropRect); UIImage * cropImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); /* Save the cropped image UIImageWriteToSavedPhotosAlbum(cropImage, nil, nil, nil);*/ //save to document folder NSData * imageData = UIImageJPEGRepresentation(cropImage, 1.0); NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* documentsDirectory = [paths objectAtIndex:0]; NSString *imagename=[NSString stringWithFormat:@"Pic.jpg"]; NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imagename]; ////NSLog(@"full path %@",fullPathToFile); [imageData writeToFile:fullPathToFile atomically:NO]; ``` Hope it helps you.
19,994,709
I am making application related to images. I have multiple images on my screen. I had take screen shot of that. But it should not provide my whole screen. Little part of the top most & bottom most part need not be shown in that. I have navigation bar on top. And some buttons at bottom. I don't want to capture that buttons and navigation bar in my screenshot image. Below is my code for screen shot. ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, [UIScreen mainScreen].scale); [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` After taking screenshot I am using it by below code in facebook share method, ``` UIImage *image12 =[self screenshot]; [mySLComposerSheet addImage:image12]; ```
2013/11/15
[ "https://Stackoverflow.com/questions/19994709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2862205/" ]
the easiest way to achieve this would be to add a UIView which holds all the content you want to take a screenshot of and then call `drawViewHierarchyInRect` from that UIView instead of the main UIView. Something like this: ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(contentView.bounds.size, YES, [UIScreen mainScreen].scale); [contentView drawViewHierarchyInRect:contentView.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` Hope this helps!
use this code ``` -(IBAction)captureScreen:(id)sender { UIGraphicsBeginImageContext(webview.frame.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil); } ``` sample project [www.cocoalibrary.blogspot.com](http://www.icodeblog.com/wp-content/uploads/2009/07/ScreenCapture1.zip) <http://www.bobmccune.com/2011/09/08/screen-capture-in-ios-apps/>
19,994,709
I am making application related to images. I have multiple images on my screen. I had take screen shot of that. But it should not provide my whole screen. Little part of the top most & bottom most part need not be shown in that. I have navigation bar on top. And some buttons at bottom. I don't want to capture that buttons and navigation bar in my screenshot image. Below is my code for screen shot. ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, [UIScreen mainScreen].scale); [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` After taking screenshot I am using it by below code in facebook share method, ``` UIImage *image12 =[self screenshot]; [mySLComposerSheet addImage:image12]; ```
2013/11/15
[ "https://Stackoverflow.com/questions/19994709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2862205/" ]
the easiest way to achieve this would be to add a UIView which holds all the content you want to take a screenshot of and then call `drawViewHierarchyInRect` from that UIView instead of the main UIView. Something like this: ``` -(UIImage *) screenshot { UIGraphicsBeginImageContextWithOptions(contentView.bounds.size, YES, [UIScreen mainScreen].scale); [contentView drawViewHierarchyInRect:contentView.frame afterScreenUpdates:YES]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } ``` Hope this helps!
snapshotViewAfterScreenUpdates but it is only Available in **iOS 7.0 and later**. ``` - (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates ``` This method captures the current visual contents of the screen from the render server and uses them to build a new snapshot view. You can use the returned snapshot view as a visual stand-in for the screen’s contents in your app. For example, you might use a snapshot view to facilitate a full screen animation. Because the content is captured from the already rendered content, this method reflects the current visual appearance of the screen and is not updated to reflect animations that are scheduled or in progress. However, this method is faster than trying to render the contents of the screen into a bitmap image yourself. [https://developer.apple.com/library/ios/documentation/uikit/reference/UIScreen\_Class/Reference/UIScreen.html#//apple\_ref/occ/instm/UIScreen/snapshotViewAfterScreenUpdates:](https://developer.apple.com/library/ios/documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html#//apple_ref/occ/instm/UIScreen/snapshotViewAfterScreenUpdates%3a)
65,361,194
I'm doing some requests through some proxy servers. The function that defines which proxy url to use will choose randomly from a list of proxies. I would like to know for a given request, which proxy url is being used. As far as I know, when using a proxy server the http headers remain the same, but the tcp headers are the one that change. Here's some code illustrating it (no error handling for simplicity): ``` func main() { transport := &http.Transport{Proxy: chooseProxy} client := http.Client{Transport: transport} request, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil) checkErr(err) // How to know here which proxy was used? Suppose the same client will perform several requests to different URL's. response, err := client.Do(request) checkErr(err) dump, _ := httputil.DumpRequest(response.Request, false) fmt.Println(dump) } func chooseProxy(request *http.Request) (*url.URL, error) { proxies := []string{"proxy1", "proxy2", "proxy3"} proxyToUse := proxies[rand.Intn(len(proxies))] return url.Parse(proxyToUse) } ``` I'm assuming that the Proxy function in the transport is called for each request even if the same client is used, as per the docs that say "Proxy specifies a function to return a proxy for a given Request". Am I right?
2020/12/18
[ "https://Stackoverflow.com/questions/65361194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11518830/" ]
Some HTTP proxies add a `Via` header that tell who they are. <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via>
The request which contains the target URI is given as argument `request` to `chooseProxy`. So you can have the correct mapping already inside your `chooseProxy` function, all you need to to is check `proxyToUse` vs. `request.URL` there. If you don't really trust the code that this mapping is actually done, then you need to look outside the code. For example you can look at the actual network traffic with Wireshark to see which proxy gets accessed.
65,361,194
I'm doing some requests through some proxy servers. The function that defines which proxy url to use will choose randomly from a list of proxies. I would like to know for a given request, which proxy url is being used. As far as I know, when using a proxy server the http headers remain the same, but the tcp headers are the one that change. Here's some code illustrating it (no error handling for simplicity): ``` func main() { transport := &http.Transport{Proxy: chooseProxy} client := http.Client{Transport: transport} request, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil) checkErr(err) // How to know here which proxy was used? Suppose the same client will perform several requests to different URL's. response, err := client.Do(request) checkErr(err) dump, _ := httputil.DumpRequest(response.Request, false) fmt.Println(dump) } func chooseProxy(request *http.Request) (*url.URL, error) { proxies := []string{"proxy1", "proxy2", "proxy3"} proxyToUse := proxies[rand.Intn(len(proxies))] return url.Parse(proxyToUse) } ``` I'm assuming that the Proxy function in the transport is called for each request even if the same client is used, as per the docs that say "Proxy specifies a function to return a proxy for a given Request". Am I right?
2020/12/18
[ "https://Stackoverflow.com/questions/65361194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11518830/" ]
You can modify your chooseProxy function so that it saves the proxy selected. To do that, you can transform the chooseProxy func into a method of a type that will be used as storage for the information you want to keep: ``` type proxySelector string func (sel *proxySelector) chooseProxy(request *http.Request) (*url.URL, error) { proxies := []string{"proxy1", "proxy2", "proxy3"} proxyToUse := proxies[rand.Intn(len(proxies))] *sel = proxySelector(proxyToUse) // <----- return url.Parse(proxyToUse) } func main() { var proxy proxySelector transport := &http.Transport{Proxy: proxy.chooseProxy} // <----- client := http.Client{Transport: transport} request, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil) checkErr(err) // How to know here which proxy was used? Suppose the same client will perform several requests to different URL's. response, err := client.Do(request) checkErr(err) dump, _ := httputil.DumpRequest(response.Request, false) fmt.Println(dump) fmt.Println("Proxy:", string(proxy)) // <----- } ```
The request which contains the target URI is given as argument `request` to `chooseProxy`. So you can have the correct mapping already inside your `chooseProxy` function, all you need to to is check `proxyToUse` vs. `request.URL` there. If you don't really trust the code that this mapping is actually done, then you need to look outside the code. For example you can look at the actual network traffic with Wireshark to see which proxy gets accessed.
12,971,280
In my application i set some animations in View1's view load() ,At first launch its working propely,if im pushed into otherview ,and while pop into view1 its not animating,What shoud i do for animate while pop view from other view?here my view did load code, ``` - (void)viewDidLoad { artext=[[NSMutableArray alloc] init]; arimage=[[NSMutableArray alloc] init]; arsound=[[NSMutableArray alloc] init]; [super viewDidLoad]; [self copysqlitetodocuments]; [self Readthesqlitefile]; self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"classroom.png"]]; } ``` i tried with ``` - (void)viewDidAppear:(BOOL)animated { [self buttonmover]; [super viewDidAppear:animated]; } ``` its not working,Can any one pls help me to solve this problem
2012/10/19
[ "https://Stackoverflow.com/questions/12971280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1656298/" ]
try another way to integerate twitter in your app 1. Using auth & webview(Twitter4j library) <http://davidcrowley.me/?p=410> <http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/> code(url open in web view) ``` twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY, TwitterConstants.CONSUMER_SECRET); RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); System.out.println("requesttoken"+requestToken); } catch (TwitterException e) { e.printStackTrace(); } twitterUrl = requestToken.getAuthorizationURL(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN); builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET); builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY); builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET); OAuthAuthorization auth = new OAuthAuthorization(builder.build()); twitter = new TwitterFactory().getInstance(auth); try { twitter.updateStatus("Hello World!"); } catch (TwitterException e) { System.err.println("Error occurred while updating the status!"); } ``` 2. On Button Click(Without auth) ``` String message=""; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message))); startActivity(i); ```
Please put following permission in your Manifest file ``` <uses-permission android:name="android.permission.INTERNET"/> ``` also check this link.... <http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application>
304,459
I have a Dissemination Areas boundaries shapefile with has an attribute table full of data needed for lowest quartile analysis and I have a neighborhood shapefile which has lowest income data which also needs to be considered but am not sure how I can combine these shapefiles so I can consider both the lowest income neighborhood data as well as the dissemination area data in my analysis of worst overall dissemination areas. I tried spatial joining but they don't share a similar value.
2018/11/29
[ "https://gis.stackexchange.com/questions/304459", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/92028/" ]
This depends of course completely on your data. Let's take into account the following 4 topologies (<https://pro.arcgis.com/de/pro-app/tool-reference/data-management/select-by-location-graphical-examples.htm>): 1. Distinct 2. Dissemination COMPLETELY\_CONTAINS neighborhood 3. Dissemination INTERSECT neighborhood 4. Dissemination COMPLETELY\_WITHIN neighborhood [![enter image description here](https://i.stack.imgur.com/JwGFJ.png)](https://i.stack.imgur.com/JwGFJ.png) Then for the first option in the spatial join window (sorry for the German) the join will work for the cases 2-4. The count column shows how many neigborhoods intersects the Dissemination areas. If there are more you need to decide if you want to have mean, max, min ect. The second option of the spatial join only joins if case 4 is true. **NOTE:** The Geometry of the Dissemination areas will not change, only attributes are joined. [![enter image description here](https://i.stack.imgur.com/cQD3X.png)](https://i.stack.imgur.com/cQD3X.png)
I don't think you can spatial join if your geometries do not overlap somewhere. The way I would do it is to convert your boundaries (lines) to polygons, merge them and then you would have your data merged as well. Just check if your boundaries are closed and isolate them before.
26,076
A search finds no words to the copyrighted song title.
2017/01/15
[ "https://writers.stackexchange.com/questions/26076", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/23016/" ]
This is not a copyright question, it is a contract question. You signed a contract with them. The terms of the contract tell you what you can and can't do. No one here can tell you what your contract says. Find it and read it. If you are uncertain how to interpret it, ask a lawyer.
Vanity presses make money from authors, not from selling copies, so there's at least a decent chance you've kept or can get back your copyright. Unfortunately, if you didn't study your contract to begin with, and they've proven so very poor, they're probably optimized mostly to wring more money out of you :-/ You need to check your contract to look for: * **Who owns copyright.** * **Who owns the book design,** which is different from who owns copyright over the text. * **Rights reversion or contract termination,** which are the procedures to get back copyright from them if you've sold it. * (I have also found [reference](http://www.fictionfactor.com/self/vanity.html) to an abhorrent practice where they don't claim copyright, but *do* stipulate that "that "Author agrees that 1st Books indefinitely will retain possession of the materials submitted by Author to 1st Books and used to format the Work." i.e., your manuscript. I am not a lawyer and don't know if such terms can be challenged or interpreted more reasonably.) This should, at least, help you know where you stand. The other thing that can be very helpful is to search Google for stories of others in the same situation, with the same publisher. Try googling "[publisher name] scam". You might find others who have already dealt with this successfully. Best of luck to you.
58,943
I have a web application where (among other things) customers can upload files and administrators can then download those files. The uploaded files are stored on `ServerA` and the web application used to upload/download those files runs on `ServerB`. I would like to make it so that while the files are stored on `ServerA` they are encrypted and that only the web application can encrypt/decrypt, but my concern is that there might not be an effective way to store an encryption key, which would make the file encryption mostly for show. I came across [this question/answer](https://security.stackexchange.com/questions/12332/where-to-store-a-key-for-encryption) which suggested some good ways to securely store a key, but I think that the most secure ones do not apply since I need different people to be able to decrypt the file. For example, I cannot create a key based on user credentials, because customers must be able to encrypt all admin users must be able to decrypt (right?). From what I can tell, my best option is to store the encrypted files on one server and store the encryption key in the code on my web server, but this does not seem particularly secure. It seems likely that if a malicious user gains access to one server they probably gain access to both. My question - is it even worth implementing "encrypted files on ServerA" and "encryption key on ServerB", or would I just be kidding myself to think this is more secure? Is there an effective way to encrypt files based on the conditions that I laid out above?
2014/05/28
[ "https://security.stackexchange.com/questions/58943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/5169/" ]
The most effective method is to use secure hardware to store the key. You can get SSL accelerators that will securely store and process keys onboard so that they never leave the secure hardware module. Relatively expensive and requires you to have physical access to the hardware (so no VPS or cloud solutions).
You can use public key/asymmetric encryption, for example using the gnupg program. The administrator generates a public/private key pair, and stores the private key somewhere safe (possibly on neither ServerA nor ServerB). You can store the public key anywhere, and in particular on the web server, where it will be used to encrypt uploaded files. Once encrypted, you can store the (encrypted version of the) uploaded files on either ServerA or ServerB; either way, without the private key, it won't be possible to read them. To view the files, the administrator can copy an uploaded file to a trusted computer and then use the private key to decrypt.
58,943
I have a web application where (among other things) customers can upload files and administrators can then download those files. The uploaded files are stored on `ServerA` and the web application used to upload/download those files runs on `ServerB`. I would like to make it so that while the files are stored on `ServerA` they are encrypted and that only the web application can encrypt/decrypt, but my concern is that there might not be an effective way to store an encryption key, which would make the file encryption mostly for show. I came across [this question/answer](https://security.stackexchange.com/questions/12332/where-to-store-a-key-for-encryption) which suggested some good ways to securely store a key, but I think that the most secure ones do not apply since I need different people to be able to decrypt the file. For example, I cannot create a key based on user credentials, because customers must be able to encrypt all admin users must be able to decrypt (right?). From what I can tell, my best option is to store the encrypted files on one server and store the encryption key in the code on my web server, but this does not seem particularly secure. It seems likely that if a malicious user gains access to one server they probably gain access to both. My question - is it even worth implementing "encrypted files on ServerA" and "encryption key on ServerB", or would I just be kidding myself to think this is more secure? Is there an effective way to encrypt files based on the conditions that I laid out above?
2014/05/28
[ "https://security.stackexchange.com/questions/58943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/5169/" ]
You can use public key/asymmetric encryption, for example using the gnupg program. The administrator generates a public/private key pair, and stores the private key somewhere safe (possibly on neither ServerA nor ServerB). You can store the public key anywhere, and in particular on the web server, where it will be used to encrypt uploaded files. Once encrypted, you can store the (encrypted version of the) uploaded files on either ServerA or ServerB; either way, without the private key, it won't be possible to read them. To view the files, the administrator can copy an uploaded file to a trusted computer and then use the private key to decrypt.
A way you can tie user credentials to the key is by having one key for the encrypted file, and encrypting that key multiple times with key based on each user's credentials. You'll have a ton of small key files (one per user), and each user who has access can decrypt the key to use in order to decrypt the final file.
58,943
I have a web application where (among other things) customers can upload files and administrators can then download those files. The uploaded files are stored on `ServerA` and the web application used to upload/download those files runs on `ServerB`. I would like to make it so that while the files are stored on `ServerA` they are encrypted and that only the web application can encrypt/decrypt, but my concern is that there might not be an effective way to store an encryption key, which would make the file encryption mostly for show. I came across [this question/answer](https://security.stackexchange.com/questions/12332/where-to-store-a-key-for-encryption) which suggested some good ways to securely store a key, but I think that the most secure ones do not apply since I need different people to be able to decrypt the file. For example, I cannot create a key based on user credentials, because customers must be able to encrypt all admin users must be able to decrypt (right?). From what I can tell, my best option is to store the encrypted files on one server and store the encryption key in the code on my web server, but this does not seem particularly secure. It seems likely that if a malicious user gains access to one server they probably gain access to both. My question - is it even worth implementing "encrypted files on ServerA" and "encryption key on ServerB", or would I just be kidding myself to think this is more secure? Is there an effective way to encrypt files based on the conditions that I laid out above?
2014/05/28
[ "https://security.stackexchange.com/questions/58943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/5169/" ]
You can use public key/asymmetric encryption, for example using the gnupg program. The administrator generates a public/private key pair, and stores the private key somewhere safe (possibly on neither ServerA nor ServerB). You can store the public key anywhere, and in particular on the web server, where it will be used to encrypt uploaded files. Once encrypted, you can store the (encrypted version of the) uploaded files on either ServerA or ServerB; either way, without the private key, it won't be possible to read them. To view the files, the administrator can copy an uploaded file to a trusted computer and then use the private key to decrypt.
Let's say that users A, B, C and D want to share files with each other on a remote location. Each user generates a pair of public and private keys (let's say RSA1024/2048 bit). Each user publishes his public key on the remote server. Now let's say that A wants to share a file with B and C, but not with D. A will create a symmetric encryption key (let's say AES-256, symmetric because they're faster). A then continue to encrypt the file with the symmetric key he just created for that purpose. He then encrypts the key 3 separate times: once with his own public key, once with B's public key, and once with C's public key. A then uploads the encrypted file and and all of the different encryptions of the symmetric key to the remote server. The remote server doesn't know how to open these files and he doesn't need to. When B asks for the file, he receives the encrypted file and the symmetric key that was encrypted with B's public key. B can now go on and open the file. Note that we require a different symmetric key for every file because we want to control the sharing on a per-file basis. The only problem with this method is that now A,B,C and D need to keep a private key somewhere. If you don't want them to store the private key themselves, you encrypt the private key with a password protected encryption (which is different from their login password) and store the password protected private key on the same (or different) server. Now, whenever a user logs on, he will have to first download his password protected private key and open it with another password prompt.
58,943
I have a web application where (among other things) customers can upload files and administrators can then download those files. The uploaded files are stored on `ServerA` and the web application used to upload/download those files runs on `ServerB`. I would like to make it so that while the files are stored on `ServerA` they are encrypted and that only the web application can encrypt/decrypt, but my concern is that there might not be an effective way to store an encryption key, which would make the file encryption mostly for show. I came across [this question/answer](https://security.stackexchange.com/questions/12332/where-to-store-a-key-for-encryption) which suggested some good ways to securely store a key, but I think that the most secure ones do not apply since I need different people to be able to decrypt the file. For example, I cannot create a key based on user credentials, because customers must be able to encrypt all admin users must be able to decrypt (right?). From what I can tell, my best option is to store the encrypted files on one server and store the encryption key in the code on my web server, but this does not seem particularly secure. It seems likely that if a malicious user gains access to one server they probably gain access to both. My question - is it even worth implementing "encrypted files on ServerA" and "encryption key on ServerB", or would I just be kidding myself to think this is more secure? Is there an effective way to encrypt files based on the conditions that I laid out above?
2014/05/28
[ "https://security.stackexchange.com/questions/58943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/5169/" ]
The most effective method is to use secure hardware to store the key. You can get SSL accelerators that will securely store and process keys onboard so that they never leave the secure hardware module. Relatively expensive and requires you to have physical access to the hardware (so no VPS or cloud solutions).
A way you can tie user credentials to the key is by having one key for the encrypted file, and encrypting that key multiple times with key based on each user's credentials. You'll have a ton of small key files (one per user), and each user who has access can decrypt the key to use in order to decrypt the final file.
58,943
I have a web application where (among other things) customers can upload files and administrators can then download those files. The uploaded files are stored on `ServerA` and the web application used to upload/download those files runs on `ServerB`. I would like to make it so that while the files are stored on `ServerA` they are encrypted and that only the web application can encrypt/decrypt, but my concern is that there might not be an effective way to store an encryption key, which would make the file encryption mostly for show. I came across [this question/answer](https://security.stackexchange.com/questions/12332/where-to-store-a-key-for-encryption) which suggested some good ways to securely store a key, but I think that the most secure ones do not apply since I need different people to be able to decrypt the file. For example, I cannot create a key based on user credentials, because customers must be able to encrypt all admin users must be able to decrypt (right?). From what I can tell, my best option is to store the encrypted files on one server and store the encryption key in the code on my web server, but this does not seem particularly secure. It seems likely that if a malicious user gains access to one server they probably gain access to both. My question - is it even worth implementing "encrypted files on ServerA" and "encryption key on ServerB", or would I just be kidding myself to think this is more secure? Is there an effective way to encrypt files based on the conditions that I laid out above?
2014/05/28
[ "https://security.stackexchange.com/questions/58943", "https://security.stackexchange.com", "https://security.stackexchange.com/users/5169/" ]
The most effective method is to use secure hardware to store the key. You can get SSL accelerators that will securely store and process keys onboard so that they never leave the secure hardware module. Relatively expensive and requires you to have physical access to the hardware (so no VPS or cloud solutions).
Let's say that users A, B, C and D want to share files with each other on a remote location. Each user generates a pair of public and private keys (let's say RSA1024/2048 bit). Each user publishes his public key on the remote server. Now let's say that A wants to share a file with B and C, but not with D. A will create a symmetric encryption key (let's say AES-256, symmetric because they're faster). A then continue to encrypt the file with the symmetric key he just created for that purpose. He then encrypts the key 3 separate times: once with his own public key, once with B's public key, and once with C's public key. A then uploads the encrypted file and and all of the different encryptions of the symmetric key to the remote server. The remote server doesn't know how to open these files and he doesn't need to. When B asks for the file, he receives the encrypted file and the symmetric key that was encrypted with B's public key. B can now go on and open the file. Note that we require a different symmetric key for every file because we want to control the sharing on a per-file basis. The only problem with this method is that now A,B,C and D need to keep a private key somewhere. If you don't want them to store the private key themselves, you encrypt the private key with a password protected encryption (which is different from their login password) and store the password protected private key on the same (or different) server. Now, whenever a user logs on, he will have to first download his password protected private key and open it with another password prompt.
24,497,571
I have two applications. The first is used as an internal user management application that was developed to for multiple applications to use as a central authentication service. It is placed in an IFrame inside the second application. The second application is the application users are logging into after they have been authenticated. My problem is the show password eye icon in IE10. I have the CSS code in the central authentication app to hide the eye icon. ``` .input::-ms-reveal { display:none; } ``` When I run just the central authentication app, the eye icon is hidden. However when I run the second app, with the central authentication app inside an IFrame, the CSS appears to be overridden and the eye icon is visible. Has anyone encounter this before and what was your solution?
2014/06/30
[ "https://Stackoverflow.com/questions/24497571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166672/" ]
As of XML 3.98-1.4 and R 3.1 on Win7, this problem can be solved perfectly by using the function `free()`. But it does not work with `readHTMLTable()`. The following code works perfectly. ``` library(XML) a = readLines("http://en.wikipedia.org/wiki/2014_FIFA_World_Cup") while(TRUE){ b = xmlParse(paste(a, collapse = "")) #do something with b free(b) } ``` The xml2 package has similar issues and the memory can be released by using the function `remove_xml()` followed by `gc()`.
I had a lot of problems with memory leaks in the XML pakackage too (under both windows and linux), but the way I solved it eventually was to remove the object at the end of each processing step, i.e. add a rm(b) and a gc() at the end of each iteration. Let me know if this works for you too.
24,497,571
I have two applications. The first is used as an internal user management application that was developed to for multiple applications to use as a central authentication service. It is placed in an IFrame inside the second application. The second application is the application users are logging into after they have been authenticated. My problem is the show password eye icon in IE10. I have the CSS code in the central authentication app to hide the eye icon. ``` .input::-ms-reveal { display:none; } ``` When I run just the central authentication app, the eye icon is hidden. However when I run the second app, with the central authentication app inside an IFrame, the CSS appears to be overridden and the eye icon is visible. Has anyone encounter this before and what was your solution?
2014/06/30
[ "https://Stackoverflow.com/questions/24497571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166672/" ]
As of XML 3.98-1.4 and R 3.1 on Win7, this problem can be solved perfectly by using the function `free()`. But it does not work with `readHTMLTable()`. The following code works perfectly. ``` library(XML) a = readLines("http://en.wikipedia.org/wiki/2014_FIFA_World_Cup") while(TRUE){ b = xmlParse(paste(a, collapse = "")) #do something with b free(b) } ``` The xml2 package has similar issues and the memory can be released by using the function `remove_xml()` followed by `gc()`.
Same problem here, even doing nothing more than reading in the document with `doc <- xmlParse(...); root <- xmlRoot(doc)`, the memory allocated to `doc` is just never released to the O/S (as monitored in Windows' Task Manager). A crazy idea that we might try is to employ `system("Rscript ...")` to perform the XML parsing in a separate R session, saving the parsed R object to a file, which we then read in in the main R session. Hacky but it would at least ensure that whatever memory is gobbled up by the XML parsing, is released when the Rscript session terminates and doesn't affect the main process!
12,577,851
Please help to resolve this error illegal string offset 'tittle' here goes the jquery ``` data:{option:'catapply',sr:$(":input").serialize()}, ``` and the catapply php data ``` if($_REQUEST['option']=='catapply'){ $sc = serialize($_POST['sr']); mysql_query("insert into user_data(uid,mid,cid,scid,data) values('$session->userid','5','5','5','$sc')"); ``` now i am unserializing the above data in db stored by using the above method ``` $sql = mysql_query("SELECT * from user_data where uid='$session->userid'"); while ($row = mysql_fetch_array($sql)) { $un=unserialize($row['data']); $tittle=$un['tittle']; echo $tittle; ```
2012/09/25
[ "https://Stackoverflow.com/questions/12577851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393355/" ]
Try this ``` dtpTime.Format = DateTimePickerFormat.Custom dtpTime.CustomFormat = "hh:mm tt" ```
try this: ``` Private Sub mainform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Timer1.Enabled = True End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Label7.Text = DateTime.Now.ToString("MMM dd yyyy hh:mm:ss tt") End Sub ```
12,577,851
Please help to resolve this error illegal string offset 'tittle' here goes the jquery ``` data:{option:'catapply',sr:$(":input").serialize()}, ``` and the catapply php data ``` if($_REQUEST['option']=='catapply'){ $sc = serialize($_POST['sr']); mysql_query("insert into user_data(uid,mid,cid,scid,data) values('$session->userid','5','5','5','$sc')"); ``` now i am unserializing the above data in db stored by using the above method ``` $sql = mysql_query("SELECT * from user_data where uid='$session->userid'"); while ($row = mysql_fetch_array($sql)) { $un=unserialize($row['data']); $tittle=$un['tittle']; echo $tittle; ```
2012/09/25
[ "https://Stackoverflow.com/questions/12577851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393355/" ]
Try this ``` dtpTime.Format = DateTimePickerFormat.Custom dtpTime.CustomFormat = "hh:mm tt" ```
Make sure that in Windows settings you also have set time format properly to display AM/PM. Time format in Windows should be also set to H:mm tt to display your result properly.
12,577,851
Please help to resolve this error illegal string offset 'tittle' here goes the jquery ``` data:{option:'catapply',sr:$(":input").serialize()}, ``` and the catapply php data ``` if($_REQUEST['option']=='catapply'){ $sc = serialize($_POST['sr']); mysql_query("insert into user_data(uid,mid,cid,scid,data) values('$session->userid','5','5','5','$sc')"); ``` now i am unserializing the above data in db stored by using the above method ``` $sql = mysql_query("SELECT * from user_data where uid='$session->userid'"); while ($row = mysql_fetch_array($sql)) { $un=unserialize($row['data']); $tittle=$un['tittle']; echo $tittle; ```
2012/09/25
[ "https://Stackoverflow.com/questions/12577851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393355/" ]
Try this ``` dtpTime.Format = DateTimePickerFormat.Custom dtpTime.CustomFormat = "hh:mm tt" ```
I have the same issue. This for the "Why" : Actually according to MS : <https://support2.microsoft.com/Default.aspx?scid=kb%3ben-us%3b889834&x=18&y=19> Date picker don't use the current thread culture : it uses the user regional settings. SO if you force the date picker custom format something containing "tt", and if the user regional setting doesnt have any designator ... well it won't be shown.
12,577,851
Please help to resolve this error illegal string offset 'tittle' here goes the jquery ``` data:{option:'catapply',sr:$(":input").serialize()}, ``` and the catapply php data ``` if($_REQUEST['option']=='catapply'){ $sc = serialize($_POST['sr']); mysql_query("insert into user_data(uid,mid,cid,scid,data) values('$session->userid','5','5','5','$sc')"); ``` now i am unserializing the above data in db stored by using the above method ``` $sql = mysql_query("SELECT * from user_data where uid='$session->userid'"); while ($row = mysql_fetch_array($sql)) { $un=unserialize($row['data']); $tittle=$un['tittle']; echo $tittle; ```
2012/09/25
[ "https://Stackoverflow.com/questions/12577851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393355/" ]
I have the same issue. This for the "Why" : Actually according to MS : <https://support2.microsoft.com/Default.aspx?scid=kb%3ben-us%3b889834&x=18&y=19> Date picker don't use the current thread culture : it uses the user regional settings. SO if you force the date picker custom format something containing "tt", and if the user regional setting doesnt have any designator ... well it won't be shown.
try this: ``` Private Sub mainform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Timer1.Enabled = True End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Label7.Text = DateTime.Now.ToString("MMM dd yyyy hh:mm:ss tt") End Sub ```
12,577,851
Please help to resolve this error illegal string offset 'tittle' here goes the jquery ``` data:{option:'catapply',sr:$(":input").serialize()}, ``` and the catapply php data ``` if($_REQUEST['option']=='catapply'){ $sc = serialize($_POST['sr']); mysql_query("insert into user_data(uid,mid,cid,scid,data) values('$session->userid','5','5','5','$sc')"); ``` now i am unserializing the above data in db stored by using the above method ``` $sql = mysql_query("SELECT * from user_data where uid='$session->userid'"); while ($row = mysql_fetch_array($sql)) { $un=unserialize($row['data']); $tittle=$un['tittle']; echo $tittle; ```
2012/09/25
[ "https://Stackoverflow.com/questions/12577851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1393355/" ]
I have the same issue. This for the "Why" : Actually according to MS : <https://support2.microsoft.com/Default.aspx?scid=kb%3ben-us%3b889834&x=18&y=19> Date picker don't use the current thread culture : it uses the user regional settings. SO if you force the date picker custom format something containing "tt", and if the user regional setting doesnt have any designator ... well it won't be shown.
Make sure that in Windows settings you also have set time format properly to display AM/PM. Time format in Windows should be also set to H:mm tt to display your result properly.
3,118,985
Ive been learning MVC2 and MVVM lately and I think it works like this. ASP.NET MVC2 - Can test the whole web site using unit tests ASP.NET MVC2 + jquery web service calls - Can no longer just use MSTest unit test. What is the MS product to test the javascript side? ASP.NET Webforms - Unit Tests are near impossible when the coder doesnt create the Webforms site with Testing in mind. Therefore Asp.NET web performance tests are the closest thing to testing that is realistic. Coded UI Tests are too trivial to really be useful for things like ASP.NET validators. ASP.NET Webforms + jquery web service calls - Can only unit test the web service calls. Cannot use Web Performance tests because of javsscript calls. Need some sort of javascript testing framework. Silverlight - No tests. Maybe Coded UI Tests. Silverlight MVVM - Use silverlight unit test framework to test ViewModel similiar to MVC. Silverlight MEF - How does MEF affect testing scenerios if at all ? Is this accurate? Is there anything I am missing ? I am trying to make a argument to the people in charge that we should use MVC over Webforms so that we can create automated testing. As it is we are doing Webforms all in one project and impossible to test so people just test off of manual scripts :(
2010/06/25
[ "https://Stackoverflow.com/questions/3118985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193189/" ]
Rather than specifying the reasons why you should use MVC over Webforms, I'd take a step back and sell the management team on why you should use unit tests. After that's sold you have a case of saying that MVC would allow you to do this more efficiently than webforms. Are you looking at going the full TDD route, or just creating tests after? I'd highly recommend going down the TDD path even though it does have a steeper learning curve and will lessen your productivity while you are learning it. Since you are already looking into testing, you probably know most of these, but I'll re-iterate some of the benefits: Less defects get through to QA. Tests can be created for issues that QA and customers find. Designing for testing creates a more loosely coupled application which tend to be more maintainable. Increased developer confidence when making changes leading to sustained productivity as the application code base matures. Tests are great documentation for new developers joining the project, as they can see what's trying to be achieved. Note: the cost of fixing a defect that has made it through to production can be up to 80 x the cost of finding and fixing it in the development and QA process (I'll try to find my source for that figure). Unit testing is only one piece of the puzzle though, you'll also want to look at using a Continuous Integration server such as CruiseControl.NET to automate your builds and tests. This will make sure that everyone keeps the build in a working state. For an existing Webforms project you might also want to look into the Web Client Software Factory. I've found it to be very useful for migrating legacy webforms apps over time, though it's a little more convoluted than MVC2.
I don't know about other technologies, but I can talk about using Silverlight with MVVM pattern. Using MVVM pattern along with command pattern, we have been able to unit test all of our C# code. I mean barring xaml code, we have a very high code coverage for our C# code. We actually use a modified version of MVVM wherein we also use a controller. If you ensure that you have no code in code-behind files, you can simulate button click/other such UI events. This is very useful for integration tests. We have found out that our pattern of MVVM along with controller and using command pattern facilitates unit testing.
48,820,207
I want to know that is there any way in the git by which we can pull a particular folder or a particular file from the git. Thanks in advance.
2018/02/16
[ "https://Stackoverflow.com/questions/48820207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7305772/" ]
For now, you have to fetch everything, and: * either do a [shallow clone](https://git-scm.com/docs/git-clone#git-clone---depthltdepthgt) * or copy what you need from the cloned repo in another working folder. But that won't always be the case. A future 2.16.x/2.17 Q2 2018 Git will introduce what is called a partial clone (or narrow clone) See See [commit 3aa6694](https://github.com/git/git/commit/3aa6694fb3d38a3afe623ccbdf59fb15f338a94d), [commit aa57b87](https://github.com/git/git/commit/aa57b871dad3cca07abead9a8d1fefceffe7578d), [commit 35a7ae9](https://github.com/git/git/commit/35a7ae952ffee0d47d4f6302163488abea3bf418), [commit 1e1e39b](https://github.com/git/git/commit/1e1e39b308fe9dd68a3312992a06270da7dd07af), [commit acb0c57](https://github.com/git/git/commit/acb0c57260aa78fc99939de2a27c48b5a3fb4f21), [commit bc2d0c3](https://github.com/git/git/commit/bc2d0c3396fad7b7064c6e9599e6321742538aa0), [commit 640d8b7](https://github.com/git/git/commit/640d8b72feaae0b96d5faa663ad624963e416d54), [commit 10ac85c](https://github.com/git/git/commit/10ac85c785afed4163ed931149a87b30c7c5eaf9) (08 Dec 2017) by [Jeff Hostetler (`jeffhostetler`)](https://github.com/jeffhostetler). See [commit a1c6d7c](https://github.com/git/git/commit/a1c6d7c1a792bd2c60bbfb07597d13f7d0c4eb37), [commit c0c578b](https://github.com/git/git/commit/c0c578b33ca48ee6003d85706e13d97d12781354), [commit 548719f](https://github.com/git/git/commit/548719fbdc4ccd5d678afafbb5e3b5c8dac28489), [commit a174334](https://github.com/git/git/commit/a1743343f410290578fbd6e0ada50b8cdf1e7df8), [commit 0b6069f](https://github.com/git/git/commit/0b6069fe0a1e694d632e54a43fc6e546e83edad6) (08 Dec 2017) by [Jonathan Tan (`jhowtan`)](https://github.com/jhowtan). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 6bed209](https://github.com/git/git/commit/6bed209a20a06f2d6b7142216dabff456de798e1), 13 Feb 2018) See the [tests for a partial clone here](https://github.com/git/git/commit/35a7ae952ffee0d47d4f6302163488abea3bf418): ``` git clone --no-checkout --filter=blob:none "file://$(pwd)/srv.bare" pc1 ``` --- Combine that with the [Git 2.25 (Q1 2020) `git sparse-checkout` command](https://stackoverflow.com/a/59515426/6309). See more with "[**Bring your monorepo down to size with sparse-checkout**](https://twitter.com/stolee)" from **[Derrick Stolee](https://twitter.com/stolee)** > > Pairing sparse-checkout with the **[partial clone feature](https://git-scm.com/docs/partial-clone)** accelerates these workflows even more. > > This combination speeds up the data transfer process since you don’t need every reachable Git object, and instead, can download only those you need to populate your cone of the working directory > > > ``` $ git clone --filter=blob:none --no-checkout https://github.com/derrickstolee/sparse-checkout-example Cloning into 'sparse-checkout-example'... Receiving objects: 100% (373/373), 75.98 KiB | 2.71 MiB/s, done. Resolving deltas: 100% (23/23), done. $ cd sparse-checkout-example/ $ git sparse-checkout init --cone Receiving objects: 100% (3/3), 1.41 KiB | 1.41 MiB/s, done. $ git sparse-checkout set client/android Receiving objects: 100% (26/26), 985.91 KiB | 5.76 MiB/s, done. ``` --- With Git 2.31 (Q1 2021), fix in passing custom args from "[`git clone`](https://github.com/git/git/blob/60f81219403d708ab6271f68d8e4e42a39f7459b/Documentation/git-clone.txt)"([man](https://git-scm.com/docs/git-clone)) to `upload-pack` on the other side. See [commit ad6b5fe](https://github.com/git/git/commit/ad6b5fefbd15f08a32145e77d0c08394c7f17b9c) (02 Feb 2021), and [commit ad5df6b](https://github.com/git/git/commit/ad5df6b782a13854c9ae9d273dd03c5b935ed7cb) (28 Jan 2021) by [Jacob Vosmaer (`jacobvosmaer`)](https://github.com/jacobvosmaer). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 60f8121](https://github.com/git/git/commit/60f81219403d708ab6271f68d8e4e42a39f7459b), 12 Feb 2021) > > [`upload-pack.c`](https://github.com/git/git/commit/ad5df6b782a13854c9ae9d273dd03c5b935ed7cb): fix filter spec quoting bug > -------------------------------------------------------------------------------------------------------------------------- > > > Signed-off-by: Jacob Vosmaer > > > > > Fix a bug in [`upload-pack.c`](https://github.com/git/git/blob/ad5df6b782a13854c9ae9d273dd03c5b935ed7cb/upload-pack.c) that occurs when you combine partial clone and uploadpack.packObjectsHook. > > You can reproduce it as follows: > > > > ``` > git clone -u 'git -c uploadpack.allowfilter '\ > uploadpack.packobjectshook=env '\ > load-pack' --filter=blob:none --no-local \ > .git dst.git > > ``` > > Be careful with the line endings because this has a long quoted string as the -u argument. > > > The error I get when I run this is: > > > > ``` > Cloning into '/tmp/broken'... > remote: fatal: invalid filter-spec ''blob:none'' > error: git upload-pack: git-pack-objects died with error. > fatal: git upload-pack: aborting due to possible repository corruption on the remote side. > remote: aborting due to possible repository corruption on the remote side. > fatal: early EOF > fatal: index-pack failed > > ``` > > The problem is caused by unneeded quoting. > > > This bug was already present in [10ac85c](https://github.com/git/git/commit/10ac85c785afed4163ed931149a87b30c7c5eaf9) ("`upload-pack`: add object filtering for partial clone", 2017-12-08, Git v2.17.0-rc0 -- [merge](https://github.com/git/git/commit/6bed209a20a06f2d6b7142216dabff456de798e1) listed in [batch #2](https://github.com/git/git/commit/b2e45c695d09f6a31ce09347ae0a5d2cdfe9dd4e)) when the server side filter support was introduced. > > In fact, in [10ac85c](https://github.com/git/git/commit/10ac85c785afed4163ed931149a87b30c7c5eaf9) this was broken regardless of uploadpack.packObjectsHook. > > Then in [0b6069f](https://github.com/git/git/commit/0b6069fe0a1e694d632e54a43fc6e546e83edad6) ("`fetch-pack`: test support excluding large blobs", 2017-12-08, Git v2.17.0-rc0 -- [merge](https://github.com/git/git/commit/6bed209a20a06f2d6b7142216dabff456de798e1) listed in [batch #2](https://github.com/git/git/commit/b2e45c695d09f6a31ce09347ae0a5d2cdfe9dd4e)) the quoting was removed but only behind a conditional that depends on whether `uploadpack.packObjectsHook` is set. > > > Because `uploadpack.packObjectsHook` is apparently rarely used, nobody noticed the problematic quoting could still happen. > > > Remove the conditional quoting. > > >
If you want to update particular file to `origin` state do: ``` git fetch origin git checkout origin/[yourbranch] -- [path_to_your_files] ```
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
No, it's not thread-safe. Imagine it's called twice at the same time with the same ID, which isn't previously present. Both threads would get as far as `RetrieveUser`, and they'd *both* call `_users.Add(id, u)`. The second call would fail because the key would already exist in the dictionary. (As an aside, I'd strongly recommend using braces for locks, if statements etc, for the sake of readability.)
It is threadsafe in the sense that it will not corrupt any data structures. It is not thread-safe in the sense that the entire method behaves atomically. Two threads might find the item to be missing, then create it then add it. One of the adders will fail.
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
No, it's not thread-safe. Imagine it's called twice at the same time with the same ID, which isn't previously present. Both threads would get as far as `RetrieveUser`, and they'd *both* call `_users.Add(id, u)`. The second call would fail because the key would already exist in the dictionary. (As an aside, I'd strongly recommend using braces for locks, if statements etc, for the sake of readability.)
I think you must apply the singleton pattern to have a really thread safe code. In this moment you can have 2 instances of your class.
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
No, it's not thread-safe. Imagine it's called twice at the same time with the same ID, which isn't previously present. Both threads would get as far as `RetrieveUser`, and they'd *both* call `_users.Add(id, u)`. The second call would fail because the key would already exist in the dictionary. (As an aside, I'd strongly recommend using braces for locks, if statements etc, for the sake of readability.)
Idon't think you have more choice here because the result of \_users.Add(id,u) depend on RetrieveUser you have to lock all method to make it thread safe. may be john skeet can confirm this the solution may look like this ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); private readonly object _syncLock = new object(); public User GetUser(int id) { User u = null; lock (_syncLock) { if (_users.containsKey(id)) return _users[id]; //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; _users.Add(id, u); } return u; } ``` } hope this help
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
It is threadsafe in the sense that it will not corrupt any data structures. It is not thread-safe in the sense that the entire method behaves atomically. Two threads might find the item to be missing, then create it then add it. One of the adders will fail.
I think you must apply the singleton pattern to have a really thread safe code. In this moment you can have 2 instances of your class.
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
It is threadsafe in the sense that it will not corrupt any data structures. It is not thread-safe in the sense that the entire method behaves atomically. Two threads might find the item to be missing, then create it then add it. One of the adders will fail.
Idon't think you have more choice here because the result of \_users.Add(id,u) depend on RetrieveUser you have to lock all method to make it thread safe. may be john skeet can confirm this the solution may look like this ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); private readonly object _syncLock = new object(); public User GetUser(int id) { User u = null; lock (_syncLock) { if (_users.containsKey(id)) return _users[id]; //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; _users.Add(id, u); } return u; } ``` } hope this help
18,992,790
I have a piece of code like this: ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); public User GetUser(int id) { User u = null; lock (_users) { if (_users.containsKey(id)) return _users[id]; } //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; lock (_users) { _users.Add(id, u); } return u; } } ``` I'm locking the access to dictionary, however someone in my team told that its still not threadsafe(without an explanation). Question is - do you think this is thread safe at all? Edit: Forgot to ask,what a solution would look like.Please note that I'mnot looking to lock the whole method, as the retrieve user is a time consuming operation.
2013/09/24
[ "https://Stackoverflow.com/questions/18992790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336749/" ]
Idon't think you have more choice here because the result of \_users.Add(id,u) depend on RetrieveUser you have to lock all method to make it thread safe. may be john skeet can confirm this the solution may look like this ``` public class UserCache { private Dictionary<int, User> _users = new Dictionary<int, User>(); private readonly object _syncLock = new object(); public User GetUser(int id) { User u = null; lock (_syncLock) { if (_users.containsKey(id)) return _users[id]; //The below line is threadsafe, so no worries on that. u = RetrieveUser(id); // Method to retrieve from database; _users.Add(id, u); } return u; } ``` } hope this help
I think you must apply the singleton pattern to have a really thread safe code. In this moment you can have 2 instances of your class.
31,579,781
I'm pretty new to regex, but I did some study. I got into a problem that might turn out impossible to be solved by regex, so I need a piece of advice. I have the following string: ``` some text key 12, 32, 311 ,465 and 345. some other text dog 612, 12, 32, 9 and 10. some text key 1, 2. ``` I'm trying to figure if it possible (using regex only) to extract the numbers `12` `32` `311` `465` `345` `1` `2` only - as a set of individual matches. When I approach this problem I tried to look for a pattern that matches only the relevant results. So I came up with : * get numbers that have prefix of "key" and NOT have prefix of "dog". But I'm not sure if it is even possible. I mean that I know that for the number `1` I can use `(?<=key )+[\d]+` and get it as a result, but for the rest of the numbers (i.e. `2..5`), can I "use" the `key` prefix again?
2015/07/23
[ "https://Stackoverflow.com/questions/31579781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577035/" ]
You can do it in `2` steps. ``` (?<=key\\s)\\d+(?:\\s*(?:,|and)\\s*\\d+)* ``` Grab all the numbers.See demo. <https://regex101.com/r/uK9cD8/6> Then `split` or `extract \\d+` from it.See demo. <https://regex101.com/r/uK9cD8/7>
You can use a positive look behind which ensure that your sequence doesn't precede by any word except `key` : ``` (?<=key)\s(?:\d+[\s,]+)+(?:and )?\d+ ``` Note that here you don't need to use a negative look behind for `dog` because this regex will just match if your sequence precede by `key`. See demo <https://regex101.com/r/gZ4hS4/3>
31,579,781
I'm pretty new to regex, but I did some study. I got into a problem that might turn out impossible to be solved by regex, so I need a piece of advice. I have the following string: ``` some text key 12, 32, 311 ,465 and 345. some other text dog 612, 12, 32, 9 and 10. some text key 1, 2. ``` I'm trying to figure if it possible (using regex only) to extract the numbers `12` `32` `311` `465` `345` `1` `2` only - as a set of individual matches. When I approach this problem I tried to look for a pattern that matches only the relevant results. So I came up with : * get numbers that have prefix of "key" and NOT have prefix of "dog". But I'm not sure if it is even possible. I mean that I know that for the number `1` I can use `(?<=key )+[\d]+` and get it as a result, but for the rest of the numbers (i.e. `2..5`), can I "use" the `key` prefix again?
2015/07/23
[ "https://Stackoverflow.com/questions/31579781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577035/" ]
In Java, you can make use of a constrained width look-behind that accepts `{n,m}` limiting quantifier. So, you can use ``` (?<=key(?:(?!dog)[^.]){0,100})[0-9]+ ``` Or, if `key` and `dog` are whole words, use `\b` word boundary: ``` String pattern = "(?<=\\bkey\\b(?:(?!\\bdog\\b)[^.]){0,100})[0-9]+"; ``` The only problem there may arise if the distance between the `dog` or `key` and the numbers is bigger than `m`. You may increase it to 1000 and I think that would work for most cases. Sample [IDEONE demo](http://ideone.com/QsGhvD) ``` String str = "some text key 12, 32, 311 ,465 and 345. some other text dog 612,\n12, 32, 9 and 10. some text key 1, 2."; String str2 = "some text key 1, 2, 3 ,4 and 5. some other text dog 6, 7, 8, 9 and 10. some text, key 1, 2 dog 3, 4 key 5, 6"; Pattern ptrn = Pattern.compile("(?<=key(?:(?!dog)[^.]){0,100})[0-9]+"); Matcher m = ptrn.matcher(str); while (m.find()) { System.out.println(m.group(0)); } System.out.println("-----"); m = ptrn.matcher(str2); while (m.find()) { System.out.println(m.group(0)); } ```
You can use a positive look behind which ensure that your sequence doesn't precede by any word except `key` : ``` (?<=key)\s(?:\d+[\s,]+)+(?:and )?\d+ ``` Note that here you don't need to use a negative look behind for `dog` because this regex will just match if your sequence precede by `key`. See demo <https://regex101.com/r/gZ4hS4/3>
31,579,781
I'm pretty new to regex, but I did some study. I got into a problem that might turn out impossible to be solved by regex, so I need a piece of advice. I have the following string: ``` some text key 12, 32, 311 ,465 and 345. some other text dog 612, 12, 32, 9 and 10. some text key 1, 2. ``` I'm trying to figure if it possible (using regex only) to extract the numbers `12` `32` `311` `465` `345` `1` `2` only - as a set of individual matches. When I approach this problem I tried to look for a pattern that matches only the relevant results. So I came up with : * get numbers that have prefix of "key" and NOT have prefix of "dog". But I'm not sure if it is even possible. I mean that I know that for the number `1` I can use `(?<=key )+[\d]+` and get it as a result, but for the rest of the numbers (i.e. `2..5`), can I "use" the `key` prefix again?
2015/07/23
[ "https://Stackoverflow.com/questions/31579781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577035/" ]
I wouldn't recommend using code that you can't understand and customize, but here is my one-pass solution, using [the method described in this answer of mine](https://stackoverflow.com/questions/15268504/collapse-and-capture-a-repeating-pattern-in-a-single-regex-expression/15418942#15418942). If you want to understand the construction method, please read the other answer. ``` (?:key(?>\s+and\s+|[\s,]+)|(?!^)\G(?>\s+and\s+|[\s,]+))(\d+) ``` Compared to the method described in the other post, I dropped the look-ahead, since in this case, we don't need to check against a suffix. The separator here is `(?>\s+and\s+|[\s,]+)`. It currently allows "and" with spaces on both sides, or any mix of spaces and commas. I use `(?>pattern)` to inhibit backtracking, so the order of the alternation is significant. Change it back to `(?:pattern)` if you want to modify it and you are unsure of what you are doing. Sample code: ``` String input = "some text key 12, 32, 311 ,465 and 345. some other text dog 612,\n12, 32, 9 and 10. some text key 1, 2. key 1, 2 dog 3, 4 key 5, 6. key is dog 23, 45. key 4"; Pattern p = Pattern.compile("(?:key(?>\\s+and\\s+|[\\s,]+)|(?!^)\\G(?>\\s+and\\s+|[\\s,]+))(\\d+)"); Matcher m = p.matcher(input); List<String> numbers = new ArrayList<>(); while (m.find()) { numbers.add(m.group(1)); } System.out.println(numbers); ``` [**Demo on ideone**](http://ideone.com/OFLEg7)
You can use a positive look behind which ensure that your sequence doesn't precede by any word except `key` : ``` (?<=key)\s(?:\d+[\s,]+)+(?:and )?\d+ ``` Note that here you don't need to use a negative look behind for `dog` because this regex will just match if your sequence precede by `key`. See demo <https://regex101.com/r/gZ4hS4/3>
70,734,540
Let say I have below code: ``` import pandas as pd import numpy as np import random import string data = ['DF1', 'DF2', 'DF2'] for i in data : DF = pd.DataFrame([random.choices(string.ascii_lowercase,k=5), [10, 11, 12, 13, 14]]).T DF.columns = ['col1', 'col2'] DF['i'] = i ``` So for each `i`, I have different `DF`. Finally I need to merge all those data frames based on `col1` and add numbers in `col2` row-wise. In this case, total number of such dataframes is based on length of `data` array, and therefore variable. In `R` we can use `do.call()` function to merge such varying number of data frames. In `Python` is there any way to achieve this? For example, lets say we have 3 individual tables as below: [![enter image description here](https://i.stack.imgur.com/IaehL.png)](https://i.stack.imgur.com/IaehL.png) [![enter image description here](https://i.stack.imgur.com/feUDJ.png)](https://i.stack.imgur.com/feUDJ.png) [![enter image description here](https://i.stack.imgur.com/NEiKY.png)](https://i.stack.imgur.com/NEiKY.png) After joining based on `col1`, I expect below table (sorted based on `col1`) [![enter image description here](https://i.stack.imgur.com/uBBSB.png)](https://i.stack.imgur.com/uBBSB.png) Any pointer will be highly appreciated.
2022/01/16
[ "https://Stackoverflow.com/questions/70734540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867328/" ]
IIUC, try: ``` df1 = pd.DataFrame({'col1':[*'adrtg'] ,'col2':[10,11,12,13,14] ,'data':['DF1']*5}) df2 = pd.DataFrame({'col1':[*'adspq'] ,'col2':[10,11,12,13,14] ,'data':['DF2']*5}) df3 = pd.DataFrame({'col1':[*'dcxyz'] ,'col2':[10,11,12,13,14] ,'data':['DF3']*5}) pd.concat([df1, df2, df3]).groupby('col1', as_index=False)['col2'].sum() ``` Output: ``` col1 col2 0 a 20 1 c 11 2 d 32 3 g 14 4 p 13 5 q 14 6 r 12 7 s 12 8 t 13 9 x 12 10 y 13 11 z 14 ```
you can use `merge` and actually you will be `cross join`ing the dataframes : ``` import pandas as pd import random import string data = ['DF1', 'DF2', 'DF2'] df = pd.DataFrame([random.choices(string.ascii_lowercase,k=5), [10, 11, 12, 13, 14]], ).T df.columns = ['col1', 'col2'] da = pd.DataFrame(data, columns=['data']) res = df.merge(da ,how='cross',) print(res) ``` output: ``` >>> col1 col2 data 0 j 10 DF1 1 j 10 DF2 2 j 10 DF2 3 d 11 DF1 4 d 11 DF2 5 d 11 DF2 6 k 12 DF1 7 k 12 DF2 8 k 12 DF2 9 e 13 DF1 10 e 13 DF2 11 e 13 DF2 12 n 14 DF1 13 n 14 DF2 14 n 14 DF2 Process finished with exit code 0 ```
56,936,636
I want to build an auto login bot or something. It has two parts: 1.login 2.verify login The last line of the login part finds and clicks on a button(Log In). When I run only the login part it works, but when I add verifying lines it doesn't work and can't find the button to click. Then I use Explicit Waits but it can't define the name "element". I'm confused. Here's the code: ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("My Website") username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") username.clear() username.send_keys("My Username") password.clear() password.send_keys("My Password") driver.find_element_by_xpath("//div[@type='submit']").click() if len(driver.find_elements_by_xpath("//input[@name='username']"))>0: print("Not!") else: print ("Logged IN!") ``` The second code(Explicit Waits added): ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("My Website") username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") username.clear() username.send_keys("My Username") password.clear() password.send_keys("My Password") try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//div[@type='submit']")) ) finally: element.click() if len(driver.find_elements_by_xpath("//form[@id='slfErrorAlert']"))>0: # Element is present print("Not!") else: # Element is not present print ("Logged IN!") ``` My Website is <https://www.instagram.com/accounts/login/> if it helps. Result for the first code: ``` >>> from selenium import webdriver >>> from selenium.webdriver.common.keys import Keys >>> driver = webdriver.Firefox() >>> driver.get("My Website") >>> username = driver.find_element_by_xpath("//input[@name='username']") >>> password = driver.find_element_by_xpath("//input[@name='password']") >>> username.clear() >>> username.send_keys("My Username") >>> password.clear() >>> password.send_keys("My Password") >>> driver.find_element_by_xpath("//div[@type='submit']").click() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\A\Python3.7.3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "E:\A\Python3.7.3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element 'value': value})['value'] File "E:\A\Python3.7.3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "E:\A\Python3.7.3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //div[@type='submit'] >>> if len(driver.find_elements_by_xpath("//input[@name='username']"))>0: ... # Element is present ... print("Not!") ... else: ... # Element is not present ... print ("Logged In!") ... Logged In! >>> ``` Result for the second code: ``` >>> from selenium import webdriver >>> from selenium.webdriver.common.keys import Keys >>> from selenium.webdriver.common.by import By >>> from selenium.webdriver.support.ui import WebDriverWait >>> from selenium.webdriver.support import expected_conditions as EC >>> >>> driver = webdriver.Firefox() >>> driver.get("My Website") >>> username = driver.find_element_by_xpath("//input[@name='username']") >>> password = driver.find_element_by_xpath("//input[@name='password']") >>> username.clear() >>> username.send_keys("My Username") >>> password.clear() >>> password.send_keys("My Password") >>> try: ... element = WebDriverWait(driver, 10).until( ... EC.presence_of_element_located((By.XPATH, "//div[@type='submit']")) ... ) ... finally: ... element.click() ... Traceback (most recent call last): File "<stdin>", line 3, in <module> File "E:\A\Python3.7.3\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 6, in <module> NameError: name 'element' is not defined >>> if len(driver.find_elements_by_xpath("//form[@id='slfErrorAlert']"))>0: ... # Element is present ... print("Not!") ... else: ... # Element is not present ... print ("Logged In!") ... Logged In! ``` : It shows Logged In! because I verify Login by the error message that says the username or password is invalid. When the login button isn't clicked, the message doesn't turn up and the bot(program,code,...) thinks that you logged in.
2019/07/08
[ "https://Stackoverflow.com/questions/56936636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think the issue comes from the fact that you defined your `replaceTransaction` method as generic, but you're not using `T` at all in that method, so type inference doesn't know what type to use in place of `T`. To give you a simpler example, this will cause the same error: ``` fun <T> foo() { println("Hello, world!") } fun main() { foo() } ``` That happens because `T` cannot be inferred, so you need to explicitly tell what type to use (even though it's not used at all in `foo`): ``` fun main() { foo<Unit>() // I used Unit, but any other type would do } ``` Given that, do you need `T` at all in your code? Both `FragmentRight` and `FragmentLeft` extend from `Fragment`, so unless you need to use specific functionalities from those classes, you can discard `T` and use the parent type `Fragment` (as you're already doing).
Instead of using `t:Fragment`, change the type of `t` to `T`, not `Fragment` Try to write your extension function this way: ``` fun <T : Fragment> FragmentTransaction.replaceTransaction(layout: Int, t: T): FragmentTransaction { return this.replace(layout, t) } ```
9,488,891
I'm making a WPF application making use of the MVVM light framework. What I'm trying to do is have a login form in a view, when the user presses a button within that view it launches a LoginCommand for the attached ViewModel. From there I either want to launch a new window which holds the rest of the application, or simply switch views from the same window. Currently I have it so that there is a view called MainView which has a content control inside bound to View1. However to switch to View2 I need to put the button for this on MainView, and not within View1 where it belongs. Any advice?
2012/02/28
[ "https://Stackoverflow.com/questions/9488891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226583/" ]
Usually I do this one of two ways: If the login window is a one-time thing required before starting the application, I will put it in the `OnStartup()` method of the `Application` object ``` protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // Login var login = new LoginDialog(); var loginVm = new LoginViewModel(); login.DataContext = loginVm; login.ShowDialog(); if (!login.DialogResult.GetValueOrDefault()) { // Error is handled in login class, not here Environment.Exit(0); } // If login is successful, show main application var app = new ShellView(); var appModel = new ShellViewModel(); app.DataContext = viewModel; app.Show(); } ``` The other way I usually do this is through a `ShellViewModel` or `ApplicationViewModel` which handles all my window management. This method uses `DataTemplates` to define each screen, and uses a `ContentControl` as a placeholder for the current screen in the `ShellView` or `ApplicationView`. I usually combine this with an Event System of some kind, like Microsoft Prism's `EventAggregator`, so it can listen for messages of a specific type, such as `OpenWindow` or `CloseWindow` messages. If you're interested, I have a blog post about [Communication between ViewModels](http://rachel53461.wordpress.com/2011/06/05/communication-between-viewmodels-with-mvvm/) that should give you a better idea of what an event system looks like. For example, my `ShellViewModel` might start by displaying a `LoginViewModel` (a `DataTemplate` is used to tell WPF to draw the `LoginViewModel` with the `LoginView`), and it would subscribe to receive messages of type `SuccessfulLogin`. Once the `LoginViewModel` broadcasts a `SuccessfulLogin` message, the `ShellViewModel` will close the `LoginViewModel` and replace it with the `ApplicationViewModel`. You can see an example of this in my article on [Navigation with MVVM](http://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/)
Put your views inside `Page` elements, inside your `MainWindow` create a Frame and point it's source to your first page. From then on you can use the frame's `NavigationService` to navigate your frame to another view, much like a web browser.
53,155,105
I have a console program which sends async HTTP requests to an external web API. (`HttpClient.GetAsync());`) These tasks can take several minutes to complete - during which I'd like to be able to show to the user that the app is still running - for example by sending `Console.WriteLine("I ain't dead - yet")` every 10 seconds. I am not sure how to do it right, without the risk of hiding exceptions, introducing deadlocks etc. **I am aware of the IProgress<T>, however I don't know whether I can introduce it in this case. I am await a single async call which does not report progress. (It's essentially an SDK which calls httpClient GetAsync() method** Also: I cannot set the GUI to 'InProgress', because there is no GUI, its a console app - and it seems to the user as if it stopped working if I don't send an update message every now and then. Current idea: ``` try { var task = httpClient.GetAsync(uri); //actually this is an SDK method call (which I cannot control and which does not report progress itself) while (!task.IsCompleted) { await Task.Delay(1000 * 10); this.Logger.Log(Verbosity.Verbose, "Waiting for reply..."); } onSuccessCallback(task.Result); } catch (Exception ex) { if (onErrorCallback == null) { throw this.Logger.Error(this.GetProperException(ex, caller)); } this.Logger.Log(Verbosity.Error, $"An error when executing command [{action?.Command}] on {typeof(T).Name}", ex); onErrorCallback(this.GetProperException(ex, caller)); } ```
2018/11/05
[ "https://Stackoverflow.com/questions/53155105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892378/" ]
Let me tidy this code up a bit for you ``` async Task Main() { var reporter = new ConsoleProgress(); var result = await WeatherWaxProgressWrapper(() => GetAsync("foo"), reporter); Console.WriteLine(result); } public async Task<int> GetAsync(string uri) { await Task.Delay(TimeSpan.FromSeconds(10)); return 1; } public async Task<T> WeatherWaxProgressWrapper<T>(Func<Task<T>> method, System.IProgress<string> progress) { var task = method(); while(!task.IsCompleted && !task.IsCanceled && !task.IsFaulted) { await Task.WhenAny(task, Task.Delay(1000)); progress.Report("I ain't dead"); } return await task; } public class ConsoleProgress : System.IProgress<string> { public void Report(string value) { Console.WriteLine(value); } } ```
You are looking for `System.Progress<T>`, a wonderful implementation of `IProgress`. <https://learn.microsoft.com/en-us/dotnet/api/system.progress-1> You create an object of this class on the "UI thread" or the main thread in your case, and it captures the `SynchronizationContext` for you. Pass it to your worker thread and every call to `Report` will be executed on the captured thread, you don't have to worry about anything. Very useful in WPF or WinForms applications.
53,155,105
I have a console program which sends async HTTP requests to an external web API. (`HttpClient.GetAsync());`) These tasks can take several minutes to complete - during which I'd like to be able to show to the user that the app is still running - for example by sending `Console.WriteLine("I ain't dead - yet")` every 10 seconds. I am not sure how to do it right, without the risk of hiding exceptions, introducing deadlocks etc. **I am aware of the IProgress<T>, however I don't know whether I can introduce it in this case. I am await a single async call which does not report progress. (It's essentially an SDK which calls httpClient GetAsync() method** Also: I cannot set the GUI to 'InProgress', because there is no GUI, its a console app - and it seems to the user as if it stopped working if I don't send an update message every now and then. Current idea: ``` try { var task = httpClient.GetAsync(uri); //actually this is an SDK method call (which I cannot control and which does not report progress itself) while (!task.IsCompleted) { await Task.Delay(1000 * 10); this.Logger.Log(Verbosity.Verbose, "Waiting for reply..."); } onSuccessCallback(task.Result); } catch (Exception ex) { if (onErrorCallback == null) { throw this.Logger.Error(this.GetProperException(ex, caller)); } this.Logger.Log(Verbosity.Error, $"An error when executing command [{action?.Command}] on {typeof(T).Name}", ex); onErrorCallback(this.GetProperException(ex, caller)); } ```
2018/11/05
[ "https://Stackoverflow.com/questions/53155105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892378/" ]
Let me tidy this code up a bit for you ``` async Task Main() { var reporter = new ConsoleProgress(); var result = await WeatherWaxProgressWrapper(() => GetAsync("foo"), reporter); Console.WriteLine(result); } public async Task<int> GetAsync(string uri) { await Task.Delay(TimeSpan.FromSeconds(10)); return 1; } public async Task<T> WeatherWaxProgressWrapper<T>(Func<Task<T>> method, System.IProgress<string> progress) { var task = method(); while(!task.IsCompleted && !task.IsCanceled && !task.IsFaulted) { await Task.WhenAny(task, Task.Delay(1000)); progress.Report("I ain't dead"); } return await task; } public class ConsoleProgress : System.IProgress<string> { public void Report(string value) { Console.WriteLine(value); } } ```
You could have a never-ending `Task` as a beacon that signals every 10 sec, and cancel it after the completion of the long running I/O operation: ``` var beaconCts = new CancellationTokenSource(); var beaconTask = Task.Run(async () => { while (true) { await Task.Delay(TimeSpan.FromSeconds(10), beaconCts.Token); Console.WriteLine("Still going..."); } }); await LongRunningOperationAsync(); beaconCts.Cancel(); ```
53,155,105
I have a console program which sends async HTTP requests to an external web API. (`HttpClient.GetAsync());`) These tasks can take several minutes to complete - during which I'd like to be able to show to the user that the app is still running - for example by sending `Console.WriteLine("I ain't dead - yet")` every 10 seconds. I am not sure how to do it right, without the risk of hiding exceptions, introducing deadlocks etc. **I am aware of the IProgress<T>, however I don't know whether I can introduce it in this case. I am await a single async call which does not report progress. (It's essentially an SDK which calls httpClient GetAsync() method** Also: I cannot set the GUI to 'InProgress', because there is no GUI, its a console app - and it seems to the user as if it stopped working if I don't send an update message every now and then. Current idea: ``` try { var task = httpClient.GetAsync(uri); //actually this is an SDK method call (which I cannot control and which does not report progress itself) while (!task.IsCompleted) { await Task.Delay(1000 * 10); this.Logger.Log(Verbosity.Verbose, "Waiting for reply..."); } onSuccessCallback(task.Result); } catch (Exception ex) { if (onErrorCallback == null) { throw this.Logger.Error(this.GetProperException(ex, caller)); } this.Logger.Log(Verbosity.Error, $"An error when executing command [{action?.Command}] on {typeof(T).Name}", ex); onErrorCallback(this.GetProperException(ex, caller)); } ```
2018/11/05
[ "https://Stackoverflow.com/questions/53155105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892378/" ]
You could have a never-ending `Task` as a beacon that signals every 10 sec, and cancel it after the completion of the long running I/O operation: ``` var beaconCts = new CancellationTokenSource(); var beaconTask = Task.Run(async () => { while (true) { await Task.Delay(TimeSpan.FromSeconds(10), beaconCts.Token); Console.WriteLine("Still going..."); } }); await LongRunningOperationAsync(); beaconCts.Cancel(); ```
You are looking for `System.Progress<T>`, a wonderful implementation of `IProgress`. <https://learn.microsoft.com/en-us/dotnet/api/system.progress-1> You create an object of this class on the "UI thread" or the main thread in your case, and it captures the `SynchronizationContext` for you. Pass it to your worker thread and every call to `Report` will be executed on the captured thread, you don't have to worry about anything. Very useful in WPF or WinForms applications.
61,189,365
I have two lists in a list: ``` t = [['this','is','a','sentence'],['Hello','I','am','Daniel']] ``` I want to combine them in order to get two sentences: ``` 'this is a sentence. Hello I am Daniel.' ``` I quickly came up with the following solution: ``` text = '' for sent in t: text = text + ' '.join(sent) + '. ' ``` But maybe there is more readable(better styled) solution for this task?
2020/04/13
[ "https://Stackoverflow.com/questions/61189365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12347331/" ]
You can shorten it to a single list comprehension, with another "." at the end: ```py text = '. '.join(' '.join(sent) for sent in t) + '.' ```
You could also use `list comprehensions`: ``` In [584]: ''.join([' '+ ' '.join(sent) + '. ' for sent in t]) Out[584]: ' this is a sentence. Hello I am Daniel. ' ```
43,844,260
Does Jenkins by default keeps all the builds and artifacts generated in each build. Or it deletes them after a certain period of time. I know I can configure the "Discard Old builds" option, but I want to know the Jenkins default behavior.
2017/05/08
[ "https://Stackoverflow.com/questions/43844260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947158/" ]
Default is to keep all builds and artifacts. Might add that i don't know of any plugin which alters this default behavior.
Jenkins doesn't keep the artifacts. Jenkins only keeps the build history, means the log of the build and meta information like buildumber, time etc. If you want that jenkins keeps your artifacts, you have to archive them. You do this by using the archive step in your job config or by using the <https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#archive-archive-artifacts> step in your Jenkinsfile. But Jenkins is not a artifact archive tool. Best is to use an artifact archiving tool, like <http://www.sonatype.org/nexus/> or <https://www.jfrog.com/artifactory/>.
43,844,260
Does Jenkins by default keeps all the builds and artifacts generated in each build. Or it deletes them after a certain period of time. I know I can configure the "Discard Old builds" option, but I want to know the Jenkins default behavior.
2017/05/08
[ "https://Stackoverflow.com/questions/43844260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947158/" ]
Default is to keep all builds and artifacts. Might add that i don't know of any plugin which alters this default behavior.
As far I can determine with current Jenkins, default is: * keep the build logs forever. * assuming you have an "archive artifacts" post-build step, keep artifacts for one month. * keep artifacts even if build failed or was aborted.
43,844,260
Does Jenkins by default keeps all the builds and artifacts generated in each build. Or it deletes them after a certain period of time. I know I can configure the "Discard Old builds" option, but I want to know the Jenkins default behavior.
2017/05/08
[ "https://Stackoverflow.com/questions/43844260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2947158/" ]
Jenkins doesn't keep the artifacts. Jenkins only keeps the build history, means the log of the build and meta information like buildumber, time etc. If you want that jenkins keeps your artifacts, you have to archive them. You do this by using the archive step in your job config or by using the <https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#archive-archive-artifacts> step in your Jenkinsfile. But Jenkins is not a artifact archive tool. Best is to use an artifact archiving tool, like <http://www.sonatype.org/nexus/> or <https://www.jfrog.com/artifactory/>.
As far I can determine with current Jenkins, default is: * keep the build logs forever. * assuming you have an "archive artifacts" post-build step, keep artifacts for one month. * keep artifacts even if build failed or was aborted.
6,421,871
I'm wondering if it would be possible to send an email from a lua script. I am using linux so I do have the `mail` command, but I can't work out how to use it. Any help would be much appreciated.
2011/06/21
[ "https://Stackoverflow.com/questions/6421871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363606/" ]
[LuaSocket](http://w3.impa.br/~diego/software/luasocket) offers support for sending email: <http://w3.impa.br/~diego/software/luasocket/smtp.html>
You've probably already found a solution, but since this question still shows up in google, here's another answer that works on linux: ``` mail = io.popen("mail -s 'SUBJECT' [email protected]", "w") mail:write("testing some stuff\n\4") -- tested with lua 5.2 on ubuntu server ``` io.popen opens the mail program as a file as explained in the lua reference manual. It is important to open it in writing mode ("w") to be able to actually write the body of the email. Then you just write your message with :write and when you're done, append a newline character "\n" followed by a EOT "\4" character to tell the program to send the message. This method has the advantage that you do not need to handle the sending of the message yourself, as with the LuaSocket library and that you don't need to have SMTP support on your mail server enabled, which can be a lot of work to set up propperly and the disadvantage that you need to have access to mailx, so you can't send messages from anywhere. Hope this helps :)
44,716,242
For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end. So 123456 would return as 135246 I am having trouble selecting every other letter after the first ``` def encrypt(message): return "%s%s" % (message[::-1],message[::2]) print(encrypt("123456")) ```
2017/06/23
[ "https://Stackoverflow.com/questions/44716242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796098/" ]
You could tweak your method a little as follows: ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) print(encrypt("123456")) # 135246 ```
Use `slicing` and `indexing` ``` msg = [1, 2, 3, 4, 5, 6] In [30]: msg[::2] + msg[1::2] Out[30]: [1, 3, 5, 2, 4, 6] ``` and for your function ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) print(encrypt("123456")) ```
44,716,242
For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end. So 123456 would return as 135246 I am having trouble selecting every other letter after the first ``` def encrypt(message): return "%s%s" % (message[::-1],message[::2]) print(encrypt("123456")) ```
2017/06/23
[ "https://Stackoverflow.com/questions/44716242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796098/" ]
use following code ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) ```
You could tweak your method a little as follows: ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) print(encrypt("123456")) # 135246 ```
44,716,242
For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end. So 123456 would return as 135246 I am having trouble selecting every other letter after the first ``` def encrypt(message): return "%s%s" % (message[::-1],message[::2]) print(encrypt("123456")) ```
2017/06/23
[ "https://Stackoverflow.com/questions/44716242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796098/" ]
You could tweak your method a little as follows: ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) print(encrypt("123456")) # 135246 ```
When you use `message[::-1]` you are actually commanding to display all the values in reverse. So expected output for `message[::-1]` will be **654321** So use ``` (message[::2],message[1::2]) ``` This should work like a charm.
44,716,242
For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end. So 123456 would return as 135246 I am having trouble selecting every other letter after the first ``` def encrypt(message): return "%s%s" % (message[::-1],message[::2]) print(encrypt("123456")) ```
2017/06/23
[ "https://Stackoverflow.com/questions/44716242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796098/" ]
use following code ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) ```
Use `slicing` and `indexing` ``` msg = [1, 2, 3, 4, 5, 6] In [30]: msg[::2] + msg[1::2] Out[30]: [1, 3, 5, 2, 4, 6] ``` and for your function ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) print(encrypt("123456")) ```
44,716,242
For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end. So 123456 would return as 135246 I am having trouble selecting every other letter after the first ``` def encrypt(message): return "%s%s" % (message[::-1],message[::2]) print(encrypt("123456")) ```
2017/06/23
[ "https://Stackoverflow.com/questions/44716242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796098/" ]
use following code ``` def encrypt(message): return "%s%s" % (message[::2],message[1::2]) ```
When you use `message[::-1]` you are actually commanding to display all the values in reverse. So expected output for `message[::-1]` will be **654321** So use ``` (message[::2],message[1::2]) ``` This should work like a charm.
58,714,978
I've started using `FluentValidation` on a WPF project, till now I used it in a simple way checking if a field has been filled or less then n character. Now I've to check if the value inserted (which is a string...damn old code) is greater then 0. Is there a simple way I can convert it using ``` RuleFor(x=>x.MyStringField).Somehow().GreaterThen(0) ? ``` Thanks in advance
2019/11/05
[ "https://Stackoverflow.com/questions/58714978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278204/" ]
Just write a custom validator like this ``` public class Validator : AbstractValidator<Test> { public Validator() { RuleFor(x => x.MyString) .Custom((x, context) => { if ((!(int.TryParse(x, out int value)) || value < 0)) { context.AddFailure($"{x} is not a valid number or less than 0"); } }); } } ``` And from your place where you need to validate do this ``` var validator = new Validator(); var result = validator.Validate(test); Console.WriteLine(result.IsValid ? $"Entered value is a number and is > 0" : "Fail"); ``` Update 11/8/21 -------------- If you are going to use this on a large project or API, you are probably better by doing this from the `Startup` and we don't need to manually call the `validator.Validate()` in each and every method. ```cs services.AddMvc(options => options.EnableEndpointRouting = false) .AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining<BaseValidator>(); fv.ImplicitlyValidateChildProperties = true; fv.ValidatorOptions.CascadeMode = CascadeMode.Stop; }) ```
Another solution: ``` RuleFor(a => a.MyStringField).Must(x => int.TryParse(x, out var val) && val > 0) .WithMessage("Invalid Number."); ```
58,714,978
I've started using `FluentValidation` on a WPF project, till now I used it in a simple way checking if a field has been filled or less then n character. Now I've to check if the value inserted (which is a string...damn old code) is greater then 0. Is there a simple way I can convert it using ``` RuleFor(x=>x.MyStringField).Somehow().GreaterThen(0) ? ``` Thanks in advance
2019/11/05
[ "https://Stackoverflow.com/questions/58714978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278204/" ]
Just write a custom validator like this ``` public class Validator : AbstractValidator<Test> { public Validator() { RuleFor(x => x.MyString) .Custom((x, context) => { if ((!(int.TryParse(x, out int value)) || value < 0)) { context.AddFailure($"{x} is not a valid number or less than 0"); } }); } } ``` And from your place where you need to validate do this ``` var validator = new Validator(); var result = validator.Validate(test); Console.WriteLine(result.IsValid ? $"Entered value is a number and is > 0" : "Fail"); ``` Update 11/8/21 -------------- If you are going to use this on a large project or API, you are probably better by doing this from the `Startup` and we don't need to manually call the `validator.Validate()` in each and every method. ```cs services.AddMvc(options => options.EnableEndpointRouting = false) .AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining<BaseValidator>(); fv.ImplicitlyValidateChildProperties = true; fv.ValidatorOptions.CascadeMode = CascadeMode.Stop; }) ```
You can use **transformation**: <https://docs.fluentvalidation.net/en/latest/transform.html> ``` Transform(from: x => x.SomeStringProperty, to: value => int.TryParse(value, out int val) ? (int?) val : null) .GreaterThan(0); ```
58,714,978
I've started using `FluentValidation` on a WPF project, till now I used it in a simple way checking if a field has been filled or less then n character. Now I've to check if the value inserted (which is a string...damn old code) is greater then 0. Is there a simple way I can convert it using ``` RuleFor(x=>x.MyStringField).Somehow().GreaterThen(0) ? ``` Thanks in advance
2019/11/05
[ "https://Stackoverflow.com/questions/58714978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278204/" ]
Another solution: ``` RuleFor(a => a.MyStringField).Must(x => int.TryParse(x, out var val) && val > 0) .WithMessage("Invalid Number."); ```
You can use **transformation**: <https://docs.fluentvalidation.net/en/latest/transform.html> ``` Transform(from: x => x.SomeStringProperty, to: value => int.TryParse(value, out int val) ? (int?) val : null) .GreaterThan(0); ```
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
The [IPCC report](http://www.ipcc.ch/publications_and_data/publications_ipcc_fourth_assessment_report_wg1_report_the_physical_science_basis.htm) gives the following probabilities: > > The total radiative forcing of the Earth’s climate > due to increases in the concentrations of the LLGHGs > CO2, CH4 and N2O, and very likely the rate of increase > in the total forcing due to these gases over the > period since 1750 > > > What do they mean when they say *very likely*? They mean 0.95 < p < 0.99. When someone says that the evidence for climate change is comparable to the evidence for evolution they are either advocating that the IPCC is wrong by orders of magnitude or they are gravely insulting academic biology. 255 members of the US National Academy of Sciences including 11 Nobel Price winners issued [a letter](https://www.theguardian.com/environment/2010/may/06/climate-science-open-letter) that claims: > > For instance, there is compelling scientific evidence that our planet is about 4.5bn years old (the theory of the origin of Earth), that our universe was born from a single event about 14bn years ago (the Big Bang theory), and that today's organisms evolved from ones living in the past (the theory of evolution). Even as these are overwhelmingly accepted by the scientific community, fame still awaits anyone who could show these theories to be wrong. Climate change now falls into this category. > > > In an attempt to defend orthodox wisdom mainstream scientists seem to be willing to pretend that the evidence is for climate change is a lot better than it actually is. [Other people](http://andrewgelman.com/2009/12/15/say_a_little_pr/) who see themselves in defense of climate change think that the IPCC is a bit overconfident. There are a lot of reasons why that might be the case: * Humans typically suffer from confirmation bias. Even a friendly reading of the [climate gate emails](https://wikileaks.org/wiki/Climatic_Research_Unit_emails,_data,_models,_1996-2009) that Wikileaks published suggest that they don't engage in mental strategies to reduce their vulnerability to confirmation bias. * The computer code that they use to generate the models has [low standards](https://pjmedia.com/blog/climategate-computer-codes-are-the-real-story/). It has probably a lot of bugs that throw extra inaccuracy into the models that aren't accounted for. * Some data isn't openly available to allow for independent verification. * We have seen in the financial crisis that complex computer models often include a lot of assumptions that make them overconfident. * Climate scientists test their models on past data and generally don't make predictions about the future to test their models. [As the models have a lot of parameters that makes the models to appear better than they are.](http://archives.sethroberts.net/blog/2011/02/27/the-best-argument-against-man-made-global-warming/) That doesn't mean that we should assume p=0 but it might be reasonable to use a lower likelihood value than the IPCC value. If we go from 0.95 < p < 0.99 to 0.80 < p < 0.90 we have more than a 10% chance of being wrong. Even if we just go to 0.90 < p < 0.95 we have more than a 5% chance of being wrong. Why does that matter? Isn't p=0.80 enough for starting to reduce CO2 emissions? That might be true. If we, however, start geoengineering, the confidence in our models matters a great deal. Starting geoengineering on the assumptions that our models are magnitudes better than they really are is dangerous. Part of being a good skeptic should be to avoid being more confident in your beliefs than the data warrants. We should move past binary classification. Instead of showing tribal loyalty we should call out our friends when they overstate the evidence.
There is an overwhelming amount of evidence that, while humans didn't like CAUSE climate change, we are indeed accelerating it. A couple of excellent links of research to explain this are here: [Is Current Warming Natural?](http://earthobservatory.nasa.gov/Features/GlobalWarming/page4.php) [How do Human Activities Contribute to Climate Change and How do They Compare with Natural Influences?](http://oceanservice.noaa.gov/education/pd/climate/factsheets/howhuman.pdf)
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Humans affect the weather in mainly the following ways: Direct emissions of various gasses ================================== Typically CO2 is considered, but also other greenhouse gasses. The greenhouse effect of carbon dioxide was first measured in 1859. ![Greenhouse effect](https://i.stack.imgur.com/4Pc5W.jpg) [source](https://en.wikipedia.org/wiki/File:The_green_house_effect.svg) > > In the 19th century, scientists realized that gases in the atmosphere cause a "greenhouse effect" which affects the planet's temperature. These scientists were interested chiefly in the possibility that a lower level of carbon dioxide gas might explain the ice ages of the distant past. At the turn of the century, Svante Arrhenius calculated that emissions from human industry might someday bring a global warming. Other scientists dismissed his idea as faulty. In 1938, G.S. Callendar argued that the level of carbon dioxide was climbing and raising global temperature, but most scientists found his arguments implausible. It was almost by chance that a few researchers in the 1950s discovered that global warming truly was possible. In the early 1960s, C.D. Keeling measured the level of carbon dioxide in the atmosphere: it was rising fast. Researchers began to take an interest, struggling to understand how the level of carbon dioxide had changed in the past, and how the level was influenced by chemical and biological forces. They found that the gas plays a crucial role in climate change, so that the rising level could gravely affect our future. > > > —[The Carbon Dioxide Greenhouse Effect](http://www.aip.org/history/climate/co2.htm) ![List of greenhouse gases](https://i.stack.imgur.com/Zhm68.jpg) [source](https://en.wikipedia.org/wiki/IPCC_list_of_greenhouse_gases) Farming ======= Another man-made source is the [direct emission](https://web.archive.org/web/20111130103419/http://jas.fass.org/content/77/6/1392.abstract) of [greenhouse gasses](http://www.practicalchemistry.org/experiments/the-greenhouse-effect,296,EX.html) through farming (funny, but true!): manure (and cows) produce methane which is a pretty effective greenhouse gas. ![US cattle methane emissions](https://i.stack.imgur.com/aS0wq.gif) [source](http://www.epa.gov/rlep/faq.html) > > Increasing atmospheric concentrations of methane have led scientists to examine its sources of origin. Ruminant livestock can produce 250 to 500 L of methane per day. This level of production results in estimates of the contribution by cattle to global warming that may occur in the next 50 to 100 yr to be a little less than 2%. > > > —[Methane emissions from cattle](https://www.ncbi.nlm.nih.gov/pubmed/8567486) Deforestation ============= Plants "fix" carbon (a phenomena called "Carbon sequestration"), the less plants, the less fixing (and the more carbon released by fires). ![Forest carbon cycle](https://i.stack.imgur.com/5ap7d.jpg) [source](https://forestthreats.org/products/news-updates/volume-1-issue-2-winter-2008/what-happens-to-all-the-carbon) > > ![Carbon sequestration](https://i.stack.imgur.com/I1kss.jpg) > > > —[Carbon sequestration: Forest and soil, by Jukka Muukkonen, Statistics Finland](https://unstats.un.org/unsd/envaccounting/londongroup/meeting14/LG14_12a.pdf) The Oceans ========== Changes to the [biological equilibrium](https://www.nature.com/articles/387272a0) of the oceans affect the climate because marine biology is known to have a [large carbon-fixating effect](https://www.gfdl.noaa.gov/bibliography/related_files/jls9202.pdf) ![Carbon sequestration by the ocean](https://i.stack.imgur.com/qTvNr.jpg) [source](https://web.archive.org/web/20170316060635/http://theresilientearth.com/?q=content/ocean-co2-storage-revised) > > One of the most promising places to sequester carbon is in the oceans, which currently take up a third of the carbon emitted by human activity, roughly two billion metric tons each year. > > > —[Carbon Sequestration in the Ocean](http://www.lbl.gov/Science-Articles/Archive/sea-carb-bish.html) Conclusion ========== All four of these effect can be shown in a laboratory and no model is required to do so, but we have very very good models to explain the lab experiments. Differently from the lab, the whole climate system is much less understood. And, yes, the model are not as reliable as we would like. However — due to our knowledge of chemistry — it is undeniable that we are affecting climate. Note that nobody has asserted that human intervention is the *only* cause of climate change, but it can be said, with a straight face, that humans are changing climate. A very simple example, the rise in temperature melts ice at the pole - which is not only responsible for reflecting some light out of the atmosphere, but also contains methane, which is then released. The debate can only be on "how much" and "how well can we reverse the trend (even beyond our contribution)".
There is an overwhelming amount of evidence that, while humans didn't like CAUSE climate change, we are indeed accelerating it. A couple of excellent links of research to explain this are here: [Is Current Warming Natural?](http://earthobservatory.nasa.gov/Features/GlobalWarming/page4.php) [How do Human Activities Contribute to Climate Change and How do They Compare with Natural Influences?](http://oceanservice.noaa.gov/education/pd/climate/factsheets/howhuman.pdf)
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
**Trends in solar radiation don't match up with trends in temperature.** One of the arguments from skeptics of climate change is that rising global temperatures are a natural phenomenon caused by the Sun. However, most measures of total solar irradiance (also known as solar radiation, the electromagnetic energy incident on Earth's surface) show that, on the whole, it is falling. (This, of course, necessitates taking a step back to see [larger TSI trends](http://lasp.colorado.edu/lisird/tsi/historical_tsi.html), beyond the valleys and peaks caused by the solar cycle.) ![ACRIM's Irradiance Data from 1978-1984](https://i.stack.imgur.com/8z1Pb.jpg) In short, it looks like the Sun is actually cooling. Not dramatically, but it's certainly not becoming hotter, and certainly not enough to account for rising global temperatures. In fact, when we juxtapose climate temperature with solar irradiance, as shown below, we find that they have little to do with one another. This is a basic, common sense approach, but if you require mathematical proof, then Skeptical Science has put together [a digestible calculation and analysis](http://www.skepticalscience.com/solar-activity-sunspots-global-warming-advanced.htm). Anyhow, just a graph: ![From atmospheric scientist Bart Verheggen's blog, *Our Changing Climate*](https://i.stack.imgur.com/tmQ20.png) So you may not agree that global warming is anthropogenic. But as scientists look at solar irradiance as just one piece of evidence that correlates with various others that fellow commenters have left, it's becoming increasingly clear that it's not caused by the Sun. What does that leave?
There is an overwhelming amount of evidence that, while humans didn't like CAUSE climate change, we are indeed accelerating it. A couple of excellent links of research to explain this are here: [Is Current Warming Natural?](http://earthobservatory.nasa.gov/Features/GlobalWarming/page4.php) [How do Human Activities Contribute to Climate Change and How do They Compare with Natural Influences?](http://oceanservice.noaa.gov/education/pd/climate/factsheets/howhuman.pdf)
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
**Trends in solar radiation don't match up with trends in temperature.** One of the arguments from skeptics of climate change is that rising global temperatures are a natural phenomenon caused by the Sun. However, most measures of total solar irradiance (also known as solar radiation, the electromagnetic energy incident on Earth's surface) show that, on the whole, it is falling. (This, of course, necessitates taking a step back to see [larger TSI trends](http://lasp.colorado.edu/lisird/tsi/historical_tsi.html), beyond the valleys and peaks caused by the solar cycle.) ![ACRIM's Irradiance Data from 1978-1984](https://i.stack.imgur.com/8z1Pb.jpg) In short, it looks like the Sun is actually cooling. Not dramatically, but it's certainly not becoming hotter, and certainly not enough to account for rising global temperatures. In fact, when we juxtapose climate temperature with solar irradiance, as shown below, we find that they have little to do with one another. This is a basic, common sense approach, but if you require mathematical proof, then Skeptical Science has put together [a digestible calculation and analysis](http://www.skepticalscience.com/solar-activity-sunspots-global-warming-advanced.htm). Anyhow, just a graph: ![From atmospheric scientist Bart Verheggen's blog, *Our Changing Climate*](https://i.stack.imgur.com/tmQ20.png) So you may not agree that global warming is anthropogenic. But as scientists look at solar irradiance as just one piece of evidence that correlates with various others that fellow commenters have left, it's becoming increasingly clear that it's not caused by the Sun. What does that leave?
Yes, humans contribute to climate change, but there is significant disagreement regarding to what degree humans contribute. Climate change happens, and it has been happening for billions of years. That industrialized human existence is but an insignificant blip on the geological time scale undermines the ***frequentist*** views on significance. To promote convenient views on anthropogenic climate change (ACC), we are often show ***recentist*** graphs such as this: [![https://www.ncdc.noaa.gov/monitoring-references/faq/images/global-temp-and-co2-1880-2009.gif](https://i.stack.imgur.com/rNKae.gif)](https://i.stack.imgur.com/rNKae.gif) The premise is that correlation implies causation. However, in addition to the greenhouse effect, there are other [facile natural mechanisms](http://www.earth-syst-dynam.net/8/177/2017/) which help to explain this correlation. These mechanisms are not mutually exclusive but tend to support the idea that temperature causes carbon --- not the reverse. When you take a step back from the ***recentist*** view in order to examine a longer time scale, this relationship between temperature and CO2 weakens. In fact, it indicates that the Earth was warmer even over the most recent Milankovitch cycle. This directly contravenes views that ACC is a result of the human industrial revolution. [![Temperature over the last phase of the Milankovitch Cycle](https://i.stack.imgur.com/aM250.gif)](https://i.stack.imgur.com/aM250.gif) But then again, we are often reminded that the correlation is significant over longer periods (if you cherry-pick the data, that is), as evidenced here: [![https://wattsupwiththat.com/2016/12/16/climate-change-debate-latest-results/](https://i.stack.imgur.com/Xy40z.jpg)](https://i.stack.imgur.com/Xy40z.jpg) However, this relationship only holds while Milankovitch cycles are relevant. Over even longer geological time periods, the relationship between CO2 and temperature is nil: [![Phanerzoic CO2](https://i.stack.imgur.com/lGdJ9.png)](https://i.stack.imgur.com/lGdJ9.png) So, I think it's important to take all facts into consideration. Anyway, a more extended version of this argument against "the consensus" argument is found [here](http://the-world-is.com/blog/2017/04/desmog-blogs-mission-statement-quashes-rational-skepticism/).
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Yes, humans cause climate change (each doubling of CO2 causes about [1C increase](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/2/)). It's really a meaningless question. [Any input to any chaos system will cause some effect on that system](http://en.wikipedia.org/wiki/Chaos_theory#Sensitivity_to_initial_conditions). Do we know what effect we are having? Can we measure/predict it? Do we have any idea how to alter/change/control that change? And really, what the hubbub is about is not "will the climate change", but ["will it change in a really bad way"](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/) (ie, catastrophic global warming) According to [Peter Stott](http://worldnews.msnbc.msn.com/_news/2012/04/23/11144098-gaia-scientist-james-lovelock-i-was-alarmist-about-climate-change) models failed to predict current temperatures (though he echoes the recurring claim that they'll be correct in the future), [which means that no existing model has predicted, correctly, any significant amount of future climate change](http://www.drroyspencer.com/2012/02/ten-years-after-the-warming/), and [new research is steadily revealing flaws](http://www.theregister.co.uk/2012/06/25/antarctic_ice_not_melting/) in existing catastrophic prediction models, so the answer to those questions should be no. A model which has yet to make an accurate prediction cannot be said to be an accurate model. Therefore, we don't know what effect we're having, we can't predict it, and as a result of those two, we do not know how to alter or control that affect. Causation on a chaos system is nigh impossible to prove with our current abilities, so we rely on modeling. Unfortunately, instead of insisting that a model make a prediction and have it come true before accepting it, we accept models as true if they accurately predict past events (not kidding), which is trivially easy.
I can’t answer the question directly. However, there has been [at least one large-scale review](http://www.sciencemag.org/content/306/5702/1686.full) on the scientific consensus. And it can safely be said that the scientific consensus is **overwhelmingly** that the current trend in global warming is caused by mankind. It would be weird if this consensus came to be without good evidence. The review did a literature mining for peer-reviewed literature published between 1993 and 2003 with the words “global climate change” in their abstracts. They found 928 abstracts. Of those, 75% explicitly or implicitly *endorsed* AGW. 0% rejected it. 25% did not take a position. As Russell has noted in the comment, these also include mitigation proposals which shouldn’t be counted towards the consensus (since they merely refer to other papers) but were. Furthermore, the review only used one key phrase for their search, excluding parts of the available literature. So the review contains one systematic error (inclusion of mitigation proposals) and one unsystematic error. Nevertheless, because of the large number of papers it is still safe to assume that these will not change the reported consensus significantly. Note that this does *not* mean that there are no dissenting opinions in the scientific community – [there are](http://www.youtube.com/user/potholer54#p/c/A4F0994AFB057BB8/1/PoSVoxwYrKI) – merely that the overwhelming majority of experts accepts AGW and that they probably have good reasons to do so. (Still, this “answer’ is more of an FYI than an actual answer since, I want to stress again, it does not provide any of the *evidence* asked for.)
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
I can’t answer the question directly. However, there has been [at least one large-scale review](http://www.sciencemag.org/content/306/5702/1686.full) on the scientific consensus. And it can safely be said that the scientific consensus is **overwhelmingly** that the current trend in global warming is caused by mankind. It would be weird if this consensus came to be without good evidence. The review did a literature mining for peer-reviewed literature published between 1993 and 2003 with the words “global climate change” in their abstracts. They found 928 abstracts. Of those, 75% explicitly or implicitly *endorsed* AGW. 0% rejected it. 25% did not take a position. As Russell has noted in the comment, these also include mitigation proposals which shouldn’t be counted towards the consensus (since they merely refer to other papers) but were. Furthermore, the review only used one key phrase for their search, excluding parts of the available literature. So the review contains one systematic error (inclusion of mitigation proposals) and one unsystematic error. Nevertheless, because of the large number of papers it is still safe to assume that these will not change the reported consensus significantly. Note that this does *not* mean that there are no dissenting opinions in the scientific community – [there are](http://www.youtube.com/user/potholer54#p/c/A4F0994AFB057BB8/1/PoSVoxwYrKI) – merely that the overwhelming majority of experts accepts AGW and that they probably have good reasons to do so. (Still, this “answer’ is more of an FYI than an actual answer since, I want to stress again, it does not provide any of the *evidence* asked for.)
Yes, humans contribute to climate change, but there is significant disagreement regarding to what degree humans contribute. Climate change happens, and it has been happening for billions of years. That industrialized human existence is but an insignificant blip on the geological time scale undermines the ***frequentist*** views on significance. To promote convenient views on anthropogenic climate change (ACC), we are often show ***recentist*** graphs such as this: [![https://www.ncdc.noaa.gov/monitoring-references/faq/images/global-temp-and-co2-1880-2009.gif](https://i.stack.imgur.com/rNKae.gif)](https://i.stack.imgur.com/rNKae.gif) The premise is that correlation implies causation. However, in addition to the greenhouse effect, there are other [facile natural mechanisms](http://www.earth-syst-dynam.net/8/177/2017/) which help to explain this correlation. These mechanisms are not mutually exclusive but tend to support the idea that temperature causes carbon --- not the reverse. When you take a step back from the ***recentist*** view in order to examine a longer time scale, this relationship between temperature and CO2 weakens. In fact, it indicates that the Earth was warmer even over the most recent Milankovitch cycle. This directly contravenes views that ACC is a result of the human industrial revolution. [![Temperature over the last phase of the Milankovitch Cycle](https://i.stack.imgur.com/aM250.gif)](https://i.stack.imgur.com/aM250.gif) But then again, we are often reminded that the correlation is significant over longer periods (if you cherry-pick the data, that is), as evidenced here: [![https://wattsupwiththat.com/2016/12/16/climate-change-debate-latest-results/](https://i.stack.imgur.com/Xy40z.jpg)](https://i.stack.imgur.com/Xy40z.jpg) However, this relationship only holds while Milankovitch cycles are relevant. Over even longer geological time periods, the relationship between CO2 and temperature is nil: [![Phanerzoic CO2](https://i.stack.imgur.com/lGdJ9.png)](https://i.stack.imgur.com/lGdJ9.png) So, I think it's important to take all facts into consideration. Anyway, a more extended version of this argument against "the consensus" argument is found [here](http://the-world-is.com/blog/2017/04/desmog-blogs-mission-statement-quashes-rational-skepticism/).
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Humans affect the weather in mainly the following ways: Direct emissions of various gasses ================================== Typically CO2 is considered, but also other greenhouse gasses. The greenhouse effect of carbon dioxide was first measured in 1859. ![Greenhouse effect](https://i.stack.imgur.com/4Pc5W.jpg) [source](https://en.wikipedia.org/wiki/File:The_green_house_effect.svg) > > In the 19th century, scientists realized that gases in the atmosphere cause a "greenhouse effect" which affects the planet's temperature. These scientists were interested chiefly in the possibility that a lower level of carbon dioxide gas might explain the ice ages of the distant past. At the turn of the century, Svante Arrhenius calculated that emissions from human industry might someday bring a global warming. Other scientists dismissed his idea as faulty. In 1938, G.S. Callendar argued that the level of carbon dioxide was climbing and raising global temperature, but most scientists found his arguments implausible. It was almost by chance that a few researchers in the 1950s discovered that global warming truly was possible. In the early 1960s, C.D. Keeling measured the level of carbon dioxide in the atmosphere: it was rising fast. Researchers began to take an interest, struggling to understand how the level of carbon dioxide had changed in the past, and how the level was influenced by chemical and biological forces. They found that the gas plays a crucial role in climate change, so that the rising level could gravely affect our future. > > > —[The Carbon Dioxide Greenhouse Effect](http://www.aip.org/history/climate/co2.htm) ![List of greenhouse gases](https://i.stack.imgur.com/Zhm68.jpg) [source](https://en.wikipedia.org/wiki/IPCC_list_of_greenhouse_gases) Farming ======= Another man-made source is the [direct emission](https://web.archive.org/web/20111130103419/http://jas.fass.org/content/77/6/1392.abstract) of [greenhouse gasses](http://www.practicalchemistry.org/experiments/the-greenhouse-effect,296,EX.html) through farming (funny, but true!): manure (and cows) produce methane which is a pretty effective greenhouse gas. ![US cattle methane emissions](https://i.stack.imgur.com/aS0wq.gif) [source](http://www.epa.gov/rlep/faq.html) > > Increasing atmospheric concentrations of methane have led scientists to examine its sources of origin. Ruminant livestock can produce 250 to 500 L of methane per day. This level of production results in estimates of the contribution by cattle to global warming that may occur in the next 50 to 100 yr to be a little less than 2%. > > > —[Methane emissions from cattle](https://www.ncbi.nlm.nih.gov/pubmed/8567486) Deforestation ============= Plants "fix" carbon (a phenomena called "Carbon sequestration"), the less plants, the less fixing (and the more carbon released by fires). ![Forest carbon cycle](https://i.stack.imgur.com/5ap7d.jpg) [source](https://forestthreats.org/products/news-updates/volume-1-issue-2-winter-2008/what-happens-to-all-the-carbon) > > ![Carbon sequestration](https://i.stack.imgur.com/I1kss.jpg) > > > —[Carbon sequestration: Forest and soil, by Jukka Muukkonen, Statistics Finland](https://unstats.un.org/unsd/envaccounting/londongroup/meeting14/LG14_12a.pdf) The Oceans ========== Changes to the [biological equilibrium](https://www.nature.com/articles/387272a0) of the oceans affect the climate because marine biology is known to have a [large carbon-fixating effect](https://www.gfdl.noaa.gov/bibliography/related_files/jls9202.pdf) ![Carbon sequestration by the ocean](https://i.stack.imgur.com/qTvNr.jpg) [source](https://web.archive.org/web/20170316060635/http://theresilientearth.com/?q=content/ocean-co2-storage-revised) > > One of the most promising places to sequester carbon is in the oceans, which currently take up a third of the carbon emitted by human activity, roughly two billion metric tons each year. > > > —[Carbon Sequestration in the Ocean](http://www.lbl.gov/Science-Articles/Archive/sea-carb-bish.html) Conclusion ========== All four of these effect can be shown in a laboratory and no model is required to do so, but we have very very good models to explain the lab experiments. Differently from the lab, the whole climate system is much less understood. And, yes, the model are not as reliable as we would like. However — due to our knowledge of chemistry — it is undeniable that we are affecting climate. Note that nobody has asserted that human intervention is the *only* cause of climate change, but it can be said, with a straight face, that humans are changing climate. A very simple example, the rise in temperature melts ice at the pole - which is not only responsible for reflecting some light out of the atmosphere, but also contains methane, which is then released. The debate can only be on "how much" and "how well can we reverse the trend (even beyond our contribution)".
The [IPCC report](http://www.ipcc.ch/publications_and_data/publications_ipcc_fourth_assessment_report_wg1_report_the_physical_science_basis.htm) gives the following probabilities: > > The total radiative forcing of the Earth’s climate > due to increases in the concentrations of the LLGHGs > CO2, CH4 and N2O, and very likely the rate of increase > in the total forcing due to these gases over the > period since 1750 > > > What do they mean when they say *very likely*? They mean 0.95 < p < 0.99. When someone says that the evidence for climate change is comparable to the evidence for evolution they are either advocating that the IPCC is wrong by orders of magnitude or they are gravely insulting academic biology. 255 members of the US National Academy of Sciences including 11 Nobel Price winners issued [a letter](https://www.theguardian.com/environment/2010/may/06/climate-science-open-letter) that claims: > > For instance, there is compelling scientific evidence that our planet is about 4.5bn years old (the theory of the origin of Earth), that our universe was born from a single event about 14bn years ago (the Big Bang theory), and that today's organisms evolved from ones living in the past (the theory of evolution). Even as these are overwhelmingly accepted by the scientific community, fame still awaits anyone who could show these theories to be wrong. Climate change now falls into this category. > > > In an attempt to defend orthodox wisdom mainstream scientists seem to be willing to pretend that the evidence is for climate change is a lot better than it actually is. [Other people](http://andrewgelman.com/2009/12/15/say_a_little_pr/) who see themselves in defense of climate change think that the IPCC is a bit overconfident. There are a lot of reasons why that might be the case: * Humans typically suffer from confirmation bias. Even a friendly reading of the [climate gate emails](https://wikileaks.org/wiki/Climatic_Research_Unit_emails,_data,_models,_1996-2009) that Wikileaks published suggest that they don't engage in mental strategies to reduce their vulnerability to confirmation bias. * The computer code that they use to generate the models has [low standards](https://pjmedia.com/blog/climategate-computer-codes-are-the-real-story/). It has probably a lot of bugs that throw extra inaccuracy into the models that aren't accounted for. * Some data isn't openly available to allow for independent verification. * We have seen in the financial crisis that complex computer models often include a lot of assumptions that make them overconfident. * Climate scientists test their models on past data and generally don't make predictions about the future to test their models. [As the models have a lot of parameters that makes the models to appear better than they are.](http://archives.sethroberts.net/blog/2011/02/27/the-best-argument-against-man-made-global-warming/) That doesn't mean that we should assume p=0 but it might be reasonable to use a lower likelihood value than the IPCC value. If we go from 0.95 < p < 0.99 to 0.80 < p < 0.90 we have more than a 10% chance of being wrong. Even if we just go to 0.90 < p < 0.95 we have more than a 5% chance of being wrong. Why does that matter? Isn't p=0.80 enough for starting to reduce CO2 emissions? That might be true. If we, however, start geoengineering, the confidence in our models matters a great deal. Starting geoengineering on the assumptions that our models are magnitudes better than they really are is dangerous. Part of being a good skeptic should be to avoid being more confident in your beliefs than the data warrants. We should move past binary classification. Instead of showing tribal loyalty we should call out our friends when they overstate the evidence.
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Yes, humans cause climate change (each doubling of CO2 causes about [1C increase](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/2/)). It's really a meaningless question. [Any input to any chaos system will cause some effect on that system](http://en.wikipedia.org/wiki/Chaos_theory#Sensitivity_to_initial_conditions). Do we know what effect we are having? Can we measure/predict it? Do we have any idea how to alter/change/control that change? And really, what the hubbub is about is not "will the climate change", but ["will it change in a really bad way"](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/) (ie, catastrophic global warming) According to [Peter Stott](http://worldnews.msnbc.msn.com/_news/2012/04/23/11144098-gaia-scientist-james-lovelock-i-was-alarmist-about-climate-change) models failed to predict current temperatures (though he echoes the recurring claim that they'll be correct in the future), [which means that no existing model has predicted, correctly, any significant amount of future climate change](http://www.drroyspencer.com/2012/02/ten-years-after-the-warming/), and [new research is steadily revealing flaws](http://www.theregister.co.uk/2012/06/25/antarctic_ice_not_melting/) in existing catastrophic prediction models, so the answer to those questions should be no. A model which has yet to make an accurate prediction cannot be said to be an accurate model. Therefore, we don't know what effect we're having, we can't predict it, and as a result of those two, we do not know how to alter or control that affect. Causation on a chaos system is nigh impossible to prove with our current abilities, so we rely on modeling. Unfortunately, instead of insisting that a model make a prediction and have it come true before accepting it, we accept models as true if they accurately predict past events (not kidding), which is trivially easy.
Yes, humans contribute to climate change, but there is significant disagreement regarding to what degree humans contribute. Climate change happens, and it has been happening for billions of years. That industrialized human existence is but an insignificant blip on the geological time scale undermines the ***frequentist*** views on significance. To promote convenient views on anthropogenic climate change (ACC), we are often show ***recentist*** graphs such as this: [![https://www.ncdc.noaa.gov/monitoring-references/faq/images/global-temp-and-co2-1880-2009.gif](https://i.stack.imgur.com/rNKae.gif)](https://i.stack.imgur.com/rNKae.gif) The premise is that correlation implies causation. However, in addition to the greenhouse effect, there are other [facile natural mechanisms](http://www.earth-syst-dynam.net/8/177/2017/) which help to explain this correlation. These mechanisms are not mutually exclusive but tend to support the idea that temperature causes carbon --- not the reverse. When you take a step back from the ***recentist*** view in order to examine a longer time scale, this relationship between temperature and CO2 weakens. In fact, it indicates that the Earth was warmer even over the most recent Milankovitch cycle. This directly contravenes views that ACC is a result of the human industrial revolution. [![Temperature over the last phase of the Milankovitch Cycle](https://i.stack.imgur.com/aM250.gif)](https://i.stack.imgur.com/aM250.gif) But then again, we are often reminded that the correlation is significant over longer periods (if you cherry-pick the data, that is), as evidenced here: [![https://wattsupwiththat.com/2016/12/16/climate-change-debate-latest-results/](https://i.stack.imgur.com/Xy40z.jpg)](https://i.stack.imgur.com/Xy40z.jpg) However, this relationship only holds while Milankovitch cycles are relevant. Over even longer geological time periods, the relationship between CO2 and temperature is nil: [![Phanerzoic CO2](https://i.stack.imgur.com/lGdJ9.png)](https://i.stack.imgur.com/lGdJ9.png) So, I think it's important to take all facts into consideration. Anyway, a more extended version of this argument against "the consensus" argument is found [here](http://the-world-is.com/blog/2017/04/desmog-blogs-mission-statement-quashes-rational-skepticism/).
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Yes, humans cause climate change (each doubling of CO2 causes about [1C increase](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/2/)). It's really a meaningless question. [Any input to any chaos system will cause some effect on that system](http://en.wikipedia.org/wiki/Chaos_theory#Sensitivity_to_initial_conditions). Do we know what effect we are having? Can we measure/predict it? Do we have any idea how to alter/change/control that change? And really, what the hubbub is about is not "will the climate change", but ["will it change in a really bad way"](http://www.forbes.com/sites/warrenmeyer/2012/02/09/understanding-the-global-warming-debate/) (ie, catastrophic global warming) According to [Peter Stott](http://worldnews.msnbc.msn.com/_news/2012/04/23/11144098-gaia-scientist-james-lovelock-i-was-alarmist-about-climate-change) models failed to predict current temperatures (though he echoes the recurring claim that they'll be correct in the future), [which means that no existing model has predicted, correctly, any significant amount of future climate change](http://www.drroyspencer.com/2012/02/ten-years-after-the-warming/), and [new research is steadily revealing flaws](http://www.theregister.co.uk/2012/06/25/antarctic_ice_not_melting/) in existing catastrophic prediction models, so the answer to those questions should be no. A model which has yet to make an accurate prediction cannot be said to be an accurate model. Therefore, we don't know what effect we're having, we can't predict it, and as a result of those two, we do not know how to alter or control that affect. Causation on a chaos system is nigh impossible to prove with our current abilities, so we rely on modeling. Unfortunately, instead of insisting that a model make a prediction and have it come true before accepting it, we accept models as true if they accurately predict past events (not kidding), which is trivially easy.
The [IPCC report](http://www.ipcc.ch/publications_and_data/publications_ipcc_fourth_assessment_report_wg1_report_the_physical_science_basis.htm) gives the following probabilities: > > The total radiative forcing of the Earth’s climate > due to increases in the concentrations of the LLGHGs > CO2, CH4 and N2O, and very likely the rate of increase > in the total forcing due to these gases over the > period since 1750 > > > What do they mean when they say *very likely*? They mean 0.95 < p < 0.99. When someone says that the evidence for climate change is comparable to the evidence for evolution they are either advocating that the IPCC is wrong by orders of magnitude or they are gravely insulting academic biology. 255 members of the US National Academy of Sciences including 11 Nobel Price winners issued [a letter](https://www.theguardian.com/environment/2010/may/06/climate-science-open-letter) that claims: > > For instance, there is compelling scientific evidence that our planet is about 4.5bn years old (the theory of the origin of Earth), that our universe was born from a single event about 14bn years ago (the Big Bang theory), and that today's organisms evolved from ones living in the past (the theory of evolution). Even as these are overwhelmingly accepted by the scientific community, fame still awaits anyone who could show these theories to be wrong. Climate change now falls into this category. > > > In an attempt to defend orthodox wisdom mainstream scientists seem to be willing to pretend that the evidence is for climate change is a lot better than it actually is. [Other people](http://andrewgelman.com/2009/12/15/say_a_little_pr/) who see themselves in defense of climate change think that the IPCC is a bit overconfident. There are a lot of reasons why that might be the case: * Humans typically suffer from confirmation bias. Even a friendly reading of the [climate gate emails](https://wikileaks.org/wiki/Climatic_Research_Unit_emails,_data,_models,_1996-2009) that Wikileaks published suggest that they don't engage in mental strategies to reduce their vulnerability to confirmation bias. * The computer code that they use to generate the models has [low standards](https://pjmedia.com/blog/climategate-computer-codes-are-the-real-story/). It has probably a lot of bugs that throw extra inaccuracy into the models that aren't accounted for. * Some data isn't openly available to allow for independent verification. * We have seen in the financial crisis that complex computer models often include a lot of assumptions that make them overconfident. * Climate scientists test their models on past data and generally don't make predictions about the future to test their models. [As the models have a lot of parameters that makes the models to appear better than they are.](http://archives.sethroberts.net/blog/2011/02/27/the-best-argument-against-man-made-global-warming/) That doesn't mean that we should assume p=0 but it might be reasonable to use a lower likelihood value than the IPCC value. If we go from 0.95 < p < 0.99 to 0.80 < p < 0.90 we have more than a 10% chance of being wrong. Even if we just go to 0.90 < p < 0.95 we have more than a 5% chance of being wrong. Why does that matter? Isn't p=0.80 enough for starting to reduce CO2 emissions? That might be true. If we, however, start geoengineering, the confidence in our models matters a great deal. Starting geoengineering on the assumptions that our models are magnitudes better than they really are is dangerous. Part of being a good skeptic should be to avoid being more confident in your beliefs than the data warrants. We should move past binary classification. Instead of showing tribal loyalty we should call out our friends when they overstate the evidence.
41
There is lots of evidence that I have seen showing **correlation** between human activities and climate change but what evidence is there to support **causation**?
2011/02/25
[ "https://skeptics.stackexchange.com/questions/41", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/25/" ]
Humans affect the weather in mainly the following ways: Direct emissions of various gasses ================================== Typically CO2 is considered, but also other greenhouse gasses. The greenhouse effect of carbon dioxide was first measured in 1859. ![Greenhouse effect](https://i.stack.imgur.com/4Pc5W.jpg) [source](https://en.wikipedia.org/wiki/File:The_green_house_effect.svg) > > In the 19th century, scientists realized that gases in the atmosphere cause a "greenhouse effect" which affects the planet's temperature. These scientists were interested chiefly in the possibility that a lower level of carbon dioxide gas might explain the ice ages of the distant past. At the turn of the century, Svante Arrhenius calculated that emissions from human industry might someday bring a global warming. Other scientists dismissed his idea as faulty. In 1938, G.S. Callendar argued that the level of carbon dioxide was climbing and raising global temperature, but most scientists found his arguments implausible. It was almost by chance that a few researchers in the 1950s discovered that global warming truly was possible. In the early 1960s, C.D. Keeling measured the level of carbon dioxide in the atmosphere: it was rising fast. Researchers began to take an interest, struggling to understand how the level of carbon dioxide had changed in the past, and how the level was influenced by chemical and biological forces. They found that the gas plays a crucial role in climate change, so that the rising level could gravely affect our future. > > > —[The Carbon Dioxide Greenhouse Effect](http://www.aip.org/history/climate/co2.htm) ![List of greenhouse gases](https://i.stack.imgur.com/Zhm68.jpg) [source](https://en.wikipedia.org/wiki/IPCC_list_of_greenhouse_gases) Farming ======= Another man-made source is the [direct emission](https://web.archive.org/web/20111130103419/http://jas.fass.org/content/77/6/1392.abstract) of [greenhouse gasses](http://www.practicalchemistry.org/experiments/the-greenhouse-effect,296,EX.html) through farming (funny, but true!): manure (and cows) produce methane which is a pretty effective greenhouse gas. ![US cattle methane emissions](https://i.stack.imgur.com/aS0wq.gif) [source](http://www.epa.gov/rlep/faq.html) > > Increasing atmospheric concentrations of methane have led scientists to examine its sources of origin. Ruminant livestock can produce 250 to 500 L of methane per day. This level of production results in estimates of the contribution by cattle to global warming that may occur in the next 50 to 100 yr to be a little less than 2%. > > > —[Methane emissions from cattle](https://www.ncbi.nlm.nih.gov/pubmed/8567486) Deforestation ============= Plants "fix" carbon (a phenomena called "Carbon sequestration"), the less plants, the less fixing (and the more carbon released by fires). ![Forest carbon cycle](https://i.stack.imgur.com/5ap7d.jpg) [source](https://forestthreats.org/products/news-updates/volume-1-issue-2-winter-2008/what-happens-to-all-the-carbon) > > ![Carbon sequestration](https://i.stack.imgur.com/I1kss.jpg) > > > —[Carbon sequestration: Forest and soil, by Jukka Muukkonen, Statistics Finland](https://unstats.un.org/unsd/envaccounting/londongroup/meeting14/LG14_12a.pdf) The Oceans ========== Changes to the [biological equilibrium](https://www.nature.com/articles/387272a0) of the oceans affect the climate because marine biology is known to have a [large carbon-fixating effect](https://www.gfdl.noaa.gov/bibliography/related_files/jls9202.pdf) ![Carbon sequestration by the ocean](https://i.stack.imgur.com/qTvNr.jpg) [source](https://web.archive.org/web/20170316060635/http://theresilientearth.com/?q=content/ocean-co2-storage-revised) > > One of the most promising places to sequester carbon is in the oceans, which currently take up a third of the carbon emitted by human activity, roughly two billion metric tons each year. > > > —[Carbon Sequestration in the Ocean](http://www.lbl.gov/Science-Articles/Archive/sea-carb-bish.html) Conclusion ========== All four of these effect can be shown in a laboratory and no model is required to do so, but we have very very good models to explain the lab experiments. Differently from the lab, the whole climate system is much less understood. And, yes, the model are not as reliable as we would like. However — due to our knowledge of chemistry — it is undeniable that we are affecting climate. Note that nobody has asserted that human intervention is the *only* cause of climate change, but it can be said, with a straight face, that humans are changing climate. A very simple example, the rise in temperature melts ice at the pole - which is not only responsible for reflecting some light out of the atmosphere, but also contains methane, which is then released. The debate can only be on "how much" and "how well can we reverse the trend (even beyond our contribution)".
Yes, humans contribute to climate change, but there is significant disagreement regarding to what degree humans contribute. Climate change happens, and it has been happening for billions of years. That industrialized human existence is but an insignificant blip on the geological time scale undermines the ***frequentist*** views on significance. To promote convenient views on anthropogenic climate change (ACC), we are often show ***recentist*** graphs such as this: [![https://www.ncdc.noaa.gov/monitoring-references/faq/images/global-temp-and-co2-1880-2009.gif](https://i.stack.imgur.com/rNKae.gif)](https://i.stack.imgur.com/rNKae.gif) The premise is that correlation implies causation. However, in addition to the greenhouse effect, there are other [facile natural mechanisms](http://www.earth-syst-dynam.net/8/177/2017/) which help to explain this correlation. These mechanisms are not mutually exclusive but tend to support the idea that temperature causes carbon --- not the reverse. When you take a step back from the ***recentist*** view in order to examine a longer time scale, this relationship between temperature and CO2 weakens. In fact, it indicates that the Earth was warmer even over the most recent Milankovitch cycle. This directly contravenes views that ACC is a result of the human industrial revolution. [![Temperature over the last phase of the Milankovitch Cycle](https://i.stack.imgur.com/aM250.gif)](https://i.stack.imgur.com/aM250.gif) But then again, we are often reminded that the correlation is significant over longer periods (if you cherry-pick the data, that is), as evidenced here: [![https://wattsupwiththat.com/2016/12/16/climate-change-debate-latest-results/](https://i.stack.imgur.com/Xy40z.jpg)](https://i.stack.imgur.com/Xy40z.jpg) However, this relationship only holds while Milankovitch cycles are relevant. Over even longer geological time periods, the relationship between CO2 and temperature is nil: [![Phanerzoic CO2](https://i.stack.imgur.com/lGdJ9.png)](https://i.stack.imgur.com/lGdJ9.png) So, I think it's important to take all facts into consideration. Anyway, a more extended version of this argument against "the consensus" argument is found [here](http://the-world-is.com/blog/2017/04/desmog-blogs-mission-statement-quashes-rational-skepticism/).
199,197
We have integrated our Salesforce and Marketing Cloud instances via the Marketing Cloud Connector. Our Marketing Cloud instance has 4 business units. We recently set up a synchronized data source between Salesforce and the Marketing Cloud at the parent business unit. However, we need to access the synchronized data extension from one of the child business units. Our understanding is that we need to write a query for this but we aren't having any luck finding any documentation regarding how to write a query. Please point us in the right direction.
2017/11/16
[ "https://salesforce.stackexchange.com/questions/199197", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/28171/" ]
In my experience, you can manage this through a combination of queries, date extensions, and automations to populate children business units (BUs). 1. Create as many regular Data Extensions (DEs) in the parent BU as you need to populate from the Synchronized Data Source (SDS) DEs. 2. Create your queries to push from the SDS DEs into regular DEs. 3. Setup up an automation to run your queries on a schedule. 4. Replicate steps 1 through 3 as needed in the appropriate BUs. Depending on your data model, you may need to break things into pieces in order to manage this effectively. One major difference in the child BUs is you will need to modify your queries to pull from the parent. Add the prefix "Ent" to your parent object(s). It's important to either name the field attributes exactly the same in both places or include naming convention logic to avoid errors. Here's a simple example that shows how to pull some data from the Contact object: ``` Select c.id as "Contact ID" , c.email as "Contact Email" from Ent.Contact_Salesforce as c ``` In this scenario, I did not use Shared Data Extensions because each BU needed its own data that was not to be shared with any other BUs.
You can't access synchronised DEs in child BU, I recommend below steps: 1. In Shared Data Extension folder, create folder for each business unit, for example if you have two BUs: Home Service and Business Service, the folder structure looks like: > > Shared Data Extension > > > * Home Service > * Business Service > > > 2. Right click on each BU folder and only give permission to that child BU and parent BU, so user in one BU cannot access the data folder for another BU 3. In Child BU folder, create data extension with fields exactly like your Synchronized data extension (Lead\_Salesforce, Contact\_Salesforce etc) 4. In Parent BU's Automation Studio, create an Automation job, for the 1st step: drag a query activity to write query to copy data from Syncrhonized data extension into new data extension. for example for Lead\_Salesforce > > select \* from Lead\_Salesforce > > > Then select the DE you created in Shared Data Extension-> Child BU folder, use "Overwrite" type, when it runs it will empty the target DE and fetch all records again. Setup schedule to run every x minutes (by default, synchronised DE are refreshed every 15 minutes, so you can set your automation job to run every 30 minutes. 1 hour etc) 5. You should have data available in that DE at child BU level.
57,740
Sometimes I want a special font for the word "true", use it in mathmode as well as outside, and have a correct space afterwords if I am not in mathmode. Using ``` \newcommand{\tru}{\ifmmode {\text{\upshape \bfseries true}}% \else {{\upshape \bfseries true}\@\xspace}\fi}% ``` xspace sometimes does not put a space when it should, eg. in `$s=$ \tru iff`. Why? How can I fix it?
2012/05/29
[ "https://tex.stackexchange.com/questions/57740", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/7635/" ]
`\xspace` looks ahead to the next token to see if it should add space or not, you have extra brace groups in your definition which will defeat that. The outer brace groups in both your true and false branch are not doing much, `{\text{\upshape \bfseries true}}` is more or less the same as `\text{\upshape \bfseries true}`. Try ``` \newcommand{\tru}{\relax\ifmmode \text{\upshape \bfseries true}% \else {\upshape \bfseries true}\@\expandafter\xspace\fi} ```
In this particular case I don't see why doing all that work: ``` \newcommand{\tru}{\textbf{\textup{true}}\xspace} ``` will do exactly the same. On the other hand, `\text` works both in math mode and in text mode. In text mode it will produce an `\mbox` which is probably what you want ("true" can't be hyphenated, but longer words could). So ``` \newcommand{\tru}{\text{\upshape \bfseries true}\xspace} ``` would be sufficient (and perhaps better, if you don't want the word to be tried for hyphenation). The `\@` is not necessary, as after an `\mbox` the space factor is always 1000. It wouldn't also with the more complicated definition, because the sfcode of `e` is 1000.
25,443
This seems like a simple thing to do, but for some reason no one's been able to give me a clear answer at all. If I'm working with one stereo full mix track and one vocal track, how can I get the full mix to duck down when the voice over comes in? I haven't got any external hardware to work with -- just the base ProTools 8 plugins.
2010/12/16
[ "https://sound.stackexchange.com/questions/25443", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/-1/" ]
Set up a compressor on the stereo track (PT's own will do). Send the vocal track through a bus(mono) into the sidechain input of the compressor. Make sure to activate the sidechain, it's the knob with the key on it in the Sidechain section of the plugin. Experiment with the knobs in order to get it to sound smooth. Depends on what you are working on though. For bigger projects like commentary on a feature film it's a time saver bu not always the best choice. I wouldn't recommend it for smaller things like ads or infomercials, then it's best to do a volume automation manually. It can be hard to make it sound natural and smooth, bear in mind that in order to duck a signal it needs to reach the threshold first. So it'll never be as good as manual volume control. Hope this helps.
* Create an empty project * Import or create an audio track you want to duck (mono) (track A) * Create an Aux track and assign its input to bus1 (track B) * In track A send 0 dB to bus1 = track B * Put Track B in mute (it only need for the compressor to "key") * Create another Aux track and assign its input to bus2 (Track C) * In track A send 0 dB to bus2 = track C * In track C put in the First insert slot the effect you need to duck (reverb or delay) * Then, in the second slot in Track C, put the compressor that will make the duck (use Dynamics->Compressor/Limiter Dyn 3 (mono)) * Now open the compressor setting and in the "key input" select Bus 1 *and* in the SIDE-CHAIN area activate the button with a key icon Finally experiment with the compressor parameters to find out your ducking amount. For example try this: Ratio=2:1, Attack=10.0 ms, Release=1.5 s, Thresh=-39.5 dB Work especially on Thresh to find the right amount of ducking.
8,614,862
Is it possible to select an element that is focused, like a:focus or input:focus, but on the other element, such as div, li, span or else? If it's not possible, how can it be substituted with a tag? I am trying to modify height of a li element when it's focused, tried with a, but the height won't change. --- Requested Info : > > "Can you also explain how do you put focus on LI?" > > > Via css selector `li:focus`. See <https://jsfiddle.net/s4nji/Rjqy5/>.
2011/12/23
[ "https://Stackoverflow.com/questions/8614862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113225/" ]
That's simple: just add a `tabindex` attribute to the elements which normally don't receive focus.
You can't focus list items. Not even using a script. I've tried doing `$("li:first").focus()` but it doesn't do anything. CSS doesn't get set as if it was focussed. This simply means that you either can't focus list items or that `:focus` pseudo classes don't work on list items. Put anchors inside list items ----------------------------- ``` <ul> <li><a href="#">...</a></li> <li><a href="#">...</a></li> <li><a href="#">...</a></li> ... </ul> ``` This will seemingly focus your list item but it will actually focus anchor tags.
25,324,151
Here's what brought this question up: ``` with open(path + "/OneChance1.mid") as f: for line in f.readline(): print(line) ``` Here I am simply trying to read a midi file to scour its contents. I then receive this error message: `UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 153: character maps to <undefined>` If I use `open()`'s second param like so: with `open(path + "/OneChance1.mid"m encoding='utf-8) as f:` then I receive this error: `UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 13: invalid start byte` If I change the encoding param to ascii I get another error about an ordinal being out of range. Lastly I tried utf-16 and it said that the file didn't start with BOM (which made me smile for some reason). Also, if I ignore the errors I get characters that resemble nothing of the kind of data I am expecting. My expectations are based on this source: <http://www.sonicspot.com/guide/midifiles.html> Anyway, does anyone know what kind of encoding a midi file uses? My research is coming up short in that regard so I thought it would be worth asking on SO. Or maybe someone can point out some other possibilities or blunders?
2014/08/15
[ "https://Stackoverflow.com/questions/25324151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820306/" ]
MIDI files are **binary content**. By opening the file as a text file however, Python applies the default system encoding in trying to decode the text as Unicode. Open the file in *binary mode* instead: ``` with open(midifile, 'rb') as mfile: leader = mfile.read(4) if leader != b'MThd': raise ValueError('Not a MIDI file!') ``` You'd have to study the [MIDI standard file format](http://faydoc.tripod.com/formats/mid.htm) if you wanted to learn more from the file. Also see [What is the structure of a MIDI file?](https://stackoverflow.com/questions/3087277/what-is-the-structure-of-a-midi-file)
It's a binary file, it's not text using a text encoding like you seem to expect. To open a file in binary mode in Python, pass a string containing `"b"` as the second argument to [`open()`](https://docs.python.org/2/library/functions.html#open). [This page](http://www.sonicspot.com/guide/midifiles.html) contains a description of the format.
30,660,972
serious problem here, I have an array like this: ``` [[0,50],[0,68],[1,26],[2,9],[2,32]] ``` The form I need is to split this array into two separated arrays like this: ``` array1 = [[0,50][1,0][2,9]] array2 = [[0,68][1,26][2,32]] ``` Yeah you are right guys, I need that to build flot chart. If anybody interested in source of data this is how it looks in firebase: ``` { "1433203200000" : { "-JpgJnANTpQFprRieImv" : { "events" : 5, "name" : "Home office", "returningVisitors" : 9, "totalVisitors" : 50 }, "-JqsQjFTjHpzKqWgE_KJ" : { "events" : 10, "name" : "Samin Place", "returningVisitors" : 32, "totalVisitors" : 68 } }, "1433289600000" : { "-JqsQjFTjHpzKqWgE_KJ" : { "name" : "Samin Place", "newVisitors" : 1, "returningVisitors" : 25, "totalVisitors" : 26 } }, "1433376000000" : { "-JpgJnANTpQFprRieImv" : { "events" : 5, "name" : "Home office", "returningVisitors" : 9, "totalVisitors" : 9 }, "-JqsQjFTjHpzKqWgE_KJ" : { "events" : 10, "name" : "Samin Place", "returningVisitors" : 32, "totalVisitors" : 32 } } } ``` The point is loop each timestamp and each child, there we have totalVisitors that's the value I need for my chart. **BONUS** As you can see first timestamp have two childs thats fine, but second timestamp have only one child - "-JqsQjFTjHpzKqWgE\_KJ" so I need to add null value for missing one into new array (in our example it's array1 second position). That's what I'm calling **CHALLENGE** :) Any help is very appreciated, thanks for attention. Edit: maybe if it can help to someone this is chart which I need [here is link](http://i.stack.imgur.com/GRaHS.jpg) X-axis - are timestamps Y-axis - totalVisitors value Lines - every unique timestamp child
2015/06/05
[ "https://Stackoverflow.com/questions/30660972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4842562/" ]
I created jsfiddle for you. Please tell, is it what you need? <http://jsfiddle.net/1vdryy3L/1/> ``` // first, we'll get all possible keys ('key' is e.g. "-JpgJnANTpQFprRieImv") var keys = []; for (var i in data) { for (var j in data[i]) { if (keys.indexOf(j) == -1) { keys.push(j); } } } var result = {}, tmp, k; for (i in keys) { tmp = []; k = 0; for (var j in data) { if (data[j][keys[i]]) { tmp.push([k, data[j][keys[i]].totalVisitors]); } else { tmp.push([k, 0]); } k++; } result['array' + i] = tmp; } console.log(JSON.stringify(result)); ```
Something like this should work provided that you are using jQuery. If you are not simply replace the jquery statements with standard js ones. (I have prepared a jsfiddle: [jsfiddle](http://jsfiddle.net/xcjrb5mz/1): ``` var first = [] var second = []; var my_data = { "1433203200000" : { "-JpgJnANTpQFprRieImv" : { "events" : 5, "name" : "Home office", "returningVisitors" : 9, "totalVisitors" : 50 }, "-JqsQjFTjHpzKqWgE_KJ" : { "events" : 10, "name" : "Samin Place", "returningVisitors" : 32, "totalVisitors" : 68 } }, "1433289600000" : { "-JqsQjFTjHpzKqWgE_KJ" : { "name" : "Samin Place", "newVisitors" : 1, "returningVisitors" : 25, "totalVisitors" : 26 } }, "1433376000000" : { "-JpgJnANTpQFprRieImv" : { "events" : 5, "name" : "Home office", "returningVisitors" : 9, "totalVisitors" : 9 }, "-JqsQjFTjHpzKqWgE_KJ" : { "events" : 10, "name" : "Samin Place", "returningVisitors" : 32, "totalVisitors" : 32 } } } var count = 0; $.each(my_data, function(key, value){ if (value["-JpgJnANTpQFprRieImv"]){ first.push([count, value["-JpgJnANTpQFprRieImv"]["totalVisitors"]]) } else { first.push([count, 0]) } if (value["-JqsQjFTjHpzKqWgE_KJ"]){ second.push([count, value["-JqsQjFTjHpzKqWgE_KJ"]["totalVisitors"]]) } else { second.push([count, 0]) } count++; }); ```
37,696,505
I am quite new to MATLAB matrix calculation and don't know how to improve the performance when I have many for-loops. I have tried to figure it out by looking through similar questions, but I still feel puzzled. Here is my code: ``` pred = zeros(n_test,1) % vector saving all prediction results for d = 1:n_test % n_test test data u = user(d); p_locations = zeros(n_location,1); for i = 1:n_location for z = 1:n_topic for r = 1:n_region p_locations(i) = p_locations(i)+para.Pzu(z,u)*para.Pru(r,u)*para.Piz(i,z)*para.Pir(i,r); % calculate the probability of the location i end end end [val, pos] = max(p_locations); % find the location of the largest probability pred(d) = pos; end ``` As commented, basically, I want to predict location for each test data. Then I will compare with ground truth. I have almost 80000 test data and the calculation is really slow. It's already 13 hours and it's still running. So could you teach me how to re-write the code? Thanks a lot!
2016/06/08
[ "https://Stackoverflow.com/questions/37696505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4129364/" ]
Performing broadcasted operations in parts using [`bsxfun`](http://www.mathworks.com/help/matlab/ref/bsxfun.html) and the efficient [`matrix-multiplication`](https://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication), here's a fully vectorized approach - ``` p1 = bsxfun(@times,Pzu(:,user).',permute(Pru(:,user),[2,3,1])); p2 = bsxfun(@times,Piz,permute(Pir,[1,3,2])); [~,m,n] = size(p1); sums = reshape(p2,[],m*n)*(reshape(p1,[],m*n).'); [~, pred_out] = max(sums,[],1); ``` Benchmarking ------------ Benchmarking code - ``` % Setup inputs n_topic = 70; n_test = 70; n_region = 70; n_location = 70; user = randi(n_test,n_test,1); Pzu = rand(n_topic,n_test); Pru = rand(n_region,n_test); Piz = rand(n_location,n_topic); Pir = rand(n_location,n_region); disp('----------- With original loopy approach') tic % ... Original code toc disp('----------- With vectorized approach') tic % ... Proposed code toc max_error = max(abs(pred(:)-pred_out(:))) ``` Output - ``` ----------- With original loopy approach Elapsed time is 1.157094 seconds. ----------- With vectorized approach Elapsed time is 0.016201 seconds. max_error = 0 ```
How about you write the associated matrix operations for this problem. Then you compute the probability of each location by using matrix operations directly not element wise operations. Matlab is much faster to use matrix operations as they use your CPU's vector instructions. Relevant to your use case, bsxfun and potentially sparse matrices, if you can't find a nice dense matrix formulation.
51,459,957
``` package main import ( "fmt" ) func printArray(x [3]int) { fmt.Printf("%d", x[1]); // cannot convert "%d" (type untyped string) to type int // invalid operation: "%d" + v (mismatched types string and int) // for _, v := range x { // fmt.Printf("%d" + v); // } } func main() { a := [3]int{1, 2, 3}; for _, v := range a { fmt.Printf("%d\n", v); } printArray(a); } ``` I can successfully print the array in the go method, but when I pass array into the method, it throws an error when it tries to print. What cause's the method to treat it differently then main method?
2018/07/21
[ "https://Stackoverflow.com/questions/51459957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9273148/" ]
I see your error now. You are trying to concatenate or add the string and the int, instead of passing the two arguments to the function. ``` for _, v := range x { fmt.Printf("%d" + v); // The error is in this line } ``` It should be: ``` func printArray(x [3]int) { for _, v := range x { fmt.Printf("%d", v); } } ```
My Answer is not particularly related to this Question, But I had similar error and the way I solved is updating here, may be some future users may found helpful! **Got the same error for below Code: Here `itemID` is `int`** ``` strSQL := "SELECT item_desc,item_sel_price FROM item_master WHERE item_id=" + itemID) ``` **Solved by using `fmt.Sprintf`** ``` strSQL := fmt.Sprintf("%s%d","SELECT item_desc,item_sel_price FROM item_master WHERE item_id=", itemID) ```
27,377,306
How can i create a menu effect like below, ![enter image description here](https://i.stack.imgur.com/3qWeU.png) Currently my application menu looks like this, ![enter image description here](https://i.stack.imgur.com/t25K9.jpg) **HTML:** ``` <nav id="nav"> <ul id="navigation"> <li><a href="#" class="first">Reports</a></li> <li><a href="#">Analytics</a></li> <li><a href="#">Dashboards</a></li> <li><a href="#">Monitors &raquo;</a> <ul> <li><a href="#">Real time</a></li> <li><a href="#">Real time monitoring</a></li> </ul> </li> </ul> </nav> ``` Here is my css for the li, ``` #nav { display: inline; position:relative; margin:0; padding:0px; } ul#navigation { position:relative; float:left; border-left:0px solid #c4dbe7; list-style-type: none; margin: 0px; padding: 0px; border-right:0px solid #c4dbe7; } ul#navigation li { display:inline; font-size:12px; font-weight:bold; margin:0; padding:0; float:left; position:relative; border-top:0px solid #c4dbe7; border-bottom:0px solid #c4dbe7; } ul#navigation li a { padding:15px 15px; color:#858585; /*text-shadow:1px 1px 0px #fff;*/ text-decoration:none; display:inline-block; border-right:0px solid #fff; border-left:0px solid #C2C2C2; border-top:0px solid #fff; -webkit-transition:color 0.2s linear, background 0.2s linear; -moz-transition:color 0.2s linear, background 0.2s linear; -o-transition:color 0.2s linear, background 0.2s linear; transition:color 0.2s linear, background 0.2s linear; } ul#navigation li a:hover { background:#df191a; color:#282828; } ul#navigation li a.first { border-left: 0 none; } ul#navigation li a.last { border-right: 0 none; } ul#navigation li:hover > a { background:#df191a; } /* Drop-Down Navigation */ ul#navigation li:hover > ul { /*these 2 styles are very important, being the ones which make the drop-down to appear on hover */ visibility:visible; opacity:1; } ul#navigation ul, ul#navigation ul li ul { list-style: none; margin: 0; padding: 0; /*the next 2 styles are very important, being the ones which make the drop-down to stay hidden */ visibility:hidden; opacity:0; position: absolute; z-index: 99999; width:180px; background:#f8f8f8; box-shadow:1px 1px 3px #ccc; /* css3 transitions for smooth hover effect */ -webkit-transition:opacity 0.2s linear, visibility 0.2s linear; -moz-transition:opacity 0.2s linear, visibility 0.2s linear; -o-transition:opacity 0.2s linear, visibility 0.2s linear; transition:opacity 0.2s linear, visibility 0.2s linear; } ul#navigation ul { top: 47px; left: 0px; } ul#navigation ul li ul { top: 0; left: 181px; /* strong related to width:180px; from above */ } ul#navigation ul li { clear:both; width:100%; border:0 none; border-bottom:1px solid #c9c9c9; } ```
2014/12/09
[ "https://Stackoverflow.com/questions/27377306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1749403/" ]
A pseudo-element 'triangle' made using the border technique on the first `li` of any submenu would seem to be the answer. ```css * { margin: 0; padding: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } a { color:white; text-decoration: none; } ul#navigation li { display: inline-block; background: #ccc; vertical-align: top; position: relative; } ul#navigation > li > ul { position: absolute; top:100%; left:0; display: none; } ul#navigation > li:hover > ul { display: block; } ul#navigation > li > ul > li { width:100%; position: relative; background: white; color:grey; border-bottom: 1px solid grey; } ul#navigation > li > ul > li:first-child:before { position: absolute; content:""; bottom:100%; left:25%; transform:translateX(-50%); border: solid transparent; content:" "; height: 0; width: 0; border-bottom-color: white; border-width: 12px; } ul#navigation li a { display: block; height: 0 1rem; line-height: 25px; padding: 0.5rem; } ul#navigation > li > ul > li a { color: grey; white-space:nowrap; } ``` ```html <nav id="nav"> <ul id="navigation"> <li><a href="#" class="first">Reports</a> </li> <li><a href="#">Analytics</a> <ul> <li><a href="#">Real time</a> </li> <li><a href="#">Real time monitoring</a> </li> </ul> </li> <li><a href="#">Dashboards</a> </li> <li><a href="#">Monitors &raquo;</a> <ul> <li><a href="#">Real time</a> </li> <li><a href="#">Real time monitoring</a> </li> </ul> </li> </ul> </nav> ```
I don't know your entire code, but, it's something like this: ``` ul#navigation:before { bottom: 100%; left: 50%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(136, 183, 213, 0); border-bottom-color: #cbcbcb; border-width: 12px; margin-left: -12px; } ``` You will only need to position the triangle on the menu ...
4,993,035
I have the following snippet for distinguishing between clicks and doubleclicks: ``` observeSingleAndDoubleClick: function (element, singleClickHandler, doubleClickHandler, timeout) { var clicks; $(element).observe('click', function (event) { ++clicks; if (clicks === 1) { var timeoutCallback = function (event) { if (clicks === 1) { singleClickHandler.call(this, event); } else { doubleClickHandler.call(this, event); } clicks = 0; }; timeoutCallback.bind(this).delay(timeout / 1000); } }.bind(this)); } ``` Problem: The event does not live anymore when the delay callback gets called. Though it works in Firefox but it does not in IE8. The event object passed to the click handlers is "dead" since the event itself is already passed. Anyone has an advice how to solve this problem?
2011/02/14
[ "https://Stackoverflow.com/questions/4993035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468102/" ]
Don't only observe the click event but also the doubleclick event. ``` $(element).observe('click',singleClickHandler); $(element).observe('dblclick',doubleClickHandler); ``` Here is a changed version after all the discussion: ``` var clicks; observeSingleAndDoubleClick: function (element, singleClickHandler, doubleClickHandler, timeout) { $(element).observe('click', function (event) { ++clicks; if (clicks === 1) { var timeoutCallback = function (event) { if (clicks === 1) { singleClickHandler.call(this, event); } else { doubleClickHandler.call(this, event); } clicks = 0; }; timeoutCallback.bind(this, event).delay(timeout / 1000); } }.bind(this)); ``` }
There's a `dblclick` event id on Prototype. Why don't you use it? ``` observeSingleAndDoubleClick: function (element, singleClickHandler, doubleClickHandler) { $(element).observe('click', function (event) { singleClickHandler.call(this, event); } $(element).observe('dblclick', function (event) { doubleClickHandler.call(this, event); } } ```
4,993,035
I have the following snippet for distinguishing between clicks and doubleclicks: ``` observeSingleAndDoubleClick: function (element, singleClickHandler, doubleClickHandler, timeout) { var clicks; $(element).observe('click', function (event) { ++clicks; if (clicks === 1) { var timeoutCallback = function (event) { if (clicks === 1) { singleClickHandler.call(this, event); } else { doubleClickHandler.call(this, event); } clicks = 0; }; timeoutCallback.bind(this).delay(timeout / 1000); } }.bind(this)); } ``` Problem: The event does not live anymore when the delay callback gets called. Though it works in Firefox but it does not in IE8. The event object passed to the click handlers is "dead" since the event itself is already passed. Anyone has an advice how to solve this problem?
2011/02/14
[ "https://Stackoverflow.com/questions/4993035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468102/" ]
I know the OpenLayers project foes something similar. Look at line 210 in this file: [OpenLayers.Handler.Click sourcecode](http://trac.osgeo.org/openlayers/browser/trunk/openlayers/lib/OpenLayers/Handler/Click.js "See the sourcecode for OpenLayers.Handler.Click"). I don't know how to use this with the Prototype framework, but I hope it can get you on the right way :) Another thing: wouldn't it better to use the mouseUp event instead of the click?
There's a `dblclick` event id on Prototype. Why don't you use it? ``` observeSingleAndDoubleClick: function (element, singleClickHandler, doubleClickHandler) { $(element).observe('click', function (event) { singleClickHandler.call(this, event); } $(element).observe('dblclick', function (event) { doubleClickHandler.call(this, event); } } ```
41,412,360
I am writing a code for Facebook where it takes the URL, ID, Password from a properties file but upon logging in I am hinted with a "Facebook wants to show notifications - Allow - Block" How do I make it so after login it (A.) Presses ESP or ALT+F4 and closes the popup or (B.) Finds the notification and closes it itself. This is what Im using but its not working. Any help is appreciated. ``` public void closePopup() throws InterruptedException{ Thread.sleep(1000); Actions action=new Actions(driver); action.keyDown(Keys.ESCAPE).keyUp(Keys.ESCAPE).build().perform(); ```
2016/12/31
[ "https://Stackoverflow.com/questions/41412360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7327177/" ]
After further research I found my answer. It is a chrome notification so here is the required step to solve my problem. ``` ChromeOptions ops = new ChromeOptions(); ops.addArguments("--disable-notifications"); System.setProperty("webdriver.chrome.driver", "./lib/chromedriver"); driver = new ChromeDriver(ops); ```
**Please Follow below steps :** **Step 1:** //Create a instance of ChromeOptions class ``` ChromeOptions options = new ChromeOptions(); ``` **Step 2:** //Add chrome switch to disable notification - "**--disable-notifications**" ``` options.addArguments("--disable-notifications"); ``` **Step 3:** //Set path for driver exe ``` System.setProperty("webdriver.chrome.driver","path/to/driver/exe"); ``` **Step 4 :** //Pass ChromeOptions instance to ChromeDriver Constructor ``` WebDriver driver =new ChromeDriver(options); ```
587,332
Why is the `*` raised in the first example, unlike the second one? ``` \documentclass{article} \usepackage{amsmath} \begin{document} $ \operatorname{\text{$*$}hello} $ vs. $ *\operatorname{hello} $ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/TVyZN.png)](https://i.stack.imgur.com/TVyZN.png)
2021/03/14
[ "https://tex.stackexchange.com/questions/587332", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/19809/" ]
It's by design of `\operatorname`. In the documentation of `amsopn` we read: > > In operator names, it is sometimes desired to have text-mode > punctuation characters such as \*-/:’. Because the body of an operator > name is set in math mode, these few punctuation characters will not > come out right (wrong symbol/and or wrong spacing). The purpose of > \newmcodes@ is to make them act like their normal text versions. > > > The definition `\newmacodes@` is: `\gdef\newmcodes@{\mathcode‘\’39\mathcode‘\*42\mathcode‘\."613A%` So, the mathcode of `*` is changed in `\operatorname`.
Since you say you are trying to work around the way `\operatorname` handles punctuation, you might have an XY problem. Defining a new command that typesets with the same font and spacing, but does not do that, might work for you: ``` \documentclass{article} \usepackage{amsmath} \makeatletter \newcommand\varopname[1]{\mathop{\operator@font #1}\nolimits} \makeatother \begin{document} $\varopname{*hello}$ \end{document} ``` [![Computer Modern sample](https://i.stack.imgur.com/wNmoi.png)](https://i.stack.imgur.com/wNmoi.png) You might also define a version without `\nolimits` and an equivalent to `\DeclareMathOperator`.
587,332
Why is the `*` raised in the first example, unlike the second one? ``` \documentclass{article} \usepackage{amsmath} \begin{document} $ \operatorname{\text{$*$}hello} $ vs. $ *\operatorname{hello} $ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/TVyZN.png)](https://i.stack.imgur.com/TVyZN.png)
2021/03/14
[ "https://tex.stackexchange.com/questions/587332", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/19809/" ]
It's by design of `\operatorname`. In the documentation of `amsopn` we read: > > In operator names, it is sometimes desired to have text-mode > punctuation characters such as \*-/:’. Because the body of an operator > name is set in math mode, these few punctuation characters will not > come out right (wrong symbol/and or wrong spacing). The purpose of > \newmcodes@ is to make them act like their normal text versions. > > > The definition `\newmacodes@` is: `\gdef\newmcodes@{\mathcode‘\’39\mathcode‘\*42\mathcode‘\."613A%` So, the mathcode of `*` is changed in `\operatorname`.
The operations for `\operatorname` and `\DeclareMathOperator` do `\newmcodes@`, which is defined as ``` % amsopn.sty, line 30: \gdef\newmcodes@{\mathcode`\'39\mathcode`\*42\mathcode`\."613A% \ifnum\mathcode`\-=45 \else \mathchardef\std@minus\mathcode`\-\relax \fi \mathcode`\-45\mathcode`\/47\mathcode`\:"603A\relax} ``` and going to text mode with `\text` doesn't reverse the assignment. The asterisk is now taken from the text font, the same as used for the letters. Perhaps `\text` should revert the assignment, but it's been like this for more than a quarter of a century, so… On the other hand, you can notice that there's no setting to `\ast`. ``` \documentclass{article} \usepackage{amsmath} \DeclareMathOperator{\bad}{{*}hello} \DeclareMathOperator{\good}{{\ast}hello} \begin{document} This has a raised asterisk $\bad$ This has a centered asterisk $\good$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/GaIzz.png)](https://i.stack.imgur.com/GaIzz.png)
587,332
Why is the `*` raised in the first example, unlike the second one? ``` \documentclass{article} \usepackage{amsmath} \begin{document} $ \operatorname{\text{$*$}hello} $ vs. $ *\operatorname{hello} $ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/TVyZN.png)](https://i.stack.imgur.com/TVyZN.png)
2021/03/14
[ "https://tex.stackexchange.com/questions/587332", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/19809/" ]
The operations for `\operatorname` and `\DeclareMathOperator` do `\newmcodes@`, which is defined as ``` % amsopn.sty, line 30: \gdef\newmcodes@{\mathcode`\'39\mathcode`\*42\mathcode`\."613A% \ifnum\mathcode`\-=45 \else \mathchardef\std@minus\mathcode`\-\relax \fi \mathcode`\-45\mathcode`\/47\mathcode`\:"603A\relax} ``` and going to text mode with `\text` doesn't reverse the assignment. The asterisk is now taken from the text font, the same as used for the letters. Perhaps `\text` should revert the assignment, but it's been like this for more than a quarter of a century, so… On the other hand, you can notice that there's no setting to `\ast`. ``` \documentclass{article} \usepackage{amsmath} \DeclareMathOperator{\bad}{{*}hello} \DeclareMathOperator{\good}{{\ast}hello} \begin{document} This has a raised asterisk $\bad$ This has a centered asterisk $\good$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/GaIzz.png)](https://i.stack.imgur.com/GaIzz.png)
Since you say you are trying to work around the way `\operatorname` handles punctuation, you might have an XY problem. Defining a new command that typesets with the same font and spacing, but does not do that, might work for you: ``` \documentclass{article} \usepackage{amsmath} \makeatletter \newcommand\varopname[1]{\mathop{\operator@font #1}\nolimits} \makeatother \begin{document} $\varopname{*hello}$ \end{document} ``` [![Computer Modern sample](https://i.stack.imgur.com/wNmoi.png)](https://i.stack.imgur.com/wNmoi.png) You might also define a version without `\nolimits` and an equivalent to `\DeclareMathOperator`.
14,727,627
I have 2 project in my solution, a `web-service` project and a `win-forms` project. I want to cast returning data of web-service to win-forms data. I have class **Terminal** defined in both projects. In the win app I have written this cast: ``` static public implicit operator List<Terminal>(EService.Terminal[] svcTerminals) { List<Terminal> terminals = new List<Terminal>(); foreach (var svcTerminal in svcTerminals) { Terminal terminal = new Terminal(); terminal.TerminalID = svcTerminal.TerminalID; terminal.TerminalTypeID = svcTerminal.TerminalTypeID; terminal.TerminalGUID = svcTerminal.TerminalGUID; terminal.Description = svcTerminal.Description; terminal.Name = svcTerminal.Name; terminal.PortID = svcTerminal.PortID; terminals.Add(terminal); } return terminals; } ``` but it does not work and gives the error *user-defined conversion must convert to or from enclosing type*, this happens for **List** cast. But in **Terminal** cast everything is ok ``` static public implicit operator Terminal(EService.Terminal svcTerminal) { Terminal terminal = new Terminal(); terminal.TerminalID = svcTerminal.TerminalID; terminal.TerminalTypeID = svcTerminal.TerminalTypeID; terminal.TerminalGUID = svcTerminal.TerminalGUID; terminal.Description = svcTerminal.Description; terminal.Name = svcTerminal.Name; terminal.PortID = svcTerminal.PortID; return terminal; } ``` Can anyone help me fix this so that I can ``` return (List<Terminal>)eService.CheckTerminal(guid, ref cityName, ref portName); ``` Instead of ``` List<Terminal> terminals = new List<Terminal>(); var svcTerminals = eService.CheckTerminal(guid, ref cityName, ref portName); foreach (var svcTerminal in svcTerminals) { Terminal terminal = new Terminal(); terminal.TerminalID = svcTerminal.TerminalID; terminal.TerminalTypeID = svcTerminal.TerminalTypeID; terminal.TerminalGUID = svcTerminal.TerminalGUID; terminal.Description = svcTerminal.Description; terminal.Name = svcTerminal.Name; terminal.PortID = svcTerminal.PortID; terminals.Add((Terminal)svcTerminal); } return terminals; ```
2013/02/06
[ "https://Stackoverflow.com/questions/14727627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471381/" ]
You can do: ``` eService.CheckTerminal(guid, ref cityName, ref portName).Select(x => (Terminal) x); ```
MSDN says > > Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type. > > > So, for his to work you need to move your conversion operator declaration into the class you are converting to (or from), i.e. `List<Terminal>` or `EService.Terminal[]`. Since you can't add methods into a standard classes, I would recommend making this method rather than an operator, or using LINQ.