qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
### It works perfectly well. `$.inArray` returns index of the element found in the given array (or `-1` if not found). As an example, ``` $.inArray("United State", ["United State", "America"]) === 0 $.inArray("Unknown", ["United State", "America"]) === -1 ``` So, in order to check if the element exists in the array you have to use: ``` if ($.inArray("Unknown", ["United State", "America"]) > -1) { // ... } ```
> > The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0. > > > Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1. > > > Read more here: <http://api.jquery.com/jQuery.inArray/>
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
### It works perfectly well. `$.inArray` returns index of the element found in the given array (or `-1` if not found). As an example, ``` $.inArray("United State", ["United State", "America"]) === 0 $.inArray("Unknown", ["United State", "America"]) === -1 ``` So, in order to check if the element exists in the array you have to use: ``` if ($.inArray("Unknown", ["United State", "America"]) > -1) { // ... } ```
From the DOCS : > > Because JavaScript treats 0 as loosely equal to false (i.e. 0 == > false, but 0 !== false), if we're checking for the presence of value > within array, we need to check if it's not equal to (or greater than) > -1. > > > so : ``` if( $.inArray($('#id').text(), a) != -1) alert(2); ```
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
### It works perfectly well. `$.inArray` returns index of the element found in the given array (or `-1` if not found). As an example, ``` $.inArray("United State", ["United State", "America"]) === 0 $.inArray("Unknown", ["United State", "America"]) === -1 ``` So, in order to check if the element exists in the array you have to use: ``` if ($.inArray("Unknown", ["United State", "America"]) > -1) { // ... } ```
Is the search term the first element in your array by any chance? This would return 0, which javascript treats as false. Your if statement should be: ``` if($.inArray($('#id').text(), a) < 0) alert(2); ``` Read the documentation <http://api.jquery.com/jQuery.inArray/>
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
### It works perfectly well. `$.inArray` returns index of the element found in the given array (or `-1` if not found). As an example, ``` $.inArray("United State", ["United State", "America"]) === 0 $.inArray("Unknown", ["United State", "America"]) === -1 ``` So, in order to check if the element exists in the array you have to use: ``` if ($.inArray("Unknown", ["United State", "America"]) > -1) { // ... } ```
Arrays from a split are 0 based indexed, and the string you are asking for is the first one, so it returns a 0 value - which is falsy, so your alerts inside the conditional do not fire because you are getting the 0 index from the inArray. change your input value to "fred,United State, America" and you will see it alert.
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
> > The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0. > > > Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1. > > > Read more here: <http://api.jquery.com/jQuery.inArray/>
Arrays from a split are 0 based indexed, and the string you are asking for is the first one, so it returns a 0 value - which is falsy, so your alerts inside the conditional do not fire because you are getting the 0 index from the inArray. change your input value to "fred,United State, America" and you will see it alert.
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
From the DOCS : > > Because JavaScript treats 0 as loosely equal to false (i.e. 0 == > false, but 0 !== false), if we're checking for the presence of value > within array, we need to check if it's not equal to (or greater than) > -1. > > > so : ``` if( $.inArray($('#id').text(), a) != -1) alert(2); ```
Arrays from a split are 0 based indexed, and the string you are asking for is the first one, so it returns a 0 value - which is falsy, so your alerts inside the conditional do not fire because you are getting the 0 index from the inArray. change your input value to "fred,United State, America" and you will see it alert.
14,844,549
I want to ask a question why this is not working? <http://jsfiddle.net/2FMue/4/> ``` var a = $('input').attr('value').split(','); if(a instanceof Array) alert(1); if($.inArray($('#id').text(), a)) alert(2); if($.inArray('United State', a)) alert(3); // a is array but no return correct match. ``` I split a value into array and use $.inArray to check where a string has in the array. But it will not return correct index. I dont know what is wrong in the example. Please advice. Thank you very much.
2013/02/13
[ "https://Stackoverflow.com/questions/14844549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920368/" ]
Is the search term the first element in your array by any chance? This would return 0, which javascript treats as false. Your if statement should be: ``` if($.inArray($('#id').text(), a) < 0) alert(2); ``` Read the documentation <http://api.jquery.com/jQuery.inArray/>
Arrays from a split are 0 based indexed, and the string you are asking for is the first one, so it returns a 0 value - which is falsy, so your alerts inside the conditional do not fire because you are getting the 0 index from the inArray. change your input value to "fred,United State, America" and you will see it alert.
17,682,034
I changed my windows. But I can not attach `mdf,ldf` files and cannot move or copy them. My error is: > > Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc) > > An exception occurred while executing a Transact-SQL statement or batch. > > CREATE FILE encountered operating system error 5 (Access is denied) while attempting to open or create the physical file 'D:\Project\Masoomi\UniversityService\DataBase\Universityservice.mdf'. (Microsoft SQL Server, **Error: 5123**) > > > I run as administrator too. My windows is 7 and I installed SQL Server 2008 R2. My previous windows was 7 and SQL Server 2008 R2. What shall I do?
2013/07/16
[ "https://Stackoverflow.com/questions/17682034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1181998/" ]
I shared the mdf,ldf files and problem solved.
As another solution I came across this today and was able to resolve it by simply running SQL Server Management Studio as administrator. I am using SQL Server 2008 R2.
9,643,370
I am using generic code (from the iOS Fireworks demo) in a slightly changed way. I have the following in a subclass of UIView. What I want is to make the firework appear at the point the user touches (not hard) and play out for the length of the CAEmitterLayer/CAEmitterCells 'lifetime'. Instead, this is immediately starting when i add it to addSublayer -- like I am sure it is meant to. However, I would like to use it in a slightly different way. Is there a way that I can change this so there is a CATransaction with a completion block (to removeFromSuperlayer) or something like that? Any ideas are welcomed. ``` #import "FireworksView.h" @implementation FireworksView - (void)launchFirework{ //Load the spark image for the particle CAEmitterLayer *mortor = [CAEmitterLayer layer]; mortor.emitterPosition = CGPointMake(self.bounds.size.width/2, self.bounds.size.height*(.75)); mortor.renderMode = kCAEmitterLayerAdditive; //Invisible particle representing the rocket before the explosion CAEmitterCell *rocket = [CAEmitterCell emitterCell]; rocket.emissionLongitude = -M_PI / 2; rocket.emissionLatitude = 0; rocket.lifetime = 1.6; rocket.birthRate = 1; rocket.velocity = 400; rocket.velocityRange = 100; rocket.yAcceleration = 250; rocket.emissionRange = M_PI / 4; rocket.color = CGColorCreateCopy([UIColor colorWithRed:.5 green:.5 blue:.5 alpha:.5].CGColor); rocket.redRange = 0.5; rocket.greenRange = 0.5; rocket.blueRange = 0.5; //Name the cell so that it can be animated later using keypath [rocket setName:@"rocket"]; //Flare particles emitted from the rocket as it flys CAEmitterCell *flare = [CAEmitterCell emitterCell]; flare.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage; flare.emissionLongitude = (4 * M_PI) / 2; flare.scale = 0.4; flare.velocity = 100; flare.birthRate = 45; flare.lifetime = 1.5; flare.yAcceleration = 350; flare.emissionRange = M_PI / 7; flare.alphaSpeed = -0.7; flare.scaleSpeed = -0.1; flare.scaleRange = 0.1; flare.beginTime = 0.01; flare.duration = 0.7; //The particles that make up the explosion CAEmitterCell *firework = [CAEmitterCell emitterCell]; firework.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage; firework.birthRate = 9999; firework.scale = 0.6; firework.velocity = 130; firework.lifetime = 2; firework.alphaSpeed = -0.2; firework.yAcceleration = 80; firework.beginTime = 1.5; firework.duration = 0.1; firework.emissionRange = 2 * M_PI; firework.scaleSpeed = -0.1; firework.spin = 2; //Name the cell so that it can be animated later using keypath [firework setName:@"firework"]; //preSpark is an invisible particle used to later emit the spark CAEmitterCell *preSpark = [CAEmitterCell emitterCell]; preSpark.birthRate = 80; preSpark.velocity = firework.velocity * 0.70; preSpark.lifetime = 1.7; preSpark.yAcceleration = firework.yAcceleration * 0.85; preSpark.beginTime = firework.beginTime - 0.2; preSpark.emissionRange = firework.emissionRange; preSpark.greenSpeed = 100; preSpark.blueSpeed = 100; preSpark.redSpeed = 100; //Name the cell so that it can be animated later using keypath [preSpark setName:@"preSpark"]; //The 'sparkle' at the end of a firework CAEmitterCell *spark = [CAEmitterCell emitterCell]; spark.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage; spark.lifetime = 0.05; spark.yAcceleration = 250; spark.beginTime = 0.8; spark.scale = 0.4; spark.birthRate = 10; preSpark.emitterCells = [NSArray arrayWithObjects:spark, nil]; rocket.emitterCells = [NSArray arrayWithObjects:flare, firework, preSpark, nil]; mortor.emitterCells = [NSArray arrayWithObjects:rocket, nil]; [self.layer addSublayer:mortor]; } ```
2012/03/10
[ "https://Stackoverflow.com/questions/9643370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/263028/" ]
The answer to this is, using CAEmitter, there is NO WAY -- delegate, etc -- to stop the emitter when it ends the cycle. The only thing you can do is gracefully remove it from the layer when you think it should be removed.
Ok, so I was able to sort of achieve this by creating an animation with delegate that fired along with the emitter. in the animationDidStop i made a for loop that went through my view hierarchy and looked for emitters and removed them. it's buggy and I still want a real solution, but this works for now. ``` for (CALayer *layer in _plusButton.layer.sublayers) { if (layer.class == [CAEmitterLayer class]) { [layer removeFromSuperlayer]; } } ```
3,019,427
I know there are plenty of questions here already about this topic (I've read through as many as I could find), but I haven't yet been able to figure out how best to satisfy my particular criteria. Here are the goals: 1. The ASP.NET application will run on a few different web servers, including localhost workstations for development. ~~This means encrypting web.config using a machine key is out.~~ Each "type" or environment of web server (dev, test, prod) has its own corresponding database (dev, test, prod). We want to separate these connection strings so that a developer working on the "dev" code is not able to see any "prod" connection string passwords, nor allow these production passwords to ever get deployed to the wrong server or committed to SVN. 2. The application ~~will~~ should be able to decide which connection string to attempt to use based on the server name (using a switch statement). For example, "localhost" and "dev.example.com" ~~will~~ should know to use the DevDatabaseConnectionString, "test.example.com" will use the TestDatabaseConnectionString, and "www.example.com" will use the ProdDatabaseConnectionString, for example. The reason for this is to limit the chance for any deployment accidents, where the wrong type of web server connects to the wrong database. 3. Ideally, the exact same executables and web.config should be able to run on any of these environments, without needing to tailor or configure each environment separately every time that we deploy (something that seems like it would be easy to forget/mess up one day during a deployment, which is why we moved away from having just one connectionstring that has to be changed on each target). Deployment is currently accomplished via FTP. *Update:* Using "build events " and revising our deployment procedures is probably not a bad idea. 4. ~~We will not have command-line access to the production web server. This means using aspnet\_regiis.exe to encrypt the web.config is out.~~ *Update:* We can do this programmatically so this point is moot. 5. We would prefer to not have to recompile the application whenever a password changes, so using web.config (or db.config or whatever) seems to make the most sense. 6. A developer should not be able to get to the production database password. If a developer checks the source code out onto their localhost laptop (which would determine that it should be using the DevDatabaseConnectionString, remember?) and the laptop gets lost or stolen, it should not be possible to get at the other connection strings. Thus, having a single RSA private key to un-encrypt all three passwords cannot be considered. (Contrary to #3 above, it does seem like we'd need to have three separate key files if we went this route; these could be installed once per machine, and should the wrong key file get deployed to the wrong server, the worst that should happen is that the app can't decrypt anything---and not allow the wrong host to access the wrong database!) 7. UPDATE/ADDENDUM: The app has several separate web-facing components to it: a classic ASMX Web Services project, an ASPX Web Forms app, and a newer MVC app. In order to not go mad having the same connection string configured in each of these separate projects for each separate environment, it would be nice to have this only appear in one place. (Probably in our DAL class library or in a single linked config file.) I know this is probably a subjective question (asking for a "best" way to do something), but given the criteria I've mentioned, I'm hoping that a single best answer will indeed arise. Thank you!
2010/06/11
[ "https://Stackoverflow.com/questions/3019427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110871/" ]
Integrated authentication/windows authentication is a good option. No passwords, at least none that need be stored in the web.config. In fact, it's the option I prefer unless admins have explicity taken it away from me. Personally, for anything that varies by machine (which isn't just connection string) I put in a external reference from the web.config using this technique: <http://www.devx.com/vb2themax/Tip/18880> When I throw code over the fence to the production server admin, he gets a new web.config, but doesn't get the external file-- he uses the one he had earlier.
1. you can have multiple web servers with the same encrypted key. you would do this in machine config just ensure each key is the same. .. one common practice, is to store first connection string encrypted somewhere on the machine such as registry. after the server connects using that string, it will than retrieve all other connection strings which would be managed in the database (also encrypted). that way connection strings can be dynamically generated based on authorization requirements (requestor, application being used, etc) for example the same tables can be accessed with different rights depending on context and users/groups i believe this scenario addresses all (or most?) of your points..
3,019,427
I know there are plenty of questions here already about this topic (I've read through as many as I could find), but I haven't yet been able to figure out how best to satisfy my particular criteria. Here are the goals: 1. The ASP.NET application will run on a few different web servers, including localhost workstations for development. ~~This means encrypting web.config using a machine key is out.~~ Each "type" or environment of web server (dev, test, prod) has its own corresponding database (dev, test, prod). We want to separate these connection strings so that a developer working on the "dev" code is not able to see any "prod" connection string passwords, nor allow these production passwords to ever get deployed to the wrong server or committed to SVN. 2. The application ~~will~~ should be able to decide which connection string to attempt to use based on the server name (using a switch statement). For example, "localhost" and "dev.example.com" ~~will~~ should know to use the DevDatabaseConnectionString, "test.example.com" will use the TestDatabaseConnectionString, and "www.example.com" will use the ProdDatabaseConnectionString, for example. The reason for this is to limit the chance for any deployment accidents, where the wrong type of web server connects to the wrong database. 3. Ideally, the exact same executables and web.config should be able to run on any of these environments, without needing to tailor or configure each environment separately every time that we deploy (something that seems like it would be easy to forget/mess up one day during a deployment, which is why we moved away from having just one connectionstring that has to be changed on each target). Deployment is currently accomplished via FTP. *Update:* Using "build events " and revising our deployment procedures is probably not a bad idea. 4. ~~We will not have command-line access to the production web server. This means using aspnet\_regiis.exe to encrypt the web.config is out.~~ *Update:* We can do this programmatically so this point is moot. 5. We would prefer to not have to recompile the application whenever a password changes, so using web.config (or db.config or whatever) seems to make the most sense. 6. A developer should not be able to get to the production database password. If a developer checks the source code out onto their localhost laptop (which would determine that it should be using the DevDatabaseConnectionString, remember?) and the laptop gets lost or stolen, it should not be possible to get at the other connection strings. Thus, having a single RSA private key to un-encrypt all three passwords cannot be considered. (Contrary to #3 above, it does seem like we'd need to have three separate key files if we went this route; these could be installed once per machine, and should the wrong key file get deployed to the wrong server, the worst that should happen is that the app can't decrypt anything---and not allow the wrong host to access the wrong database!) 7. UPDATE/ADDENDUM: The app has several separate web-facing components to it: a classic ASMX Web Services project, an ASPX Web Forms app, and a newer MVC app. In order to not go mad having the same connection string configured in each of these separate projects for each separate environment, it would be nice to have this only appear in one place. (Probably in our DAL class library or in a single linked config file.) I know this is probably a subjective question (asking for a "best" way to do something), but given the criteria I've mentioned, I'm hoping that a single best answer will indeed arise. Thank you!
2010/06/11
[ "https://Stackoverflow.com/questions/3019427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110871/" ]
Integrated authentication/windows authentication is a good option. No passwords, at least none that need be stored in the web.config. In fact, it's the option I prefer unless admins have explicity taken it away from me. Personally, for anything that varies by machine (which isn't just connection string) I put in a external reference from the web.config using this technique: <http://www.devx.com/vb2themax/Tip/18880> When I throw code over the fence to the production server admin, he gets a new web.config, but doesn't get the external file-- he uses the one he had earlier.
(First, Wow, I think 2 or 3 "quick paragraphs" turned out a little longer than I'd thought! Here I go...) I've come to the conclusion (perhaps you'll disagree with me on this) that the ability to "protect" the web.config whilst on the server (or by using aspnet\_iisreg) has only limited benefit, and is perhaps maybe not such a good thing as it may possibly give a false sense of security. My theory is that if someone is able to obtain access to the filesystem in order to read this web.config in the first place, then they also probably have access to create their own simple ASPX file which can "unprotect" it and reveal its secrets to them. But if unauthorized people are trouncing around in your filesystem—well… then you have bigger problems at hand, so my whole concern is now moot! 1 I also realize that there isn’t a foolproof way to securely hide passwords within a DLL either, as they can eventually be disassembled and discovered, perhaps by using something like ILDASM. 2 An additional measure of ~~security~~ obscurity can be obtained by obfuscating and encrypting your binaries, such as by using Dotfuscator, but this isn’t to be considered “secure.” And again, if someone has read access (and likely write access too) to your binaries and filesystem, you’ve again got bigger problems at hand methinks. To address the concerns I mentioned about not wanting the passwords to live on developer laptops or in SVN: solving this through a separate “.config” file that does not live in SVN is (now!) the blindingly obvious choice. Web.config can live happily in source control, while just the secret parts do not. However---and this is why I’m following up on my own question with such a long response---there are still a few extra steps I’ve taken to try and make this if not any more secure, then at least a little bit more *obscure*. Connection strings we want to try to keep secret (those other than the development passwords) won’t ever live as plain text in *any* files. These are now encrypted first with a secret (symmetric) key---using, of course, the new ridiculous Encryptinator(TM)! utility built just for this purpose---before they get placed in a copy of a “db.config” file. The db.config is then just uploaded only to its respective server. The secret key is compiled directly into the DAL’s dll, which itself would then (ideally!) be further obfuscated and encrypted with something like Dotfuscator. This will hopefully keep out any casual curiosity at the least. I’m not going to worry much at all about the symmetric "DbKey" living in the DLLs or SVN or on developer laptops. It’s the passwords themselves I’ll keep out. We do still need to have a “db.config” file in the project in order to develop and debug, but it has all fake passwords in it except for development ones. Actual servers have actual copies with just their own proper secrets. The db.config file is typically reverted (using SVN) to a safe state and never stored with real secrets in our subversion repository. With all this said, I know it’s not a perfect solution (does one exist?), and one that does still require a post-it note with some deployment reminders on it, but it does seem like enough of an extra layer of hassle that might very well keep out all but the most clever and determined attackers. I’ve had to resign myself to "good-enough" security which isn’t perfect, but does let me get back to work after feeling alright about having given it the ol’ "College Try!" --- 1. Per my comment on June 15 here <http://www.dotnetcurry.com/ShowArticle.aspx?ID=185> - let me know if I'm off-base! -and some more good commentary here [Encrypting connection strings so other devs can't decrypt, but app still has access](https://stackoverflow.com/questions/936253/) here [Is encrypting web.config pointless?](https://stackoverflow.com/questions/1153216/is-encrypting-web-config-pointless) and here [Encrypting web.config using Protected Configuration pointless?](https://stackoverflow.com/questions/682698/) 2. Good discussion and food for thought on a different subject but very-related concepts here: [Securely store a password in program code?](https://stackoverflow.com/questions/3041322/securely-store-a-password-in-program-code) - what really hit home is the Pidgin FAQ linked from the selected answer: If someone has your program, they can get to its secrets.
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
The Working Directory is wherever your files are on your local machine. The Local Repository is the `.git/` subdirectory inside the Working Directory. The Index is a conceptual place that also physically resides in the `.git/` subdirectory.
.git is a place where local repository is stored (not the working directory!) Working directory usually is a directory where the .git directory is placed
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
The Working Directory is wherever your files are on your local machine. The Local Repository is the `.git/` subdirectory inside the Working Directory. The Index is a conceptual place that also physically resides in the `.git/` subdirectory.
Working directory is your code directory Local repository is .git folder in Working directory Remote repository is bare repository on server or in the filesystem
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
The Working Directory is wherever your files are on your local machine. The Local Repository is the `.git/` subdirectory inside the Working Directory. The Index is a conceptual place that also physically resides in the `.git/` subdirectory.
Working Directory is where your code resides on local machine. Git Local repo is .git/ which is generally inside the Working Directory. It contains HEAD and various useful info. You can have a look of what it contains: ``` cd .git ls -a ```
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
The Working Directory is wherever your files are on your local machine. The Local Repository is the `.git/` subdirectory inside the Working Directory. The Index is a conceptual place that also physically resides in the `.git/` subdirectory.
Uttams-MBP:project uttamgc$ ls -al drwxr-xr-x 9 uttamgc staff 288 Sep 28 14:19 .git In the example above, project is the folder or directory [mkdir] once this folder is created I move into project directory [cd project] then I git init from the folder and create .git subdirectory. [the third row with .git is the local repository]
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
Working directory is your code directory Local repository is .git folder in Working directory Remote repository is bare repository on server or in the filesystem
.git is a place where local repository is stored (not the working directory!) Working directory usually is a directory where the .git directory is placed
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
.git is a place where local repository is stored (not the working directory!) Working directory usually is a directory where the .git directory is placed
Working Directory is where your code resides on local machine. Git Local repo is .git/ which is generally inside the Working Directory. It contains HEAD and various useful info. You can have a look of what it contains: ``` cd .git ls -a ```
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
.git is a place where local repository is stored (not the working directory!) Working directory usually is a directory where the .git directory is placed
Uttams-MBP:project uttamgc$ ls -al drwxr-xr-x 9 uttamgc staff 288 Sep 28 14:19 .git In the example above, project is the folder or directory [mkdir] once this folder is created I move into project directory [cd project] then I git init from the folder and create .git subdirectory. [the third row with .git is the local repository]
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
Working directory is your code directory Local repository is .git folder in Working directory Remote repository is bare repository on server or in the filesystem
Working Directory is where your code resides on local machine. Git Local repo is .git/ which is generally inside the Working Directory. It contains HEAD and various useful info. You can have a look of what it contains: ``` cd .git ls -a ```
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
Working directory is your code directory Local repository is .git folder in Working directory Remote repository is bare repository on server or in the filesystem
Uttams-MBP:project uttamgc$ ls -al drwxr-xr-x 9 uttamgc staff 288 Sep 28 14:19 .git In the example above, project is the folder or directory [mkdir] once this folder is created I move into project directory [cd project] then I git init from the folder and create .git subdirectory. [the third row with .git is the local repository]
8,855,880
From [Wikipedia](https://commons.wikimedia.org/wiki/File:Git_data_flow_simplified.svg): ![enter image description here](https://i.stack.imgur.com/r6NBW.png) Where is said "Local repository" located **physically** (in the file system)?
2012/01/13
[ "https://Stackoverflow.com/questions/8855880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586707/" ]
Working Directory is where your code resides on local machine. Git Local repo is .git/ which is generally inside the Working Directory. It contains HEAD and various useful info. You can have a look of what it contains: ``` cd .git ls -a ```
Uttams-MBP:project uttamgc$ ls -al drwxr-xr-x 9 uttamgc staff 288 Sep 28 14:19 .git In the example above, project is the folder or directory [mkdir] once this folder is created I move into project directory [cd project] then I git init from the folder and create .git subdirectory. [the third row with .git is the local repository]
4,379,574
``` NSEntityDescription *entity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:managedObjectContext]; ``` That line doesn't seem to work anymore (I'm pretty sure its that line). I can't seem to work out whats the problem. The application worked perfectly on Xcode with iOS 4.1 and now crashes with this error in the console: ``` 2010-12-07 17:12:27.552 SMSApp[9222:207] +[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580 2010-12-07 17:12:27.553 SMSApp[9222:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580' *** Call stack at first throw: ( 0 CoreFoundation 0x01547be9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x0169c5c2 objc_exception_throw + 47 2 CoreFoundation 0x015497bb +[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x014b9366 ___forwarding___ + 966 4 CoreFoundation 0x014b8f22 _CF_forwarding_prep_0 + 50 5 CoreData 0x00e6f3ca +[NSEntityDescription entityForName:inManagedObjectContext:] + 42 6 SMSApp 0x000046b9 -[MessagesRootViewController reloadMessages:] + 146 7 SMSApp 0x00004a09 -[MessagesRootViewController viewDidLoad] + 85 8 UIKit 0x0052265e -[UIViewController view] + 179 9 UIKit 0x00520a57 -[UIViewController contentScrollView] + 42 10 UIKit 0x00531201 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48 11 UIKit 0x0052f831 -[UINavigationController _layoutViewController:] + 43 12 UIKit 0x00530b4c -[UINavigationController _startTransition:fromViewController:toViewController:] + 524 13 UIKit 0x0052b606 -[UINavigationController _startDeferredTransitionIfNeeded] + 266 14 UIKit 0x00643e01 -[UILayoutContainerView layoutSubviews] + 226 15 QuartzCore 0x010b4451 -[CALayer layoutSublayers] + 181 16 QuartzCore 0x010b417c CALayerLayoutIfNeeded + 220 17 QuartzCore 0x010ad37c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310 18 QuartzCore 0x010ad0d0 _ZN2CA11Transaction6commitEv + 292 19 UIKit 0x0047719f -[UIApplication _reportAppLaunchFinished] + 39 20 UIKit 0x00477659 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690 21 UIKit 0x00481db2 -[UIApplication handleEvent:withNewEvent:] + 1533 22 UIKit 0x0047a202 -[UIApplication sendEvent:] + 71 23 UIKit 0x0047f732 _UIApplicationHandleEvent + 7576 24 GraphicsServices 0x01b2ca36 PurpleEventCallback + 1550 25 CoreFoundation 0x01529064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52 26 CoreFoundation 0x014896f7 __CFRunLoopDoSource1 + 215 27 CoreFoundation 0x01486983 __CFRunLoopRun + 979 28 CoreFoundation 0x01486240 CFRunLoopRunSpecific + 208 29 CoreFoundation 0x01486161 CFRunLoopRunInMode + 97 30 UIKit 0x00476fa8 -[UIApplication _run] + 636 31 UIKit 0x0048342e UIApplicationMain + 1160 32 SMSApp 0x000025c4 main + 102 33 SMSApp 0x00002555 start + 53 ) terminate called after throwing an instance of 'NSException' ``` Any idea where this error is coming from or what is causing it? Just to let you know as well, upgrading to XCode with iOS 4.2 caused some of the files to be deleted from my project. I don't know why this was, whether it was because they were linked files and not actually in the folder I dunno. Any ideas? Thanks // EDIT This method is in the AppDelegate: ``` - (NSManagedObjectContext *)managedObjectContext { if (managedObjectContext_ != nil) { return managedObjectContext_; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext_ = [[NSManagedObjectContext alloc] init]; [managedObjectContext_ setPersistentStoreCoordinator:coordinator]; } return managedObjectContext_; } ``` // EDIT AGAIN ``` - (void)reloadMessages:(NSNotification *)notification { NSLog(@"RECIEVED NEW MESSAGES TO MessagesRootViewController"); NSLog(@"%@",managedObjectContext); // we need to get the threads from the database... NSFetchRequest *theReq = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:self.managedObjectContext]; [theReq setEntity:entity]; threads = [NSArray arrayWithArray:[managedObjectContext executeFetchRequest:theReq error:nil]]; [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; if(notification != nil){ // if its been caused by a notification UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New Message" message:@"A new message has been received" delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil]; [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO]; [alert release]; } } ``` // EDIT 3 If I put this code in the applicationDidFinishLoading of my app delegate it works fine! ``` NSFetchRequest *theReq = [[NSFetchRequest alloc] init]; NSEntityDescription *theEntity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:self.managedObjectContext]; [theReq setEntity:theEntity]; NSArray *theThreads = [NSArray arrayWithArray:[self.managedObjectContext executeFetchRequest:theReq error:nil]]; ```
2010/12/07
[ "https://Stackoverflow.com/questions/4379574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414972/" ]
After having a quick look at your code I think I found a couple of parts that needed attention. I'll try and break them down below: **SMSAppAppDelegate** 1) Notice that in your interface file, you declare your CoreData variables with an underscore at the end of the variable name. Then you create properties for each of the ivar **without** the underscore. That is all fine as long as you @synthesize them making the correct assignment, which seems to be missing from your implementation: ``` @synthesize managedObjectContext=managedObjectContext_; @synthesize managedObjectModel=managedObjectModel_; @synthesize persistentStoreCoordinator=persistentStoreCoordinator_; ``` **DownloadContacts** 1) In this class you are calling the managedObjectContext directly through the variable. I wouldn't recommend that but this is not your actual problem. Notice that you release the managedObjectContext on dealloc even though you have no ownership of it! 2) What I would do in this case is declare a property for the context and **always** access it via the property. Also if you rename your instance variable to include an underscore at the end you are minimising your chances of accessing it directly (i.e. without using self.) and it will make it easier for you to find where in this class you are actually doing that (there are a couple of places from memory). So in your interface file, rename managedObjectContext ivar and declare a property: ``` NSManagedObjectContext *managedObjectContext_; ... @property (nonatomic, retain) NSManagedObjectContext managedObjectContext; ``` And don't forget to make the assignment on @sythesize and release on dealloc, since you are using a retain property: ``` @synthesize managedObjectContext=managedObjectContext_; ... [managedObjectContext_ release]; ``` Then if you try and compile you will get two or three errors of unrecognised instance variable which is where you have to go and change it to `self.managedObjectContext` **MessagesRootViewController** And finally I'd recommend you go through the same process in your MessagesRootViewController but this one should still work fine as is! See how you go and let me know if any of the above is not clear! Cheers, Rog
I'm assuming you're doing something like: ``` [ClassName persistentStoreCoordinator] ``` Make sure `ClassName` is defined and has the `persistentStoreCoordinator` class method. Perhaps the file that did these things got deleted? Matt
4,379,574
``` NSEntityDescription *entity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:managedObjectContext]; ``` That line doesn't seem to work anymore (I'm pretty sure its that line). I can't seem to work out whats the problem. The application worked perfectly on Xcode with iOS 4.1 and now crashes with this error in the console: ``` 2010-12-07 17:12:27.552 SMSApp[9222:207] +[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580 2010-12-07 17:12:27.553 SMSApp[9222:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580' *** Call stack at first throw: ( 0 CoreFoundation 0x01547be9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x0169c5c2 objc_exception_throw + 47 2 CoreFoundation 0x015497bb +[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x014b9366 ___forwarding___ + 966 4 CoreFoundation 0x014b8f22 _CF_forwarding_prep_0 + 50 5 CoreData 0x00e6f3ca +[NSEntityDescription entityForName:inManagedObjectContext:] + 42 6 SMSApp 0x000046b9 -[MessagesRootViewController reloadMessages:] + 146 7 SMSApp 0x00004a09 -[MessagesRootViewController viewDidLoad] + 85 8 UIKit 0x0052265e -[UIViewController view] + 179 9 UIKit 0x00520a57 -[UIViewController contentScrollView] + 42 10 UIKit 0x00531201 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48 11 UIKit 0x0052f831 -[UINavigationController _layoutViewController:] + 43 12 UIKit 0x00530b4c -[UINavigationController _startTransition:fromViewController:toViewController:] + 524 13 UIKit 0x0052b606 -[UINavigationController _startDeferredTransitionIfNeeded] + 266 14 UIKit 0x00643e01 -[UILayoutContainerView layoutSubviews] + 226 15 QuartzCore 0x010b4451 -[CALayer layoutSublayers] + 181 16 QuartzCore 0x010b417c CALayerLayoutIfNeeded + 220 17 QuartzCore 0x010ad37c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310 18 QuartzCore 0x010ad0d0 _ZN2CA11Transaction6commitEv + 292 19 UIKit 0x0047719f -[UIApplication _reportAppLaunchFinished] + 39 20 UIKit 0x00477659 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690 21 UIKit 0x00481db2 -[UIApplication handleEvent:withNewEvent:] + 1533 22 UIKit 0x0047a202 -[UIApplication sendEvent:] + 71 23 UIKit 0x0047f732 _UIApplicationHandleEvent + 7576 24 GraphicsServices 0x01b2ca36 PurpleEventCallback + 1550 25 CoreFoundation 0x01529064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52 26 CoreFoundation 0x014896f7 __CFRunLoopDoSource1 + 215 27 CoreFoundation 0x01486983 __CFRunLoopRun + 979 28 CoreFoundation 0x01486240 CFRunLoopRunSpecific + 208 29 CoreFoundation 0x01486161 CFRunLoopRunInMode + 97 30 UIKit 0x00476fa8 -[UIApplication _run] + 636 31 UIKit 0x0048342e UIApplicationMain + 1160 32 SMSApp 0x000025c4 main + 102 33 SMSApp 0x00002555 start + 53 ) terminate called after throwing an instance of 'NSException' ``` Any idea where this error is coming from or what is causing it? Just to let you know as well, upgrading to XCode with iOS 4.2 caused some of the files to be deleted from my project. I don't know why this was, whether it was because they were linked files and not actually in the folder I dunno. Any ideas? Thanks // EDIT This method is in the AppDelegate: ``` - (NSManagedObjectContext *)managedObjectContext { if (managedObjectContext_ != nil) { return managedObjectContext_; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext_ = [[NSManagedObjectContext alloc] init]; [managedObjectContext_ setPersistentStoreCoordinator:coordinator]; } return managedObjectContext_; } ``` // EDIT AGAIN ``` - (void)reloadMessages:(NSNotification *)notification { NSLog(@"RECIEVED NEW MESSAGES TO MessagesRootViewController"); NSLog(@"%@",managedObjectContext); // we need to get the threads from the database... NSFetchRequest *theReq = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:self.managedObjectContext]; [theReq setEntity:entity]; threads = [NSArray arrayWithArray:[managedObjectContext executeFetchRequest:theReq error:nil]]; [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; if(notification != nil){ // if its been caused by a notification UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New Message" message:@"A new message has been received" delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil]; [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO]; [alert release]; } } ``` // EDIT 3 If I put this code in the applicationDidFinishLoading of my app delegate it works fine! ``` NSFetchRequest *theReq = [[NSFetchRequest alloc] init]; NSEntityDescription *theEntity = [NSEntityDescription entityForName:@"Thread" inManagedObjectContext:self.managedObjectContext]; [theReq setEntity:theEntity]; NSArray *theThreads = [NSArray arrayWithArray:[self.managedObjectContext executeFetchRequest:theReq error:nil]]; ```
2010/12/07
[ "https://Stackoverflow.com/questions/4379574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414972/" ]
After having a quick look at your code I think I found a couple of parts that needed attention. I'll try and break them down below: **SMSAppAppDelegate** 1) Notice that in your interface file, you declare your CoreData variables with an underscore at the end of the variable name. Then you create properties for each of the ivar **without** the underscore. That is all fine as long as you @synthesize them making the correct assignment, which seems to be missing from your implementation: ``` @synthesize managedObjectContext=managedObjectContext_; @synthesize managedObjectModel=managedObjectModel_; @synthesize persistentStoreCoordinator=persistentStoreCoordinator_; ``` **DownloadContacts** 1) In this class you are calling the managedObjectContext directly through the variable. I wouldn't recommend that but this is not your actual problem. Notice that you release the managedObjectContext on dealloc even though you have no ownership of it! 2) What I would do in this case is declare a property for the context and **always** access it via the property. Also if you rename your instance variable to include an underscore at the end you are minimising your chances of accessing it directly (i.e. without using self.) and it will make it easier for you to find where in this class you are actually doing that (there are a couple of places from memory). So in your interface file, rename managedObjectContext ivar and declare a property: ``` NSManagedObjectContext *managedObjectContext_; ... @property (nonatomic, retain) NSManagedObjectContext managedObjectContext; ``` And don't forget to make the assignment on @sythesize and release on dealloc, since you are using a retain property: ``` @synthesize managedObjectContext=managedObjectContext_; ... [managedObjectContext_ release]; ``` Then if you try and compile you will get two or three errors of unrecognised instance variable which is where you have to go and change it to `self.managedObjectContext` **MessagesRootViewController** And finally I'd recommend you go through the same process in your MessagesRootViewController but this one should still work fine as is! See how you go and let me know if any of the above is not clear! Cheers, Rog
Your database might be corrupted, try resetting the iOS simulator by clicking on iOS Simulator>Reset contents and settings. **Edit**: It looks like you're trying to call a selector that doesn't exist. Try figuring out which files were deleted, as it seems like you have a method that is called that can't be found at runtime. Did your core data classes get erased, maybe?
4,056,239
Good night, I have a method in which I need to select from an SQLite database a value obtained by querying the database with two strings. The strings are passed to the method and inside the method I make some string concatenation to build `SQLiteCommand.CommandText`. What surprises me is that even with string concatenation, and despite the fact that everyone says parametrizes queries are faster than using string concatenation, when I parametrize this query outside the method and only assign values to the parameters in the method itself it runs much slower (3ms compared to 7/8ms)... Am I doing something wrong or is this normal? Outside the method I have the following code: `ComandoBD = new SQLiteCommand(@"SELECT Something FROM SomeTable WHERE (Field1 = @TextField1 AND Field2 = @TextField2)", LigacaoBD);`. Inside the method I just write `ComandoBD.AddWithValue("@TextField1", StringWithValue1);` `ComandoBD.AddWithValue("@TextField2", StringWithValue2);` Strangely, this runs faster: `ComandoBD.CommandText = "SELECT Something FROM SomeTable WHERE (Field1 = '" + StringWithValue1 + "' AND TextField2 = '" + StringWithValue2 + "')";` Thank you very much.
2010/10/29
[ "https://Stackoverflow.com/questions/4056239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477505/" ]
The redirection operator (>) is a feature of the Windows command processor. You aren't actually invoking the command processor with Process.Start (unless you start "cmd.exe"). To use stdio redirection, you must read it from the StandardOutput stream. Here's an example that shows how to do it: <http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx> You've almost got it!
You can't do redirection like that. Cmd.exe handles seeing the "> file.txt" and sets up the redirection before executing the process. Remove the "> file.txt" from strArg. After starting the process you need to read the StandardOutput stream and write the data to the file. There is a simple example here: <http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx>
2,438,750
While I was trying to do at least some progress having to do with [this](https://math.stackexchange.com/questions/2433244/sum-of-digits-of-31000?newsletter=1&nlcode=812219%7cf4fc) awesome question I calculated digit sum in base $10$ of $3^a$ for $a=1,2,...,25$ and the pattern goes like this: $3,9,9,9,9,18,18,18,27,27,27,18,27,45,36,27,27,45,36,45,27,45,54,54,63...$ Since numbers grow with every next step the digit sum could be monotone after some $3^{n\_0}$ but I doubt that this is the case, that is, I believe that this sequence never becomes monotone, that is, that there is sequence $n\_i \in \mathbb N$ such that $ds\_{10}(3^{n\_i+1})>ds\_{10}(3^{n\_i})$. > > Is it true that this sequence of digit sums never becomes monotone? > > >
2017/09/21
[ "https://math.stackexchange.com/questions/2438750", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
A proof of this conjecture is probably out of reach, but the fact that the digit sum of $3^{10^4}$ is $21\ 663$ and the digit sum of $3^{10^4+1}$ is $21\ 267$, so smaller, clearly indicates it. I will search even larger counterexamples for monotony. UPDATE : digit sum of $3^{10^7}$ is $\color \red {\ \ \ \ \ 21\ 469\ 896}$ digit sum of $3^{10^7+1}$ is $\color\green {\ \ 21\ 461\ 742}$ so still no monotony.
**Hint:** The sum-of-digits function is itself non-monotonic (<https://oeis.org/A007953>). In the range $[10^k,10^{k+1})$ it varies from $1$ to $9k$, while there are on average $2.0959\cdots$ powers of $3$ that fall in that range, at somewhat "random" positions. [![enter image description here](https://i.stack.imgur.com/wafWI.png)](https://i.stack.imgur.com/wafWI.png)
34,282,578
I have a vector of string , and I want to return a string from vector which is similar to a string. For example vector contains: "load", "fox", "google", "firefox" and the string is: "mozilla firefox". The true result in this sample is "firefox". I use the code below, but it is wrong and returns "fox" for my sample. ``` vector<string>::const_iterator it_found = find_if(MyVector.begin(), MyVector.end(), [&MyString](string s) -> bool { return( MyString.find(s) != string::npos ); }); if(it_found != MyVector.end()) { //Do Somthing } ``` What should I do?
2015/12/15
[ "https://Stackoverflow.com/questions/34282578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4814591/" ]
You are returning the first string that is a substring of your search term. It seems you want the best match, so a more sophisticated approach is needed. You could calculate some score how good the match is and find the element that gives the maximum score, e.g. with `std::max_element` The score could be simply the length of the matched substring or something more complicated if you later improve your matching algorithm.
You can split the input string on whitespace using this implementation of `split` returning a `std::vector<std::string>`. ``` std::vector<std::string> split(std::string const &input) { std::istringstream buffer(input); std::vector<std::string> ret((std::istream_iterator<std::string>(buffer)), std::istream_iterator<std::string>()); return ret; } ``` Then compare each string in `MyVector` with the candidates from the returned vector from `split`. ``` std::string MyString = "mozzilla firefox"; std::vector<std::string> MyVector = {"fire", "fox", "firefox", "mozilla"}; auto candidates = split(MyString); auto it_found = std::find_if(MyVector.begin(), MyVector.end(), [&candidates](std::string s) -> bool{ return (std::find(candidates.begin(), candidates.end(), s) != candidates.end()); }); if(it_found != MyVector.end()){ std::cout<<"\nFound : "<<*it_found; } ``` Output : ``` Found : firefox ``` Note that this only finds the first match of strings in `MyVector`with a string in the `candidates`.
1,620,933
Let $(X,d)$ be a metric space and let $F:A(\subset X)\to X$. We say $F$ is a *contraction* if there exists $\lambda$ where $0\leq\lambda<1$ such that $$d(F(x),F(y))\leq\lambda d(x,y)$$ for all $x,y\in X$. My question is: I understand that the function $f(x)=x^2$ is a contraction on each interval on $[0,a], 0<a<0.5$. But my doubt is why is it NOT a contraction on $[0,0.5]$? [![enter image description here](https://i.stack.imgur.com/UOt17.png)](https://i.stack.imgur.com/UOt17.png) As we can see any distance on any interval on the horizontal axis is less than those on the vertical axis, so there should be some $\lambda$ that satisfy the inequality. I don't really know the reason. Maybe is there any counterexample that makes it not a contraction? Many thanks in advance for the help.
2016/01/21
[ "https://math.stackexchange.com/questions/1620933", "https://math.stackexchange.com", "https://math.stackexchange.com/users/71346/" ]
Suppose by contradiction that $x^2$ is a contraction of $[0, 0.5]$ with some constant $0<c<1$ satisfying for all $x \neq y \in [0,0.5]$ $$|x^2-y^2|< c|x-y|$$ As a simple consequence of the MVT, $c > 0.5$. But now, $$c|x-y|>|x^2-y^2|=|x+y| \cdot |x-y|$$ which implies $c > |x+y|=x+y$. Now, take simply $x=0.5$ and $y= c - 0.5$ to get a contradiction $c>c$. The fact is that $x^2$ is a contraction of $[0,a]$ for all $a \in (0,0.5)$ because of the MVT. But as $a \to 0.5$, the best Lipschitz constant $c$ approaches to $1$, so that there is no constant $c<1$ working for the whole interval $[0,0.5]$. For this limit case, necessarily $c\ge 1$ so that $x^2$ is Lipschitz but not a contraction.
Let me add a point that might help for the understanding. In the other answers, we already have seen that $$|x^2 - y^2| \le C \, |x - y| \quad\forall x,y\in [0,0.5]$$ implies $C \ge 1$. Now, the OP correctly observed "As we can see any distance on any interval on the horizontal axis is less than those on the vertical axis" Indeed, we have $$|x^2 - y^2| < |x - y| \quad \forall x,y\in[0,0.5], x\ne y.$$ But now, he OP concludes "so there should be some $\lambda$ that satisfy the inequality." And this conclusion is not valid. In fact, for every $x,y \in [0,0.5]$, $x\ne y$, we find $\lambda(x,y) < 1$, such that $$|x^2 - y^2| \le \lambda(x,y) \, |x - y|$$ However, you cannot choose $\lambda(x,y)$ to be **uniformly** smaller than $1$.
1,620,933
Let $(X,d)$ be a metric space and let $F:A(\subset X)\to X$. We say $F$ is a *contraction* if there exists $\lambda$ where $0\leq\lambda<1$ such that $$d(F(x),F(y))\leq\lambda d(x,y)$$ for all $x,y\in X$. My question is: I understand that the function $f(x)=x^2$ is a contraction on each interval on $[0,a], 0<a<0.5$. But my doubt is why is it NOT a contraction on $[0,0.5]$? [![enter image description here](https://i.stack.imgur.com/UOt17.png)](https://i.stack.imgur.com/UOt17.png) As we can see any distance on any interval on the horizontal axis is less than those on the vertical axis, so there should be some $\lambda$ that satisfy the inequality. I don't really know the reason. Maybe is there any counterexample that makes it not a contraction? Many thanks in advance for the help.
2016/01/21
[ "https://math.stackexchange.com/questions/1620933", "https://math.stackexchange.com", "https://math.stackexchange.com/users/71346/" ]
A quick argument using derivatives: note that $f'(0.5) = 1$. So, for any $c < 1$, we have $$ \lim\_{a \to 0.5^-} \frac{f(0.5) - f(a)}{0.5 - a}> c $$ So, for any such $c$, there exists an $a \in (0,0.5)$ such that $$ \frac{f(0.5) - f(a)}{0.5 - a} > c \implies\\ |f(0.5) - f(a)| > c|0.5 - a| $$ The conclusion follows.
Let me add a point that might help for the understanding. In the other answers, we already have seen that $$|x^2 - y^2| \le C \, |x - y| \quad\forall x,y\in [0,0.5]$$ implies $C \ge 1$. Now, the OP correctly observed "As we can see any distance on any interval on the horizontal axis is less than those on the vertical axis" Indeed, we have $$|x^2 - y^2| < |x - y| \quad \forall x,y\in[0,0.5], x\ne y.$$ But now, he OP concludes "so there should be some $\lambda$ that satisfy the inequality." And this conclusion is not valid. In fact, for every $x,y \in [0,0.5]$, $x\ne y$, we find $\lambda(x,y) < 1$, such that $$|x^2 - y^2| \le \lambda(x,y) \, |x - y|$$ However, you cannot choose $\lambda(x,y)$ to be **uniformly** smaller than $1$.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is SVN really such a bad option? PROS: * Can handle large repositories e.g. many linux distro's use it, also Apache, Sourceforge * Has nice GUI front end with TortoiseSVN to keep your windows users happy * Can be used with windows integrated authentication to keep admins happy * Many different backup strategies can be adopted based on your requirements (svnadmin hotcopy or dump, svnsync, post-commit hooks) to help ease your single point of failure concern. CONS: * Centralised VCS Disclaimer: I've never used Perforce and have been a happy SVN admin and user for ~6 years (since v0.29)
Microsoft just released *Git Virtual File System* (GVFS) specifically to handle large code base with git. [More details here at msdn](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) Also [Microsoft hosts the Windows source in a monstrous 300GB Git repository](https://arstechnica.com/information-technology/2017/02/microsoft-hosts-the-windows-source-in-a-monstrous-300gb-git-repository/) I do not have any experience using GVFS.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
First, I don't agree that Git is inappropriate for non-technical users. Yes, there are certain features that newbies won't use (e.g. git-send-email). But there are also GUIs like [TortoiseGit](http://code.google.com/p/tortoisegit/) to make simple things simple. However, I think you're approaching things the wrong way. Basically, you have content that will change frequently and needs to be editable very easily by Joe Bloggs, and code that will be modified less frequently by coders. The traditional solution is to use a real CMS (e.g. [Alfresco](http://www.alfresco.com/), [SugarCRM](http://www.sugarcrm.com/crm/), [Drupal](http://drupal.org/), etc. or a Wiki ([MediaWiki](http://www.mediawiki.org/), [MoinMon](http://moinmoin.wikiwikiweb.de/), etc.), with optional plug-ins. Keep in mind, wikis (and most CMSes) allow versioning of content, in a "user-friendly" way. Even if you must keep your in-house code, I think you should still want to extricate the content so they can be treated separately. Once you have the code and content separate, your repository will be a more reasonable size. Then, you can use whatever VCS you want (though I'm not really sure you're right that Git is inherently bad for large repos).
git does not scale for large repositories. It's not the space, it's the number of files. Please read my [blog article](http://web.archive.org/web/20090724190112/http://www.jaredoberhaus.com/tech_notes/2008/12/git-is-slow-too-many-lstat-operations.html) that I wrote a while back about this. In my experience, if you want a scalable, fast, centralized source control system, [P4](http://www.perforce.com/) is the way to go.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
First, I don't agree that Git is inappropriate for non-technical users. Yes, there are certain features that newbies won't use (e.g. git-send-email). But there are also GUIs like [TortoiseGit](http://code.google.com/p/tortoisegit/) to make simple things simple. However, I think you're approaching things the wrong way. Basically, you have content that will change frequently and needs to be editable very easily by Joe Bloggs, and code that will be modified less frequently by coders. The traditional solution is to use a real CMS (e.g. [Alfresco](http://www.alfresco.com/), [SugarCRM](http://www.sugarcrm.com/crm/), [Drupal](http://drupal.org/), etc. or a Wiki ([MediaWiki](http://www.mediawiki.org/), [MoinMon](http://moinmoin.wikiwikiweb.de/), etc.), with optional plug-ins. Keep in mind, wikis (and most CMSes) allow versioning of content, in a "user-friendly" way. Even if you must keep your in-house code, I think you should still want to extricate the content so they can be treated separately. Once you have the code and content separate, your repository will be a more reasonable size. Then, you can use whatever VCS you want (though I'm not really sure you're right that Git is inherently bad for large repos).
Microsoft just released *Git Virtual File System* (GVFS) specifically to handle large code base with git. [More details here at msdn](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) Also [Microsoft hosts the Windows source in a monstrous 300GB Git repository](https://arstechnica.com/information-technology/2017/02/microsoft-hosts-the-windows-source-in-a-monstrous-300gb-git-repository/) I do not have any experience using GVFS.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I just happened to be reading [this blog post](http://stevehanov.ca/blog/index.php?id=50) not one minute ago. It's a bit of a rant about the scalability of git. Edit: Eight years later, and Git has [Large File Storage](https://git-lfs.github.com/) (LFS), and Microsoft is open sourcing [Git Virtual File System](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) (GVFS) so they can use git to develop Windows.
Is SVN really such a bad option? PROS: * Can handle large repositories e.g. many linux distro's use it, also Apache, Sourceforge * Has nice GUI front end with TortoiseSVN to keep your windows users happy * Can be used with windows integrated authentication to keep admins happy * Many different backup strategies can be adopted based on your requirements (svnadmin hotcopy or dump, svnsync, post-commit hooks) to help ease your single point of failure concern. CONS: * Centralised VCS Disclaimer: I've never used Perforce and have been a happy SVN admin and user for ~6 years (since v0.29)
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is SVN really such a bad option? PROS: * Can handle large repositories e.g. many linux distro's use it, also Apache, Sourceforge * Has nice GUI front end with TortoiseSVN to keep your windows users happy * Can be used with windows integrated authentication to keep admins happy * Many different backup strategies can be adopted based on your requirements (svnadmin hotcopy or dump, svnsync, post-commit hooks) to help ease your single point of failure concern. CONS: * Centralised VCS Disclaimer: I've never used Perforce and have been a happy SVN admin and user for ~6 years (since v0.29)
I used git only once for a school project (php site with Zend Framework). We used git but the teacher needed to have the final release on a svn repo. Comparing the checkout size: git checkout was half the size of MB of the svn checkout. My two cents.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Microsoft just released *Git Virtual File System* (GVFS) specifically to handle large code base with git. [More details here at msdn](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) Also [Microsoft hosts the Windows source in a monstrous 300GB Git repository](https://arstechnica.com/information-technology/2017/02/microsoft-hosts-the-windows-source-in-a-monstrous-300gb-git-repository/) I do not have any experience using GVFS.
I used git only once for a school project (php site with Zend Framework). We used git but the teacher needed to have the final release on a svn repo. Comparing the checkout size: git checkout was half the size of MB of the svn checkout. My two cents.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
git does not scale for large repositories. It's not the space, it's the number of files. Please read my [blog article](http://web.archive.org/web/20090724190112/http://www.jaredoberhaus.com/tech_notes/2008/12/git-is-slow-too-many-lstat-operations.html) that I wrote a while back about this. In my experience, if you want a scalable, fast, centralized source control system, [P4](http://www.perforce.com/) is the way to go.
I used git only once for a school project (php site with Zend Framework). We used git but the teacher needed to have the final release on a svn repo. Comparing the checkout size: git checkout was half the size of MB of the svn checkout. My two cents.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
First, I don't agree that Git is inappropriate for non-technical users. Yes, there are certain features that newbies won't use (e.g. git-send-email). But there are also GUIs like [TortoiseGit](http://code.google.com/p/tortoisegit/) to make simple things simple. However, I think you're approaching things the wrong way. Basically, you have content that will change frequently and needs to be editable very easily by Joe Bloggs, and code that will be modified less frequently by coders. The traditional solution is to use a real CMS (e.g. [Alfresco](http://www.alfresco.com/), [SugarCRM](http://www.sugarcrm.com/crm/), [Drupal](http://drupal.org/), etc. or a Wiki ([MediaWiki](http://www.mediawiki.org/), [MoinMon](http://moinmoin.wikiwikiweb.de/), etc.), with optional plug-ins. Keep in mind, wikis (and most CMSes) allow versioning of content, in a "user-friendly" way. Even if you must keep your in-house code, I think you should still want to extricate the content so they can be treated separately. Once you have the code and content separate, your repository will be a more reasonable size. Then, you can use whatever VCS you want (though I'm not really sure you're right that Git is inherently bad for large repos).
I used git only once for a school project (php site with Zend Framework). We used git but the teacher needed to have the final release on a svn repo. Comparing the checkout size: git checkout was half the size of MB of the svn checkout. My two cents.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I just happened to be reading [this blog post](http://stevehanov.ca/blog/index.php?id=50) not one minute ago. It's a bit of a rant about the scalability of git. Edit: Eight years later, and Git has [Large File Storage](https://git-lfs.github.com/) (LFS), and Microsoft is open sourcing [Git Virtual File System](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) (GVFS) so they can use git to develop Windows.
git does not scale for large repositories. It's not the space, it's the number of files. Please read my [blog article](http://web.archive.org/web/20090724190112/http://www.jaredoberhaus.com/tech_notes/2008/12/git-is-slow-too-many-lstat-operations.html) that I wrote a while back about this. In my experience, if you want a scalable, fast, centralized source control system, [P4](http://www.perforce.com/) is the way to go.
999,748
I have a pickerView in a scollView, which would rotate if i sweep across it in sdk 2.2.1 according to <http://discussions.apple.com/thread.jspa?messageID=8284448> but when i changed the target to sdk 3.0, it is only responding to tapping and rotate 1 row at a time. but for many values that way is tiresome. can anyone help me here to rotate the picker as it did in sdk 2.2.1 ??
2009/06/16
[ "https://Stackoverflow.com/questions/999748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I just happened to be reading [this blog post](http://stevehanov.ca/blog/index.php?id=50) not one minute ago. It's a bit of a rant about the scalability of git. Edit: Eight years later, and Git has [Large File Storage](https://git-lfs.github.com/) (LFS), and Microsoft is open sourcing [Git Virtual File System](https://blogs.msdn.microsoft.com/visualstudioalm/2017/02/03/announcing-gvfs-git-virtual-file-system/) (GVFS) so they can use git to develop Windows.
There's a utility script called [git-split](http://github.com/rjp/git-split/blob/master/git-split) that chops up a git repo to make it more efficient.
71,976,826
I'm a newbie flutter developer I need some guidance regarding 2D scrolling where I can put widgets in the body and scroll 2D (vertical, horizontal AND diagonal scrolling) I do not require the actual code but guidance as to which widgets or the logic I'm supposed to use. figma has 2d scrolling which is an exact example of what I want. I'm sorry I don't have any initial code to provide as I don't know where to start.
2022/04/23
[ "https://Stackoverflow.com/questions/71976826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10118901/" ]
The `InteractiveViewer` may be what you need: ``` import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('InteractiveViewer')), body: const MyStatelessWidget(), ), ); } } class MyStatelessWidget extends StatelessWidget { const MyStatelessWidget({super.key}); @override Widget build(BuildContext context) { return Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(200), constrained: false, minScale: 0.1, maxScale: 2, child: Column( children: List.generate(100, (i) { return Row( children: List.generate(100, (j) { return Container( width: 100, height: 50, decoration: BoxDecoration(border: Border.all()), child: Text('$i:$j'), ); }), ); }), ), ), ); } } ```
You can use [SingleChildScrollView](https://api.flutter.dev/flutter/widgets/SingleChildS) or [listView](https://api.flutter.dev/flutter/widgets/ListView-class.html) for like static widgets. if you have dynamic widgets than you can use [ListView.builder](https://docs.flutter.dev/cookbook/lists/long-lists)
418,382
I am trying to derive the Klein-Gordon equation for the case of GR using the action: $$S\left[ {\varphi ,{g\_{\mu \nu }}} \right] = \int {\sqrt g {d^4}x\left( { - {1 \over 2}{g^{\mu \nu }}{\nabla \_\mu }\varphi {\nabla \_\nu }\varphi - {1 \over 2}{m^2}{\varphi ^2}} \right)} \tag{1}$$ So in the Euler - Lagrange equation for the SR case which is: $${\partial \_\mu }\left( {{{\partial L} \over {\partial \left( {{\partial \_\mu }\varphi } \right)}}} \right) = {{\partial L} \over {\partial \varphi }}\tag{2}$$ I use the correspondence $${\partial \over {\partial \left( {{\partial \_\mu }\varphi } \right)}} \to {\nabla \_{{\nabla \_\mu }\varphi }},{\partial \over {{\partial \_\mu }\varphi }} \to {\nabla \_\mu } \tag{3}$$ and so, $${\nabla \_{{\nabla \_\mu }\varphi }}L = - {1 \over 2}\sqrt g {g^{\mu \nu }}{\nabla \_\nu }\varphi - {1 \over 2}\sqrt g {g^{\mu \nu }}{\nabla \_\mu }\varphi {\nabla \_{{\nabla \_\mu }\varphi }}\left( {{\nabla \_\nu }\varphi } \right) \tag{4}$$ and using this dubious relation that I am unable to prove (extending the SR case of partial derivatives), $${\nabla \_{{\nabla \_\mu }\varphi }}\left( {{\nabla \_\nu }\varphi } \right) = \delta \_\nu ^\mu \tag{5}$$ I finally get the desired KG equation, $${\nabla \_\mu }\left( { - \sqrt g {g^{\mu \nu }}{\nabla \_\nu }\varphi } \right) = - \sqrt g {m^2}\varphi $$ However, I am very uncomfortable with my assumption 5 that I am unable to prove. Is my analysis correct? I am a 60y old doing this as retirement fun so please don't cut me down too brutally :-)
2018/07/19
[ "https://physics.stackexchange.com/questions/418382", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/196090/" ]
It's probably more straightforward to express your action in terms of partial derivatives: $$ S\left[ {\varphi ,{g\_{\mu \nu }}} \right] = \int {\sqrt g {d^4}x\left( { - {1 \over 2}{g^{\mu \nu }}{\partial\_\mu }\varphi \,{\partial\_\nu }\varphi - {1 \over 2}{m^2}{\varphi ^2}} \right)} \,, $$ since $\varphi$ is just a scalar. Then $$ \frac{\partial L}{\partial (\partial\_\mu\varphi)} = -\sqrt{g}\,g^{\mu \nu} \partial\_\nu \varphi \quad\text{and}\quad \frac{\partial L}{\partial \varphi} = -\sqrt{g}\,m^2 \varphi^ \,.$$ Finally we need the useful expression for the covariant divergence: $$ \nabla\_\mu V^\mu = \frac{1}{\sqrt{g}} \partial\_\mu(\sqrt{g}V^\mu) \,,$$ to reproduce the usual Klein-Gordon equation. --- The correspondence you state in $(3)$ is not correct. The normal procedure for turning a theory in flat spacetime into one in curved spacetime involves replacing $\partial\_\mu$ by $\nabla\_\mu$, yes, but the Euler-Lagrange equations *don't change*. The E-L equations can be derived for any action, whether in flat spacetime, curved spacetime, or in some other context entirely. One clue that we shouldn't be replacing partial derivatives by covariant derivatives here is the fact that the derivatives are with respect to *fields*; in the minimal coupling prescription, $\partial\_\mu \to \nabla\_\mu$ is a statement about how we should take derivatives with respect to *position in spacetime*.
In order to derive the Klein-Gordon equation you must vary with respect to the scalar field $\phi$. The action reads: $$S = \int d^{4}x\sqrt{-g}\left(-\cfrac{1}{2}g^{μν}\nabla\_{μ}\phi\nabla\_{ν}\phi - \cfrac{1}{2}m^{2}\phi ^{2}\right) $$ For the kinetic term you have: \begin{align} δ(g^{μν}\nabla\_{μ}\phi\nabla\_{ν}\phi) &= g^{μν}δ(\nabla\_{μ}\phi)\nabla\_{ν}\phi + g^{μν}δ(\nabla\_{ν}\phi)\nabla\_{μ}\phi\\ & = δ(\nabla\_{μ}\phi)\nabla^{μ}\phi + δ(\nabla\_{ν}\phi)\nabla^{ν}\phi \\ & = 2δ(\nabla\_{μ}\phi)\nabla^{μ}\phi \\ & = 2\nabla\_{μ}(δ\phi)\nabla^{μ}\phi \end{align} where I've summed the terms with dummy indices. From Leibnitz rule we know that: $$ \nabla\_{μ}(δ\phi\nabla^{μ}\phi) = \nabla\_{μ}(δ\phi)\nabla^{μ}\phi + δ\phi\nabla\_{μ}\nabla^{μ}\phi $$ The left hand side term in the above expression in spacetime takes the following form: $$\int d^{4}x\sqrt{-g} \nabla\_{μ}(δ\phi\nabla^{μ}\phi).$$ We can see that this term is a surface term so: $$\int d^{4}x\sqrt{-g} \nabla\_{μ}(δ\phi\nabla^{μ}\phi) = 0$$ because $δ\phi = 0$ at the surface. So we have: $$\int d^{4}x \sqrt{-g}\nabla\_{μ}(δ\phi)\nabla^{μ}\phi = -\int d^{4}x \sqrt{-g}δ\phi\nabla\_{μ}\nabla^{μ}\phi $$ The mass term is: $$δ(m^{2} \phi ^{2}) = 2\phi δ\phi m^{2}$$ Combining all the above relations one obtains the K-G equation for a massive scalar field: $$(\Box - m^{2})\phi = 0$$ where $\Box = g^{μν}\nabla\_{μ}\nabla\_{ν}$ is the D'Alambert operator. Note - Hint: You can derive K-G equation using the conservation of the energy momentum tensor: $\nabla^{μ}Τ\_{μν} = 0$
418,382
I am trying to derive the Klein-Gordon equation for the case of GR using the action: $$S\left[ {\varphi ,{g\_{\mu \nu }}} \right] = \int {\sqrt g {d^4}x\left( { - {1 \over 2}{g^{\mu \nu }}{\nabla \_\mu }\varphi {\nabla \_\nu }\varphi - {1 \over 2}{m^2}{\varphi ^2}} \right)} \tag{1}$$ So in the Euler - Lagrange equation for the SR case which is: $${\partial \_\mu }\left( {{{\partial L} \over {\partial \left( {{\partial \_\mu }\varphi } \right)}}} \right) = {{\partial L} \over {\partial \varphi }}\tag{2}$$ I use the correspondence $${\partial \over {\partial \left( {{\partial \_\mu }\varphi } \right)}} \to {\nabla \_{{\nabla \_\mu }\varphi }},{\partial \over {{\partial \_\mu }\varphi }} \to {\nabla \_\mu } \tag{3}$$ and so, $${\nabla \_{{\nabla \_\mu }\varphi }}L = - {1 \over 2}\sqrt g {g^{\mu \nu }}{\nabla \_\nu }\varphi - {1 \over 2}\sqrt g {g^{\mu \nu }}{\nabla \_\mu }\varphi {\nabla \_{{\nabla \_\mu }\varphi }}\left( {{\nabla \_\nu }\varphi } \right) \tag{4}$$ and using this dubious relation that I am unable to prove (extending the SR case of partial derivatives), $${\nabla \_{{\nabla \_\mu }\varphi }}\left( {{\nabla \_\nu }\varphi } \right) = \delta \_\nu ^\mu \tag{5}$$ I finally get the desired KG equation, $${\nabla \_\mu }\left( { - \sqrt g {g^{\mu \nu }}{\nabla \_\nu }\varphi } \right) = - \sqrt g {m^2}\varphi $$ However, I am very uncomfortable with my assumption 5 that I am unable to prove. Is my analysis correct? I am a 60y old doing this as retirement fun so please don't cut me down too brutally :-)
2018/07/19
[ "https://physics.stackexchange.com/questions/418382", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/196090/" ]
Note: technically, everywhere we've been using $\sqrt{g}$ it should be $\sqrt{|g|}$, but I'll let the former denote the latter in a slight abuse of notation like the rest of this page. gj255 has already provided the textbook approach, in which we keep to partial derivatives. You can actually do it a different way; the same from-first-principles argument that derives Eq. (2) can be modified to obtain something that manifestly works with covariant derivatives. Write the Lagrangian density as $L=\sqrt{g}L\_0$ with $L\_0=\frac{1}{2}\nabla\_\mu\varphi\nabla^\mu\varphi-\frac{1}{2}m^2\varphi^2$, so $$0=\delta S=\int d^4x \sqrt{g}\left(\delta\varphi \frac{\partial L\_0}{\partial\varphi}+\nabla\_\mu\delta\varphi \frac{\partial L\_0}{\partial\nabla\_\mu\varphi}\right)$$($\nabla\_\mu\varphi$ is actually just $\partial\_\mu\varphi$, because $\varphi$ is a scalar field), where we have written $\delta\nabla\_\mu\varphi=\nabla\_\mu\delta\varphi$. But$$\int d^4x\sqrt{g}\nabla\_\mu\left(\delta\varphi \frac{\partial L\_0}{\partial\nabla\_\mu\varphi}\right)=\int d^4x\partial\_\mu\left(\sqrt{g}\delta\varphi \frac{\partial L\_0}{\partial\nabla\_\mu\varphi}\right)$$is a boundary term, so we can rewrite $\delta S=0$ as $$0=\int d^4 x\sqrt{g}\delta\varphi \left(\frac{\partial L\_0}{\partial\varphi}-\nabla\_\mu\frac{\partial L\_0}{\partial\nabla\_\mu\varphi}\right),$$giving us an Euler-Lagrange function more in the spirit of what you wanted, viz.$$0=\frac{\partial L\_0}{\partial\varphi}-\nabla\_\mu\frac{\partial L\_0}{\partial\nabla\_\mu\varphi}=-m^2\varphi-\nabla\_\mu\nabla^\mu\varphi.$$Note: I don't know what the standard symbol is for $L/\sqrt{g}$, but I do know it's sometimes called the scalar Lagrangian density.
In order to derive the Klein-Gordon equation you must vary with respect to the scalar field $\phi$. The action reads: $$S = \int d^{4}x\sqrt{-g}\left(-\cfrac{1}{2}g^{μν}\nabla\_{μ}\phi\nabla\_{ν}\phi - \cfrac{1}{2}m^{2}\phi ^{2}\right) $$ For the kinetic term you have: \begin{align} δ(g^{μν}\nabla\_{μ}\phi\nabla\_{ν}\phi) &= g^{μν}δ(\nabla\_{μ}\phi)\nabla\_{ν}\phi + g^{μν}δ(\nabla\_{ν}\phi)\nabla\_{μ}\phi\\ & = δ(\nabla\_{μ}\phi)\nabla^{μ}\phi + δ(\nabla\_{ν}\phi)\nabla^{ν}\phi \\ & = 2δ(\nabla\_{μ}\phi)\nabla^{μ}\phi \\ & = 2\nabla\_{μ}(δ\phi)\nabla^{μ}\phi \end{align} where I've summed the terms with dummy indices. From Leibnitz rule we know that: $$ \nabla\_{μ}(δ\phi\nabla^{μ}\phi) = \nabla\_{μ}(δ\phi)\nabla^{μ}\phi + δ\phi\nabla\_{μ}\nabla^{μ}\phi $$ The left hand side term in the above expression in spacetime takes the following form: $$\int d^{4}x\sqrt{-g} \nabla\_{μ}(δ\phi\nabla^{μ}\phi).$$ We can see that this term is a surface term so: $$\int d^{4}x\sqrt{-g} \nabla\_{μ}(δ\phi\nabla^{μ}\phi) = 0$$ because $δ\phi = 0$ at the surface. So we have: $$\int d^{4}x \sqrt{-g}\nabla\_{μ}(δ\phi)\nabla^{μ}\phi = -\int d^{4}x \sqrt{-g}δ\phi\nabla\_{μ}\nabla^{μ}\phi $$ The mass term is: $$δ(m^{2} \phi ^{2}) = 2\phi δ\phi m^{2}$$ Combining all the above relations one obtains the K-G equation for a massive scalar field: $$(\Box - m^{2})\phi = 0$$ where $\Box = g^{μν}\nabla\_{μ}\nabla\_{ν}$ is the D'Alambert operator. Note - Hint: You can derive K-G equation using the conservation of the energy momentum tensor: $\nabla^{μ}Τ\_{μν} = 0$
15,353,092
I am trying to write a library that reads 5 variables, then sends them through the serial port to a bluetooth reciever, I am getting a number of errors and I am not sure where to go from here, do I need to implement pointers? Here is the Arduino code.... ``` #include <serialComms.h> serialComms testing; void setup() { Serial.begin(9600); } char data[] = {1,2,3,4,5,6}; void loop() { for(int t = 0;t<6;t++) { data[t] = data[t]++; } testing.updateUser(data); delay(250); } ``` serialComms.cpp ``` #include <Arduino.h> #include <serialComms.h> void serialComms::init() { // This is where the constructor would be...right now we are too stupid to have one } void serialComms::readAllBytes() // Target Pin,Values { } void serialComms::assignBytes() { for(int t = 0;t<5;t++) { digitalWrite(12,HIGH); delay(250); digitalWrite(12,LOW); } } void serialComms::updateUser(char t[]) { Serial.write(t,5); } ``` serialComms.h ``` #ifndef serialComms_h #define serialComms_h /* serialComms Class */ class serialComms { public: serialComms() {}; void init(); void readAllBytes(); // Will be used to create the array --> two variables for now... void assignBytes(); void updateUser(char t[]); }; #endif ``` Here are the errors that I am getting... - serialComms.cpp:28: error: initializing argument 1 of 'virtual size\_t Print::write(const uint8\_t\*, size\_t)' ``` - - serialComms.cpp:28: error: invalid conversion from 'char*' to 'const uint8_t*' - serialComms.cpp: In member function 'void serialComms::updateUser(char*)': - serialComms.cpp:27: error: expected primary-expression before ']' token ```
2013/03/12
[ "https://Stackoverflow.com/questions/15353092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1424125/" ]
Frequently, using Fragments can help with this kind of problem. In your particular case, though I see that you want to use ListActivity, as well. That makes it harder As you know, Java can't help you here. You can't inherit multiple implementations (List and MyBase). There is no simple answer. I can suggest two things: * List(Activity,Fragment) are pretty simple extensions to their base classes. You could, with a reasonable amount of work, build your own, that inherit from your base class. They would probably be simpler than the ones in the framework. Maybe that would be ok. * Delegate. Write a class that implements the common behavior but that does not inherit from Activity/Fragment. Create one of these objects during the initialization of your Fragment/Activity classes. Any time there is common behavior, delegate it to the delegate instance.
Create an abstract class called `BaseActivity`. Implement `onCreate()` for it, which should cover the basics of activity operations. Create other classes that extend from `BaseActivity`, and allow them to override that method if and only if they do something slightly more special than `BaseActivity`. The main idea here is that whatever `Activity` you have or create relates to one another in some way that they do similar code operations. Only in special cases would you need to do something extra, hence overriding `onCreate()`.
28,806,025
I am using this code to share user achievements on my app ``` if (FacebookDialog.canPresentShareDialog(getApplicationContext(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) { // Publish the post using the Share Dialog try { FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this) .setApplicationName(getString(R.string.fb_app_name)) .setName(parameters.getString("name")) .setCaption(parameters.getString("caption")) .setDescription(parameters.getString("description")) .setLink(parameters.getString("link")) .setPicture(parameters.getString("picture")) .build(); uiHelper.trackPendingDialogCall(shareDialog.present()); } catch (JSONException e) { e.printStackTrace(); } ``` when I am setting the "link" to my app Google Play link after share only content of Google Play link shown on my wall (It looks like I shared the app link), but if I am also want to see "caption" and "description". How to share a story from my app with some story + link of my app? Thanks in Advance
2015/03/02
[ "https://Stackoverflow.com/questions/28806025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1535428/" ]
I think, that we haven't got the opportunities to solve this. Official Facebook docs says: 'If your app share contains a link to any app on Google Play or the App Store, the description and image included in the share will be ignored. Instead, we will scrape the store directly for that app's title and image (and if there is no image, the share won't include one).'
It seems that the reason is some google restriction it does not allows to share a google play link and provide your own description etc. The solution for this might be put the link from google play in share massage.
71,538
I’m not a native English speaker and want to get a better grip on the nuances of the term *science.* In my native tongue, the word I’d use for *science* also refers to humanities and the social sciences. However, I’ve lately been getting the feeling that some people use the term only to refer to the natural sciences (case in point: the *S* in *STEM).* With *scientist* referring to academics working in the natural sciences, and *scholar* more to academics in the humanities and social sciences. Is my intuition correct? If so, is there an umbrella term describe everything from social science over STEM to law and what not?
2016/06/19
[ "https://academia.stackexchange.com/questions/71538", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/53401/" ]
[Merriam–Webster definition of *science*](http://www.merriam-webster.com/dictionary/science) reads (reflecting my experience with the usage of the term): > > **1 :** the state of knowing : knowledge as distinguished from ignorance or misunderstanding > > > **2a :** a department of systematized knowledge as an object of study the ‹*science* of theology› > >   **b :** something (as a sport or technique) that may be studied or learned like systematized knowledge ‹have it down to a *science›* > > > **3a :** knowledge or a system of knowledge covering general truths or the operation of general laws especially as obtained and tested through scientific method > >   **b :** such knowledge or such a system of knowledge concerned with the physical world and its phenomena : natural science > > > […] > > > So, *science* can refer just to the natural sciences (3b); include every discipline invested in the discovery of knowledge, i.e., natural sciences, social sciences, formal sciences , and so on; (3a) or have an even broader scope and include such things as theology (2a). The only way to know how narrow the term *science* is meant to be understood is usually from context. To exacerbate matters, some people (usually natural scientists) insist that *science* always is meant to be understood in the sense of definition 3b, even if it is not clear from context. In my opinion, this renders the word *science* almost useless for purposes of categorising academic fields, as you can never rely on it being understood as intended. > > is there an umbrella term describe everything from social science over STEM to law and what not? > > > I am not aware of a term that precisely covers this but in many cases one of the following terms may suffice: * *science (in the broader sense)* * *academic field* or *all academic fields*
Humanities cover everything that is not a "hard science" such arts and social sciences, as well as other fields, like history. The S in "STEM" is used to refer to "hard science" Social sciences include fields that use empirical methods to consider society and human behavior, such as anthropology, archaeology, economics, education, geography, law, political science, psychology and sociology. Some humanities are social sciences and some are not. The term "science" does encompass social sciences but does not include all humanities.
71,538
I’m not a native English speaker and want to get a better grip on the nuances of the term *science.* In my native tongue, the word I’d use for *science* also refers to humanities and the social sciences. However, I’ve lately been getting the feeling that some people use the term only to refer to the natural sciences (case in point: the *S* in *STEM).* With *scientist* referring to academics working in the natural sciences, and *scholar* more to academics in the humanities and social sciences. Is my intuition correct? If so, is there an umbrella term describe everything from social science over STEM to law and what not?
2016/06/19
[ "https://academia.stackexchange.com/questions/71538", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/53401/" ]
The term "science" in English definitely does not include the humanities. There are ambiguous cases, where it is unclear how to draw the line between humanities and social sciences, but for example literature is never considered a science. If you wish to include the humanities, then you must use a broader term. Social sciences are a little trickier. At one level, they are obviously sciences: it's even part of their name! On the other hand, people sometimes use the term "science" as shorthand for the hard sciences, without meaning to include the social sciences. This means you are welcome to use the term inclusively, but you shouldn't expect that it always includes the social sciences when you hear other people using it. If this distinction matters, then you'll need to discuss it explicitly. It's worth noting that there are a lot of other things that don't fall under "science" in English, besides the humanities. For example, engineering has some overlap with science, but engineering fields are usually not classified by universities under the sciences, and references to science will not be understood to include engineering. (This is one reason the term STEM is popular: it's the shortest way to refer to both science and engineering in English.) > > If so, is there an umbrella term describe everything from social science over STEM to law and what not? > > > Unfortunately, I don't think there is. (Maybe there are obscure terms out there, but there certainly isn't one that is widely used and understood.) You could use broad phrases like "all academic disciplines" if you really want to include everyone, but there is not a specific term like "science" for this.
Humanities cover everything that is not a "hard science" such arts and social sciences, as well as other fields, like history. The S in "STEM" is used to refer to "hard science" Social sciences include fields that use empirical methods to consider society and human behavior, such as anthropology, archaeology, economics, education, geography, law, political science, psychology and sociology. Some humanities are social sciences and some are not. The term "science" does encompass social sciences but does not include all humanities.
71,538
I’m not a native English speaker and want to get a better grip on the nuances of the term *science.* In my native tongue, the word I’d use for *science* also refers to humanities and the social sciences. However, I’ve lately been getting the feeling that some people use the term only to refer to the natural sciences (case in point: the *S* in *STEM).* With *scientist* referring to academics working in the natural sciences, and *scholar* more to academics in the humanities and social sciences. Is my intuition correct? If so, is there an umbrella term describe everything from social science over STEM to law and what not?
2016/06/19
[ "https://academia.stackexchange.com/questions/71538", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/53401/" ]
The term "science" in English definitely does not include the humanities. There are ambiguous cases, where it is unclear how to draw the line between humanities and social sciences, but for example literature is never considered a science. If you wish to include the humanities, then you must use a broader term. Social sciences are a little trickier. At one level, they are obviously sciences: it's even part of their name! On the other hand, people sometimes use the term "science" as shorthand for the hard sciences, without meaning to include the social sciences. This means you are welcome to use the term inclusively, but you shouldn't expect that it always includes the social sciences when you hear other people using it. If this distinction matters, then you'll need to discuss it explicitly. It's worth noting that there are a lot of other things that don't fall under "science" in English, besides the humanities. For example, engineering has some overlap with science, but engineering fields are usually not classified by universities under the sciences, and references to science will not be understood to include engineering. (This is one reason the term STEM is popular: it's the shortest way to refer to both science and engineering in English.) > > If so, is there an umbrella term describe everything from social science over STEM to law and what not? > > > Unfortunately, I don't think there is. (Maybe there are obscure terms out there, but there certainly isn't one that is widely used and understood.) You could use broad phrases like "all academic disciplines" if you really want to include everyone, but there is not a specific term like "science" for this.
[Merriam–Webster definition of *science*](http://www.merriam-webster.com/dictionary/science) reads (reflecting my experience with the usage of the term): > > **1 :** the state of knowing : knowledge as distinguished from ignorance or misunderstanding > > > **2a :** a department of systematized knowledge as an object of study the ‹*science* of theology› > >   **b :** something (as a sport or technique) that may be studied or learned like systematized knowledge ‹have it down to a *science›* > > > **3a :** knowledge or a system of knowledge covering general truths or the operation of general laws especially as obtained and tested through scientific method > >   **b :** such knowledge or such a system of knowledge concerned with the physical world and its phenomena : natural science > > > […] > > > So, *science* can refer just to the natural sciences (3b); include every discipline invested in the discovery of knowledge, i.e., natural sciences, social sciences, formal sciences , and so on; (3a) or have an even broader scope and include such things as theology (2a). The only way to know how narrow the term *science* is meant to be understood is usually from context. To exacerbate matters, some people (usually natural scientists) insist that *science* always is meant to be understood in the sense of definition 3b, even if it is not clear from context. In my opinion, this renders the word *science* almost useless for purposes of categorising academic fields, as you can never rely on it being understood as intended. > > is there an umbrella term describe everything from social science over STEM to law and what not? > > > I am not aware of a term that precisely covers this but in many cases one of the following terms may suffice: * *science (in the broader sense)* * *academic field* or *all academic fields*
71,538
I’m not a native English speaker and want to get a better grip on the nuances of the term *science.* In my native tongue, the word I’d use for *science* also refers to humanities and the social sciences. However, I’ve lately been getting the feeling that some people use the term only to refer to the natural sciences (case in point: the *S* in *STEM).* With *scientist* referring to academics working in the natural sciences, and *scholar* more to academics in the humanities and social sciences. Is my intuition correct? If so, is there an umbrella term describe everything from social science over STEM to law and what not?
2016/06/19
[ "https://academia.stackexchange.com/questions/71538", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/53401/" ]
[Merriam–Webster definition of *science*](http://www.merriam-webster.com/dictionary/science) reads (reflecting my experience with the usage of the term): > > **1 :** the state of knowing : knowledge as distinguished from ignorance or misunderstanding > > > **2a :** a department of systematized knowledge as an object of study the ‹*science* of theology› > >   **b :** something (as a sport or technique) that may be studied or learned like systematized knowledge ‹have it down to a *science›* > > > **3a :** knowledge or a system of knowledge covering general truths or the operation of general laws especially as obtained and tested through scientific method > >   **b :** such knowledge or such a system of knowledge concerned with the physical world and its phenomena : natural science > > > […] > > > So, *science* can refer just to the natural sciences (3b); include every discipline invested in the discovery of knowledge, i.e., natural sciences, social sciences, formal sciences , and so on; (3a) or have an even broader scope and include such things as theology (2a). The only way to know how narrow the term *science* is meant to be understood is usually from context. To exacerbate matters, some people (usually natural scientists) insist that *science* always is meant to be understood in the sense of definition 3b, even if it is not clear from context. In my opinion, this renders the word *science* almost useless for purposes of categorising academic fields, as you can never rely on it being understood as intended. > > is there an umbrella term describe everything from social science over STEM to law and what not? > > > I am not aware of a term that precisely covers this but in many cases one of the following terms may suffice: * *science (in the broader sense)* * *academic field* or *all academic fields*
Does the term "science" include the humanities? No. === Does the term "science" include the social sciences (sociology/economics)? If you ask the physics department, no. If you ask the economics department, yes.
71,538
I’m not a native English speaker and want to get a better grip on the nuances of the term *science.* In my native tongue, the word I’d use for *science* also refers to humanities and the social sciences. However, I’ve lately been getting the feeling that some people use the term only to refer to the natural sciences (case in point: the *S* in *STEM).* With *scientist* referring to academics working in the natural sciences, and *scholar* more to academics in the humanities and social sciences. Is my intuition correct? If so, is there an umbrella term describe everything from social science over STEM to law and what not?
2016/06/19
[ "https://academia.stackexchange.com/questions/71538", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/53401/" ]
The term "science" in English definitely does not include the humanities. There are ambiguous cases, where it is unclear how to draw the line between humanities and social sciences, but for example literature is never considered a science. If you wish to include the humanities, then you must use a broader term. Social sciences are a little trickier. At one level, they are obviously sciences: it's even part of their name! On the other hand, people sometimes use the term "science" as shorthand for the hard sciences, without meaning to include the social sciences. This means you are welcome to use the term inclusively, but you shouldn't expect that it always includes the social sciences when you hear other people using it. If this distinction matters, then you'll need to discuss it explicitly. It's worth noting that there are a lot of other things that don't fall under "science" in English, besides the humanities. For example, engineering has some overlap with science, but engineering fields are usually not classified by universities under the sciences, and references to science will not be understood to include engineering. (This is one reason the term STEM is popular: it's the shortest way to refer to both science and engineering in English.) > > If so, is there an umbrella term describe everything from social science over STEM to law and what not? > > > Unfortunately, I don't think there is. (Maybe there are obscure terms out there, but there certainly isn't one that is widely used and understood.) You could use broad phrases like "all academic disciplines" if you really want to include everyone, but there is not a specific term like "science" for this.
Does the term "science" include the humanities? No. === Does the term "science" include the social sciences (sociology/economics)? If you ask the physics department, no. If you ask the economics department, yes.
15,409,983
I'm having trouble with the ServiceStack Json client not deserialzing my results when I use POST. The get methods have no problems deserialzing the response into a UserCredentials object but when I use POST method, it returns an object with all null properties. If I change the type passed to the Post method to a dictionary I can see that it is getting the right results, and I can see the rest call succeeds at the http level from Fiddler. ``` public UserCredentials Login(string uname, string pwd) { var url = "/login"; //note that I have to send a dictionary because if I sent a Login Object with username and password it erronously sends {Login:} in the raw request body instead of {"Uname":uname, "Password":password} var login = new Dictionary<string, string>() { { "Uname", uname }, { "Password", pwd } }; var result = client.Post<UserCredentials>(url, login); return result; } ``` Here's the response (which is the correct and expected http response from the server) ``` HTTP/1.1 200 OK Server: nginx Date: Thu, 14 Mar 2013 12:55:33 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive Vary: Accept-Encoding Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Length: 49 {"Uid":1,"Hash":"SomeHash"} ``` And here is the UserCredentials class ``` public class UserCredentials { public long Uid; public string Hash; } ```
2013/03/14
[ "https://Stackoverflow.com/questions/15409983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611750/" ]
Apparently Django looks for fixtures in apps specified in `INSTALLED_APPS` that have a `models.py` in them. So if your app is missing one, create an empty `models.py` and Django won't skip looking for fixtures in that app.
`initial_data.yaml` should be picked up as long as: * you have pyyaml installed * it's located in `fixtures` directory of one of your apps listed in `INSTALLED_APPS` (in `settings.py`) So, given you have pyyaml it's probably the latter. Please make sure your `fixtures` directory is inside one of the apps listed in `INSTALLED_APPS` and you should be up and running. In case of this layout: ``` /djninja /djninja /bands /fixtures - initial_data.yaml /fans /lyrics ``` adding `bands` to `INSTALLED_APPS` should do the trick, given `bands` is a valid package and is on `PYTHONPATH`. If you'd like Django to look for fixtures in some other directory, you can follow the advice given in ["Where Django finds fixture files" subsection of the docs](https://docs.djangoproject.com/en/dev/howto/initial-data/#where-django-finds-fixture-files) and use the `FIXTURE_DIRS` setting, making it a list of extra directories to look in.
20,927,215
How to blur an image(png) and then load it to image view using setBackgroundResource(R.drawable.*\**). It must work on API > 10 I have found some solutions, but i don't know how to take image from @drawable and load it to imageview Thanks in advance...
2014/01/04
[ "https://Stackoverflow.com/questions/20927215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149274/" ]
HI you can simply write a code like this.. ``` try{Class.forName("com.mysql.jdbc.Driver").newInstance(); username=asfksjfjs; password=sflkaskfjhsjk; url="jdbc:mysql://178.360.01:3306/demo01"; con = (Connection) DriverManager.getConnection(url,username,password);} ``` just copy those port no and host name from your phpmyadmin... It will work surly.
I don't think you can use environment variables in a jdbc.properties file, I don't think they will get parsed (as answered here [Regarding application.properties file and environment variable](https://stackoverflow.com/questions/2263929/regarding-application-properties-file-and-environment-variable)). You MIGHT be able to use the environment variables right in your xml file if that xml file gets parsed correctly by something that will substitute them (like it does for a standalone.xml or context.xml file)
20,927,215
How to blur an image(png) and then load it to image view using setBackgroundResource(R.drawable.*\**). It must work on API > 10 I have found some solutions, but i don't know how to take image from @drawable and load it to imageview Thanks in advance...
2014/01/04
[ "https://Stackoverflow.com/questions/20927215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149274/" ]
HI you can simply write a code like this.. ``` try{Class.forName("com.mysql.jdbc.Driver").newInstance(); username=asfksjfjs; password=sflkaskfjhsjk; url="jdbc:mysql://178.360.01:3306/demo01"; con = (Connection) DriverManager.getConnection(url,username,password);} ``` just copy those port no and host name from your phpmyadmin... It will work surly.
Activate phpmyadmin, and open it you will find the ip in the header, take it and replace it in the OPENSHIFT\_MYSQL\_DB\_HOST variable, the port is the default mysql : 3306.
6,856,786
Is it possible getting cookie from an external js with Php before generating HTML to the browser? Something like ``` <? //Get if i have some cookie information if($_COOKIE["js_app"]) $cookie_js = $_COOKIE["js_app"]; //now, talk with some app.js if($cookie_js) $cookie = some_function(target = 'some_domanin/app.js',$cookie_js); else $cookie = some_function(target = 'some_domanin/app.js'); $_COOKIE["js_app"] = $cookie; //now i can generate the HTML output. .... ?> ```
2011/07/28
[ "https://Stackoverflow.com/questions/6856786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391721/" ]
We have settled on a process where "CompanyX" gives us an account to their iTunes connect so we can build, sign and upload to the App Store in their name. Probably you can build it on your machine, send them the product and they sign and upload it themselves, however that would be more tedious, as Apple's toolchain with Xcode and the Organizer has become quite good at this for the "usual" case of someone uploading their "own" apps.
AFAIK you have to sign the source code with the key you get from Apple to submit it.
32,872,217
Trying to install imagemagick ( to be used w PaperClip gem) on my mac ( Yosemite 10.10.5) raising error with 'libtool' what happen with it ? ``` $ brew update $ brew install imagemagick ==> Installing dependencies for imagemagick: libtool, jpeg, libpng, libti ==> Installing imagemagick dependency: libtool ==> Downloading https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bott curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bottle.tar.gz Warning: Bottle installation failed: building from source. ==> Downloading http://ftpmirror.gnu.org/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Trying a mirror... ==> Downloading https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz ```
2015/09/30
[ "https://Stackoverflow.com/questions/32872217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure if it's exactly what you're looking for, but what I do is just plop a trigger in the app.xaml to invoke using the `IsInDesignMode` property like; Namespace (Thanks Tono Nam); `xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework"` XAML; ``` <Style TargetType="{x:Type UserControl}"> <Style.Triggers> <Trigger Property="ComponentModel:DesignerProperties.IsInDesignMode" Value="True"> <Setter Property="Background" Value="#FFFFFF" /> </Trigger> </Style.Triggers> </Style> ``` Simple, but works, and sometimes I target other dependency properties like font and stuff too depending on the need. Hope this helps. PS - You can target other TargetType's with their own properties the same way, like for example, ChildWindows, Popups, Windows, whatever...
You can create a static class with an attached property for design mode: ``` using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Helpers.Wpf { public static class DesignModeHelper { private static bool? inDesignMode; public static readonly DependencyProperty BackgroundProperty = DependencyProperty .RegisterAttached("Background", typeof (Brush), typeof (DesignModeHelper), new PropertyMetadata(BackgroundChanged)); private static bool InDesignMode { get { if (inDesignMode == null) { var prop = DesignerProperties.IsInDesignModeProperty; inDesignMode = (bool) DependencyPropertyDescriptor .FromProperty(prop, typeof (FrameworkElement)) .Metadata.DefaultValue; if (!inDesignMode.GetValueOrDefault(false) && Process.GetCurrentProcess().ProcessName.StartsWith("devenv", StringComparison.Ordinal)) inDesignMode = true; } return inDesignMode.GetValueOrDefault(false); } } public static Brush GetBackground(DependencyObject dependencyObject) { return (Brush) dependencyObject.GetValue(BackgroundProperty); } public static void SetBackground(DependencyObject dependencyObject, Brush value) { dependencyObject.SetValue(BackgroundProperty, value); } private static void BackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!InDesignMode) return; d.SetValue(Control.BackgroundProperty, e.NewValue); } } } ``` And you can use it like this: ``` xmlns:wpf="clr-namespace:Helpers.Wpf;assembly=Helpers.Wpf" <Grid Background="Black" wpf:DesignModeHelper.Background="White"> <Button Content="Press me!"/> </Grid> ``` You can use this approach to implement other property for design mode.
32,872,217
Trying to install imagemagick ( to be used w PaperClip gem) on my mac ( Yosemite 10.10.5) raising error with 'libtool' what happen with it ? ``` $ brew update $ brew install imagemagick ==> Installing dependencies for imagemagick: libtool, jpeg, libpng, libti ==> Installing imagemagick dependency: libtool ==> Downloading https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bott curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bottle.tar.gz Warning: Bottle installation failed: building from source. ==> Downloading http://ftpmirror.gnu.org/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Trying a mirror... ==> Downloading https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz ```
2015/09/30
[ "https://Stackoverflow.com/questions/32872217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can create a static class with an attached property for design mode: ``` using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Helpers.Wpf { public static class DesignModeHelper { private static bool? inDesignMode; public static readonly DependencyProperty BackgroundProperty = DependencyProperty .RegisterAttached("Background", typeof (Brush), typeof (DesignModeHelper), new PropertyMetadata(BackgroundChanged)); private static bool InDesignMode { get { if (inDesignMode == null) { var prop = DesignerProperties.IsInDesignModeProperty; inDesignMode = (bool) DependencyPropertyDescriptor .FromProperty(prop, typeof (FrameworkElement)) .Metadata.DefaultValue; if (!inDesignMode.GetValueOrDefault(false) && Process.GetCurrentProcess().ProcessName.StartsWith("devenv", StringComparison.Ordinal)) inDesignMode = true; } return inDesignMode.GetValueOrDefault(false); } } public static Brush GetBackground(DependencyObject dependencyObject) { return (Brush) dependencyObject.GetValue(BackgroundProperty); } public static void SetBackground(DependencyObject dependencyObject, Brush value) { dependencyObject.SetValue(BackgroundProperty, value); } private static void BackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!InDesignMode) return; d.SetValue(Control.BackgroundProperty, e.NewValue); } } } ``` And you can use it like this: ``` xmlns:wpf="clr-namespace:Helpers.Wpf;assembly=Helpers.Wpf" <Grid Background="Black" wpf:DesignModeHelper.Background="White"> <Button Content="Press me!"/> </Grid> ``` You can use this approach to implement other property for design mode.
In 2022 you actually can and almost guessed it: ```xml d:Background="White" ``` Note you can set pretty much any other control properties differently for design-time when prefix them with `d:`, for example: ```xml <TextBlock Text="{Binding TextFromViewModel}" Foreground="{StaticResource PrimaryBrush}" d:Text="Design-time text" d:Foreground="Black" /> ``` Source: [Use Design Time Data with the XAML Designer in Visual Studio](https://learn.microsoft.com/en-us/visualstudio/xaml-tools/xaml-designtime-data?view=vs-2022)
32,872,217
Trying to install imagemagick ( to be used w PaperClip gem) on my mac ( Yosemite 10.10.5) raising error with 'libtool' what happen with it ? ``` $ brew update $ brew install imagemagick ==> Installing dependencies for imagemagick: libtool, jpeg, libpng, libti ==> Installing imagemagick dependency: libtool ==> Downloading https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bott curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://homebrew.bintray.com/bottles/libtool-2.4.6.yosemite.bottle.tar.gz Warning: Bottle installation failed: building from source. ==> Downloading http://ftpmirror.gnu.org/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Trying a mirror... ==> Downloading https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz curl: (4) A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. Error: Failed to download resource "libtool" Download failed: https://ftp.gnu.org/gnu/libtool/libtool-2.4.6.tar.xz ```
2015/09/30
[ "https://Stackoverflow.com/questions/32872217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure if it's exactly what you're looking for, but what I do is just plop a trigger in the app.xaml to invoke using the `IsInDesignMode` property like; Namespace (Thanks Tono Nam); `xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework"` XAML; ``` <Style TargetType="{x:Type UserControl}"> <Style.Triggers> <Trigger Property="ComponentModel:DesignerProperties.IsInDesignMode" Value="True"> <Setter Property="Background" Value="#FFFFFF" /> </Trigger> </Style.Triggers> </Style> ``` Simple, but works, and sometimes I target other dependency properties like font and stuff too depending on the need. Hope this helps. PS - You can target other TargetType's with their own properties the same way, like for example, ChildWindows, Popups, Windows, whatever...
In 2022 you actually can and almost guessed it: ```xml d:Background="White" ``` Note you can set pretty much any other control properties differently for design-time when prefix them with `d:`, for example: ```xml <TextBlock Text="{Binding TextFromViewModel}" Foreground="{StaticResource PrimaryBrush}" d:Text="Design-time text" d:Foreground="Black" /> ``` Source: [Use Design Time Data with the XAML Designer in Visual Studio](https://learn.microsoft.com/en-us/visualstudio/xaml-tools/xaml-designtime-data?view=vs-2022)
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
Use [parseFloat()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) or [parseInt()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) ``` var totalPoints = 0; $('.section input').each(function(){ totalPoints = parseFloat($(this).val()) + totalPoints; }); alert(totalPoints); ```
The value is stored as a string, so calling `+=` is doing string concatenation. You want/need to treat it as a number, so it does addition. Use the [`parseInt()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) function to convert it to a number: ``` totalPoints += parseInt($(this).val(), 10); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
You are doing "1"+"1" and expect it to be 2 ( int) it is not. a very quick (and *not* fully correct) solution is : ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below }); alert(totalPoints); }); ``` catch ? why ? answer: You should **always** use radix cause if you dont , a leading zero is **octal** ! ``` parseInt("010") //8 ( ff) parseInt("010") //10 ( chrome) parseInt("010",10) //10 ( ff) parseInt("010",10) //10 ( chrome) ``` well.... you get the idea. supply radix ! edit ==== final solution (using `.each( function(index, Element) )`) ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(i,n){ totalPoints += parseInt($(n).val(),10); }); alert(totalPoints); }); ```
``` Use eval instead of parseInt var a = "1.5"; var b = "2"; var c = parseInt(a) + parseInt(b); console.log(c); //result 3 var a = "1.5"; var b = "2"; var c = eval(a) + eval(b); console.log(c); //result 3.5 this is accurate ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
You are doing "1"+"1" and expect it to be 2 ( int) it is not. a very quick (and *not* fully correct) solution is : ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below }); alert(totalPoints); }); ``` catch ? why ? answer: You should **always** use radix cause if you dont , a leading zero is **octal** ! ``` parseInt("010") //8 ( ff) parseInt("010") //10 ( chrome) parseInt("010",10) //10 ( ff) parseInt("010",10) //10 ( chrome) ``` well.... you get the idea. supply radix ! edit ==== final solution (using `.each( function(index, Element) )`) ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(i,n){ totalPoints += parseInt($(n).val(),10); }); alert(totalPoints); }); ```
You can also use `reduce()` method of Array to get the sum: ``` var arrayOfValues = $('.section input[type=radio]').map(function(index, input) { return parseInt($(input).val()); }).toArray(); var sum = arrayOfValues.reduce(function(val1, val2) { return val1 + val2; }); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
You are doing "1"+"1" and expect it to be 2 ( int) it is not. a very quick (and *not* fully correct) solution is : ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below }); alert(totalPoints); }); ``` catch ? why ? answer: You should **always** use radix cause if you dont , a leading zero is **octal** ! ``` parseInt("010") //8 ( ff) parseInt("010") //10 ( chrome) parseInt("010",10) //10 ( ff) parseInt("010",10) //10 ( chrome) ``` well.... you get the idea. supply radix ! edit ==== final solution (using `.each( function(index, Element) )`) ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(i,n){ totalPoints += parseInt($(n).val(),10); }); alert(totalPoints); }); ```
The value is stored as a string, so calling `+=` is doing string concatenation. You want/need to treat it as a number, so it does addition. Use the [`parseInt()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) function to convert it to a number: ``` totalPoints += parseInt($(this).val(), 10); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
You are doing "1"+"1" and expect it to be 2 ( int) it is not. a very quick (and *not* fully correct) solution is : ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below }); alert(totalPoints); }); ``` catch ? why ? answer: You should **always** use radix cause if you dont , a leading zero is **octal** ! ``` parseInt("010") //8 ( ff) parseInt("010") //10 ( chrome) parseInt("010",10) //10 ( ff) parseInt("010",10) //10 ( chrome) ``` well.... you get the idea. supply radix ! edit ==== final solution (using `.each( function(index, Element) )`) ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(i,n){ totalPoints += parseInt($(n).val(),10); }); alert(totalPoints); }); ```
The javascript function parseInt() should achieve what you require, here's a fiddle: <http://jsfiddle.net/k739M/> And some formatted code: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); }); alert(totalPoints); });​ ``` Additionally, if you were to call $(each) on '.section input', you can reduce the amount of processing time (and code). ``` var totalPoints = 0; $('.section input').each(function(){ totalPoints += parseInt($(this).val()); }); alert(totalPoints); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
Use [parseFloat()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) or [parseInt()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) ``` var totalPoints = 0; $('.section input').each(function(){ totalPoints = parseFloat($(this).val()) + totalPoints; }); alert(totalPoints); ```
``` Use eval instead of parseInt var a = "1.5"; var b = "2"; var c = parseInt(a) + parseInt(b); console.log(c); //result 3 var a = "1.5"; var b = "2"; var c = eval(a) + eval(b); console.log(c); //result 3.5 this is accurate ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
The value is stored as a string, so calling `+=` is doing string concatenation. You want/need to treat it as a number, so it does addition. Use the [`parseInt()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) function to convert it to a number: ``` totalPoints += parseInt($(this).val(), 10); ```
You can also use `reduce()` method of Array to get the sum: ``` var arrayOfValues = $('.section input[type=radio]').map(function(index, input) { return parseInt($(input).val()); }).toArray(); var sum = arrayOfValues.reduce(function(val1, val2) { return val1 + val2; }); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
The value is stored as a string, so calling `+=` is doing string concatenation. You want/need to treat it as a number, so it does addition. Use the [`parseInt()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) function to convert it to a number: ``` totalPoints += parseInt($(this).val(), 10); ```
``` Use eval instead of parseInt var a = "1.5"; var b = "2"; var c = parseInt(a) + parseInt(b); console.log(c); //result 3 var a = "1.5"; var b = "2"; var c = eval(a) + eval(b); console.log(c); //result 3.5 this is accurate ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
You are doing "1"+"1" and expect it to be 2 ( int) it is not. a very quick (and *not* fully correct) solution is : ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below }); alert(totalPoints); }); ``` catch ? why ? answer: You should **always** use radix cause if you dont , a leading zero is **octal** ! ``` parseInt("010") //8 ( ff) parseInt("010") //10 ( chrome) parseInt("010",10) //10 ( ff) parseInt("010",10) //10 ( chrome) ``` well.... you get the idea. supply radix ! edit ==== final solution (using `.each( function(index, Element) )`) ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(i,n){ totalPoints += parseInt($(n).val(),10); }); alert(totalPoints); }); ```
Use [parseFloat()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) or [parseInt()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) ``` var totalPoints = 0; $('.section input').each(function(){ totalPoints = parseFloat($(this).val()) + totalPoints; }); alert(totalPoints); ```
14,142,011
I'm trying to find the sum of input values within multiple sections. I've put my code so far below. The HTML: ``` <div class="section"> <input type="radio" name="q1" value="2"/> <input type="radio" name="q2" value="0"/> <input type="radio" name="q3" value="1"/> <input type="radio" name="q4" value="3"/> </div> ``` The jQuery: ``` $('.section').each(function(){ var totalPoints = 0; $(this).find('input').each(function(){ totalPoints += $(this).val(); }); alert(totalPoints); }); ``` Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143. Any ideas how I get a cumulative sum instead of a string?
2013/01/03
[ "https://Stackoverflow.com/questions/14142011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575029/" ]
Use [parseFloat()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) or [parseInt()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) ``` var totalPoints = 0; $('.section input').each(function(){ totalPoints = parseFloat($(this).val()) + totalPoints; }); alert(totalPoints); ```
You can also use `reduce()` method of Array to get the sum: ``` var arrayOfValues = $('.section input[type=radio]').map(function(index, input) { return parseInt($(input).val()); }).toArray(); var sum = arrayOfValues.reduce(function(val1, val2) { return val1 + val2; }); ```
38,695
Compare to [underscorejs](http://underscorejs.org/) if it pleases you. Once again, I hope this is well commented. Please let me know what comments/improvements I can add. Please review all aspects of this code. ``` /*************************************************************************************************** **UTILITY - additional coverage for looping, type checking, extending ... - consistent ordering, naming conventions ... - fewer function branches - increased type checking and modularity - vector based unit testing ***************************************************************************************************/ // self used to hold client or server side global ( window or exports ) (function (self, undef) { "use strict"; // holds (P)ublic properties var $P = {}, // holds p(R)ivate properties $R = {}, // native methods (alphabetical order) nativeFilter = Array.prototype.filter, nativeIsArray = Array.isArray, nativeSlice = Array.prototype.slice, nativeSome = Array.prototype.some, nativeToString = Object.prototype.toString; $P.noConflict = (function () { // $R.g holds the single global variable, used to hold all packages // methods $R.g = '$A'; $R.previous = self[$R.g]; // utility is required by all other packages // start the "pack"age list $P.pack = { utility: true }; return function () { var temp = self[$R.g]; self[$R.g] = $R.previous; return temp; }; }()); $P.isType = function (type, obj) { return $P.getType(obj) === type; }; // returns type in a captialized string form // typeof is only accurate for function, string, number, boolean, and // undefined. null and array are both incorrectly reported as object $P.getType = function (obj) { return nativeToString.call(obj).slice(8, -1); }; $P.isFalse = function (obj) { return obj === false; }; $P.isUndefined = function (obj) { return obj === undef; }; $P.isNull = function (obj) { return obj === null; }; $P.isNumber = function (value) { return (typeof value === 'number') && isFinite(value); }; // detects null or undefined $P.isGone = function (obj) { return obj == null; }; // detects anything but null or undefined $P.isHere = function (obj) { return obj != null; }; // detects null, undefined, NaN, ('' ""), 0, -0, false $P.isFalsy = function (obj) { return !obj; }; // detects any thing but null, undefined, NaN, ('' ""), 0, -0, false $P.isTruthy = function (obj) { return !!obj; }; // shortcut as their are only two primitive boolean values // detects a "boxed" boolean as well $P.isBoolean = function (obj) { return obj === true || obj === false || nativeToString.call(obj) === '[object Boolean]'; }; // delegates to native $P.isArray = nativeIsArray || function (obj) { return nativeToString.call(obj) === '[object Array]'; }; // jslint prefers {}.constructor(obj) over Object(obj) $P.isObjectAbstract = function (obj) { // return obj === Object(obj); return !!(obj && (obj === {}.constructor(obj))); }; // has a numeric length property $P.isArrayAbstract = function (obj) { return !!(obj && obj.length === +obj.length); }; $P.someIndex = function (arr, func, con) { var ind, len; // prevent type errors, note function is validated if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) { return; } // delegate to native some() if (nativeSome && arr.some === nativeSome) { return arr.some(func, con); } // if the function passes back a truthy value, the loop will terminate for (ind = 0, len = arr.length; ind < len; ind++) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; $P.someKey = function (obj, func, con) { var key; // prevent type errors // for-in will filter out null and undefined if ((obj == null) || (typeof func !== 'function')) { return; } for (key in obj) { if (obj.hasOwnProperty(key)) { // if the function passes back a truthy value, // the loop will terminate if (func.call(con, obj[key], key, obj)) { return true; } } } return false; }; // loop through space separated "tokens" in a string $P.eachString = function (str, func, con) { // prevent type errors if (typeof str !== 'string' || str === "" || typeof func !== 'function') { return; } $P.someIndex(str.split(/\s+/), func, con); }; // does not extend through the prototype chain // implemented for objects only $P.extend = function (obj) { // loop througth elements beyond obj $P.someIndex(nativeSlice.call(arguments, 1), function (val) { // extend it $P.someKey(val, function (val_inner, key) { obj[key] = val_inner; }); }); return obj; }; // extends non-prototype properties from obj2 on to obj1 $P.extendSafe = function (obj1, obj2) { var key; for (key in obj2) { if (obj2.hasOwnProperty(key)) { if (obj1.hasOwnProperty(key)) { throw "naming collision: " + key; } obj1[key] = obj2[key]; } } return obj1; }; // if incorrect types are passed, it will return an empty array // arrays only $P.filter = function (arr, func, con) { var results = []; if ((arr == null) || (typeof func !== 'function')) { return results; } if (nativeFilter && arr.filter === nativeFilter) { return arr.filter(func, con); } $P.someIndex(arr, function (val, ind, arr) { if (func.call(con, val, ind, arr)) { results.push(val); } }); return results; }; $P.clone = function (obj) { return $P.extend({}, obj); }; $P.someIndex(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object'], function (val) { $P['is' + val] = function (obj) { return $P.isType(val, obj); }; }); $P.addU = function (str, suf) { return str + '_' + suf; }; $P.removeU = function (str) { if (typeof str !== 'string' || str === "") { return false; } return str.slice(str, str.lastIndexOf("_")); }; $P.removeSuffix = function (str, len) { if (typeof str !== 'string' || str === "") { return false; } return str.slice(0, -len); }; // equivalent to IIFE but "nicer" syntax $P.runTest = (function () { var tests = {}; return function (name, arr, func) { tests[name] = func.apply(this, arr); }; }()); self[$R.g] = $P.extendSafe($P, {}); // this will hold the global object - window or exports }(this)); ``` **`someIndex()` and `someKey()` compared to underscore `each()`** So the way I chose to write `someIndex()` and `someKey()` was organically or as a process. I wanted to abstract the looping idioms I got tired of writing into methods. Because `for` and `for-in` can be broke out of I decided that `some()` was a better building block then `each()` from my perspective. After, I did this I compared what I had to underscore. My design choices were different in other ways as well. -- Please note, if you need speed just use a for or for-in loop, if you need clean concise code, use the abstraction -- The other way I diverged from underscore is that I wrote some separately for arrays and objects, because when I code I always know which one I am looping through, hence I wanted to express this knowledge in my code - someIndex() and someKey(). Another way I diverged was that I type check all the inputs in one line, for some reason underscore chooses not to type check the callback function. The other way I diverged is I don't check for any internal breaks, that are internal use only, in underscore this is shown as an equality check for `breaker`. Also, as in all my code b.c. JS is not block scoped yet, I put my var definitions up top. Also, regarding elegance, I feel my code is more elegant, as the type checking is consistent and consolidated, my var declarations are more naturally inline with how the interpreter reads them, and comments, white space, and a 4 space indent level make the code easier to read. That's the gist of it, please let me know if I can elaborate more. Below is the code for both: ``` $P.someIndex = function (arr, func, con) { var ind, len; // prevent type errors, note function is validated if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) { return; } // delegate to native some() if (nativeSome && arr.some === nativeSome) { return arr.some(func, con); } // if the function passes back a truthy value, the loop will terminate for (ind = 0, len = arr.length; ind < len; ind++) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } }; ```
2014/01/06
[ "https://codereview.stackexchange.com/questions/38695", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/-1/" ]
The below code would be cleaner with object literal notation : ``` // a basic registry pattern with get/set and getMany/setMany $P.Reg = (function () { var publik = {}, register = {}; publik.get = function (key) { return register[key]; }; publik.set = function (key, value) { register[key] = value; }; publik.setMany = function (o) { $A.someKey(o, function (val, key) { register[key] = val; }); }; publik.getMany = function () { return register; }; return publik; }()); ``` would be ``` // a basic registry pattern with get/set and getMany/setMany $P.Reg = (function () { var register = {}; return { get : function (key) { return register[key]; }, set : function (key, value) { register[key] = value; }, setMany : function (o) { $A.someKey(o, function (val, key) { register[key] = val; }); }, getMany : function () { return register; } }; }()); ``` I also note that * getMany is wrongly named, getAll perhaps ? * not sure what `someKey` does, is it any different from `for( var key in o)` ?
I agree [object notation would look cleaner](https://codereview.stackexchange.com/a/38697/2634) in this case. I don't see why you need `Reg`. It's a very thin wrapper over an object. There's no need to implement “registry pattern” in JS because every JS object already *is* a “registry”. I'm not sure why you need a `Debug` helper that loads and unloads external scripts or styles. In fact, I don't understand its purpose at all: `addTags` accepts a `tag` parameter, which presumably is a string (you're using it as a key), but supposedly the first call will do nothing, since `hold[tag]` will be empty. Do I need to call `removeTags` first? What is a tag anyway? The code seems simple, but I fail to understand what it does and how you use it. Maybe you need to ditch simple names in favor of more descriptive ones? As for putting these utilities under a common umbrella of a “package for outer-package communications”, I stay unconvinced. These utilities have little to do with each other, and the way you describe it, grouping them doesn't sound convincing. > > By outer-package, I mean outside of this package - this can be the DOM or other packages. This package has a basic event system and a basic registry. It also has a debugger which allows you to fiddle with the DOM by removing and adding entire sets of tags. Later it might have things which allow it to Debug / Configure the server via ajax. > > > It may *seem* like each module needs a registry, or some debug tools, or event system, but you can already achieve this without grouping them: * put Pubsub separately and make it a mixin like [Backbone.Events](http://backbonejs.org/#Events); * debug tools can also be kept separately; * any JS object is a “registry” so no real need for that. Otherwise, to me, this package looks like a “[God](http://en.wikipedia.org/wiki/God_object) module”. Not that there's something wrong with it, if you *meant* it to be all-the-utilities-I-will-ever-need kind of module. I wasn't sure from your question if you meant it. The nice thing about separating even small utilities is that you can * open source them because they are decoupled from your code, and others can hack on them; * replace them one by one with different implementations; * they are immune to “specifics creep”, i.e. the situation when over time your once-generic utilities become too tightly coupled to one specific project, and grow too difficult to disentangle so you have to rewrite them once again for your next project.
118,406
I am learning ML and facing confusion about data scaling. For example, I have the following data: | Weight(KG) | Balance($) | | --- | --- | | 75 | 3401542 | | 99 | 4214514 | Now, if I use StandardScaler, I may get something like this: | Weight(KG) | Balance($) | | --- | --- | | -0.23214788 | -0.73214788 | | -0.25214788 | -0.83214788 | Now, I can train\_test\_split data, then train the model and find the accuracy of the model. Suppose, the accuracy is 82%. Now, if I want to test the model from user data by *model.predict()*, then user will not put scaled input, because users are not aware of the internal process of the model, they will put real-life values, like weight= 102 and balance= 1025455. Now, since my model is trained and tested with scaled data, how it will handle real-life values in real-life applications without scaling?
2023/02/09
[ "https://datascience.stackexchange.com/questions/118406", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/136871/" ]
I like the initiative that you answered your own question. In case you would like an additional answer: What you are referring to in your question is the concept of hierarchical clustering, a great way to cluster since it is deterministic (meaning no matter how many times you run it, the groupings are the exact same, unlike k-means clustering) and the hierarchical nature of the clustering means you can choose the number of higher-level topics via a overall intra-cluster distance threshold. A clear example of how to implement it can be found here: [Hierarchical Clustering in Python](https://www.w3schools.com/python/python_ml_hierarchial_clustering.asp#:%7E:text=Hierarchical%20clustering%20is%20an%20unsupervised,need%20a%20%22target%22%20variable) Good luck!
I do not know if this is the smartest way to do it, but it seems to work for my study case. To recap, I performed a top2vec algorithm: ``` import numpy as np import pandas as pd from top2vec import Top2Vec df = pd.read_excel('Preprocessed2.xlsx') documents = df_small_small['Translated Cleaned'].to_list() model = Top2Vec(documents, embedding_model='universal-sentence-encoder', speed='deep-learn') ``` The algorithm finds 30 topics. However, although coherent, they could be grouped into smaller *macrotopic* since there are some similarities among different topics. After having inspected them thanks to a word cloud visualization ``` topic_sizes, topic_nums = model.get_topic_sizes() for topic in topic_nums: model.generate_topic_wordcloud(topic) ``` and printing closer topics to a specific keyword ``` topic_words, word_scores, topic_scores, topic_nums = model.search_topics(keywords=["queue"], num_topics=5) topic_nums >>> array([ 5, 7, 15, 1, 3], dtype=int64) ``` I was able to detect which topics could have been grouped together and I manually created a list with the indices of the topic that refer to the same macrotopic. ``` # for example macrotopic_1 = [1,7,12,17] ``` Then I implemented this two dumb functions to get the best words and documents for that best represented the macrotopic ``` def macrotopic_words(topics_words:np.ndarray, word_scores:np.ndarray, list_of_topics:list): ''' This function takes in input the output of the top2vec model and a list of integers corresponding to topics'ids and returns two dictionaries containing the most important words and their respective value Input: - topic_words: (np.ndarray), an array of arrays containing topic words. - word_scores: (np.ndarray), an array of arrays containing words scores. These scores represent the cosine similarity to each keyword that defines the topic. - list_of_topics: (list), a list of integers. These integers have to be between 0 and the max number of topics spotted by the top2vec algorithm Output: _ diz_words: (dict) dictionary whose keys are the top 50 words and values are their associated score. These scores represent the cosine similarity to each keyword that defines the topic. ''' # The two objects that will be returned diz_words = dict() for topic_id in list_of_topics: topic_words = topics_words[topic_id].tolist() topic_words_scores = word_scores[topic_id].tolist() for i in range(len(topic_words)): word = topic_words[i] score = topic_words_scores[i] if word in diz_words: old_score = diz_words[word] diz_words[word] = (old_score + score)/2 else: diz_words[word] = score # get only the top 50 words diz_words = dict(sorted(diz_words.items(), key=lambda item: item[1], reverse=True)[:50]) return diz_words def macrotopic_docs(df, model, list_of_topics:list): ''' This function takes in input the output of the top2vec model and a list of integers corresponding to topics'ids and returns two dictionaries containing the most important words and their respective value Input: - df: (pd.Dataframe) datframe where I there are at least two columns: one with the orginal text (in my case translated reviews) and one with the pre-processed text (in my case translated reviews). This is not necessary but for my application makes the result more human readable. - model: (top2vec.Top2Vec.Top2Vec) output of the top2vec model - list_of_topics: (list), a list of integers. These integers have to be between 0 and the max number of topics spotted by the top2vec algorithm Output: _ diz_docs: (dict) dictionary whose keys are the top 50 words and values are their associated score. These scores represent the cosine similarity to each keyword that defines the topic. ''' # The two objects that will be returned diz_words = dict() for topic_id in list_of_topics: documents, document_scores, document_ids = model.search_documents_by_topic(topic_num=topic_id, num_docs=10) for i in range(len(documents)): doc = documents[i] doc_nice_idx = df.index[df['Translated Cleaned'] == doc][0] doc_nice = df.iloc[doc_nice_idx]['Translated reviews'] score = document_scores[i] if doc_nice in diz_words: old_score = diz_words[doc_nice] diz_words[doc_nice] = (old_score + score)/2 else: diz_words[doc_nice] = score # get only the top 50 words diz_words = dict(sorted(diz_words.items(), key=lambda item: item[1], reverse=True)[:10]) return diz_words macrotopic_words(topic_words,word_scores,[5,7,8] ) >>> {'ticket': 0.3825201094150543, 'queue': 0.2912799119949341, 'long': 0.2060506008565426, 'close': 0.2041976973414421, 'min': 0.19961485266685486, 'hour': 0.18805542960762978, 'stop': 0.1846560537815094, 'near': 0.1766391098499298, 'longer': 0.17402754724025726, 'forget': 0.1692977249622345, 'open': 0.16631683707237244, 'interest': 0.16506552696228027, 'quit': 0.16504628770053387, 'finish': 0.16126474738121033, 'tail': 0.16030896827578545, 'end': 0.15837934613227844, 'much': 0.15592673420906067, 'start': 0.15537860989570618, 'stay': 0.15466280281543732, 'wait': 0.15337903797626495, 'visit': 0.1528526358306408, 'time': 0.15138189494609833, 'work': 0.14888891577720642, 'gate': 0.14842548966407776, 'worth': 0.1457190401852131, ... 'full': 0.13024736940860748, 'second': 0.13011334836483002, 'buy': 0.1292862892150879, 'moment': 0.12763935327529907, 'opportun': 0.1272534765303135} macrotopic_docs(df, model, [1]) >>> {'On October 3, the Pergamon Museum reopened its gates.The pergamon altar is not yet available.But even that\'s how you can spend interesting hours in the old Orient.Highlights such as the Ischtar goal, the Milet or Diemschatta facade, are accessible.Very good audio guide with pleasantly compact explanations.It was not so nice that you are currently running "backwards" through the exhibition and the audio guide is not adapted to this.This leads to the fact that you can hear the introduction to your specific exhibition area just before you leave this room ... In the introduction, the audio guide also indicates that the pergamon altar is expected to be restored until 2019!In the months of the closure, one could really have bothered to update the audio guide! ...': 0.7808947, "The Pergamon Museum is an obligatory stop in Berlin.Ishtar's door alone is worth the ticket, but don't stop there.The whole exhibition is absolutely enviable, especially if you take the free audio guide at the entrance, which tells you anecdotes and the story of Pergamo. ...": 0.7628059, 'Beautiful experience. Babilonia Porta magnificent as well as the entry to the Miletus market. Make up the audio guides included in the price of our ticket (Euro 19 on Get Your Guide, with a priority entrance), which has a very good value for moneywhich also provides ...': 0.75661397, 'If anyone goes to Berlin, he must visit this place.Huge impressions !!!Personally, I think that you should ensure a lot of time to visit.The museum delights !!!In addition, at the entrance we get an audio guide and we decide how much time we want to spend on ...': 0.74968064, "I've never seen anything like that, this museum is unforgettable!The audio guide helps a lot, it's worth it!And it was the first time I saw a hygiene being done in audio guides.They clean each one and give you a cover to the headphones.wonderful!Hot Tip: Buying online is cheaper and cut…": 0.74947065, "I have already visited this museum twice;It is wonderful, there are entire parts of temples, a piece of the Babylon gate, it is really great.The audio guides allow a guided tour according to the visitor's time and interests.": 0.7454577, 'Unmissable museum if passing through Berlin.Unfortunately, the Pergamo section was not open, but the Babylon Palace and the Mileto market door are certainly worth the trip.Excellent audio guides provided free of charge with the ticket.It is preferable to do the ...': 0.74440473, "The pergame is wonderful.Everyone who visits Berlin must pass by.The entrance costs € 12 and if you don't have much time, in two hours you can travel it.Free guide and wardrobe audio.Keep in mind that a part of the museum is closed and its great star, the ...": 0.7332305, 'I saw it very willingly because it really represents a piece of history in a unique way.Both the Temple of Pergamon, and the Babylon gate manage to leave you without a word.The audio guide, included in the price of the entrance ticket, is very well done and accompanies ...': 0.7329705, 'I visited Berlin with the family and made a ticket that allowed us to enter all the museums.We made a rather quick visit to this museum but the emotion in seeing the area dedicated to the Ishtar gate was great.Very beautiful the audio guide who ...': 0.7325742} ``` ```
10,666,415
I want to get multiple dragged ids when i dropped to the certain div. `$(ui.draggable).attr('id');` only gets 1st id. ``` Drag <ul id="demo" > <li id="1" ></li> <li id="2" ></li> <li id="3" ></li> </ul> <div class="drop"> drop here!! </div> ``` JQUERY ``` $(".drop").droppable({ drop: function(event, ui) { var m_id = $(ui.draggable).attr('id');// only gets 1st id // i need to get multiple dragged id 1,2,3.. } }); ``` Please help me out!! Thnks
2012/05/19
[ "https://Stackoverflow.com/questions/10666415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1383645/" ]
``` var m_id = []; $.each($(ui.draggable), function(i,e) { m_id.push(e.id); }); //gives array with all ID's, could be joined with join() //for comma seperated list ```
``` $("li").draggable({ revert: true }); $(".drop").droppable({ drop: function(event, ui) { var id = ui.draggable.attr("id"); alert(id); } }); ```
25,344,950
i have local repository, which has two version: ``` $git tag v1.0.0 v1.0.4 ``` in v.0.0 is only initial reposity, with two files: `aa.txt` - content: *it's my first file* `bb.txt` - content: *it's my second file* ``` $git commit -m 'first commit' $git push (...) ``` next time i added new file, names: `cc.txt`, which has content: *it's file for next version* ``` $git commit -m 'next commit' $git push (...) ``` now i want to get pull, but not latest version, only version: **v1.0.0** what's way?
2014/08/16
[ "https://Stackoverflow.com/questions/25344950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3810460/" ]
just use the tag name: ``` git checkout v1.0.0 ``` see the [manual for checkout command](https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html)
One way is on webside: click the selected button: ![enter image description here](https://i.stack.imgur.com/ot6zE.jpg) `select tags, select your interested tag/version` and the next step's to **Download.zip**
170,291
I would like to know the forces acting on an SHM, and how they effect the motion. For example, take the motion of a simple pendulum as in the given image.![Motion of a simple pendulum](https://i.stack.imgur.com/qoYHQ.gif) Which are the forces acting on this motion? For simplicity, lets divide the motion into four parts, first one being the motion from the mean position(B) to the right extreme position(C), then back to B from C($2^{nd}$ part), then to A from B($3{rd}$ part) an finally the motion to B from A. Now, which forces act on each parts and what they do to the motion (i.e, do they accelerate the motion or retard the motion etc)?
2015/03/14
[ "https://physics.stackexchange.com/questions/170291", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/60846/" ]
In simple harmonic motion, the mass always oscillates about a stable equilibrium point. The point B is the point of stable equilibrium in this system. This means that the forces would act in such a manner, that the mass would always have a tendency to move to point B, if it is slightly displaced from that point. If it is moving from point B to C or from point B to A, the forces would be retarding and from A to B or C to B, they would be accelerating. The only force that would cause any kind of acceleration(change in the speed of the mass) would be gravity. Tension is always at a right angle to the velocity, it would change the direction of its velocity but never its magnitude.
Weight and Tension in the string are two important things to consider here. I can select my half-cone angle as $\theta$. Then, the tension T is balanced by the cosine component of weight i.e m $\times$ g and the $\sin\theta$ component is the one directed towards mean position. If the angle is small, we can approximate $\sin \theta \sim \theta$. And you get a force which is directed towards mean [negative sign] and proportional to displacement, which means it is example of SHM.
38,564,979
I find myself quite often in the following situation: I have a user control which is bound to some data. Whenever the control is updated, the underlying data is updated. Whenever the underlying data is updated, the control is updated. So it's quite easy to get stuck in a never ending loop of updates (control updates data, data updates control, control updates data, etc.). Usually I get around this by having a bool (e.g. `updatedByUser`) so I know whether a control has been updated programmatically or by the user, then I can decide whether or not to fire off the event to update the underlying data. This doesn't seem very neat. Are there some best practices for dealing with such scenarios? EDIT: I've added the following code example, but I think I have answered my own question...? ``` public partial class View : UserControl { private Model model = new Model(); public View() { InitializeComponent(); } public event EventHandler<Model> DataUpdated; public Model Model { get { return model; } set { if (value != null) { model = value; UpdateTextBoxes(); } } } private void UpdateTextBoxes() { if (InvokeRequired) { Invoke(new Action(() => UpdateTextBoxes())); } else { textBox1.Text = model.Text1; textBox2.Text = model.Text2; } } private void textBox1_TextChanged(object sender, EventArgs e) { model.Text1 = ((TextBox)sender).Text; OnModelUpdated(); } private void textBox2_TextChanged(object sender, EventArgs e) { model.Text2 = ((TextBox)sender).Text; OnModelUpdated(); } private void OnModelUpdated() { DataUpdated?.Invoke(this, model); } } public class Model { public string Text1 { get; set; } public string Text2 { get; set; } } public class Presenter { private Model model; private View view; public Presenter(Model model, View view) { this.model = model; this.view = view; view.DataUpdated += View_DataUpdated; } public Model Model { get { return model; } set { model = value; view.Model = model; } } private void View_DataUpdated(object sender, Model e) { //This is fine. model = e; //This causes the circular dependency. Model = e; } } ```
2016/07/25
[ "https://Stackoverflow.com/questions/38564979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2092267/" ]
One option would be to stop the update in case the data didn't change since the last time. For example if the data were in form of a class, you could check if the data is the same instance as the last time the event was triggered and if that is the case, stop the propagation. This is what many MVVM frameworks do to prevent raising `PropertyChanged` event in case the property didn't actually change: ``` private string _someProperty = ""; public string SomeProperty { get { return _someProperty; } set { if ( _someProperty != value ) { _someProperty = value; RaisePropertyChanged(); } } } ``` You can implement this concept similarly for Windows Forms.
You should look into MVP - it is the preferred design pattern for Winforms UI. <http://www.codeproject.com/Articles/14660/WinForms-Model-View-Presenter> using that design pattern gives you a more readable code in addition to allowing you to avoid circular events. in order to actually avoid circular events, your view should only export a property which once it is set it would make sure the txtChanged\_Event would not be called. something like this: ``` public string UserName { get { return txtUserName.Text; } set { txtUserName.TextChanged -= txtUserName_TextChanged; txtUserName.Text = value; txtUserName.TextChanged += txtUserName_TextChanged; } } ``` or you can use a [MZetko's](https://stackoverflow.com/a/38565111/3090249) answer with a private property
38,564,979
I find myself quite often in the following situation: I have a user control which is bound to some data. Whenever the control is updated, the underlying data is updated. Whenever the underlying data is updated, the control is updated. So it's quite easy to get stuck in a never ending loop of updates (control updates data, data updates control, control updates data, etc.). Usually I get around this by having a bool (e.g. `updatedByUser`) so I know whether a control has been updated programmatically or by the user, then I can decide whether or not to fire off the event to update the underlying data. This doesn't seem very neat. Are there some best practices for dealing with such scenarios? EDIT: I've added the following code example, but I think I have answered my own question...? ``` public partial class View : UserControl { private Model model = new Model(); public View() { InitializeComponent(); } public event EventHandler<Model> DataUpdated; public Model Model { get { return model; } set { if (value != null) { model = value; UpdateTextBoxes(); } } } private void UpdateTextBoxes() { if (InvokeRequired) { Invoke(new Action(() => UpdateTextBoxes())); } else { textBox1.Text = model.Text1; textBox2.Text = model.Text2; } } private void textBox1_TextChanged(object sender, EventArgs e) { model.Text1 = ((TextBox)sender).Text; OnModelUpdated(); } private void textBox2_TextChanged(object sender, EventArgs e) { model.Text2 = ((TextBox)sender).Text; OnModelUpdated(); } private void OnModelUpdated() { DataUpdated?.Invoke(this, model); } } public class Model { public string Text1 { get; set; } public string Text2 { get; set; } } public class Presenter { private Model model; private View view; public Presenter(Model model, View view) { this.model = model; this.view = view; view.DataUpdated += View_DataUpdated; } public Model Model { get { return model; } set { model = value; view.Model = model; } } private void View_DataUpdated(object sender, Model e) { //This is fine. model = e; //This causes the circular dependency. Model = e; } } ```
2016/07/25
[ "https://Stackoverflow.com/questions/38564979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2092267/" ]
What you're looking for is called [Data Binding](https://msdn.microsoft.com/en-us/library/ef2xyb33(v=vs.110).aspx). It allows you to connect two or more properties, so that when one property changes others will be updated auto-magically. In WinForms it's a little bit ugly, but works like a charm in cases such as yours. First you need a class which represents your data and implements `INotifyPropertyChanged` to notify the controls when data changes. ``` public class ViewModel : INotifyPropertyChanged { private string _textFieldValue; public string TextFieldValue { get { return _textFieldValue; } set { _textFieldValue = value; NotifyChanged(); } } public void NotifyChanged() { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(null)); } public event PropertyChangedEventHandler PropertyChanged; } ``` Than in your `Form/Control` you bind the value of `ViewModel.TextFieldValue` to `textBox.Text`. This means whenever value of `TextFieldValue` changes the `Text` property will be updated and whenever `Text` property changes `TextFieldValue` will be updated. In other words the values of those two properties will be the same. That solves the circular loops issue you're encountering. ``` public partial class Form1 : Form { public ViewModel ViewModel = new ViewModel(); public Form1() { InitializeComponent(); // Connect: textBox1.Text <-> viewModel.TextFieldValue textBox1.DataBindings.Add("Text", ViewModel , "TextFieldValue"); } } ``` If you need to modify the values from outside of the Form/Control, simply set values of the `ViewModel` ``` form.ViewModel.TextFieldValue = "new value"; ``` The control will be updated automatically.
You should look into MVP - it is the preferred design pattern for Winforms UI. <http://www.codeproject.com/Articles/14660/WinForms-Model-View-Presenter> using that design pattern gives you a more readable code in addition to allowing you to avoid circular events. in order to actually avoid circular events, your view should only export a property which once it is set it would make sure the txtChanged\_Event would not be called. something like this: ``` public string UserName { get { return txtUserName.Text; } set { txtUserName.TextChanged -= txtUserName_TextChanged; txtUserName.Text = value; txtUserName.TextChanged += txtUserName_TextChanged; } } ``` or you can use a [MZetko's](https://stackoverflow.com/a/38565111/3090249) answer with a private property
54,162
I have a superior who often communicates incorrect statements during meetings. While I want this question to be more general, because I have been in this situation with many unique settings, I will say that the statements seem to be meant to steer decision making. **As an example:** It seems as though before I arrived at this company no one had any knowledge of SEO. However I have quite a strong background in web development and internet marketing. In fact I'm passionate about it: The other day this superior dashed my "improved SEO" reasons for replacing the company website with a more modern one. He did so by interrupting me to explain to the other superiors that search engine rankings cannot be manipulated and that SEO should not even be considered to be a benefit of this project. Clearly search rankings can be improved and clearly there is some agenda against a new website project. I took this as a choose-your-battle situation and allowed him to thrash my SEO knowledge in order to move on to my other points which did result in a new website project... However this sort of situation seems to pop up quite often. **In these situations should an employee even try to explain that such a statement is incorrect?**
2015/09/10
[ "https://workplace.stackexchange.com/questions/54162", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/34165/" ]
How about a friendly chat with the Superior in question after the meeting? Sounds odd? Hear me out. The underlying goal here is that you have an idea that you believe would help the company. Unfortunately, a member of the current leadership does not believe that this idea would work. With this said, the superior's reasoning for this may vary, the superior may have a reasonable explanation or he/she may not. But the goal here isn't whether the superior is right, but whether or not you can convince your superior into looking things your way. Not a technical question mind you, but that of persuasion. This said, I am not 100% aware of your situation. But based on what you have said, you are an expert on this idea, but your superior, according to you, is not. With this in mind, can you think of anyway of presenting this idea that would benefit that superior in question? For example, if your superior is in sales. You can present the idea in a way that the idea will lead to better search engine results, leading to more consumer exposure, leading to more sales. Again, this casual chain would change depending on what that person does. The idea here is how can the idea directly benefit your superior. Once this is accomplished, the next step is identifying who else you need to talk to before the meeting to get onboard with the idea such that one you present it again, there will be a group of people who are in agreement. > > tldr: Good idea. Presented it a little bit too early from the looks of > it. Got some flak. A good course of action now is to regroup. Address > any points of opposition (your superior). Gather more support and > pitch it again. > > > On the offhand that your superior did not have a valid reasoning, then I would have to defer to JB King's response in that are you willing to face the consequences (albeit extreme, I mean losing a job for pitching an idea?) for pushing this.
Would you be prepared to back up your argument with specific sources? For example, while there are tons of possible ways to improve search rankings, which could you guarantee would work as that would likely be required for you to have a chance at winning the argument here. I'd likely consider the question of whether or not you are prepared to leave the company because of the other managers siding with someone that may well believe something that you heavily disagree. If you aren't prepared to have your job on the line, then I'd advocate staying quiet since whether you like it or not, your job could well be on the line soon in this case. --- While you may believe the statement is incorrect, there can be the question of how well can you know precisely the context well enough to ensure that you are believed more than the other person. For example, consider the question of, "What is 2+2?" that some may answer "4" and others may answer "22" and others may ask for clarification of what are "2" and "+" to denote as one could infer the natural number addition and arrive at an answer of "4" and some may infer that each "2" is a character and the "+" is a concatenation operation so that the result would be "22." How prepared were you for me to claim the numbers as characters? Similarly, I could throw out a challenge of "I'm thinking of a number between 1 and 3. I'll give 10 guesses to hit it and claim you won't be able to do it," where I could think of some obscure number like pi minus e plus 1 that I doubt many people would guess in their first dozen guesses. Beware of going head to head with those that may enjoy messing with your mind.
54,162
I have a superior who often communicates incorrect statements during meetings. While I want this question to be more general, because I have been in this situation with many unique settings, I will say that the statements seem to be meant to steer decision making. **As an example:** It seems as though before I arrived at this company no one had any knowledge of SEO. However I have quite a strong background in web development and internet marketing. In fact I'm passionate about it: The other day this superior dashed my "improved SEO" reasons for replacing the company website with a more modern one. He did so by interrupting me to explain to the other superiors that search engine rankings cannot be manipulated and that SEO should not even be considered to be a benefit of this project. Clearly search rankings can be improved and clearly there is some agenda against a new website project. I took this as a choose-your-battle situation and allowed him to thrash my SEO knowledge in order to move on to my other points which did result in a new website project... However this sort of situation seems to pop up quite often. **In these situations should an employee even try to explain that such a statement is incorrect?**
2015/09/10
[ "https://workplace.stackexchange.com/questions/54162", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/34165/" ]
**Get on the same page before the meeting.** Yes, the point is to steer decision making and your boss should let everyone know what direction he is going. There isn't time in many cases, but departments/groups/teams should have a meeting before they go into such meetings with outside members. At least the boss should outline what his intention is for the meeting. This way, you can do your job and promote his agenda instead of pushing your skill set. I always try to get with my boss before these meetings. It is difficult when you have the expertise, but don't know what the company needs. There will be a tremendous urge to want to correct him - DON'T DO IT! You can improve the SEO, but will it really be to the point to improve business? Some products and services are sold through more traditional channels and few people search the web for them. This is just an example.
Would you be prepared to back up your argument with specific sources? For example, while there are tons of possible ways to improve search rankings, which could you guarantee would work as that would likely be required for you to have a chance at winning the argument here. I'd likely consider the question of whether or not you are prepared to leave the company because of the other managers siding with someone that may well believe something that you heavily disagree. If you aren't prepared to have your job on the line, then I'd advocate staying quiet since whether you like it or not, your job could well be on the line soon in this case. --- While you may believe the statement is incorrect, there can be the question of how well can you know precisely the context well enough to ensure that you are believed more than the other person. For example, consider the question of, "What is 2+2?" that some may answer "4" and others may answer "22" and others may ask for clarification of what are "2" and "+" to denote as one could infer the natural number addition and arrive at an answer of "4" and some may infer that each "2" is a character and the "+" is a concatenation operation so that the result would be "22." How prepared were you for me to claim the numbers as characters? Similarly, I could throw out a challenge of "I'm thinking of a number between 1 and 3. I'll give 10 guesses to hit it and claim you won't be able to do it," where I could think of some obscure number like pi minus e plus 1 that I doubt many people would guess in their first dozen guesses. Beware of going head to head with those that may enjoy messing with your mind.
54,162
I have a superior who often communicates incorrect statements during meetings. While I want this question to be more general, because I have been in this situation with many unique settings, I will say that the statements seem to be meant to steer decision making. **As an example:** It seems as though before I arrived at this company no one had any knowledge of SEO. However I have quite a strong background in web development and internet marketing. In fact I'm passionate about it: The other day this superior dashed my "improved SEO" reasons for replacing the company website with a more modern one. He did so by interrupting me to explain to the other superiors that search engine rankings cannot be manipulated and that SEO should not even be considered to be a benefit of this project. Clearly search rankings can be improved and clearly there is some agenda against a new website project. I took this as a choose-your-battle situation and allowed him to thrash my SEO knowledge in order to move on to my other points which did result in a new website project... However this sort of situation seems to pop up quite often. **In these situations should an employee even try to explain that such a statement is incorrect?**
2015/09/10
[ "https://workplace.stackexchange.com/questions/54162", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/34165/" ]
Would you be prepared to back up your argument with specific sources? For example, while there are tons of possible ways to improve search rankings, which could you guarantee would work as that would likely be required for you to have a chance at winning the argument here. I'd likely consider the question of whether or not you are prepared to leave the company because of the other managers siding with someone that may well believe something that you heavily disagree. If you aren't prepared to have your job on the line, then I'd advocate staying quiet since whether you like it or not, your job could well be on the line soon in this case. --- While you may believe the statement is incorrect, there can be the question of how well can you know precisely the context well enough to ensure that you are believed more than the other person. For example, consider the question of, "What is 2+2?" that some may answer "4" and others may answer "22" and others may ask for clarification of what are "2" and "+" to denote as one could infer the natural number addition and arrive at an answer of "4" and some may infer that each "2" is a character and the "+" is a concatenation operation so that the result would be "22." How prepared were you for me to claim the numbers as characters? Similarly, I could throw out a challenge of "I'm thinking of a number between 1 and 3. I'll give 10 guesses to hit it and claim you won't be able to do it," where I could think of some obscure number like pi minus e plus 1 that I doubt many people would guess in their first dozen guesses. Beware of going head to head with those that may enjoy messing with your mind.
> > Should I tell a superior [in a meeting] their statement is incorrect? > > > (I will not focus on how to prevent the situation, as this is not the question. But of course preventing a bad situation is better than trying to fix it.) Let's try to approach this one methodically. Why would your superior make an incorrect statement? **He does not know better.** Does it matter and will be result be unalterable when the meeting is over? The answer is usually "No.". Any decision can be revoked due to "new" information. So it is sufficient to update your superior with your information after the meeting. If the answer is actually "Yes.", then politely state your information. The listeners will realize themselves that your statement contradicts your superior, no need to rub everyone's nose in. If nobody would want your input, you wouldn't be in the meeting. **He does know better.** If he does know better, yet states something else, it luckily doesn't really matter why he does it. He has a reason and your public correction will go against his agenda, no matter if his agenda is a good or bad one. He believes so much in his agenda, that he does not mind to be flexible with the truth. In such a case, correcting your superior means he will be pissed off and you gained nothing. If you update the superior after the meeting with your information and he does know better, nothing bad will happen. He might tell you the reason, he might pretend that he didn't know better but that it is "not important" enough to revoke the decision now or he might tell you to care about your own stuff. So, reviewing all the possible paths, it's easy to see that you should not say anything in the meeting, unless absolutely necessary and always update the superior with your information, because no matter what the reason was, it will end up the best way - if you couldn't prevent the situation. As a side note, if your superior states something incorrect or dumb in a meeting, you can just raise your eyebrows (this of course requires the right seat). If they are good and it is the first case scenario, they will catch this and continue with something like:"but I'm no expert on this. What is your opinion?" > > dashed my "improved SEO" reasons for replacing the company website > > > This is actually quite something different. You said "X" and he said you are wrong. It's basically the reverse situation. I think you should defend your position within reasonable limits:"Yes, you are right, it's not possible to manipulate them, but it's possible to optimize the content so they can better grasp what the website is about and therefore navigate the search engine users better." The big problem is, you usually don't have a good comeback when you need it, unless you are well-prepared for the objection. There is no better way to handle that situation than you did. Evaluate how important it actually is to insist that you are right and then follow your instinct. You can also just state that you disagree and go on:"Well, I beg to differ, but as there are other good reasons, we should focus on them then." Okay, I violate my first statement and write something about how to prevent it: If you expect objections, not only prepare counter-arguments, but add them to your presentation or lecture! Nobody can state that SEO is hocus pocus, if you have a bullet point:"Why some SEO is hocus pocus and some not".
54,162
I have a superior who often communicates incorrect statements during meetings. While I want this question to be more general, because I have been in this situation with many unique settings, I will say that the statements seem to be meant to steer decision making. **As an example:** It seems as though before I arrived at this company no one had any knowledge of SEO. However I have quite a strong background in web development and internet marketing. In fact I'm passionate about it: The other day this superior dashed my "improved SEO" reasons for replacing the company website with a more modern one. He did so by interrupting me to explain to the other superiors that search engine rankings cannot be manipulated and that SEO should not even be considered to be a benefit of this project. Clearly search rankings can be improved and clearly there is some agenda against a new website project. I took this as a choose-your-battle situation and allowed him to thrash my SEO knowledge in order to move on to my other points which did result in a new website project... However this sort of situation seems to pop up quite often. **In these situations should an employee even try to explain that such a statement is incorrect?**
2015/09/10
[ "https://workplace.stackexchange.com/questions/54162", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/34165/" ]
How about a friendly chat with the Superior in question after the meeting? Sounds odd? Hear me out. The underlying goal here is that you have an idea that you believe would help the company. Unfortunately, a member of the current leadership does not believe that this idea would work. With this said, the superior's reasoning for this may vary, the superior may have a reasonable explanation or he/she may not. But the goal here isn't whether the superior is right, but whether or not you can convince your superior into looking things your way. Not a technical question mind you, but that of persuasion. This said, I am not 100% aware of your situation. But based on what you have said, you are an expert on this idea, but your superior, according to you, is not. With this in mind, can you think of anyway of presenting this idea that would benefit that superior in question? For example, if your superior is in sales. You can present the idea in a way that the idea will lead to better search engine results, leading to more consumer exposure, leading to more sales. Again, this casual chain would change depending on what that person does. The idea here is how can the idea directly benefit your superior. Once this is accomplished, the next step is identifying who else you need to talk to before the meeting to get onboard with the idea such that one you present it again, there will be a group of people who are in agreement. > > tldr: Good idea. Presented it a little bit too early from the looks of > it. Got some flak. A good course of action now is to regroup. Address > any points of opposition (your superior). Gather more support and > pitch it again. > > > On the offhand that your superior did not have a valid reasoning, then I would have to defer to JB King's response in that are you willing to face the consequences (albeit extreme, I mean losing a job for pitching an idea?) for pushing this.
> > Should I tell a superior [in a meeting] their statement is incorrect? > > > (I will not focus on how to prevent the situation, as this is not the question. But of course preventing a bad situation is better than trying to fix it.) Let's try to approach this one methodically. Why would your superior make an incorrect statement? **He does not know better.** Does it matter and will be result be unalterable when the meeting is over? The answer is usually "No.". Any decision can be revoked due to "new" information. So it is sufficient to update your superior with your information after the meeting. If the answer is actually "Yes.", then politely state your information. The listeners will realize themselves that your statement contradicts your superior, no need to rub everyone's nose in. If nobody would want your input, you wouldn't be in the meeting. **He does know better.** If he does know better, yet states something else, it luckily doesn't really matter why he does it. He has a reason and your public correction will go against his agenda, no matter if his agenda is a good or bad one. He believes so much in his agenda, that he does not mind to be flexible with the truth. In such a case, correcting your superior means he will be pissed off and you gained nothing. If you update the superior after the meeting with your information and he does know better, nothing bad will happen. He might tell you the reason, he might pretend that he didn't know better but that it is "not important" enough to revoke the decision now or he might tell you to care about your own stuff. So, reviewing all the possible paths, it's easy to see that you should not say anything in the meeting, unless absolutely necessary and always update the superior with your information, because no matter what the reason was, it will end up the best way - if you couldn't prevent the situation. As a side note, if your superior states something incorrect or dumb in a meeting, you can just raise your eyebrows (this of course requires the right seat). If they are good and it is the first case scenario, they will catch this and continue with something like:"but I'm no expert on this. What is your opinion?" > > dashed my "improved SEO" reasons for replacing the company website > > > This is actually quite something different. You said "X" and he said you are wrong. It's basically the reverse situation. I think you should defend your position within reasonable limits:"Yes, you are right, it's not possible to manipulate them, but it's possible to optimize the content so they can better grasp what the website is about and therefore navigate the search engine users better." The big problem is, you usually don't have a good comeback when you need it, unless you are well-prepared for the objection. There is no better way to handle that situation than you did. Evaluate how important it actually is to insist that you are right and then follow your instinct. You can also just state that you disagree and go on:"Well, I beg to differ, but as there are other good reasons, we should focus on them then." Okay, I violate my first statement and write something about how to prevent it: If you expect objections, not only prepare counter-arguments, but add them to your presentation or lecture! Nobody can state that SEO is hocus pocus, if you have a bullet point:"Why some SEO is hocus pocus and some not".
54,162
I have a superior who often communicates incorrect statements during meetings. While I want this question to be more general, because I have been in this situation with many unique settings, I will say that the statements seem to be meant to steer decision making. **As an example:** It seems as though before I arrived at this company no one had any knowledge of SEO. However I have quite a strong background in web development and internet marketing. In fact I'm passionate about it: The other day this superior dashed my "improved SEO" reasons for replacing the company website with a more modern one. He did so by interrupting me to explain to the other superiors that search engine rankings cannot be manipulated and that SEO should not even be considered to be a benefit of this project. Clearly search rankings can be improved and clearly there is some agenda against a new website project. I took this as a choose-your-battle situation and allowed him to thrash my SEO knowledge in order to move on to my other points which did result in a new website project... However this sort of situation seems to pop up quite often. **In these situations should an employee even try to explain that such a statement is incorrect?**
2015/09/10
[ "https://workplace.stackexchange.com/questions/54162", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/34165/" ]
**Get on the same page before the meeting.** Yes, the point is to steer decision making and your boss should let everyone know what direction he is going. There isn't time in many cases, but departments/groups/teams should have a meeting before they go into such meetings with outside members. At least the boss should outline what his intention is for the meeting. This way, you can do your job and promote his agenda instead of pushing your skill set. I always try to get with my boss before these meetings. It is difficult when you have the expertise, but don't know what the company needs. There will be a tremendous urge to want to correct him - DON'T DO IT! You can improve the SEO, but will it really be to the point to improve business? Some products and services are sold through more traditional channels and few people search the web for them. This is just an example.
> > Should I tell a superior [in a meeting] their statement is incorrect? > > > (I will not focus on how to prevent the situation, as this is not the question. But of course preventing a bad situation is better than trying to fix it.) Let's try to approach this one methodically. Why would your superior make an incorrect statement? **He does not know better.** Does it matter and will be result be unalterable when the meeting is over? The answer is usually "No.". Any decision can be revoked due to "new" information. So it is sufficient to update your superior with your information after the meeting. If the answer is actually "Yes.", then politely state your information. The listeners will realize themselves that your statement contradicts your superior, no need to rub everyone's nose in. If nobody would want your input, you wouldn't be in the meeting. **He does know better.** If he does know better, yet states something else, it luckily doesn't really matter why he does it. He has a reason and your public correction will go against his agenda, no matter if his agenda is a good or bad one. He believes so much in his agenda, that he does not mind to be flexible with the truth. In such a case, correcting your superior means he will be pissed off and you gained nothing. If you update the superior after the meeting with your information and he does know better, nothing bad will happen. He might tell you the reason, he might pretend that he didn't know better but that it is "not important" enough to revoke the decision now or he might tell you to care about your own stuff. So, reviewing all the possible paths, it's easy to see that you should not say anything in the meeting, unless absolutely necessary and always update the superior with your information, because no matter what the reason was, it will end up the best way - if you couldn't prevent the situation. As a side note, if your superior states something incorrect or dumb in a meeting, you can just raise your eyebrows (this of course requires the right seat). If they are good and it is the first case scenario, they will catch this and continue with something like:"but I'm no expert on this. What is your opinion?" > > dashed my "improved SEO" reasons for replacing the company website > > > This is actually quite something different. You said "X" and he said you are wrong. It's basically the reverse situation. I think you should defend your position within reasonable limits:"Yes, you are right, it's not possible to manipulate them, but it's possible to optimize the content so they can better grasp what the website is about and therefore navigate the search engine users better." The big problem is, you usually don't have a good comeback when you need it, unless you are well-prepared for the objection. There is no better way to handle that situation than you did. Evaluate how important it actually is to insist that you are right and then follow your instinct. You can also just state that you disagree and go on:"Well, I beg to differ, but as there are other good reasons, we should focus on them then." Okay, I violate my first statement and write something about how to prevent it: If you expect objections, not only prepare counter-arguments, but add them to your presentation or lecture! Nobody can state that SEO is hocus pocus, if you have a bullet point:"Why some SEO is hocus pocus and some not".
74,007,260
I am new to Solidity, I am trying to build a simple smart contract and explore solidity in the process. The following build can be compiled without putting a value but when i try to put some value in it it shows the following error. > > The transaction has been reverted to the initial state. > Note: The called function should be payable if you send value and the value you send should be less than your current balance. > Debug the transaction to get more information. > > > Code: ``` pragma solidity ^0.8.0; contract SimpleBank { string public name; address public owner; mapping (address => uint256) public funds; address[] public funders; constructor() { owner = msg.sender; } modifier onlyOwner{ require(msg.sender == owner); _; } function getBalance() public view returns (uint256){ return owner.balance; } function getAddress() public view returns(address){ return owner; } function RecieveMoney() public payable{ funds[msg.sender] += msg.value; funders.push(msg.sender); } } ```
2022/10/09
[ "https://Stackoverflow.com/questions/74007260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16230867/" ]
The other answer is correct, you have an error because you misspelled a keyword in your SQL query. But that's not the question you asked. > > I use MySQL, why MariaDB in the error message? > > > MySQL Server will not mention MariaDB in its error message. MySQL and MariaDB are different products. Therefore if your error message reports MariaDB, then this is evidence that you are using MariaDB Server, not MySQL Server. The syntax error message is reported by the database server. That's where syntax checking is done. It's possible to use a MySQL client to connect to either a MySQL Server or a MariaDB Server. At least for current versions (MySQL 8.0 and MariaDB 10.6 are current), the client/server protocol is compatible (they may not always be compatible in future versions, since both products are evolving). Try the query `SELECT VERSION();` to check the version of the database server you are using.
You have a typo in your query. ```sql select * form category= ? ``` should be ```sql select * from category= ? ```
40,034,673
I realize this question has been asked many times before but I'm asking it now because the answers are quite old (compared to the new API). I've used Location Manager before but I've found it very unreliable. For example in my app, using getLastKnownLocation and/or current location, it would instantly load with the camera on the user's current location. But say if I turned the location on my device right before I started my app, it wouldn't have the camera on the user's current location but rather somewhere near Nigera (default view, I believe). Only if I used Google Maps app and pin pointed my location or if I waited some time, then my app would load with the user's location in the view (using moveCamera). Sometimes it would work and sometimes it wouldn't. But I want to use Google Api Client, or perhaps something smoother, to retrieve the user's location. I want to do it like this: 1.) If the user doesn't have their location on, prompt them to turn it on. 2.) After turning location on, start the Maps camera/view with the user's current location in the center. 3.) Finally, if the user decides to take off location or move from their location, do absolutely nothing. I've read a lot of questions here but I can't find anything that could help me configure this functionality using Google Api Client or anything else. I've tried almost everything with Location Manager but I still can't get it to work smoothly. And out of frustration, I've deleted all my Location Manager code. If you want to see what I had written down or tried, most of my sources came from this question (and related): [What is the simplest and most robust way to get the user's current location on Android?](https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-on-a?noredirect=1&lq=1) Thank you for taking the time to read this.
2016/10/14
[ "https://Stackoverflow.com/questions/40034673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6490018/" ]
You can simply store the index to which you got in the previous processing run. After all, you *don't* want to iterate the array multiple times, you want to iterate it only once but in multiple steps. ```js function process(arr, step, start) { var take = Math.min(arr.length - start, Math.round(1 + Math.random() * 3)); for (var i = start; i < start + take; i++) { console.log("processing item " + arr[i] + " in step " + step); } return take; } var arr = [1, 2, 3, 4, 5] for (var step = 0, i = 0; i < arr.length; step++) i += process(arr, step, i); ```
``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { getColorGroup(); }); function getColorGroup() { var colors = ['#FAEBD7', '#00FFFF', '#000000', '#0000FF', '#8A2BE2', '#A52A2A', '#DEB887', '#5F9EA0', '#7FFF00', '#D2691E', '#FF7F50', '#6495ED', '#DC143C', '#00FFFF', '#00008B', '#008B8B', '#B8860B', '#A9A9A9', '#A9A9A9', '#006400', '#BDB76B', '#8B008B', '#556B2F', '#FF8C00', '#9932CC', '#8B0000', '#E9967A', '#8FBC8F', '#483D8B', '#2F4F4F', '#2F4F4F', '#00CED1', '#9400D3', '#FF1493', '#00BFFF', '#696969', '#696969', '#1E90FF', '#B22222', '#228B22', '#FF00FF', '#DCDCDC', '#FFD700', '#DAA520', '#808080', '#808080', '#008000', '#ADFF2F', '#FF69B4', '#CD5C5C', '#4B0082', '#F0E68C', '#E6E6FA', '#7CFC00', '#00FF00', '#32CD32', '#FF00FF', '#800000', '#66CDAA', '#0000CD', '#BA55D3', '#9370DB', '#3CB371', '#7B68EE', '#00FA9A', '#48D1CC', '#C71585', '#191970', '#FFE4E1', '#FFE4B5', '#FFDEAD', '#000080', '#808000', '#6B8E23', '#FFA500', '#FF4500', '#DA70D6', '#EEE8AA', '#98FB98', '#AFEEEE', '#DB7093', '#FFDAB9', '#CD853F', '#FFC0CB', '#DDA0DD', '#B0E0E6', '#800080', '#663399', '#FF0000', '#BC8F8F', '#4169E1', '#8B4513', '#FA8072', '#F4A460', '#2E8B57', '#A0522D', '#C0C0C0', '#87CEEB', '#6A5ACD', '#708090', '#708090', '#00FF7F', '#4682B4', '#D2B48C', '#008080', '#D8BFD8', '#FF6347', '#40E0D0', '#EE82EE', '#F5DEB3', '#FFFF00', '#9ACD32']; var randomIndex = Math.floor(Math.random() * 1000 % colors.length); var color = colors[randomIndex]; console.log(color); var tasks = []; for (var i = 0; i < colors.length; i += 10) { tasks.push(findColor(color, colors, i, 10)); } var group = []; $.when.apply($, tasks).done(function () { for(var j = 0; j < arguments.length; j++) { group = group.concat(arguments[j]); } console.log(group); }); } function findColor(sample, colors, startIndex, segmentSize) { return $.Deferred(function (deferred) { setTimeout(function(){ var result = []; var pattern = /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i; var sampleMatch = pattern.exec(sample); if (sampleMatch) { for (var i = startIndex; i < startIndex + segmentSize && i < colors.length; i++) { var match = pattern.exec(colors[i]); if (match) { if (sampleMatch[1].toUpperCase() == match[1].toUpperCase() || sampleMatch[2].toUpperCase() == match[2].toUpperCase() || sampleMatch[3].toUpperCase() == match[3].toUpperCase()) { result.push(colors[i]); } } } } deferred.resolve(result); }, 0); }).promise(); } </script> ```
21,974,718
**Context** I am writing an event-driven application server in C++. I want to use google protocol buffers for moving my data. Since the server is event driven, the connection handler API is basically a callback function letting me know when another buffer of N bytes has arrived from the client. **Question** My question as a complete beginner of protobuf is this: is it possible to somehow coax protobuf into accepting the many buffers required to make up one complete message to facilitate a "stream parser" rather than waiting for the whole data to arrive into a temporary buffer first? *In other words i want this:* ``` //Event API. May be called multiple times for each protobuf message bool data_arrived_from_client(void *buf,size_t len){ my_protobuf.parse_part(buf,len); // THIS IS THE GROSSLY SIMPLIFIED SEMANTIC OF WHAT I WANT message_size+=len; if(message_size>COMPLETE_BUFFER_SIZE){ use_complete_protobuf(); return true; } return false; } ``` *..instead of this:* ``` //Event API. May be called multiple times for each protobuf message bool data_arrived_from_client(void *buf,size_t len){ my_temp_buffer.append_data(buf,len); message_size+=len; if(message_size>COMPLETE_BUFFER_SIZE){ my_protobuf.ParseFromArray(my_temp_buffer.data_ptr(),my_temp_buffer.size()); use_complete_protobuf(); return true; } return false; } ``` **Answer** Answers with complete code is especially appreciated!
2014/02/23
[ "https://Stackoverflow.com/questions/21974718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035897/" ]
No, this is not possible. The Protobuf parser is a recursive descent parser, meaning quite a bit of its state is stored on the stack. This makes it fast, but it means there's no way to pause the parser in the middle except to pause the whole thread. If your app is non-blocking, you'll just have to buffer bytes until you have a whole message to parse. That said, this isn't as bad as it sounds. Remember that the final parsed representation of the message (i.e. the in-memory message object) is *much* larger than the wire representation. So you are hardly wasting memory on buffering compared to what you're going to do with it later. In fact, holding off on parsing until you actually have all the data may actually save memory, since you aren't holding on to a large half-parsed object that's just sitting there waiting for data to arrive.
Yes, this is possible, I've done it in Javascript, but the design could be ported to C++. <https://github.com/chrisdew/protostream>
24,072,833
I have a 512x512 1.03 mb .ico picture and need to upload it to a website that only accepts pictures 1mb large(or smaller idk) Can somebody help me and tell me a way to reduce the size of the image.
2014/06/06
[ "https://Stackoverflow.com/questions/24072833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3712838/" ]
You can either compress/reduce the filesize of the icon (I recommend using ImageMagick to do this, you can download it [here](http://imagemagick.org)), or you can make the dimensions smaller. However, if you are putting an ico file on a website I recommend using a different image format, such as .png. You can convert it to png using a website called [ConvertICO](http://www.convertico.com/). I hope this helps, Santiago
Take a look on [this page](http://zoompf.com/blog/2012/04/instagram-and-optimizing-favicons) specially compression of ICO files and 4-bit option.
60,421,341
I am using sql to calculate the average daily temperature and max daily temperature based on a date timestamp in an existing database. Is there a quick way to accomplish this? I am using dBeaver to do all my data calculations and the following code is what I have used so far: ``` SELECT convert(varchar, OBS_TIME_LOCAL , 100) AS datepart, convert(varchar, OBS_TIME_LOCAL, 108) AS timepart, CAST (datepart AS date) date_local, CAST (timepart AS time) time_local FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER; ``` The data format as follows: ``` ID time_stamp temp -------------------------------------------- de2145 2018-07-16 16:55 103 ``` There are multiple IDs with 24hrs of temperature data at 1 min increments.
2020/02/26
[ "https://Stackoverflow.com/questions/60421341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071794/" ]
I am not sure if I understand what you need but I will try: Your question: "**Is there a quick way to separate date and time from a time stamp in sql?**" Answer: ``` select to_char(datec, 'hh24:mi') , to_char(datec, 'yyyy-mm-dd') from test; ``` Use `to_char` with format to select date part and time part.
You seem to want aggregation: ``` SELECT convert(date, OBS_TIME_LOCAL) AS datepart, avg(temp), max(temp) FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER GROUP BY convert(date, OBS_TIME_LOCAL); ```
6,547,214
I'm trying to encrypt data between my android application and a PHP webservice. I found the next piece of code in this website: <http://schneimi.wordpress.com/2008/11/25/aes-128bit-encryption-between-java-and-php/> But when I try to decrypt I get the Exception of the title "data not block size aligned" This are the method in my **MCrypt class** ``` public String encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); Cipher cipher; byte[] encrypted = null; try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return new String( encrypted ); } public String decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); Cipher cipher; byte[] decrypted = null; try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return new String( decrypted ); } private static byte[] hexToBytes(String hex) { String HEXINDEX = "0123456789abcdef"; int l = hex.length() / 2; byte data[] = new byte[l]; int j = 0; for (int i = 0; i < l; i++) { char c = hex.charAt(j++); int n, b; n = HEXINDEX.indexOf(c); b = (n & 0xf) << 4; c = hex.charAt(j++); n = HEXINDEX.indexOf(c); b += (n & 0xf); data[i] = (byte) b; } return data; } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } ``` And this is how I'm using it in my activity to test: ``` String encrypted = mcrypt.encrypt(jsonUser.toString()); String decrypted = mcrypt.decrypt(encrypted); ``` the encrypt method works fine, but the second throws an exception.
2011/07/01
[ "https://Stackoverflow.com/questions/6547214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571353/" ]
At last! I made it work! Thanks for all your suggestion. I would like to share the code just in case somebody get stuck like me: **JAVA** ``` import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MCrypt { private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!) private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!) public MCrypt() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data==null) { return null; } int len = data.length; String str = ""; for (int i=0; i<len; i++) { if ((data[i]&0xFF)<16) str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF); else str = str + java.lang.Integer.toHexString(data[i]&0xFF); } return str; } public static byte[] hexToBytes(String str) { if (str==null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i=0; i<len; i++) { buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16); } return buffer; } } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } } ``` **HOW TO USE IT (JAVA)** ``` mcrypt = new MCrypt(); /* Encrypt */ String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") ); /* Decrypt */ String decrypted = new String( mcrypt.decrypt( encrypted ) ); ``` ==================================================== **PHP** ``` <?php class MCrypt { private $iv = 'fedcba9876543210'; #Same as in JAVA private $key = '0123456789abcdef'; #Same as in JAVA function __construct() { } function encrypt($str) { //$key = $this->hex2bin($key); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return bin2hex($encrypted); } function decrypt($code) { //$key = $this->hex2bin($key); $code = $this->hex2bin($code); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $decrypted = mdecrypt_generic($td, $code); mcrypt_generic_deinit($td); mcrypt_module_close($td); return utf8_encode(trim($decrypted)); } protected function hex2bin($hexdata) { $bindata = ''; for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } } ``` **HOW TO USE IT (PHP)** ``` <?php $mcrypt = new MCrypt(); #Encrypt $encrypted = $mcrypt->encrypt("Text to encrypt"); #Decrypt $decrypted = $mcrypt->decrypt($encrypted); ```
I'm guessing your `keyspec` and `ivspec` are not valid for decryption. I've typically transformed them into `PublicKey` and `PrivateKey` instances and then use the private key to decrypt.
6,547,214
I'm trying to encrypt data between my android application and a PHP webservice. I found the next piece of code in this website: <http://schneimi.wordpress.com/2008/11/25/aes-128bit-encryption-between-java-and-php/> But when I try to decrypt I get the Exception of the title "data not block size aligned" This are the method in my **MCrypt class** ``` public String encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); Cipher cipher; byte[] encrypted = null; try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return new String( encrypted ); } public String decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); Cipher cipher; byte[] decrypted = null; try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return new String( decrypted ); } private static byte[] hexToBytes(String hex) { String HEXINDEX = "0123456789abcdef"; int l = hex.length() / 2; byte data[] = new byte[l]; int j = 0; for (int i = 0; i < l; i++) { char c = hex.charAt(j++); int n, b; n = HEXINDEX.indexOf(c); b = (n & 0xf) << 4; c = hex.charAt(j++); n = HEXINDEX.indexOf(c); b += (n & 0xf); data[i] = (byte) b; } return data; } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } ``` And this is how I'm using it in my activity to test: ``` String encrypted = mcrypt.encrypt(jsonUser.toString()); String decrypted = mcrypt.decrypt(encrypted); ``` the encrypt method works fine, but the second throws an exception.
2011/07/01
[ "https://Stackoverflow.com/questions/6547214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571353/" ]
At last! I made it work! Thanks for all your suggestion. I would like to share the code just in case somebody get stuck like me: **JAVA** ``` import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MCrypt { private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!) private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!) public MCrypt() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data==null) { return null; } int len = data.length; String str = ""; for (int i=0; i<len; i++) { if ((data[i]&0xFF)<16) str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF); else str = str + java.lang.Integer.toHexString(data[i]&0xFF); } return str; } public static byte[] hexToBytes(String str) { if (str==null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i=0; i<len; i++) { buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16); } return buffer; } } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } } ``` **HOW TO USE IT (JAVA)** ``` mcrypt = new MCrypt(); /* Encrypt */ String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") ); /* Decrypt */ String decrypted = new String( mcrypt.decrypt( encrypted ) ); ``` ==================================================== **PHP** ``` <?php class MCrypt { private $iv = 'fedcba9876543210'; #Same as in JAVA private $key = '0123456789abcdef'; #Same as in JAVA function __construct() { } function encrypt($str) { //$key = $this->hex2bin($key); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return bin2hex($encrypted); } function decrypt($code) { //$key = $this->hex2bin($key); $code = $this->hex2bin($code); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $decrypted = mdecrypt_generic($td, $code); mcrypt_generic_deinit($td); mcrypt_module_close($td); return utf8_encode(trim($decrypted)); } protected function hex2bin($hexdata) { $bindata = ''; for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } } ``` **HOW TO USE IT (PHP)** ``` <?php $mcrypt = new MCrypt(); #Encrypt $encrypted = $mcrypt->encrypt("Text to encrypt"); #Decrypt $decrypted = $mcrypt->decrypt($encrypted); ```
I looked at the comments in the other answer. I ran into a similar problem trying to encrypt a large block of text using open SSL in php (on both sides). I imagine the same issue would come up in Java. If you have a 1024 bit RSA key, you must split the incoming text into 117 byte chunks (a char is a byte) and encrypt each (you can concatenate them together). On the other end, you must split the encrypted data into 128 byte chunks and decrypt each. This should give you your original message. Also note that http may not play friendly with the non-ASCII encrypted data. I base64 encode/decode it before and after transmission (plus you have to worry about additional urlencoding for the base64 change, but it is easy). I'm not sure of your AES key length, but if it's 1024 bits the chunk length is probably the same. If it's not, you will have to divide the bits by 8 to find the byte chunk length coming out. I'm actually not sure how to get it coming in, unfortunately (maybe multiply by 117/128 ?) Here's some php code: ``` class Crypto { public function encrypt($key, $data) { $crypto = ''; foreach (str_split($data, 117) as $chunk) { openssl_public_encrypt($chunk, $encrypted, $key); $crypto .= $encrypted; } return $crypto; } //Decrypt omitted. Basically the same, change 117 to 128. /**#@+ * Update data for HTTP transmission and retrieval * Must be used on encrypted data, but also useful for any binary data * (e.g. zip files). */ public function base64_encode($value) { return rtrim(strtr(base64_encode($value), '+/', '-_'), '='); } //String length must be padded for decoding for some reason public function base64_decode($value) { return base64_decode(str_pad(strtr($value, '-_', '+/') , strlen($value) % 4, '=', STR_PAD_RIGHT)); } /**#@-*/ } ```
37,285,990
Say I have two classes: ``` class ParentClass { public function getSomething() { return $this->variable_name; } } class ChildClass extends ParentClass { private $variable_name = 'something specific to child class'; ... } ``` Then I call code to instantiate the `ChildClass` and call the inherited `getSomething()` method: ``` $object = new ChildClass(); $value = $object->getSomething(); ``` When I call that last line, it gives me an error because `$variable_name` does not exist in `ParentClass`. I'm expecting `ChildClass` to inherit the method `getSomething()`, but I understand that since it is not overridden explicitly in `ChildClass`, it uses the parent's scope when running the parent version of the method. How can I most efficiently have the `ChildClass` inherit the method *and* give it the ability to read the child class's `$variable_name` when said method is called?
2016/05/17
[ "https://Stackoverflow.com/questions/37285990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331952/" ]
> > Rule of thumb: if your parent class needs to know anything about child classes, then you do something wrong. > > > When you design classes or interfaces you should first think about `actions` (methods) which they can perform. Don't think about their `internal state` (variables). To solve your particular problem, you should first decide, whether you need to have different object states or different actions. For different states, you could implement something like this: ``` class ParentClass { private $variable; function __construct($var) { $this->variable = $var; } function getSomething() { return $this->variable; } } class ChildClass extends ParentClass { function __construct() { parent::__construct('something specific to child class'); } } ``` so, variable is part of Parent's state and child object must init it. another approach is to make contract: ``` abstract class ParentClass { function getSomething() { return $this->internalGetSomething(); } abstract function internalGetSomething(); } class ChildClass extends ParentClass { function internalGetSomething() { return 'something specific to child class'; } } ``` so, internalGetSomething is contract between parent and child
Short answer: You can't. Long answer: That's not how OO works. Parent classes doesn't know your childs. What you can do is to use Reflection, but it's not the way to go, you need to rethink your project. ``` class Parent { public function getSomething(Child $child) { $reflection = new ReflectionObject($child); $variable_name = $r->getProperty('variable_name'); $variable_name->setAccessible(true); return $variable_name->getValue($child); } } ```
37,285,990
Say I have two classes: ``` class ParentClass { public function getSomething() { return $this->variable_name; } } class ChildClass extends ParentClass { private $variable_name = 'something specific to child class'; ... } ``` Then I call code to instantiate the `ChildClass` and call the inherited `getSomething()` method: ``` $object = new ChildClass(); $value = $object->getSomething(); ``` When I call that last line, it gives me an error because `$variable_name` does not exist in `ParentClass`. I'm expecting `ChildClass` to inherit the method `getSomething()`, but I understand that since it is not overridden explicitly in `ChildClass`, it uses the parent's scope when running the parent version of the method. How can I most efficiently have the `ChildClass` inherit the method *and* give it the ability to read the child class's `$variable_name` when said method is called?
2016/05/17
[ "https://Stackoverflow.com/questions/37285990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331952/" ]
> > Rule of thumb: if your parent class needs to know anything about child classes, then you do something wrong. > > > When you design classes or interfaces you should first think about `actions` (methods) which they can perform. Don't think about their `internal state` (variables). To solve your particular problem, you should first decide, whether you need to have different object states or different actions. For different states, you could implement something like this: ``` class ParentClass { private $variable; function __construct($var) { $this->variable = $var; } function getSomething() { return $this->variable; } } class ChildClass extends ParentClass { function __construct() { parent::__construct('something specific to child class'); } } ``` so, variable is part of Parent's state and child object must init it. another approach is to make contract: ``` abstract class ParentClass { function getSomething() { return $this->internalGetSomething(); } abstract function internalGetSomething(); } class ChildClass extends ParentClass { function internalGetSomething() { return 'something specific to child class'; } } ``` so, internalGetSomething is contract between parent and child
Just like you stated, the ChildClass inherits from the ParentClass, not the other way around. To the ParentClass, `$this->variable_name` is an unknown variable. A simple way that I would suggest would be to change the ParentClass method a bit and override it in the ChildClass as such: ``` class ParentClass { public function getSomething($param) { return $param; } } class ChildClass extends ParentClass { private $variable_name = 'something specific to child class'; public function getSomething($param = "") { return parent::getSomething($param = $this->variable_name); } } $object = new ChildClass(); $value = $object->getSomething(); echo $value; ```
70,475,907
I don't understand why I'm getting this error: > > Argument of type '{ id: string; }' is not assignable to parameter of > type 'never'. > > > ... at the line `const index = state.sections.findIndex((section) => section.id === id);` in the following portion of my Vue store: ``` import { MutationTree, ActionTree, GetterTree } from 'vuex'; interface section { id: string; section_header: string; section_body: string; sectionItems: any; } interface sections extends Array<section>{} export const state = () => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); type EditorState = ReturnType<typeof state>; export const mutations: MutationTree<EditorState> = { ADD_SECTION_ITEM(state, id) { const index = state.sections.findIndex((section) => section.id === id); const sectionItem = { id: randomId() } state.sections[index].sectionItems.push(sectionItem); }, }; ```
2021/12/24
[ "https://Stackoverflow.com/questions/70475907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871404/" ]
When you don't provide a type for a value -- your function's return value, in this case -- TypeScript tries to narrow it down to the most accurate type it can. Since your returned object's `sections`' item arrays are always empty, it infers them as `never[]` (`type[]` is an alias for `Array<type>`); an array that can't actually contain any values. You can see this in the following snippet: ``` const functionReturningEmptyArray = () => ({ items: [] }); type EmptyArray = ReturnType<typeof functionReturningEmptyArray>; // type EmptyArray = { items: never[] } ``` One way you can solve this is using the `section` interface you created to specify the return type of `state`. ``` export const state = (): { sections: Array<section> } => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); ``` The colon after the empty parentheses on the first line specifies the function's return type. I've inlined the object type in this case as it only has one property, but if your `state` is more complex, or if you just prefer the readability, you can extract it to a separate type and reference that as the return type; ``` interface MyState { sections: Array<section>; } export const state = (): MyState => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); ``` At this point, TypeScript will throw an error on your returned value, because your `section` interface specifies that the object should also have a `section_body` property, which is missing in your returned `sections` array. To fix this, you can either give each object in the array a `section_body` property, or modify the interface to match the fact that the property may or may not exist; ``` interface section { id: string; section_header: string; section_body?: string; sectionItems: any; } ``` Your store should now be error-free, but to have a more type safe `sectionItems` property, you can also change it from `any` to `Array<any>`, or use a more specific object type if you know what the section items will look like beforehand.
I think you need `state.sections.push(sectionItem)` instead of `state.sections[index].sectionItems.push(sectionItems)`.
70,475,907
I don't understand why I'm getting this error: > > Argument of type '{ id: string; }' is not assignable to parameter of > type 'never'. > > > ... at the line `const index = state.sections.findIndex((section) => section.id === id);` in the following portion of my Vue store: ``` import { MutationTree, ActionTree, GetterTree } from 'vuex'; interface section { id: string; section_header: string; section_body: string; sectionItems: any; } interface sections extends Array<section>{} export const state = () => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); type EditorState = ReturnType<typeof state>; export const mutations: MutationTree<EditorState> = { ADD_SECTION_ITEM(state, id) { const index = state.sections.findIndex((section) => section.id === id); const sectionItem = { id: randomId() } state.sections[index].sectionItems.push(sectionItem); }, }; ```
2021/12/24
[ "https://Stackoverflow.com/questions/70475907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871404/" ]
When you don't provide a type for a value -- your function's return value, in this case -- TypeScript tries to narrow it down to the most accurate type it can. Since your returned object's `sections`' item arrays are always empty, it infers them as `never[]` (`type[]` is an alias for `Array<type>`); an array that can't actually contain any values. You can see this in the following snippet: ``` const functionReturningEmptyArray = () => ({ items: [] }); type EmptyArray = ReturnType<typeof functionReturningEmptyArray>; // type EmptyArray = { items: never[] } ``` One way you can solve this is using the `section` interface you created to specify the return type of `state`. ``` export const state = (): { sections: Array<section> } => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); ``` The colon after the empty parentheses on the first line specifies the function's return type. I've inlined the object type in this case as it only has one property, but if your `state` is more complex, or if you just prefer the readability, you can extract it to a separate type and reference that as the return type; ``` interface MyState { sections: Array<section>; } export const state = (): MyState => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); ``` At this point, TypeScript will throw an error on your returned value, because your `section` interface specifies that the object should also have a `section_body` property, which is missing in your returned `sections` array. To fix this, you can either give each object in the array a `section_body` property, or modify the interface to match the fact that the property may or may not exist; ``` interface section { id: string; section_header: string; section_body?: string; sectionItems: any; } ``` Your store should now be error-free, but to have a more type safe `sectionItems` property, you can also change it from `any` to `Array<any>`, or use a more specific object type if you know what the section items will look like beforehand.
I would say you probably need to type your sectionItems: ``` interface SectionItem { id: string } interface Section { id: string; section_header: string; section_body?: string; sectionItems: SectionItem; } interface State { sections: Section[] } export const state = (): State => ({ sections: [ { id: '1', section_header: 'lorem', sectionItems: [] }, { id: '2', section_header: 'ipsum', sectionItems: [] } ] }); type EditorState = ReturnType<State>; export const mutations: MutationTree<EditorState> = { ADD_SECTION_ITEM(state, id) { const index = state.sections.findIndex((section) => section.id === id); const sectionItem = { id: randomId() } state.sections[index].sectionItems.push(sectionItem); }, }; ``` Because, when you don't specify the type of sectionItems, typescript looks at the sectionItems that you initialised in your state (which are equal to []) and cannot identify the type of elements that should be in this array. So you define it. Also, section\_body should be optional because you it's not there in all your examples. Interface names should be capitalised in typescript. Also, I do not think you need the sections interface. if you want to type something as an array of an interface, just use section[] as the type, like you would do string[]. Finally, this is up to you but I would advise against using different naming conventions in your interfaces (and in your code in general): section\_body is snake\_case and sectionItems is camelCase, it's usually better to stick to one and keep it in all the code. Edited, You need to type the "state" using an interface State that describes it. Additionally, I do not have much experience with Vuex specifically, but they seem to indicate a specific way to use it with typescript, that is different than what you are doing: [vuex docs here](https://next.vuex.vuejs.org/guide/typescript-support.html)
54,881,664
I want to create a circle inside a circle like a donut, but it should be create dynamically. for eg. If I have a page width 500px and height 500px, it should fit. or if I have some other width and height like 100px and 100px, it should fit in. I am creating a component in angular project using div and css. I have gone through the below URL, but there the height and width are fixed [How to make one circle inside of another using CSS](https://stackoverflow.com/questions/22406661/how-to-make-one-circle-inside-of-another-using-css) Below is the css for inner and outer circle ``` .empty-wheel-outer { display: inline-block; width: 60px; height: 60px; border: 1px solid $alto; border-radius: 50%; } .empty-wheel-inner { display: inline-block; width: 32px; height: 32px; border: 1px solid $alto; border-radius: 50%; margin: 13px; } ```
2019/02/26
[ "https://Stackoverflow.com/questions/54881664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039996/" ]
This should help: ```css .outerCircle{ width: 60px; height: 60px; border: 1px solid #000; border-radius: 50%; display: flex; align-items: center; justify-content: center; } .innerCircle{ width: 32px; height: 32px; border: 1px solid #000; border-radius: 50%; } ``` ```html <div class="outerCircle"> <div class="innerCircle"></div> </div> ```
I made some changes in your code. Please check this [Answer to "https://stackoverflow.com/questions/54881664/how-to-create-a-circle-inside-a-circle-dynamically-like-a-donut"](https://codepen.io/anon/pen/eXYXQb) CSS : ```css .empty-wheel-outer { display: inline-block; width: -webkit-fill-available; height: -webkit-fill-available; border: 1px solid red; border-radius: 50%; } .empty-wheel-inner { display: inline-block; width: -webkit-fill-available; height: -webkit-fill-available; border: 1px solid blue; border-radius: 50%; margin: 0 10%; } ``` ```html <div class="empty-wheel-outer"> <div class="empty-wheel-inner"> </div> </div> ```
54,881,664
I want to create a circle inside a circle like a donut, but it should be create dynamically. for eg. If I have a page width 500px and height 500px, it should fit. or if I have some other width and height like 100px and 100px, it should fit in. I am creating a component in angular project using div and css. I have gone through the below URL, but there the height and width are fixed [How to make one circle inside of another using CSS](https://stackoverflow.com/questions/22406661/how-to-make-one-circle-inside-of-another-using-css) Below is the css for inner and outer circle ``` .empty-wheel-outer { display: inline-block; width: 60px; height: 60px; border: 1px solid $alto; border-radius: 50%; } .empty-wheel-inner { display: inline-block; width: 32px; height: 32px; border: 1px solid $alto; border-radius: 50%; margin: 13px; } ```
2019/02/26
[ "https://Stackoverflow.com/questions/54881664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039996/" ]
height and width will be added dynamically for child items in % and it will be centered automatically by adding circle class `Try changing child width and height it will stay in center` Ping me if you need further explanation. ```css .wraper { width: 60px; height: 60px; } .circle { display: flex; align-items: center; border: 1px solid red; border-radius: 50%; } .empty-wheel-outer { width: 100%; height: 100%; } .empty-wheel-inner { width: 50%; height: 50%; margin: auto; } ``` ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="wraper"> <span class="circle empty-wheel-outer"> <span class=" circle empty-wheel-inner"></span> </span> <div/> </div> </body> </html> ```
This should help: ```css .outerCircle{ width: 60px; height: 60px; border: 1px solid #000; border-radius: 50%; display: flex; align-items: center; justify-content: center; } .innerCircle{ width: 32px; height: 32px; border: 1px solid #000; border-radius: 50%; } ``` ```html <div class="outerCircle"> <div class="innerCircle"></div> </div> ```
54,881,664
I want to create a circle inside a circle like a donut, but it should be create dynamically. for eg. If I have a page width 500px and height 500px, it should fit. or if I have some other width and height like 100px and 100px, it should fit in. I am creating a component in angular project using div and css. I have gone through the below URL, but there the height and width are fixed [How to make one circle inside of another using CSS](https://stackoverflow.com/questions/22406661/how-to-make-one-circle-inside-of-another-using-css) Below is the css for inner and outer circle ``` .empty-wheel-outer { display: inline-block; width: 60px; height: 60px; border: 1px solid $alto; border-radius: 50%; } .empty-wheel-inner { display: inline-block; width: 32px; height: 32px; border: 1px solid $alto; border-radius: 50%; margin: 13px; } ```
2019/02/26
[ "https://Stackoverflow.com/questions/54881664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039996/" ]
height and width will be added dynamically for child items in % and it will be centered automatically by adding circle class `Try changing child width and height it will stay in center` Ping me if you need further explanation. ```css .wraper { width: 60px; height: 60px; } .circle { display: flex; align-items: center; border: 1px solid red; border-radius: 50%; } .empty-wheel-outer { width: 100%; height: 100%; } .empty-wheel-inner { width: 50%; height: 50%; margin: auto; } ``` ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="wraper"> <span class="circle empty-wheel-outer"> <span class=" circle empty-wheel-inner"></span> </span> <div/> </div> </body> </html> ```
I made some changes in your code. Please check this [Answer to "https://stackoverflow.com/questions/54881664/how-to-create-a-circle-inside-a-circle-dynamically-like-a-donut"](https://codepen.io/anon/pen/eXYXQb) CSS : ```css .empty-wheel-outer { display: inline-block; width: -webkit-fill-available; height: -webkit-fill-available; border: 1px solid red; border-radius: 50%; } .empty-wheel-inner { display: inline-block; width: -webkit-fill-available; height: -webkit-fill-available; border: 1px solid blue; border-radius: 50%; margin: 0 10%; } ``` ```html <div class="empty-wheel-outer"> <div class="empty-wheel-inner"> </div> </div> ```
24,761,088
I have downloaded the entire website from my server over an SSH connection and now I am unable to run it on my localhost. The website works fine there on the server but not on my localhost, and throws me this error whenever I try to hit localhost/CPx ``` Fatal error: Using $this when not in object context in /var/www/CPX/Controller/DashboardController.php on line 25 ``` I have looked for these type errors on the web, but none seems to satisfy my case. Also the development is in CakePHP and methods and objects in various files are being highlighted with a message "X method not found in Class X" ( I am using PhpStorm) I am sure that I have not missed a single file while downloading it from the server. My server is from AWS and is running HTTPD. localhost config: Debian 7, Apache2, MySQL. Is this due to some server configuration or else. My Line #25 `<?php echo $this->Form->create(null, Array('class' => 'no-margin', 'id' => 'frm_report'));?>` And my Apache2 conf : ``` # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.2/ for detailed information about # the directives and /usr/share/doc/apache2-common/README.Debian.gz about # Debian specific hints. # # # Summary of how the Apache 2 configuration works in Debian: # The Apache 2 web server configuration in Debian is quite different to # upstream's suggested way to configure the web server. This is because Debian's # default Apache2 installation attempts to make adding and removing modules, # virtual hosts, and extra configuration directives as flexible as possible, in # order to make automating the changes and administering the server as easy as # possible. # It is split into several files forming the configuration hierarchy outlined # below, all located in the /etc/apache2/ directory: # # /etc/apache2/ # |-- apache2.conf # | `-- ports.conf # |-- mods-enabled # | |-- *.load # | `-- *.conf # |-- conf.d # | `-- * # `-- sites-enabled # `-- * # # # * apache2.conf is the main configuration file (this file). It puts the pieces # together by including all remaining configuration files when starting up the # web server. # # In order to avoid conflicts with backup files, the Include directive is # adapted to ignore files that: # - do not begin with a letter or number # - contain a character that is neither letter nor number nor _-:. # - contain .dpkg # # Yet we strongly suggest that all configuration files either end with a # .conf or .load suffix in the file name. The next Debian release will # ignore files not ending with .conf (or .load for mods-enabled). # # * ports.conf is always included from the main configuration file. It is # supposed to determine listening ports for incoming connections, and which # of these ports are used for name based virtual hosts. # # * Configuration files in the mods-enabled/ and sites-enabled/ directories # contain particular configuration snippets which manage modules or virtual # host configurations, respectively. # # They are activated by symlinking available configuration files from their # respective *-available/ counterparts. These should be managed by using our # helpers a2enmod/a2dismod, a2ensite/a2dissite. See # their respective man pages for detailed information. # # * Configuration files in the conf.d directory are either provided by other # packages or may be added by the local administrator. Local additions # should start with local- or end with .local.conf to avoid name clashes. All # files in conf.d are considered (excluding the exceptions noted above) by # the Apache 2 web server. # # * The binary is called apache2. Due to the use of environment variables, in # the default configuration, apache2 needs to be started/stopped with # /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not # work with the default configuration. # Global configuration # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation (available # at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>); # you will save yourself a lot of trouble. # # Do NOT add a slash at the end of the directory path. # #ServerRoot "/etc/apache2" # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # LockFile ${APACHE_LOCK_DIR}/accept.lock # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 5 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # worker MPM # StartServers: initial number of server processes to start # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadLimit: ThreadsPerChild can be changed to this maximum value during a # graceful restart. ThreadLimit can only be changed by stopping # and starting Apache. # ThreadsPerChild: constant number of worker threads in each server process # MaxClients: maximum number of simultaneous client connections # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # event MPM # StartServers: initial number of server processes to start # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxClients: maximum number of simultaneous client connections # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_event_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy all </Files> # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # # It is also possible to omit any default MIME type and let the # client's browser guess an appropriate action instead. Typically the # browser will decide based on the file's extension then. In cases # where no good assumption can be made, letting the default MIME type # unset is suggested instead of forcing the browser to accept # incorrect metadata. # DefaultType None # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog ${APACHE_LOG_DIR}/error.log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # Include module configuration: Include mods-enabled/*.load Include mods-enabled/*.conf # Include list of ports to listen on and which to use for name based vhosts Include ports.conf # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # Include of directories ignores editors' and dpkg's backup files, # see the comments above for details. # Include generic snippets of statements Include conf.d/ # Include the virtual host configurations: Include sites-enabled/ Include /etc/phpmyadmin/apache.conf ```
2014/07/15
[ "https://Stackoverflow.com/questions/24761088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2647960/" ]
Start [reading about OOP in the php manual](http://php.net/manual/en/language.oop5.php) and then do the CakePHP blog tutorial, start here: <http://book.cakephp.org/2.0/en/index.html#getting-started> Using a helper (that's what your line 25 does) in a controller is a clear proof that you don't know what you do and how to use the framework. I guess the error messages comes up because your controller has no class at all or something else completely wrong and weird that shouldn't be in a controller.
The fact issue is with a controller named "DashboardController" could suggest that dashboard may be on subdomain on the production environment? (eg I have seen some people put dashboard functionality onto subdomain) You'd have to address that in your dev environment.
10,130,726
> > **Possible Duplicate:** > > [Ruby: Nils in an IF statement](https://stackoverflow.com/questions/5393974/ruby-nils-in-an-if-statement) > > [Is there a clean way to avoid calling a method on nil in a nested params hash?](https://stackoverflow.com/questions/5429790/is-there-a-clean-way-to-avoid-calling-a-method-on-nil-in-a-nested-params-hash) > > > Let's say I try to access a hash like this: ``` my_hash['key1']['key2']['key3'] ``` This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn't exist? Then I would get `NoMethodError: undefined method [] for nil:NilClass`. And nobody likes that. So far I deal with this doing a conditional like: `if my_hash['key1'] && my_hash['key1']['key2']` ... Is this appropriate, is there any other Rubiest way of doing so?
2012/04/12
[ "https://Stackoverflow.com/questions/10130726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/585456/" ]
There are many approaches to this. If you use Ruby 2.3 or above, you can use [dig](http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig) ``` my_hash.dig('key1', 'key2', 'key3') ``` Plenty of folks stick to plain ruby and chain the `&&` guard tests. You could use stdlib [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch) too: ``` my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil) ``` Some like chaining ActiveSupport's [#try](http://api.rubyonrails.org/classes/Object.html#method-i-try) method. ``` my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3') ``` Others use [andand](https://github.com/raganwald/andand) ``` myhash['key1'].andand['key2'].andand['key3'] ``` Some people think [egocentric nils](https://github.com/raganwald/homoiconic/blob/master/2009-02-02/hopeless_egocentricity.md) are a good idea (though someone might hunt you down and torture you if they found you do this). ``` class NilClass def method_missing(*args); nil; end end my_hash['key1']['key2']['key3'] ``` You could use [Enumerable#reduce](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-reduce) (or alias inject). ``` ['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] } ``` Or perhaps extend Hash or just your target hash object with a nested lookup method ``` module NestedHashLookup def nest *keys keys.reduce(self) {|m,k| m && m[k] } end end my_hash.extend(NestedHashLookup) my_hash.nest 'key1', 'key2', 'key3' ``` Oh, and how could we forget the [maybe](http://lostechies.com/derickbailey/2010/10/10/the-maybe-monad-in-ruby/) monad? ``` Maybe.new(my_hash)['key1']['key2']['key3'] ```
Conditions `my_hash['key1'] && my_hash['key1']['key2']` don't feel [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Alternatives: 1) [autovivification](http://t-a-w.blogspot.com/2006/07/autovivification-in-ruby.html) magic. From that post: ``` def autovivifying_hash Hash.new {|ht,k| ht[k] = autovivifying_hash} end ``` Then, with your example: ``` my_hash = autovivifying_hash my_hash['key1']['key2']['key3'] ``` It's similar to the Hash.fetch approach in that both operate with new hashes as default values, but this moves details to the creation time. Admittedly, this is a bit of cheating: it will never return 'nil' just an empty hash, which is created on the fly. Depending on your use case, this could be wasteful. 2) Abstract away the data structure with its lookup mechanism, and handle the non-found case behind the scenes. A simplistic example: ``` def lookup(model, key, *rest) v = model[key] if rest.empty? v else v && lookup(v, *rest) end end ##### lookup(my_hash, 'key1', 'key2', 'key3') => nil or value ``` 3) If you feel monadic you can take a look at this, [Maybe](http://meta-meta.blogspot.com/2006/12/monads-in-ruby-part-2-maybe-then-again.html)
10,130,726
> > **Possible Duplicate:** > > [Ruby: Nils in an IF statement](https://stackoverflow.com/questions/5393974/ruby-nils-in-an-if-statement) > > [Is there a clean way to avoid calling a method on nil in a nested params hash?](https://stackoverflow.com/questions/5429790/is-there-a-clean-way-to-avoid-calling-a-method-on-nil-in-a-nested-params-hash) > > > Let's say I try to access a hash like this: ``` my_hash['key1']['key2']['key3'] ``` This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn't exist? Then I would get `NoMethodError: undefined method [] for nil:NilClass`. And nobody likes that. So far I deal with this doing a conditional like: `if my_hash['key1'] && my_hash['key1']['key2']` ... Is this appropriate, is there any other Rubiest way of doing so?
2012/04/12
[ "https://Stackoverflow.com/questions/10130726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/585456/" ]
There are many approaches to this. If you use Ruby 2.3 or above, you can use [dig](http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig) ``` my_hash.dig('key1', 'key2', 'key3') ``` Plenty of folks stick to plain ruby and chain the `&&` guard tests. You could use stdlib [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch) too: ``` my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil) ``` Some like chaining ActiveSupport's [#try](http://api.rubyonrails.org/classes/Object.html#method-i-try) method. ``` my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3') ``` Others use [andand](https://github.com/raganwald/andand) ``` myhash['key1'].andand['key2'].andand['key3'] ``` Some people think [egocentric nils](https://github.com/raganwald/homoiconic/blob/master/2009-02-02/hopeless_egocentricity.md) are a good idea (though someone might hunt you down and torture you if they found you do this). ``` class NilClass def method_missing(*args); nil; end end my_hash['key1']['key2']['key3'] ``` You could use [Enumerable#reduce](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-reduce) (or alias inject). ``` ['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] } ``` Or perhaps extend Hash or just your target hash object with a nested lookup method ``` module NestedHashLookup def nest *keys keys.reduce(self) {|m,k| m && m[k] } end end my_hash.extend(NestedHashLookup) my_hash.nest 'key1', 'key2', 'key3' ``` Oh, and how could we forget the [maybe](http://lostechies.com/derickbailey/2010/10/10/the-maybe-monad-in-ruby/) monad? ``` Maybe.new(my_hash)['key1']['key2']['key3'] ```
You could also use [Object#andand](http://andand.rubyforge.org/). ``` my_hash['key1'].andand['key2'].andand['key3'] ```
43,032,249
Basically I have a txt file thats an ouput from a fortran model. The output looks a little like this: ``` Title:Model Temp(K) Ionic str Rho Phi H2O Ice ... 273.15 4 1.003 1.21 1000 0.00 Species Ini Conc Final Conc Act .... H 0.0 0.12032 0.59 NH4 3.0 3.00 0.43 Cl 1.0 1.00 0.47 ... Title:Model Temp(K) Ionic str Rho Phi H2O Ice ... 273.15 4 1.003 1.21 1000 0.00 Species Ini Conc Final Conc Act .... H 0.0 0.12032 0.59 NH4 3.0 3.00 0.43 Cl 1.0 1.00 0.47 ... ``` Each step adds another set like the above so eventually I have a txt file with 3000+ steps. So I want to recall all the temperatures at each step. I'm trying to write something to index all the points where 'Temp(K)' appears and then add 1 to that index to get the location of the actual temperature. My code looks like this: ``` import numpy as np import matplotlib.pyplot as plt main=[] main2=[] count=0 with open('FrOut.txt', 'r') as f: data=f.readlines() for line in data: main.append(line.split(',')) for value in main: for x in value: main2.append(x.split()) for value in main2: for x in value: if x=='Temp(K)':count+=1 ``` So obviously this isn't the most elegant way but I'm very much in the deep end with python. So how do I find the index of a list within list(main2) if the first value of that list=='Temp(K)'? Nb. I'm using np and matplot to plot the data after this.
2017/03/26
[ "https://Stackoverflow.com/questions/43032249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7384359/" ]
Use templates. C++ version of generic programming. -------------------------------------------------- Define your **linked list** `node` with a template: ``` template<class T> class node<T>{ public: node<T>(); T data; node<T> *next; }; ``` This means that you can now have a `node` of any kind of data type, just by accessing `node's` **data attribute member**. Then define a new container class/struct to hold that other relevant information you were mentioning to include: ``` class data { public: /* ctor, dtor, accesor and modifier operations */ private: unsigned int index, age; std:string name, surname, university, fieldOfStudy, yearOfStudy; }; ``` **You would need to redefine your `linkedList` class to also use templates:** ``` template<class T> class linkedList<T> { /* ...declaration and implementation taking in to account <T> data type. }; ``` Then outside your scope, in `main()` for example, you can do the following: ``` int main() { linkedList<data> list; list.insertBegin(); list.insertLast(); // ... etc. return 0; } ```
You could also NOT use generic programming/templates and make your `node` have specific data you want ----------------------------------------------------------------------------------------------------- This will also impact your code less, because when adding templates you would probably have to add and change more lines of code. What you can do is to simply change your node class adding all the attributes that we had added to the `data` class, like so: ``` class node { public: /* ctor, dtor, accesor and modifier operations */ private: node(); node *next; unsigned int index, age; std:string name, surname, university, fieldOfStudy, yearOfStudy; // Now we have all the attributesyou needed and we omit the data attribute member. }; ``` You will need to make **simple modifications** to your `linkedList` methods, mainly only when you're instantiating `node` objects. The problem with this solution is that it binds you to those attributes you chose above. The previous **generic solution** does not bind you to any data type and still all the linkedList functionality will work for any data type you decide to use (C++ int, double, float, std::string, custom classes).
35,836,158
I'm setting up the remote connection to oracle database and it requires that the connection should be established through port 1521 by default. However, i'm getting the error repeatly: [Oracle JDBC Driver]Error establishing socket to host and port: :1521. Reason: Connection refused Checking deeper, I realize that the port 1521 cannot be connected on the local machine: telnet localhost 1521 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... telnet: connect to address 127.0.0.1: Connection refused The connection through this port is not established by anyway. Moreover, the iptables is disable on local and remote machines as well. Ping for localhost is working fine. I notice that only port 1521 is refusing connection. When I tried to telnet with port 80, it is working fine. Do we really need to have port 1521 on netstat output to establish the connection through it? If yes then how we can do. Thank you for your help in advances. Regards, Anh
2016/03/07
[ "https://Stackoverflow.com/questions/35836158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027407/" ]
This has nothing to do with Python, but modular arithmetic: ``` print(time[(14 - 1 + 59) % 24]) ``` prints ``` 1 ```
Use modulo to get the remainder of the index you want divided by the length of the tuple: ``` time = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24) print(time[(15+59) % len(time)]) ```
35,836,158
I'm setting up the remote connection to oracle database and it requires that the connection should be established through port 1521 by default. However, i'm getting the error repeatly: [Oracle JDBC Driver]Error establishing socket to host and port: :1521. Reason: Connection refused Checking deeper, I realize that the port 1521 cannot be connected on the local machine: telnet localhost 1521 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... telnet: connect to address 127.0.0.1: Connection refused The connection through this port is not established by anyway. Moreover, the iptables is disable on local and remote machines as well. Ping for localhost is working fine. I notice that only port 1521 is refusing connection. When I tried to telnet with port 80, it is working fine. Do we really need to have port 1521 on netstat output to establish the connection through it? If yes then how we can do. Thank you for your help in advances. Regards, Anh
2016/03/07
[ "https://Stackoverflow.com/questions/35836158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027407/" ]
This has nothing to do with Python, but modular arithmetic: ``` print(time[(14 - 1 + 59) % 24]) ``` prints ``` 1 ```
[np.roll](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.roll.html) shifts all of the values in your iterable, and thus answers your original question. ``` import datetime as dt >>> dt.datetime(2016, + dt.timedelta(hours=59) datetime.datetime(2016, 1, 4, 1, 0) # 1 a.m. >>> np.roll(time, -59)[14 - 1] # -1 because of zero based indexing. 1 # 1 a.m. ``` For example: ``` >>> np.roll(time, -1) array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1]) ``` Of course, I would still go with the simpler answer using modulo, i.e. ``` time(hour - 1 + hour_offset) % 24. ```
7,228,988
What I'm wondering is basically what (if any) browsers in iOS and Android allow events to trigger when the browser is inactive/in background/sleeping? If any: What kind of events will this browser in that OS allow?
2011/08/29
[ "https://Stackoverflow.com/questions/7228988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/761168/" ]
As far as I know, they do not. If you put the browser in the background, it unloads the page to free some memory for other apps.
If you've got a `<video>` or `<audio>` element with a playing media file in iOS Safari, the `ended` event will trigger, even if the browser is not open. This allows you to select a next media file and play it, sorta emulating the native iPod experience.
7,228,988
What I'm wondering is basically what (if any) browsers in iOS and Android allow events to trigger when the browser is inactive/in background/sleeping? If any: What kind of events will this browser in that OS allow?
2011/08/29
[ "https://Stackoverflow.com/questions/7228988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/761168/" ]
In Android, you can accomplish this by writing an Activity whose sole UI component is a web view. Your activity receives many lifecycle events automatically (such as focus / loss of focus) and can request to receive more (such as screen-off, screen-on). You can easily pass these events into the underlying webkit's javascript interface.
If you've got a `<video>` or `<audio>` element with a playing media file in iOS Safari, the `ended` event will trigger, even if the browser is not open. This allows you to select a next media file and play it, sorta emulating the native iPod experience.
11,627
So tell me know, can you figure out, The clues I'll give are all about A subject many really quite hate, The moment they hear it, from the gate. It really is useful, as science would say, Scientific conclusions use it every day. The chances too are great, can you see If you use it, or hear what they may be. Consider now these clues, not so mean. Stay away from numbered errors, as they're seen. So check the clues, the hidden and viewed Something's lurking, what do you conclude?
2015/04/06
[ "https://puzzling.stackexchange.com/questions/11627", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/9951/" ]
Is it > > Statistics? > > > So tell me know, can you figure out, The clues I'll give are all about A subject many really quite hate, The moment they hear it, from the gate. > > Many people have a negative attitude towards statistics: there are lies, there are damned lies, and there is statistics. > > > It really is useful, as science would say, Scientific conclusions use it every day. > > Statistics is used everywhere in science, from physics over chemistry and biology to economics. > > > The chances too are great, can you see If you use it, or hear what they may be. Consider now these clues, not so mean. Stay away from numbered errors, as they're seen. > > "chances", "mean", "errors": standard terms in statistics > > > So check the clues, the hidden and viewed Something's lurking, what do you conclude?
Sounds like > > Math > > > A subject many really quite hate, The moment they hear it, from the gate. > > Many people dislike math > > > It really is useful, as science would say, Scientific conclusions use it every day. > > Math is useful in science! > > > The chances too are great, can you see If you use it, or hear what they may be. > > Probability is part of math > > > Consider now these clues, not so mean. Stay away from numbered errors, as they're seen. > > "numbered" -> "numbers" -> "math" > > >