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
5,267,816
I am trying to get the full path of an uploaded file. The php code is like this: ``` <?php $destination_path = getcwd() . DIRECTORY_SEPARATOR; $result = 0; $target_path = $destination_path . basename($_FILES['thefile']['name']); if(@move_uploaded_file($_FILES['thefile']['tmp_name'],*$target_path)) { $result = 1; } ?> <script language="javascript" type="text/javascript"> //d = '<?php echo basename( $_FILES['thefile']['name']); ?>'; d = '<?php echo $target_path; ?>'; window.top.window.phpUpload(d); </script> ``` I can open the json file with the rem'd out line but I need the path to return it at session end. Testing with an alert the full path is shown without slashes and the initial letter 'n' of the filename missing ... Any help much appreciated. (Click on Names then open nset.json at this [test site](http://glasier.hk) to see what I'm trying to do)
2011/03/11
[ "https://Stackoverflow.com/questions/5267816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654557/" ]
You are assumingly using this on Windows, where `DIRECTORY_SEPARATOR` is a backslash. If the filename starts with a `n` then your Javascript code will end up like this: ``` d = '..\path\nameoffile.txt'; ``` Javascript unlike PHP will interpret `\n` in single quoted strings. The solution to your dilemma is either not using `DIRECTORY_SEPARATOR`, or outputting a correctly escaped Javascript string: ``` d = <?php echo json_encode($target_path); ?>; ```
Do you mean the full path to the file on the *client's* machine? JavaScript security will not reveal that. It will just send the actual file name to the server.
26,243,506
Suppose one has the following pattern: * Foobar class, which makes use of the logic in either Foo or Bar, but not both, depending upon the arguments given by the constructor * Foo module, containing some logic * Bar module, containing some alternate logic A good example is an orbital elements calculator, which might take radius and velocity vectors, and compute orbital elements --- or alternatively, might take orbital elements and compute radius and velocity vectors. Why not do this in a more straightforward way? Well, I want to make use of instance variables to allow just-in-time computations, e.g., ``` def derived_value @derived_value ||= begin # compute only when/if necessary end end ``` I tried doing this roughly as follows: ``` class Orbit def initialize options = {} if [:radius,:velocity].all? { |key| options.has_key?(key) } # Provide instance methods which derive orbital elements from radius, velocity self.include Orbit::FromRadiusAndVelocity else # Provide instance methods which derive radius and velocity from orbital elements self.include Orbit::FromOrbitalElements end initialize_helper options end end module Orbit::FromOrbitalElements module ClassMethods class << self def initialize_helper options @argument_of_perigee = options[:argument_of_perigee] puts "From orbital elements" end attr_reader :argument_of_perigee end end def self.included(base) base.extend Orbit::FromOrbitalElements::ClassMethods end def self.radius # Instance method to calculate the radius from the orbital elements @radius ||= begin # If radius is not already defined, calculate it from some intermediate # values, which themselves depend upon orbital elements. end end end module Orbit::FromRadiusAndVelocity module ClassMethods class << self def initialize_helper options @radius = options[:radius] @velocity = options[:velocity] puts "From radius and velocity" end attr_reader :radius, :velocity end end def self.included(base) base.extend Orbit::FromRadiusAndVelocity::ClassMethods end def self.argument_of_perigee # Instance method to calculate an orbital element # (There would be more instance methods like this) @argument_of_perigee ||= begin # If argument_of_perigee is not already defined, calculate it from some intermediate # values, which themselves depend upon radius and velocity. end end end ``` Is there a better pattern / is this an advisable usage? Is it possible to do this?
2014/10/07
[ "https://Stackoverflow.com/questions/26243506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170300/" ]
I'm not really sure why you want to mask an instance of two different entities under one but if you want simple decision logic based on arguments, this works: ``` # orbit.rb module Orbit module_function def from_options(options = {}) klass = if options[:radius] && options[:velocity] FromRadiusAndVelocity else FromOrbitalElements end klass.new(options) end end # orbit/from_orbital_elements.rb module Orbit class FromOrbitalElements attr_reader :argument_of_perigee def initialize(options) @argument_of_perigee = options[:argument_of_perigee] puts 'From orbital elements' end def radius @radius ||= begin # ... end end end end # orbit/from_radius_and_velocity.rb module Orbit class FromRadiusAndVelocity attr_reader :radius, :velocity def initialize(options) @radius = options[:radius] @velocity = options[:velocity] puts 'From radius and velocity' end def argument_of_perigee @argument_of_perigee ||= begin # ... end end end end # Usage orbit = Orbit.from_options(radius: 5, velocity: 6) orbit = Orbit.from_options(argument_of_perigee: 5) ``` If you want to do some kind of same-interface-thingy, may want to turn Orbit into a class and subclass it in the other classes but that isn't clear from your code.
To me it sounds like a job for simple inheritance: ``` class FooBar def self.new(options) if [:radius,:velocity].all? { |key| options.has_key?(key) } Foo.new options else Bar.new options end end # common Foo and Barlogic here end class Foo < FooBar end class Bar < FooBar end ```
26,243,506
Suppose one has the following pattern: * Foobar class, which makes use of the logic in either Foo or Bar, but not both, depending upon the arguments given by the constructor * Foo module, containing some logic * Bar module, containing some alternate logic A good example is an orbital elements calculator, which might take radius and velocity vectors, and compute orbital elements --- or alternatively, might take orbital elements and compute radius and velocity vectors. Why not do this in a more straightforward way? Well, I want to make use of instance variables to allow just-in-time computations, e.g., ``` def derived_value @derived_value ||= begin # compute only when/if necessary end end ``` I tried doing this roughly as follows: ``` class Orbit def initialize options = {} if [:radius,:velocity].all? { |key| options.has_key?(key) } # Provide instance methods which derive orbital elements from radius, velocity self.include Orbit::FromRadiusAndVelocity else # Provide instance methods which derive radius and velocity from orbital elements self.include Orbit::FromOrbitalElements end initialize_helper options end end module Orbit::FromOrbitalElements module ClassMethods class << self def initialize_helper options @argument_of_perigee = options[:argument_of_perigee] puts "From orbital elements" end attr_reader :argument_of_perigee end end def self.included(base) base.extend Orbit::FromOrbitalElements::ClassMethods end def self.radius # Instance method to calculate the radius from the orbital elements @radius ||= begin # If radius is not already defined, calculate it from some intermediate # values, which themselves depend upon orbital elements. end end end module Orbit::FromRadiusAndVelocity module ClassMethods class << self def initialize_helper options @radius = options[:radius] @velocity = options[:velocity] puts "From radius and velocity" end attr_reader :radius, :velocity end end def self.included(base) base.extend Orbit::FromRadiusAndVelocity::ClassMethods end def self.argument_of_perigee # Instance method to calculate an orbital element # (There would be more instance methods like this) @argument_of_perigee ||= begin # If argument_of_perigee is not already defined, calculate it from some intermediate # values, which themselves depend upon radius and velocity. end end end ``` Is there a better pattern / is this an advisable usage? Is it possible to do this?
2014/10/07
[ "https://Stackoverflow.com/questions/26243506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170300/" ]
You can by including the module of choice in the singleton class (sometimes called eigenclass), not the object itself. So the initializer can look like this ``` class Orbit def initialize options = {} if [:radius,:velocity].all? { |key| options.has_key?(key) } self.singleton_class.include Orbit::FromRadiusAndVelocity else self.singleton_class.include Orbit::FromOrbitalElements end initialize_helper options end end ``` If you're going to use this approach, then you need to adjust your modules accordingly: 1. No need for `ClassMethod` modules, all the method included are (supposedly) called from an object, not from a class 2. Remove the `self.` from the method names (except `self.included` of course) The rest of the code can look like this ``` module Orbit::FromOrbitalElements def initialize_helper options @argument_of_perigee = options[:argument_of_perigee] puts "From orbital elements" end def self.included(base) base.instance_eval do attr_reader :argument_of_perigee end end def radius @radius ||= begin end end end module Orbit::FromRadiusAndVelocity def self.included(base) base.instance_eval do attr_reader :radius, :velocity end end def initialize_helper options @radius = options[:radius] @velocity = options[:velocity] puts "From radius and velocity" end def argument_of_perigee @argument_of_perigee ||= begin end end end ``` That said, this solution is just for demonstration and I suggest you follow the example @Ollie mentioned in his answer as it is much cleaner.
To me it sounds like a job for simple inheritance: ``` class FooBar def self.new(options) if [:radius,:velocity].all? { |key| options.has_key?(key) } Foo.new options else Bar.new options end end # common Foo and Barlogic here end class Foo < FooBar end class Bar < FooBar end ```
17,673,492
I get an error while running yo webapp as "Easy with the sudo. Yeoman is the master around here" Please help me out. I followed the same instructions in the yoeman.io website. Without sudo , on running in /usr/node/ with the directory changed to 777 with chmod, Error: EACCES, permission denied '/home/manish/.config/configstore/insight-yo.yml' at Object.fs.openSync (fs.js:427:18) at Object.fs.writeFileSync (fs.js:966:15) at Object.create.all.set (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/node\_modules/configstore/configstore.js:39:7) at Object.Configstore (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/node\_modules/configstore/configstore.js:30:11) at new Insight (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/lib/insight.js:20:16) at Object. (/home/manish/local/lib/node\_modules/yo/bin/yo:26:15) at Module.\_compile (module.js:456:26) at Object.Module.\_extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module.\_load (module.js:312:12)
2013/07/16
[ "https://Stackoverflow.com/questions/17673492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2149185/" ]
This happens because you must be trying to start your application as root. See this for more information: <https://github.com/passy/yo/commit/d33e7a67d74343d836a14881b17b3072b92f2532> If you're starting your applciation by running: ``` sudo node app.js ``` Try doing this instead: ``` node app.js ``` I.e. this won't try to start the application as root. Same goes for scaffolding, if you're trying to create your application. you shouldn't need sudo for that if you're doing that under your home (~/) directory.
There's a Gist here with a selection of shell scripts to help you install Node and NPM without requiring sudo permissions: <https://gist.github.com/isaacs/579814>
17,673,492
I get an error while running yo webapp as "Easy with the sudo. Yeoman is the master around here" Please help me out. I followed the same instructions in the yoeman.io website. Without sudo , on running in /usr/node/ with the directory changed to 777 with chmod, Error: EACCES, permission denied '/home/manish/.config/configstore/insight-yo.yml' at Object.fs.openSync (fs.js:427:18) at Object.fs.writeFileSync (fs.js:966:15) at Object.create.all.set (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/node\_modules/configstore/configstore.js:39:7) at Object.Configstore (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/node\_modules/configstore/configstore.js:30:11) at new Insight (/home/manish/local/lib/node\_modules/yo/node\_modules/insight/lib/insight.js:20:16) at Object. (/home/manish/local/lib/node\_modules/yo/bin/yo:26:15) at Module.\_compile (module.js:456:26) at Object.Module.\_extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module.\_load (module.js:312:12)
2013/07/16
[ "https://Stackoverflow.com/questions/17673492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2149185/" ]
This happens because you must be trying to start your application as root. See this for more information: <https://github.com/passy/yo/commit/d33e7a67d74343d836a14881b17b3072b92f2532> If you're starting your applciation by running: ``` sudo node app.js ``` Try doing this instead: ``` node app.js ``` I.e. this won't try to start the application as root. Same goes for scaffolding, if you're trying to create your application. you shouldn't need sudo for that if you're doing that under your home (~/) directory.
So running yo ? gives the error above - maybe like for me it installed ~/Users/yourusername/.config/configstore/insight-yo.yml with the root permissions and this needs chowning to the name of the user. chown yourusername ~/Users/yourusername/.config/configstore/insight-yo.yml This was my issue and may be a part of the full solution given here <https://gist.github.com/isaacs/579814>
25,368,773
I am jumping into building an ASP.NET MVC site and I am stuck on a probably simple issue. I am attempting to filter a query by date using a lambda expression. The other ways I have attempted to filter have been successful. Here is what I am trying to accomplish. The data is stored in a SQL Server 2008 R2 database with a `date` data type. I am not sure if this is why the results will not display. ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Project.Models; public class CreateController : Controller { // GET: Create public ActionResult Create() { var dt = DateTime.Now.AddDays(-10); var db = new Models.Entities(); var apps = db.tableName.Where(x => x.col1 == dt); return View(apps.OrderBy(x => x.col2)); } } ``` And my view ``` @model IEnumerable<Project.Models.table1> @{ ViewBag.Title = "Project"; } @foreach (var apps in Model) { <table> <tr> <th>col z</th> <th>col x</th> <th>col y</th> <th>col w</th> </tr> <tr> <td>@apps.col1</td> <td>@apps.col2</td> <td>@apps.col3</td> <td>@apps.col4</td> </tr> </table> } ```
2014/08/18
[ "https://Stackoverflow.com/questions/25368773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3352768/" ]
``` //per lordkain: var dt = DateTime.Now.Date.AddDays(-10); //per Yuliam Chandra: db.tableName.Where(x => x.col1 >= dt); ```
At the looks of your code the c# datatype is DateTime, and the one in your database is Date. you probally want to change your code in youre create function as ``` var dt = DateTime.Today.AddDays(-10); ``` now the code is only Date, without the time!
57,756,440
I have dumped the output of a command into a text file which consists of multiple columns results in multiple rows. The first column contains the Equipment ID and second column contain the time (In UTC) I want to sort the rows on the basis of increasing time order(Setup time). How to do that? Here is my command out put (dumped to a text file) : ``` Equipment ID | Setup Time - GPS (UTC) | End Time - GPS (UTC) 3 | 2068512564500 (2019-08-30 22:22:26.500 UTC) | 2068513054300 (2019-08-30 22:30:36.300 UTC) 2 | 2068506579500 (2019-08-30 20:42:41.500 UTC) | 2068507041300 (2019-08-30 20:50:23.300 UTC) 2 | 2068513133500 (2019-08-30 22:31:55.500 UTC) | 2068513614300 (2019-08-30 22:39:56.300 UTC) 3 | 2068506038500 (2019-08-30 20:33:40.500 UTC) | 2068506399300 (2019-08-30 20:39:41.300 UTC) 1 | 2068512827500 (2019-08-30 22:26:49.500 UTC) | 2068512852300 (2019-08-30 22:27:14.300 UTC) ```
2019/09/02
[ "https://Stackoverflow.com/questions/57756440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11986993/" ]
Is the class `dest-sitemap__sublist-title-empty` unique for this element? you can use it ``` elem = driver.find_element_by_class_name('dest-sitemap__sublist-title-empty') ```
You can use XPATH and text() function. XPATH provides a rich possibility to locate elements. So if you want to locate all h4 elements with empty strings, you can use the following way. ``` xpath = "//h4[text()='']" elems = driver.find_elements_by_xpath(xpath) ```
27,001,838
I have an Angular 1.0 app, and I have been asked to upgrade it to 1.3.2 What are the main changes / new features between these two version. What are the biggest challenges. I'm aware this question is kind of broad. I don't know how to narrow it at this point. Suggestions for how to narrow in the comments would be most welcome.
2014/11/18
[ "https://Stackoverflow.com/questions/27001838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687677/" ]
well I have to say since it feels like a minor version, definitely it feels like doing an upgrade to a major version (with all the breaking changes with it). I'd point some cases that for me are in one or another way challenges: * Third party libraries are not up to date with 1.3, some of them are making the effort to be compatible, but at this day you'll find issues there. * Not Compatible with IE 8 (it may be a concern for some people) * Breaking changes + $cancelUpdate + $animate + $compile + $route * Changes in the API + How to register interceptors * Behavior changes + provider registration always occurs prior to configuration for a given module + $resources + $location * Angular Splitted into several modules Modules + NgRoute + NgResource and so on....... I'd recommend you to read this [migration guide](https://docs.angularjs.org/guide/migration) and [this other](http://ng-learn.org/2014/06/Migration_Guide_from_1-2_to1-3/), try to go through every single note and review the changes that you'll need to do. this could sound like a big nightmare definitely you'll have to sit some time and refactor a lot of code in your application but I'd say not everything is bad the angular team (and the community) have fixed a lot of performance issues and other issues in general and they added some cool features like [one time bindings](https://docs.angularjs.org/guide/expression), ngAria, ngMessages, ngModelOptions, etc. I just wanted to point that with all the pain at the end you'll get a reward
`ng-route` & `ng-resource` are made as seperate modules/libraries in angular 1.3.2. so, these js files need to be script included in your html file.
27,001,838
I have an Angular 1.0 app, and I have been asked to upgrade it to 1.3.2 What are the main changes / new features between these two version. What are the biggest challenges. I'm aware this question is kind of broad. I don't know how to narrow it at this point. Suggestions for how to narrow in the comments would be most welcome.
2014/11/18
[ "https://Stackoverflow.com/questions/27001838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687677/" ]
Angular has documented the detailed list of breaking changes / migration issues in its website. You can have a look on the document from here: [Breaking Changes](https://docs.angularjs.org/guide/migration) I have made a brief list on the major breaking changes Summary of Breaking Changes by Migrating from 1.0 to 1.2: 1. ngRoute has been moved into its own module 2. Templates no longerautomatically unwrap promises 3. Syntax for named wildcard parameters changed in $route. 4. You can only bind one expression to [src], [ng-src] or action. 5. Interpolations inside DOM event handlers are now disallowed 6. Directives cannot end with -start or -end 7. In $q,promise.always has been renamed promise.finally 8. ngMobile is now ngTouch 9. resource.$then has been removed 10. Resource methods return the promise 11. Resource promises are resolved with the resource instance 12. $location.search supports multiple keys 13. ngBindHtmlUnsafe has been removed and replaced by ngBindHtml 14. Form names that are expressions are evaluated 15. hasOwnProperty disallowed as an input name 16. Directives:Order of postLink functions reversed 17. Directive priority 18. ngScenario 19. ngInclude and ngView replace its entire element on update 20. URLs are now sanitized against a whitelist 21. Isolate scope only exposed to directives with scope property 22. Change to interpolation priority 23. Underscore-prefixed/suffixed properties are non-bindable 24. You cannot bind to select[multiple] 25. Uncommon region-specific local files were removed from i18n 26. Services can now return functions Summary of Breaking Changes by Migrating from 1.2 to 1.3: 1. You can no longer invoke .bind, .call or .apply on a function in angular expressions. 2. The proto property does not work inside angular expressions any more. 3. Angular.copy: it applies the prototype of the original object to the copied object. Previously, angular.copy would copy properties of the original object's prototype chain directly onto the copied object. 4. values 'f', '0', 'false', 'no', 'n', '[]' are no longer treated as falsy. Only JavaScript falsy values are now treated as falsy by the expression parser; there are six of them: false, null, undefined, NaN, 0 and "". 5. If you find that your code is now throwing a $compile:multidir error, check that you do not have directives on the same element that are trying to request both an isolate and a non-isolate scope and fix your code. 6. input: types date, time, datetime-local, month, week now always require a Date object as model 7. the jQuery detach() method does not trigger the $destroy event. If you want to destroy Angular data attached to the element, use remove(). 8. $broadcast and $emit will now reset the currentScope property of the event to null once the event finished propagating. If any code depends on asynchronously accessing their currentScope property, it should be migrated to use targetScope instead. All of these cases should be considered programming bugs. 9. angular.toJson: If you expected toJson to strip these types of properties before, you will have to manually do this yourself now. 10. $resource 11. previously it was possible to set jqLite data on Text/Comment nodes, but now that is allowed only on Element and Document nodes just like in jQuery. We don't expect that app code actually depends on this accidental feature.
`ng-route` & `ng-resource` are made as seperate modules/libraries in angular 1.3.2. so, these js files need to be script included in your html file.
27,001,838
I have an Angular 1.0 app, and I have been asked to upgrade it to 1.3.2 What are the main changes / new features between these two version. What are the biggest challenges. I'm aware this question is kind of broad. I don't know how to narrow it at this point. Suggestions for how to narrow in the comments would be most welcome.
2014/11/18
[ "https://Stackoverflow.com/questions/27001838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687677/" ]
well I have to say since it feels like a minor version, definitely it feels like doing an upgrade to a major version (with all the breaking changes with it). I'd point some cases that for me are in one or another way challenges: * Third party libraries are not up to date with 1.3, some of them are making the effort to be compatible, but at this day you'll find issues there. * Not Compatible with IE 8 (it may be a concern for some people) * Breaking changes + $cancelUpdate + $animate + $compile + $route * Changes in the API + How to register interceptors * Behavior changes + provider registration always occurs prior to configuration for a given module + $resources + $location * Angular Splitted into several modules Modules + NgRoute + NgResource and so on....... I'd recommend you to read this [migration guide](https://docs.angularjs.org/guide/migration) and [this other](http://ng-learn.org/2014/06/Migration_Guide_from_1-2_to1-3/), try to go through every single note and review the changes that you'll need to do. this could sound like a big nightmare definitely you'll have to sit some time and refactor a lot of code in your application but I'd say not everything is bad the angular team (and the community) have fixed a lot of performance issues and other issues in general and they added some cool features like [one time bindings](https://docs.angularjs.org/guide/expression), ngAria, ngMessages, ngModelOptions, etc. I just wanted to point that with all the pain at the end you'll get a reward
Angular has documented the detailed list of breaking changes / migration issues in its website. You can have a look on the document from here: [Breaking Changes](https://docs.angularjs.org/guide/migration) I have made a brief list on the major breaking changes Summary of Breaking Changes by Migrating from 1.0 to 1.2: 1. ngRoute has been moved into its own module 2. Templates no longerautomatically unwrap promises 3. Syntax for named wildcard parameters changed in $route. 4. You can only bind one expression to [src], [ng-src] or action. 5. Interpolations inside DOM event handlers are now disallowed 6. Directives cannot end with -start or -end 7. In $q,promise.always has been renamed promise.finally 8. ngMobile is now ngTouch 9. resource.$then has been removed 10. Resource methods return the promise 11. Resource promises are resolved with the resource instance 12. $location.search supports multiple keys 13. ngBindHtmlUnsafe has been removed and replaced by ngBindHtml 14. Form names that are expressions are evaluated 15. hasOwnProperty disallowed as an input name 16. Directives:Order of postLink functions reversed 17. Directive priority 18. ngScenario 19. ngInclude and ngView replace its entire element on update 20. URLs are now sanitized against a whitelist 21. Isolate scope only exposed to directives with scope property 22. Change to interpolation priority 23. Underscore-prefixed/suffixed properties are non-bindable 24. You cannot bind to select[multiple] 25. Uncommon region-specific local files were removed from i18n 26. Services can now return functions Summary of Breaking Changes by Migrating from 1.2 to 1.3: 1. You can no longer invoke .bind, .call or .apply on a function in angular expressions. 2. The proto property does not work inside angular expressions any more. 3. Angular.copy: it applies the prototype of the original object to the copied object. Previously, angular.copy would copy properties of the original object's prototype chain directly onto the copied object. 4. values 'f', '0', 'false', 'no', 'n', '[]' are no longer treated as falsy. Only JavaScript falsy values are now treated as falsy by the expression parser; there are six of them: false, null, undefined, NaN, 0 and "". 5. If you find that your code is now throwing a $compile:multidir error, check that you do not have directives on the same element that are trying to request both an isolate and a non-isolate scope and fix your code. 6. input: types date, time, datetime-local, month, week now always require a Date object as model 7. the jQuery detach() method does not trigger the $destroy event. If you want to destroy Angular data attached to the element, use remove(). 8. $broadcast and $emit will now reset the currentScope property of the event to null once the event finished propagating. If any code depends on asynchronously accessing their currentScope property, it should be migrated to use targetScope instead. All of these cases should be considered programming bugs. 9. angular.toJson: If you expected toJson to strip these types of properties before, you will have to manually do this yourself now. 10. $resource 11. previously it was possible to set jqLite data on Text/Comment nodes, but now that is allowed only on Element and Document nodes just like in jQuery. We don't expect that app code actually depends on this accidental feature.
27,001,838
I have an Angular 1.0 app, and I have been asked to upgrade it to 1.3.2 What are the main changes / new features between these two version. What are the biggest challenges. I'm aware this question is kind of broad. I don't know how to narrow it at this point. Suggestions for how to narrow in the comments would be most welcome.
2014/11/18
[ "https://Stackoverflow.com/questions/27001838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687677/" ]
well I have to say since it feels like a minor version, definitely it feels like doing an upgrade to a major version (with all the breaking changes with it). I'd point some cases that for me are in one or another way challenges: * Third party libraries are not up to date with 1.3, some of them are making the effort to be compatible, but at this day you'll find issues there. * Not Compatible with IE 8 (it may be a concern for some people) * Breaking changes + $cancelUpdate + $animate + $compile + $route * Changes in the API + How to register interceptors * Behavior changes + provider registration always occurs prior to configuration for a given module + $resources + $location * Angular Splitted into several modules Modules + NgRoute + NgResource and so on....... I'd recommend you to read this [migration guide](https://docs.angularjs.org/guide/migration) and [this other](http://ng-learn.org/2014/06/Migration_Guide_from_1-2_to1-3/), try to go through every single note and review the changes that you'll need to do. this could sound like a big nightmare definitely you'll have to sit some time and refactor a lot of code in your application but I'd say not everything is bad the angular team (and the community) have fixed a lot of performance issues and other issues in general and they added some cool features like [one time bindings](https://docs.angularjs.org/guide/expression), ngAria, ngMessages, ngModelOptions, etc. I just wanted to point that with all the pain at the end you'll get a reward
There is one main change I found while working angularjs application that is filter usages in template. For example, **In older version** | filter: { product.name: stock.product.name } **In updated version** | filter: { product: { name: stock.product.name }}
27,001,838
I have an Angular 1.0 app, and I have been asked to upgrade it to 1.3.2 What are the main changes / new features between these two version. What are the biggest challenges. I'm aware this question is kind of broad. I don't know how to narrow it at this point. Suggestions for how to narrow in the comments would be most welcome.
2014/11/18
[ "https://Stackoverflow.com/questions/27001838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687677/" ]
Angular has documented the detailed list of breaking changes / migration issues in its website. You can have a look on the document from here: [Breaking Changes](https://docs.angularjs.org/guide/migration) I have made a brief list on the major breaking changes Summary of Breaking Changes by Migrating from 1.0 to 1.2: 1. ngRoute has been moved into its own module 2. Templates no longerautomatically unwrap promises 3. Syntax for named wildcard parameters changed in $route. 4. You can only bind one expression to [src], [ng-src] or action. 5. Interpolations inside DOM event handlers are now disallowed 6. Directives cannot end with -start or -end 7. In $q,promise.always has been renamed promise.finally 8. ngMobile is now ngTouch 9. resource.$then has been removed 10. Resource methods return the promise 11. Resource promises are resolved with the resource instance 12. $location.search supports multiple keys 13. ngBindHtmlUnsafe has been removed and replaced by ngBindHtml 14. Form names that are expressions are evaluated 15. hasOwnProperty disallowed as an input name 16. Directives:Order of postLink functions reversed 17. Directive priority 18. ngScenario 19. ngInclude and ngView replace its entire element on update 20. URLs are now sanitized against a whitelist 21. Isolate scope only exposed to directives with scope property 22. Change to interpolation priority 23. Underscore-prefixed/suffixed properties are non-bindable 24. You cannot bind to select[multiple] 25. Uncommon region-specific local files were removed from i18n 26. Services can now return functions Summary of Breaking Changes by Migrating from 1.2 to 1.3: 1. You can no longer invoke .bind, .call or .apply on a function in angular expressions. 2. The proto property does not work inside angular expressions any more. 3. Angular.copy: it applies the prototype of the original object to the copied object. Previously, angular.copy would copy properties of the original object's prototype chain directly onto the copied object. 4. values 'f', '0', 'false', 'no', 'n', '[]' are no longer treated as falsy. Only JavaScript falsy values are now treated as falsy by the expression parser; there are six of them: false, null, undefined, NaN, 0 and "". 5. If you find that your code is now throwing a $compile:multidir error, check that you do not have directives on the same element that are trying to request both an isolate and a non-isolate scope and fix your code. 6. input: types date, time, datetime-local, month, week now always require a Date object as model 7. the jQuery detach() method does not trigger the $destroy event. If you want to destroy Angular data attached to the element, use remove(). 8. $broadcast and $emit will now reset the currentScope property of the event to null once the event finished propagating. If any code depends on asynchronously accessing their currentScope property, it should be migrated to use targetScope instead. All of these cases should be considered programming bugs. 9. angular.toJson: If you expected toJson to strip these types of properties before, you will have to manually do this yourself now. 10. $resource 11. previously it was possible to set jqLite data on Text/Comment nodes, but now that is allowed only on Element and Document nodes just like in jQuery. We don't expect that app code actually depends on this accidental feature.
There is one main change I found while working angularjs application that is filter usages in template. For example, **In older version** | filter: { product.name: stock.product.name } **In updated version** | filter: { product: { name: stock.product.name }}
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
Note that these days the best answer for solar, if you aren't determined to go completely off-grid and if your electric company supports it, may be to get inverters that support line synchronization and ask the electric company to set you up for net metering. In this setup the inverters and line feed the house in parallel. If you're producing less power than you need, you buy the remainder from the power company; if you're producing more than you need, you sell the excess back to the power company. Much simpler than trying to maintain local batteries for extra or nighttime power, ensures that all power generated deducts from your electric costs, and in some cases you may be able to sell carbon-reduction credits as well. I've been quite happy with this setup. I have a relatively small solar setup (8 "standard" panels), but my electricity use is relatively low too, and in the summer I usually do have one or two months of negative net usage. I haven't yet gone negative enough to actually have a negative bill, due to the utility's $6 account fee, but I've come close. Note: The one disadvantage of a newer metering system is that, to keep your system from electrocuting linemen who expected a cable to be unpowered, net-metering systems are designed explicitly not to run in "island mode"; if the network goes dead, they shut down for safety. That does mean you have to make other plans for dealing with blackouts. As I said, if being able to go completely off-grid is important to you this may not be the best solution. If it sounds interesting, ask your solar supplier/contractor for details. Anyone competent should be able to explain it in detail, and run numbers to tell you how long it would take for the system to pay back it's purchase cost after figuring in any currently available rebates and carbon credits (though the latter will be a best-guess, since these are sold via an auction mechanism and prices may change depending on supply and demand).
Separate the supply to your lights so that they are supplied from one of [these](http://www.ceshowroom.com/ProductDetails.asp?ProductCode=PETMDT4642W&click=2&gclid=Cj0KEQiAzai0BRCs2Yydo8yptuIBEiQAN3_lFnNoTQ7I3RsatvuM6fFvFvEb4i_B7WuxekM-m_OJz3YaAlDI8P8HAQ). Get a double-pole 120v relay capable of switching 15-20 amps, powered off the inverter. The common being your lights, the NO being inverter in, and the NC being mains in. Use short 12 AWG extension cords for their connectors to save time and keep the project looking clean. Tie all grounds together and to the enclosure you use for the relay. Then plug it all in. When the inverter comes on, the lights may flicker because the phase angle won't match, but that should be the extent of it and they will run on battery until it depletes to the point the inverter cannot run. If you want GFCI protection, I'd recommend using in-line GFCIs so it's more modular. You might also consider using "a proper transfer switch" if you want to spend some more and appease building codes, but the above will work, and is easily removable during any inspection or when you go to sell the house. And if you want to be more efficient, consider using DC lighting at the same voltage as your batteries. Do the same thing with the relays, but entirely on the DC side. It will be safer, better compliant with code, and by not running an inverter you will save significant energy in waste heat.
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
I think the simplest answer is to install a piece of SO/SJO cord with a cord cap to the switch box for your lighting circuit and plug it in to the inverter when you wish to use it. Make sure you disconnect the lighting circuit from the existing main power wiring first. Good luck!
Separate the supply to your lights so that they are supplied from one of [these](http://www.ceshowroom.com/ProductDetails.asp?ProductCode=PETMDT4642W&click=2&gclid=Cj0KEQiAzai0BRCs2Yydo8yptuIBEiQAN3_lFnNoTQ7I3RsatvuM6fFvFvEb4i_B7WuxekM-m_OJz3YaAlDI8P8HAQ). Get a double-pole 120v relay capable of switching 15-20 amps, powered off the inverter. The common being your lights, the NO being inverter in, and the NC being mains in. Use short 12 AWG extension cords for their connectors to save time and keep the project looking clean. Tie all grounds together and to the enclosure you use for the relay. Then plug it all in. When the inverter comes on, the lights may flicker because the phase angle won't match, but that should be the extent of it and they will run on battery until it depletes to the point the inverter cannot run. If you want GFCI protection, I'd recommend using in-line GFCIs so it's more modular. You might also consider using "a proper transfer switch" if you want to spend some more and appease building codes, but the above will work, and is easily removable during any inspection or when you go to sell the house. And if you want to be more efficient, consider using DC lighting at the same voltage as your batteries. Do the same thing with the relays, but entirely on the DC side. It will be safer, better compliant with code, and by not running an inverter you will save significant energy in waste heat.
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
Note that these days the best answer for solar, if you aren't determined to go completely off-grid and if your electric company supports it, may be to get inverters that support line synchronization and ask the electric company to set you up for net metering. In this setup the inverters and line feed the house in parallel. If you're producing less power than you need, you buy the remainder from the power company; if you're producing more than you need, you sell the excess back to the power company. Much simpler than trying to maintain local batteries for extra or nighttime power, ensures that all power generated deducts from your electric costs, and in some cases you may be able to sell carbon-reduction credits as well. I've been quite happy with this setup. I have a relatively small solar setup (8 "standard" panels), but my electricity use is relatively low too, and in the summer I usually do have one or two months of negative net usage. I haven't yet gone negative enough to actually have a negative bill, due to the utility's $6 account fee, but I've come close. Note: The one disadvantage of a newer metering system is that, to keep your system from electrocuting linemen who expected a cable to be unpowered, net-metering systems are designed explicitly not to run in "island mode"; if the network goes dead, they shut down for safety. That does mean you have to make other plans for dealing with blackouts. As I said, if being able to go completely off-grid is important to you this may not be the best solution. If it sounds interesting, ask your solar supplier/contractor for details. Anyone competent should be able to explain it in detail, and run numbers to tell you how long it would take for the system to pay back it's purchase cost after figuring in any currently available rebates and carbon credits (though the latter will be a best-guess, since these are sold via an auction mechanism and prices may change depending on supply and demand).
**The easiest method to achieve what you appear to want is:** 1. Disconnect power to your garage circuitry in your breaker panel. **NOTE**: If there is ANY chance that someone could fiddle with your breakers, it would be ideally best to physically disconnect the garage circuit wires from its circuit breaker. Otherwise, it is possible that your inverter could cause harm to someone who has to service the power lines in your electric service area. 2. Install a male to male power cord from the inverter outlet to any outlet in your garage. (wiring = hot to hot, neutral to neutral, & ground to ground). **NOTE:** this suggestion is a hack (i.e. not a building code compliant solution). 3. When you want to provide inverted battery power to your garage circuit, connect your inverter to the battery terminals & switch on the inverter power switch. Note, you may need to switch on the wall-mounted light switch to allow power to flow to the other parts of the garage wiring. **Note:** The major disadvantage of this setup is that you will not have power to your garage circuitry when the inverter is off or your battery is drained. Depending on the wiring in your garage, it may be possible to use your light switch to switch between mains power & inverter power, but you will likely need to install a pull switch light fixture to control the light & do some rewiring inside the light switch box. That setup, however, would also definitely NOT conform to standard wiring codes.
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
I think the simplest answer is to install a piece of SO/SJO cord with a cord cap to the switch box for your lighting circuit and plug it in to the inverter when you wish to use it. Make sure you disconnect the lighting circuit from the existing main power wiring first. Good luck!
**The easiest method to achieve what you appear to want is:** 1. Disconnect power to your garage circuitry in your breaker panel. **NOTE**: If there is ANY chance that someone could fiddle with your breakers, it would be ideally best to physically disconnect the garage circuit wires from its circuit breaker. Otherwise, it is possible that your inverter could cause harm to someone who has to service the power lines in your electric service area. 2. Install a male to male power cord from the inverter outlet to any outlet in your garage. (wiring = hot to hot, neutral to neutral, & ground to ground). **NOTE:** this suggestion is a hack (i.e. not a building code compliant solution). 3. When you want to provide inverted battery power to your garage circuit, connect your inverter to the battery terminals & switch on the inverter power switch. Note, you may need to switch on the wall-mounted light switch to allow power to flow to the other parts of the garage wiring. **Note:** The major disadvantage of this setup is that you will not have power to your garage circuitry when the inverter is off or your battery is drained. Depending on the wiring in your garage, it may be possible to use your light switch to switch between mains power & inverter power, but you will likely need to install a pull switch light fixture to control the light & do some rewiring inside the light switch box. That setup, however, would also definitely NOT conform to standard wiring codes.
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
I think the simplest answer is to install a piece of SO/SJO cord with a cord cap to the switch box for your lighting circuit and plug it in to the inverter when you wish to use it. Make sure you disconnect the lighting circuit from the existing main power wiring first. Good luck!
Note that these days the best answer for solar, if you aren't determined to go completely off-grid and if your electric company supports it, may be to get inverters that support line synchronization and ask the electric company to set you up for net metering. In this setup the inverters and line feed the house in parallel. If you're producing less power than you need, you buy the remainder from the power company; if you're producing more than you need, you sell the excess back to the power company. Much simpler than trying to maintain local batteries for extra or nighttime power, ensures that all power generated deducts from your electric costs, and in some cases you may be able to sell carbon-reduction credits as well. I've been quite happy with this setup. I have a relatively small solar setup (8 "standard" panels), but my electricity use is relatively low too, and in the summer I usually do have one or two months of negative net usage. I haven't yet gone negative enough to actually have a negative bill, due to the utility's $6 account fee, but I've come close. Note: The one disadvantage of a newer metering system is that, to keep your system from electrocuting linemen who expected a cable to be unpowered, net-metering systems are designed explicitly not to run in "island mode"; if the network goes dead, they shut down for safety. That does mean you have to make other plans for dealing with blackouts. As I said, if being able to go completely off-grid is important to you this may not be the best solution. If it sounds interesting, ask your solar supplier/contractor for details. Anyone competent should be able to explain it in detail, and run numbers to tell you how long it would take for the system to pay back it's purchase cost after figuring in any currently available rebates and carbon credits (though the latter will be a best-guess, since these are sold via an auction mechanism and prices may change depending on supply and demand).
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
Note that these days the best answer for solar, if you aren't determined to go completely off-grid and if your electric company supports it, may be to get inverters that support line synchronization and ask the electric company to set you up for net metering. In this setup the inverters and line feed the house in parallel. If you're producing less power than you need, you buy the remainder from the power company; if you're producing more than you need, you sell the excess back to the power company. Much simpler than trying to maintain local batteries for extra or nighttime power, ensures that all power generated deducts from your electric costs, and in some cases you may be able to sell carbon-reduction credits as well. I've been quite happy with this setup. I have a relatively small solar setup (8 "standard" panels), but my electricity use is relatively low too, and in the summer I usually do have one or two months of negative net usage. I haven't yet gone negative enough to actually have a negative bill, due to the utility's $6 account fee, but I've come close. Note: The one disadvantage of a newer metering system is that, to keep your system from electrocuting linemen who expected a cable to be unpowered, net-metering systems are designed explicitly not to run in "island mode"; if the network goes dead, they shut down for safety. That does mean you have to make other plans for dealing with blackouts. As I said, if being able to go completely off-grid is important to you this may not be the best solution. If it sounds interesting, ask your solar supplier/contractor for details. Anyone competent should be able to explain it in detail, and run numbers to tell you how long it would take for the system to pay back it's purchase cost after figuring in any currently available rebates and carbon credits (though the latter will be a best-guess, since these are sold via an auction mechanism and prices may change depending on supply and demand).
Disconnect means to physically disconnect - not switch or turn it off. To me that is logical. When you disconnect an electrical appliance you pull the plug on it not just simply switch it off. The M-M connection could be in the form of Anderson connectors where the terminals are not exposed. Anderson connectors are used in solar system arrays quite frequently and come with different current ratings to suit. Those are what I use in my solar system and they are very safe. The ones I use are rated at 50amps.
81,209
I'm interested in installing a solar power system in my garage and am wondering how to connect the three-prong receptacle output of the power inverter to a NM-B lighting circuit that was previously hooked into a switch in an electric box receiving power from the main panel. [Here's the inverter](http://rads.stackoverflow.com/amzn/click/B007SLDDHQ), in case it helps. I'm comfortable with basic electric work like rewiring receptacles, installing GFCIs, etc., but I haven't done this before and want to be sure I'm not under- or over-thinking this.
2016/01/04
[ "https://diy.stackexchange.com/questions/81209", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/47326/" ]
I think the simplest answer is to install a piece of SO/SJO cord with a cord cap to the switch box for your lighting circuit and plug it in to the inverter when you wish to use it. Make sure you disconnect the lighting circuit from the existing main power wiring first. Good luck!
Disconnect means to physically disconnect - not switch or turn it off. To me that is logical. When you disconnect an electrical appliance you pull the plug on it not just simply switch it off. The M-M connection could be in the form of Anderson connectors where the terminals are not exposed. Anderson connectors are used in solar system arrays quite frequently and come with different current ratings to suit. Those are what I use in my solar system and they are very safe. The ones I use are rated at 50amps.
594,123
In 1d, for $V(x) = g\delta(x)$, integrating the TISE yields (assuming that $\psi$ is *bounded*$^\dagger$, so as to suppress the term containing $E$) $$ -\frac{\hbar^2}{2m} \left( \psi'(\varepsilon) - \psi'(-\varepsilon) \right) + g\psi(0) = 0 $$ for $\varepsilon\to0^+$. Now, this doesn't at all imply that $\psi$ has to be continuous (even though it is bounded) at $x=0$ (unlike the case when $V$ is bounded). But still, everywhere I've seen, it is implicitly assumed that $\psi$ is continuous at $x=0$, and eigenstates are derived using this. I can see that in the above equation, if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$—I could define it anything if it isn't continuous. Moreover, I am doubtful is the following equality for $\varepsilon>0$ (which was used in getting the above equation) is valid even when $\psi$ is discontinuous at $x=0$. $$ \int\_{-\varepsilon}^\varepsilon \delta(x)\psi(x)\; dx \stackrel{?}{=} \psi(0) $$ **Question:** If the above questioned equation is valid only for continuous $\psi$, is it "our desire" to exploit this equality so that we end up restricting the continuity of $\psi$ "by hand?" If so, what is the guarantee that there are not other kinds of solutions? --- $^\dagger$This *is* "put in by hand." Note: A [similar question](https://physics.stackexchange.com/q/218314/231957) was posted five years ago, but was never satisfactorily answered. So I post this again, with more details, hoping that it'll be clearly answered this time.
2020/11/15
[ "https://physics.stackexchange.com/questions/594123", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/231957/" ]
Were $\psi(x)$ not continuous at $x=0$ then $\psi''(x)$ would contain the derivative of a $\delta$-function, and there is nothing else in the equation $H\psi=E\psi$ that could cancel it, so a discontinuity is not allowed.
Well, let's carefully analyze the system: 1. Let us assume the integral form $$ \psi(x)~=~ \frac{2m}{\hbar^2} \int^{x}\mathrm{d}y \int^{y}\mathrm{d}z\ (V(z)-E)\psi(z) \tag{1}$$ of the time independent 1D [Schrödinger equation](http://en.wikipedia.org/wiki/Schr%C3%B6dinger_equation) (TISE), where the potential $$V(x)~=~V\_0\delta(x)\tag{2}$$ is a Dirac delta potential. 2. Let us assume that the wavefunction $\psi\in {\cal L}\_{\rm loc}^1(\mathbb{R})$ is a [locally](http://en.wikipedia.org/wiki/Locally_integrable_function) [integrable](http://en.wikipedia.org/wiki/Lp_space) function, so that the [integral](https://en.wikipedia.org/wiki/Antiderivative) $\int^{y}\mathrm{d}z\ E\psi(z)$ in eq. (1) is well-defined. 3. Note in particular that we do *not* assume that $\psi$ is continuous, cf. OP's title question. The following crucial question arises: How should we define the integral $$\int^{y}\mathrm{d}z\ V(z)\psi(z)\tag{3}$$ in eq. (1)? * Should we define (3) to be equal to $$V\_0\theta(y)\psi(0)+C,\tag{3'}$$ where $C$ is an integration constant? * Or if the [left and right limits](https://en.wikipedia.org/wiki/One-sided_limit) $\psi(0^-)$ and $\psi(0^+)$ exist, should we define (3) to be equal to $$V\_0\theta(y)\frac{\psi(0^-)+\psi(0^+)}{2}+C~?\tag{3''}$$ 4. Whatever definition we propose for the Dirac delta distribution, it seems likely that (3) will become a locally integrable function of $y$. 5. A mathematical bootstrap argument involving the TISE (1) then [shows](https://math.stackexchange.com/q/4335545/11127) that $\psi\in C(\mathbb{R})$ is continuous, cf. OP's title question. This conclusion is largely independent of how we defined (3). 6. See also e.g. my related Phys.SE answer [here](https://physics.stackexchange.com/a/19715/2451).
594,123
In 1d, for $V(x) = g\delta(x)$, integrating the TISE yields (assuming that $\psi$ is *bounded*$^\dagger$, so as to suppress the term containing $E$) $$ -\frac{\hbar^2}{2m} \left( \psi'(\varepsilon) - \psi'(-\varepsilon) \right) + g\psi(0) = 0 $$ for $\varepsilon\to0^+$. Now, this doesn't at all imply that $\psi$ has to be continuous (even though it is bounded) at $x=0$ (unlike the case when $V$ is bounded). But still, everywhere I've seen, it is implicitly assumed that $\psi$ is continuous at $x=0$, and eigenstates are derived using this. I can see that in the above equation, if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$—I could define it anything if it isn't continuous. Moreover, I am doubtful is the following equality for $\varepsilon>0$ (which was used in getting the above equation) is valid even when $\psi$ is discontinuous at $x=0$. $$ \int\_{-\varepsilon}^\varepsilon \delta(x)\psi(x)\; dx \stackrel{?}{=} \psi(0) $$ **Question:** If the above questioned equation is valid only for continuous $\psi$, is it "our desire" to exploit this equality so that we end up restricting the continuity of $\psi$ "by hand?" If so, what is the guarantee that there are not other kinds of solutions? --- $^\dagger$This *is* "put in by hand." Note: A [similar question](https://physics.stackexchange.com/q/218314/231957) was posted five years ago, but was never satisfactorily answered. So I post this again, with more details, hoping that it'll be clearly answered this time.
2020/11/15
[ "https://physics.stackexchange.com/questions/594123", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/231957/" ]
Were $\psi(x)$ not continuous at $x=0$ then $\psi''(x)$ would contain the derivative of a $\delta$-function, and there is nothing else in the equation $H\psi=E\psi$ that could cancel it, so a discontinuity is not allowed.
You can think of the delta potential $V(x)=g\delta(x)$ as representing the limiting form of a potential barrier (or well) of height $\Lambda$ and width $w$, with $w\Lambda=g$. For any finite $\Lambda$, $\psi(x)$ and $\psi’(x)$ must be continuous at both edges of the barrier. Within the barrier, Schrödinger’s equation implies that $\psi’’(x)\sim\Lambda$, so the total change in $\psi’(x)$ across the barrier is $\sim g$. This means that, in the limit $\Lambda\rightarrow\infty$ with $g$ fixed, $\psi’(x)$ is finite everywhere within the barrier, but changes by a finite amount from one side of the barrier to the other. Since $\psi’(x)$ is finite everywhere, $\psi(x)$ is continuous.
594,123
In 1d, for $V(x) = g\delta(x)$, integrating the TISE yields (assuming that $\psi$ is *bounded*$^\dagger$, so as to suppress the term containing $E$) $$ -\frac{\hbar^2}{2m} \left( \psi'(\varepsilon) - \psi'(-\varepsilon) \right) + g\psi(0) = 0 $$ for $\varepsilon\to0^+$. Now, this doesn't at all imply that $\psi$ has to be continuous (even though it is bounded) at $x=0$ (unlike the case when $V$ is bounded). But still, everywhere I've seen, it is implicitly assumed that $\psi$ is continuous at $x=0$, and eigenstates are derived using this. I can see that in the above equation, if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$—I could define it anything if it isn't continuous. Moreover, I am doubtful is the following equality for $\varepsilon>0$ (which was used in getting the above equation) is valid even when $\psi$ is discontinuous at $x=0$. $$ \int\_{-\varepsilon}^\varepsilon \delta(x)\psi(x)\; dx \stackrel{?}{=} \psi(0) $$ **Question:** If the above questioned equation is valid only for continuous $\psi$, is it "our desire" to exploit this equality so that we end up restricting the continuity of $\psi$ "by hand?" If so, what is the guarantee that there are not other kinds of solutions? --- $^\dagger$This *is* "put in by hand." Note: A [similar question](https://physics.stackexchange.com/q/218314/231957) was posted five years ago, but was never satisfactorily answered. So I post this again, with more details, hoping that it'll be clearly answered this time.
2020/11/15
[ "https://physics.stackexchange.com/questions/594123", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/231957/" ]
Were $\psi(x)$ not continuous at $x=0$ then $\psi''(x)$ would contain the derivative of a $\delta$-function, and there is nothing else in the equation $H\psi=E\psi$ that could cancel it, so a discontinuity is not allowed.
The other answers are very good. I want to address one mis-think in the question. > > "... if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$ ..." > > > Not always. As a vast oversimplification, suppose that you have obtained $\psi$ as a Fourier transform, which has $\lim\_{x \rightarrow 0^-} \psi(x) = -1$ and $\lim\_{x \rightarrow 0^+} \psi(x) = 1$. Then we know $\psi(0) = 0$. At a step discontinuity, a Fourier series converges to the midpoint between the values to the left and right. (This is part of the [Dirichlet conditions](https://en.wikipedia.org/wiki/Dirichlet_conditions). There are mild technical hypotheses. The cited reference describes the real-valued version; the complex-valued version is essentially the same.)
594,123
In 1d, for $V(x) = g\delta(x)$, integrating the TISE yields (assuming that $\psi$ is *bounded*$^\dagger$, so as to suppress the term containing $E$) $$ -\frac{\hbar^2}{2m} \left( \psi'(\varepsilon) - \psi'(-\varepsilon) \right) + g\psi(0) = 0 $$ for $\varepsilon\to0^+$. Now, this doesn't at all imply that $\psi$ has to be continuous (even though it is bounded) at $x=0$ (unlike the case when $V$ is bounded). But still, everywhere I've seen, it is implicitly assumed that $\psi$ is continuous at $x=0$, and eigenstates are derived using this. I can see that in the above equation, if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$—I could define it anything if it isn't continuous. Moreover, I am doubtful is the following equality for $\varepsilon>0$ (which was used in getting the above equation) is valid even when $\psi$ is discontinuous at $x=0$. $$ \int\_{-\varepsilon}^\varepsilon \delta(x)\psi(x)\; dx \stackrel{?}{=} \psi(0) $$ **Question:** If the above questioned equation is valid only for continuous $\psi$, is it "our desire" to exploit this equality so that we end up restricting the continuity of $\psi$ "by hand?" If so, what is the guarantee that there are not other kinds of solutions? --- $^\dagger$This *is* "put in by hand." Note: A [similar question](https://physics.stackexchange.com/q/218314/231957) was posted five years ago, but was never satisfactorily answered. So I post this again, with more details, hoping that it'll be clearly answered this time.
2020/11/15
[ "https://physics.stackexchange.com/questions/594123", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/231957/" ]
Well, let's carefully analyze the system: 1. Let us assume the integral form $$ \psi(x)~=~ \frac{2m}{\hbar^2} \int^{x}\mathrm{d}y \int^{y}\mathrm{d}z\ (V(z)-E)\psi(z) \tag{1}$$ of the time independent 1D [Schrödinger equation](http://en.wikipedia.org/wiki/Schr%C3%B6dinger_equation) (TISE), where the potential $$V(x)~=~V\_0\delta(x)\tag{2}$$ is a Dirac delta potential. 2. Let us assume that the wavefunction $\psi\in {\cal L}\_{\rm loc}^1(\mathbb{R})$ is a [locally](http://en.wikipedia.org/wiki/Locally_integrable_function) [integrable](http://en.wikipedia.org/wiki/Lp_space) function, so that the [integral](https://en.wikipedia.org/wiki/Antiderivative) $\int^{y}\mathrm{d}z\ E\psi(z)$ in eq. (1) is well-defined. 3. Note in particular that we do *not* assume that $\psi$ is continuous, cf. OP's title question. The following crucial question arises: How should we define the integral $$\int^{y}\mathrm{d}z\ V(z)\psi(z)\tag{3}$$ in eq. (1)? * Should we define (3) to be equal to $$V\_0\theta(y)\psi(0)+C,\tag{3'}$$ where $C$ is an integration constant? * Or if the [left and right limits](https://en.wikipedia.org/wiki/One-sided_limit) $\psi(0^-)$ and $\psi(0^+)$ exist, should we define (3) to be equal to $$V\_0\theta(y)\frac{\psi(0^-)+\psi(0^+)}{2}+C~?\tag{3''}$$ 4. Whatever definition we propose for the Dirac delta distribution, it seems likely that (3) will become a locally integrable function of $y$. 5. A mathematical bootstrap argument involving the TISE (1) then [shows](https://math.stackexchange.com/q/4335545/11127) that $\psi\in C(\mathbb{R})$ is continuous, cf. OP's title question. This conclusion is largely independent of how we defined (3). 6. See also e.g. my related Phys.SE answer [here](https://physics.stackexchange.com/a/19715/2451).
You can think of the delta potential $V(x)=g\delta(x)$ as representing the limiting form of a potential barrier (or well) of height $\Lambda$ and width $w$, with $w\Lambda=g$. For any finite $\Lambda$, $\psi(x)$ and $\psi’(x)$ must be continuous at both edges of the barrier. Within the barrier, Schrödinger’s equation implies that $\psi’’(x)\sim\Lambda$, so the total change in $\psi’(x)$ across the barrier is $\sim g$. This means that, in the limit $\Lambda\rightarrow\infty$ with $g$ fixed, $\psi’(x)$ is finite everywhere within the barrier, but changes by a finite amount from one side of the barrier to the other. Since $\psi’(x)$ is finite everywhere, $\psi(x)$ is continuous.
594,123
In 1d, for $V(x) = g\delta(x)$, integrating the TISE yields (assuming that $\psi$ is *bounded*$^\dagger$, so as to suppress the term containing $E$) $$ -\frac{\hbar^2}{2m} \left( \psi'(\varepsilon) - \psi'(-\varepsilon) \right) + g\psi(0) = 0 $$ for $\varepsilon\to0^+$. Now, this doesn't at all imply that $\psi$ has to be continuous (even though it is bounded) at $x=0$ (unlike the case when $V$ is bounded). But still, everywhere I've seen, it is implicitly assumed that $\psi$ is continuous at $x=0$, and eigenstates are derived using this. I can see that in the above equation, if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$—I could define it anything if it isn't continuous. Moreover, I am doubtful is the following equality for $\varepsilon>0$ (which was used in getting the above equation) is valid even when $\psi$ is discontinuous at $x=0$. $$ \int\_{-\varepsilon}^\varepsilon \delta(x)\psi(x)\; dx \stackrel{?}{=} \psi(0) $$ **Question:** If the above questioned equation is valid only for continuous $\psi$, is it "our desire" to exploit this equality so that we end up restricting the continuity of $\psi$ "by hand?" If so, what is the guarantee that there are not other kinds of solutions? --- $^\dagger$This *is* "put in by hand." Note: A [similar question](https://physics.stackexchange.com/q/218314/231957) was posted five years ago, but was never satisfactorily answered. So I post this again, with more details, hoping that it'll be clearly answered this time.
2020/11/15
[ "https://physics.stackexchange.com/questions/594123", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/231957/" ]
Well, let's carefully analyze the system: 1. Let us assume the integral form $$ \psi(x)~=~ \frac{2m}{\hbar^2} \int^{x}\mathrm{d}y \int^{y}\mathrm{d}z\ (V(z)-E)\psi(z) \tag{1}$$ of the time independent 1D [Schrödinger equation](http://en.wikipedia.org/wiki/Schr%C3%B6dinger_equation) (TISE), where the potential $$V(x)~=~V\_0\delta(x)\tag{2}$$ is a Dirac delta potential. 2. Let us assume that the wavefunction $\psi\in {\cal L}\_{\rm loc}^1(\mathbb{R})$ is a [locally](http://en.wikipedia.org/wiki/Locally_integrable_function) [integrable](http://en.wikipedia.org/wiki/Lp_space) function, so that the [integral](https://en.wikipedia.org/wiki/Antiderivative) $\int^{y}\mathrm{d}z\ E\psi(z)$ in eq. (1) is well-defined. 3. Note in particular that we do *not* assume that $\psi$ is continuous, cf. OP's title question. The following crucial question arises: How should we define the integral $$\int^{y}\mathrm{d}z\ V(z)\psi(z)\tag{3}$$ in eq. (1)? * Should we define (3) to be equal to $$V\_0\theta(y)\psi(0)+C,\tag{3'}$$ where $C$ is an integration constant? * Or if the [left and right limits](https://en.wikipedia.org/wiki/One-sided_limit) $\psi(0^-)$ and $\psi(0^+)$ exist, should we define (3) to be equal to $$V\_0\theta(y)\frac{\psi(0^-)+\psi(0^+)}{2}+C~?\tag{3''}$$ 4. Whatever definition we propose for the Dirac delta distribution, it seems likely that (3) will become a locally integrable function of $y$. 5. A mathematical bootstrap argument involving the TISE (1) then [shows](https://math.stackexchange.com/q/4335545/11127) that $\psi\in C(\mathbb{R})$ is continuous, cf. OP's title question. This conclusion is largely independent of how we defined (3). 6. See also e.g. my related Phys.SE answer [here](https://physics.stackexchange.com/a/19715/2451).
The other answers are very good. I want to address one mis-think in the question. > > "... if $\psi$ is discontinuous at $x=0$, then we'll have trouble writing $\psi(0)$ ..." > > > Not always. As a vast oversimplification, suppose that you have obtained $\psi$ as a Fourier transform, which has $\lim\_{x \rightarrow 0^-} \psi(x) = -1$ and $\lim\_{x \rightarrow 0^+} \psi(x) = 1$. Then we know $\psi(0) = 0$. At a step discontinuity, a Fourier series converges to the midpoint between the values to the left and right. (This is part of the [Dirichlet conditions](https://en.wikipedia.org/wiki/Dirichlet_conditions). There are mild technical hypotheses. The cited reference describes the real-valued version; the complex-valued version is essentially the same.)
59,315,909
I have a hangman game that almost works. The issue is that when I got all letters correct, YOU WIN message is not displayed until I click on a letter once more. I'll list only parts that I feel relevant. Game.js is a container. Game contains state: ``` state = { lives: 12, solution: 'my name is logan', correctUsedLetters: [], availableLetters: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'], usedLetters: [], solved: false }; ``` And many handlers including setSolvedHandler: ``` setSolvedHandler = () => { const solution = this.state.solution.replace(/\s/g, '').replace(/-/g, '').split(''); const compare = [ ...this.state.correctUsedLetters].sort(); const unique = solution.filter( (elem,index,self) => (index===self.indexOf(elem)) ).sort(); const solved = JSON.stringify(unique) === JSON.stringify(compare); this.setState({ solved: solved }); }; ``` This handler sets solved to true if correctUsedLetters match solution, in effect if the player has solved the puzzle. Also inside Game.js Letters is rendered: ``` <div className={classes.LettersAndHangman}> <Hangman lives={this.state.lives} /> <Letters setSolved={this.setSolvedHandler} solution={this.state.solution} correct={this.guessedCorrectHandler} incorrect={this.guessedIncorrectHandler} feed={this.state.availableLetters} /> </div> ``` Game.js calls on Letters so let's have a look at that. Letters.js has state called lettersMap that contains each letter of the alphabet with a boolean value indicating whether the letter has been clicked or not. ``` const [lettersMap, setLettersMap]=useState( { "a":false,"b":false,"c":false,"d":false,"e":false,"f":false,"g":false,"h":false,"i":false,"j":false,"k":false,"l":false,"m":false,"n":false,"o":false,"p":false,"q":false,"r":false,"s":false,"t":false,"u":false,"v":false,"w":false,"x":false,"y":false,"z":false } ); ``` It contains playHandler which tests whether the clicked letter is a correct one or not. But we'll skip this for now. More importantly, it contains updateClickedHandler which sets the boolean to true for the letter clicked. This updates the lettersMap. ``` const updateClickedHandler = (letter) => { setLettersMap( { ...lettersMap,[letter]:true } ); }; ``` Then two things are rendered from Letters.js. AvailableLetter and DisabledLetter. AvailableLetter represents a letter that has not been clicked. DisabledLetter represents a letter that has been clicked and now disabled from clicking again. ``` const renderedLetters = Object.keys(lettersMap).map( (letter,i)=>{ if (!lettersMap[letter]) //letter is not yet clicked { return ( <AvailableLetter updateClicked={updateClickedHandler} setSolved={props.setSolved} play={()=>playHandler(letter)} correct={()=>props.correct(letter)} incorrect={()=>props.incorrect(letter)} solution={props.solution} key={i} alphabet={letter} /> ) } else //letter is clicked { return ( <DisabledLetter alphabet={letter} key={i} /> ) } } ); ``` Here are codes for AvailableLetter and DisabledLetter: ``` const AvailableLetter = (props) => { const setStuff = () => { if (props.play()) { props.correct(); } else { props.incorrect(); } props.setSolved(); props.updateClicked(props.alphabet); }; return ( <Ax> <span className={classes.AvailableLetter} onClick={setStuff}>{props.alphabet}</span> </Ax> ); } ``` ``` const DisabledLetter = (props) => { return ( <span className={classes.DisabledLetter} >{props.alphabet}</span> ); }; ``` Now I'll introduce Model.js which displays messages YOU WIN or GAME OVER. ``` const modal = (props) => { let show = props.gameOver() || props.solved ? true : false; const attachedClasses = [ classes.Message ]; if (!show) { attachedClasses.push(classes.Hide); } return ( <div> <Backdrop show={show} /> <div className={attachedClasses.join(' ')} > {props.gameOver()?<p>GAME OVER</p>:null} {props.solved?<p>YOU WIN!</p>:null} </div> </div> ); }; ``` Investigating the code, the show becomes true if either game over or solved. This value is used to show/hide backdrop. It is also used to show/hide messages. Then depending on game over or solved you get appropriate message: GAME OVER or YOU WIN. I'm not sure yet what the root of the problem is, but the issue is that YOU WIN does not display even when the puzzle is solved until you click on one more letter(that doesn't do anything other than trigger the message). Currently, setSolved() is called inside AvailableLetter.js when span is clicked. It seems like effect of calling setSolved when a letter is clicked is somehow delayed. I'll try to construct the question succinctly as I can. Thank you for your patience. You can get complete source here: <https://github.com/gunitinug/hangmanclicked/tree/master/src>
2019/12/13
[ "https://Stackoverflow.com/questions/59315909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6656508/" ]
With minimal changes to your code, you can get it working. I think the problem is that you've used `split` rather than `replace` on the string: ``` def decimal(s): num = s dec_value = 0; base1 = 1; len1 = len(num); for x in range(len1 - 1, -1, -1): if (num[x] == '1'): dec_value += base1; base1 = base1 * 2; return dec_value num=list(input("Please input a binary sequence (comma separated every 4 digits):").replace(',','')) # only change to code is using .replace instead of .split print(num) print("The decimal integer of the number is:", (decimal(num))) ``` split is giving you a list of [10, 1011] (using your example), so the items in the list are ignored by your code (x is never equal to 1 - it's either 10 or 1011, in this case). replace gives you the list [1,0,1,0,1,1] which works with your function as written.
Try this ( pass a binary string in): ``` def seethat(hm): j=1 for c in range(0, len(hm)): if hm[c] == '0': j<<=1 else: j = (j<<1)-1 return j-1 ``` ``` seethat('10111') # 23 seethat('101011') # 43 ```
402,579
Under a translation in spacetime i.e., $$x\mapsto x^\prime=x+a,\tag{a}$$ a scalar field $\phi(x)$ $$\phi(x)\mapsto\phi^\prime(x)=\phi(x-a).\tag{b}$$ My aim is to verify the invariance of an action of the form $S[\phi(x)]=\int d^4x~ \phi^2(x)$. This [video](https://www.youtube.com/watch?v=8XeHlQcf3fc&t=1679s) by M. Luty shows the invariance (around time 17.40 minuties) as follows. $$\int d^4x~\phi^{2}(x)\mapsto\int d^4x~\phi^{\prime 2}(x)\tag{1}$$ $$=\int d^4x~\phi^{2}(x-a)\tag{2}.$$ Now by changing variables $x-a=y$, one has $$S[\phi(x)]\mapsto\int d^4y~\phi^2(y)=S[\phi(y)]\tag{3}$$ which readily establishes the invariance of the action. **Question** *I'm a bit confused about step (1). Since the coordinates also change shouldn't we also change $d^4x\to d^4x^\prime$ in step (1)? I know that differentials don't change by adding a constant to a variable. In fact, that's what is used in arriving at step (3) from step (2). But the step (1) looks like $\phi(x)$ is mapped to $\phi^\prime(x-a)$ and $x$ is mapped to $x$. I'm suspicious whether it is $d^4x$ or really $d^4x^\prime$ (which is in turn equal to $d^4x$) in step (1).* --- **$S\_2[\phi]$ of AFT's answer** Using (a) and (b), (when both the intergrand and $dx$ are changed) we get, $$S\_2[\phi]=\int x^2 \phi(x)^2 dx\mapsto \int (x+a)^2\phi(x-a)d(x+a)=\int (x+a)^2\phi(x-a)dx.$$ Changing variable $y=x-a$, I find $$S\_2[\phi]\mapsto \int(y+2a)^2\phi^2(y)dy\neq S\_2[\phi].$$ So it shows that even when $dx$ is changed to $dx^\prime$, the action is not translationally invariant. --- **References** 1. [A Modern Introduction to Quanrum Field Theory](https://books.google.co.in/books?id=yykTDAAAQBAJ&pg=PA47&lpg=PA47&dq=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&source=bl&ots=KAXp1oVaEw&sig=rrhvybZu2vcj1HWgGPNwTEDkYug&hl=en&sa=X&ved=0ahUKEwjG67On-e7aAhUKv48KHapdBzoQ6AEIKDAA#v=onepage&q=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&f=false) Eq. 3.19, 3.20 and 3.21. 2. [Field Quantization-W. Greiner](https://books.google.co.in/books?id=C-DVBAAAQBAJ&pg=PA41&lpg=PA41&dq=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&source=bl&ots=Ul21tFC_26&sig=xA6Ubc1We2KSg6Ou2mv28pc0PgA&hl=en&sa=X&ved=0ahUKEwizsuv37O7aAhUHLY8KHaJQD78Q6AEIKDAA#v=onepage&q=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&f=false) Eq. 2.38, 2.39, and 2.45. 3. [An introduction to Quantum Field theory- Peskin and Schroeder](https://books.google.co.in/books?id=_Q84DgAAQBAJ&pg=PT45&lpg=PT45&dq=noether%27s%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&source=bl&ots=yZmSlt2qi8&sig=eNMrbrc8_kZJuMFvigo4m6ce4vw&hl=en&sa=X&ved=0ahUKEwjC3bqw-u7aAhXIOY8KHYnpDBQQ6AEIKDAA#v=onepage&q=noether's%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&f=false) page 18. 4. [Lectures on Classical Field Theory by Suresh Govindrajan](https://www.youtube.com/watch?v=SY5JILTzYiY&list=PLbMVogVj5nJRYLTwyuusiiFchFU-WvElW) 5. [Lectures on Quantum Field Theory by Ashok Das](https://books.google.co.in/books?id=HFFkDQAAQBAJ&pg=PA212&lpg=PA212&dq=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&source=bl&ots=PFAqZ7q_Zz&sig=UZL_MGocmMLXkC1pFixrwHF1G_E&hl=en&sa=X&ved=0ahUKEwiFy6uF_u7aAhWJK48KHXE8AjQQ6AEIKDAA#v=onepage&q=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&f=false) page 212, Eq. 6.4 6. [Relativistic Quantum Physics-Tommy Ohlsson](https://books.google.co.in/books?id=hRavtAW5EFcC&pg=PA119&lpg=PA119&dq=to%20each%20continuous%20symmetry%20transformation%20of%20a%20local%20lagrangian%20tommy%20ohlsson&source=bl&ots=3ejGdWs9XF&sig=EfpbFY_5pge8wXJn8it_QwDtV9c&hl=en&sa=X&ved=0ahUKEwikxIvM_u7aAhUHTo8KHSBgD5wQ6AEIKDAA#v=onepage&q&f=false) Eq. 5.66, page 119. 7. [A first book on quantum field theory by P. B. Pal](https://books.google.co.in/books?id=_UmPP8Yr5mYC&pg=PA22&lpg=PA22&dq=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&source=bl&ots=tcSydVEb1I&sig=MNz8ili2s71R-ybjbniYP__Iezc&hl=en&sa=X&ved=0ahUKEwjY673x_-7aAhUEMY8KHc7yAQ8Q6AEINjAB#v=onepage&q=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&f=false) Page 22, Eq. 2.38.
2018/04/28
[ "https://physics.stackexchange.com/questions/402579", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/36793/" ]
Perhaps the most clear way to see what's going on is to compare the action $$ S\_1[\phi]=\int\_{\mathbb R^d} \phi(x)^2\mathrm dx\tag1 $$ to the action $$ S\_2[\phi]=\int\_{\mathbb R^d} x^2\phi(x)^2\mathrm dx\tag2 $$ The first one should be invariant under translations, while the second one should not. We define the translation operator $T\_a\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $a\in\mathbb R^d$, as (ref.1) $$ (T\_a\phi)(x):=\phi(x-a)\tag3 $$ With this, an action is invariant under translations if and only if $$ S[T\_a\phi]\equiv S[\phi],\quad\forall a\in\mathbb R^d\tag4 $$ What follows is a standard textbook exercise: $$ S\_1[T\_a\phi]\overset{(1)}=\int\_{\mathbb R^d} (T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} \phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} \phi(y)^2\mathrm dy=S\_1[\phi]\tag5 $$ and $$ S\_2[T\_a\phi]\overset{(2)}=\int\_{\mathbb R^d} x^2(T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} x^2\phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} (y+a)^2\phi(y)^2\mathrm dy\neq S[\phi]\tag6 $$ where in both cases we defined $y:=x-a$. This is the expected result: $S\_1$ is translation invariant, and $S\_2$ is not. Note that a very similar computation shows that both $S\_1$ and $S\_2$ are invariant under *Lorentz transformations* $T\_\Lambda\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $\Lambda\in\mathrm{SO}(1,d-1)$, defined in the obvious way: $(T\_\Lambda\phi)(x):=\phi(\Lambda x)$. Here, and as before, it proves essential that $\mathrm dx$ is Poincaré invariant (indeed, it's the Haar measure of $\mathrm{ISO}(1,d-1)$), and that $x\mapsto \Lambda x+a$ is one-to-one over the integration region, $\mathbb R^d$. But this doesn't mean that $\mathrm dx$ *transforms* under $T\_a,T\_\Lambda$. Symmetry transformations are defined at the level of the field $\phi$, with no reference to $\mathrm dx$. Indeed, the definition of invariance $S[T\phi]=S[\phi]$ is quite general, and it is not limited to local functionals: $S[\phi]$ could be *any* functional, not necessarily given by an integral. The volume form $\mathrm dx$ doesn't transform under symmetry operations1, and neither does $x$. The "arrows and primes" notation $\phi\to\phi'$ can be ambiguous and imprecise. If you stick to well-defined operations, the picture is rather clear. In any case, and not to be mislead to think that invariance of the measure is necessary and/or sufficient for invariance of $S$, the reader should consider other symmetry transformations, such as: internal symmetries (e.g., the $\mathbb Z\_2$ transformation $(T\phi)(x):=-\phi(x)$), and non-isometric external symmetries (i.e., conformal transformations). The simplest example of a conformal transformation is the dilatation $$ (T\_\lambda\phi)(x):=\lambda^\Delta\phi(\lambda x)\tag7 $$ with $\lambda\in\mathbb R$. The canonical example of a dilatation-invariant theory is $$ S\_3[\phi]=\int\_{\mathbb R^d} \frac12(\partial\_x\phi(x))^2-\frac{1}{n!}\phi(x)^n\ \mathrm dx\tag8 $$ which satisfies $$ \begin{aligned} S\_3[T\_\lambda\phi]&\overset{(8)}=\int\_{\mathbb R^d} \frac12(\partial\_x(T\_\lambda\phi)(x))^2-\frac{1}{n!}(T\_\lambda\phi)(x)^n\ \mathrm dx\\ &\overset{(7)}=\int\_{\mathbb R^d} \frac12\lambda^{2(\Delta+1)-d}(\partial\_y\phi(y))^2-\lambda^{n\Delta-d}\frac{1}{n!}\phi(y)^n\ \mathrm dy \end{aligned}\tag9 $$ where I set $y:=\lambda x$. This equals $S\_3[\phi]$ iff $2(\Delta+1)=n\Delta=d$, that is, $\Delta=(d-2)/2$ and $n=2d/(d-2)$ (which, for $d=4$, becomes $\Delta=1$ and $n=4$; i.e., $\phi^4$ theory in four space-time dimensions is scale invariant, as is well-known; more generally, $n$ is an integer only in $d=3,4,6$ space-time dimensions). -- More generally, let $\phi\colon\mathbb R^d\to V$, with $V$ a finite-dimensional vector space. We say $T\in\mathrm{End}(\mathscr C(\mathbb R^d,V))$ is a symmetry of a functional $S\colon\mathscr C(\mathbb R^d,V)\to\mathbb R$ if $$ S[T\phi]=S[\phi],\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{10} $$ It is typically the case that symmetry transformations are coordinatised by some manifold $\mathcal M$, so that $T\colon\mathcal M\to \mathrm{End}(\mathscr C(\mathbb R^d,V))$. Moreover, we assume that $T\_0=1$, with $0\in\mathcal M$ the origin of $\mathcal M$ and $1$ the identity transformation. In this case, there is a weaker notion of symmetry: we say $S$ is quasi-invariant under $T$ if the directional derivative of $S[T\_x\phi]$ vanishes at the origin of $\mathcal M$: $$ \lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}S[T\_{vt}\phi]=0,\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{11} $$ for some $v\in\mathrm T\_0\mathcal M$. The pushforward (differential) of $T$ at the origin is usually denoted by $\delta$: $$ \delta\_v=\lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}T\_{vt}\tag{12} $$ with components $\delta\_v=v^a\delta\_a$, with $a=1,2,\dots,\dim\mathcal M$. Quasi-invariance is therefore equivalent to $$ 0=S[\phi+t\delta\_v\phi]-S[\phi]=tS'[\phi]\cdot\delta\_v\phi+\mathcal O(t^2)\tag{13} $$ where $\cdot$ denotes summation-integration, and $'$ denotes a functional derivative. Noether's first theorem is precisely the statement that there is a current for every quasi-symmetry of $S$, which is divergenceless whenever $\phi$ satisfies $S'[\phi]\equiv 0$. Finally, it bears mentioning that usually $\mathcal M$ is a homogeneous space for some Lie group $G$; in which case we say that $S$ is invariant under $G$. If $G$ is connected and compact, then we can reconstruct it from its algebra $\mathfrak g=\mathrm T\_1G$ by means of the exponential map. This algebra is generated by $\delta$, and therefore quasi-symmetry implies symmetry, and vice-versa. If $\exp$ is not surjective, then quasi-symmetry is truly weaker than symmetry. **References:** 1. Bogolubov, Logunov, Oksak, Todorov - General principles of quantum field theory, §7.1.C. --- 1: Here we are advocating for a *passive* point of view, as opposed to an *active* one. Internal transformations are always passive, so it is convenient to regard external ones as passive to, so as to have a uniform framework. It appears that the books OP is following introduce a mixed point of view, where both the fields *and* the spacetime point are allowed to vary, if somewhat redundantly. The passive point of view is, IMHO, the most general and clear one, and the one most people use nowadays.
Adding a constant does not change the differential, so $d^4x'=d^4x$
402,579
Under a translation in spacetime i.e., $$x\mapsto x^\prime=x+a,\tag{a}$$ a scalar field $\phi(x)$ $$\phi(x)\mapsto\phi^\prime(x)=\phi(x-a).\tag{b}$$ My aim is to verify the invariance of an action of the form $S[\phi(x)]=\int d^4x~ \phi^2(x)$. This [video](https://www.youtube.com/watch?v=8XeHlQcf3fc&t=1679s) by M. Luty shows the invariance (around time 17.40 minuties) as follows. $$\int d^4x~\phi^{2}(x)\mapsto\int d^4x~\phi^{\prime 2}(x)\tag{1}$$ $$=\int d^4x~\phi^{2}(x-a)\tag{2}.$$ Now by changing variables $x-a=y$, one has $$S[\phi(x)]\mapsto\int d^4y~\phi^2(y)=S[\phi(y)]\tag{3}$$ which readily establishes the invariance of the action. **Question** *I'm a bit confused about step (1). Since the coordinates also change shouldn't we also change $d^4x\to d^4x^\prime$ in step (1)? I know that differentials don't change by adding a constant to a variable. In fact, that's what is used in arriving at step (3) from step (2). But the step (1) looks like $\phi(x)$ is mapped to $\phi^\prime(x-a)$ and $x$ is mapped to $x$. I'm suspicious whether it is $d^4x$ or really $d^4x^\prime$ (which is in turn equal to $d^4x$) in step (1).* --- **$S\_2[\phi]$ of AFT's answer** Using (a) and (b), (when both the intergrand and $dx$ are changed) we get, $$S\_2[\phi]=\int x^2 \phi(x)^2 dx\mapsto \int (x+a)^2\phi(x-a)d(x+a)=\int (x+a)^2\phi(x-a)dx.$$ Changing variable $y=x-a$, I find $$S\_2[\phi]\mapsto \int(y+2a)^2\phi^2(y)dy\neq S\_2[\phi].$$ So it shows that even when $dx$ is changed to $dx^\prime$, the action is not translationally invariant. --- **References** 1. [A Modern Introduction to Quanrum Field Theory](https://books.google.co.in/books?id=yykTDAAAQBAJ&pg=PA47&lpg=PA47&dq=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&source=bl&ots=KAXp1oVaEw&sig=rrhvybZu2vcj1HWgGPNwTEDkYug&hl=en&sa=X&ved=0ahUKEwjG67On-e7aAhUKv48KHapdBzoQ6AEIKDAA#v=onepage&q=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&f=false) Eq. 3.19, 3.20 and 3.21. 2. [Field Quantization-W. Greiner](https://books.google.co.in/books?id=C-DVBAAAQBAJ&pg=PA41&lpg=PA41&dq=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&source=bl&ots=Ul21tFC_26&sig=xA6Ubc1We2KSg6Ou2mv28pc0PgA&hl=en&sa=X&ved=0ahUKEwizsuv37O7aAhUHLY8KHaJQD78Q6AEIKDAA#v=onepage&q=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&f=false) Eq. 2.38, 2.39, and 2.45. 3. [An introduction to Quantum Field theory- Peskin and Schroeder](https://books.google.co.in/books?id=_Q84DgAAQBAJ&pg=PT45&lpg=PT45&dq=noether%27s%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&source=bl&ots=yZmSlt2qi8&sig=eNMrbrc8_kZJuMFvigo4m6ce4vw&hl=en&sa=X&ved=0ahUKEwjC3bqw-u7aAhXIOY8KHYnpDBQQ6AEIKDAA#v=onepage&q=noether's%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&f=false) page 18. 4. [Lectures on Classical Field Theory by Suresh Govindrajan](https://www.youtube.com/watch?v=SY5JILTzYiY&list=PLbMVogVj5nJRYLTwyuusiiFchFU-WvElW) 5. [Lectures on Quantum Field Theory by Ashok Das](https://books.google.co.in/books?id=HFFkDQAAQBAJ&pg=PA212&lpg=PA212&dq=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&source=bl&ots=PFAqZ7q_Zz&sig=UZL_MGocmMLXkC1pFixrwHF1G_E&hl=en&sa=X&ved=0ahUKEwiFy6uF_u7aAhWJK48KHXE8AjQQ6AEIKDAA#v=onepage&q=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&f=false) page 212, Eq. 6.4 6. [Relativistic Quantum Physics-Tommy Ohlsson](https://books.google.co.in/books?id=hRavtAW5EFcC&pg=PA119&lpg=PA119&dq=to%20each%20continuous%20symmetry%20transformation%20of%20a%20local%20lagrangian%20tommy%20ohlsson&source=bl&ots=3ejGdWs9XF&sig=EfpbFY_5pge8wXJn8it_QwDtV9c&hl=en&sa=X&ved=0ahUKEwikxIvM_u7aAhUHTo8KHSBgD5wQ6AEIKDAA#v=onepage&q&f=false) Eq. 5.66, page 119. 7. [A first book on quantum field theory by P. B. Pal](https://books.google.co.in/books?id=_UmPP8Yr5mYC&pg=PA22&lpg=PA22&dq=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&source=bl&ots=tcSydVEb1I&sig=MNz8ili2s71R-ybjbniYP__Iezc&hl=en&sa=X&ved=0ahUKEwjY673x_-7aAhUEMY8KHc7yAQ8Q6AEINjAB#v=onepage&q=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&f=false) Page 22, Eq. 2.38.
2018/04/28
[ "https://physics.stackexchange.com/questions/402579", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/36793/" ]
Adding a constant does not change the differential, so $d^4x'=d^4x$
It looks like you are getting too caught up in the *notation* and the *formalism* of it all. In this case the notation is not what is important, what is more important is the concept. The concept may be easier to understand if you think about what the statement regarding the action means in one dimensional space rather than in four dimensional space-time. What is meant is that the total area under a curve in the x-y plane doesn't change if you slide the curve back and forth along the x-axis. In order to show that this is true more formally, you want replace "under the integral sign" a curve $f(x)$ by a different curve $g(x)$, where the curve g looks exactly like the curve f was grabbed and slid over to the right (along the x-axis) by an amount $a$. Well, obviously the two integrals are going to be equal if we are integrating from $x=-\infty$ to $x=+\infty$, right? This is all that is meant by the statement that the action is invariant under this transformation. In the original problem the curve $f$ is called $\phi^2$. The fact that the function is squared does not matter for this proof. If could be any function.
402,579
Under a translation in spacetime i.e., $$x\mapsto x^\prime=x+a,\tag{a}$$ a scalar field $\phi(x)$ $$\phi(x)\mapsto\phi^\prime(x)=\phi(x-a).\tag{b}$$ My aim is to verify the invariance of an action of the form $S[\phi(x)]=\int d^4x~ \phi^2(x)$. This [video](https://www.youtube.com/watch?v=8XeHlQcf3fc&t=1679s) by M. Luty shows the invariance (around time 17.40 minuties) as follows. $$\int d^4x~\phi^{2}(x)\mapsto\int d^4x~\phi^{\prime 2}(x)\tag{1}$$ $$=\int d^4x~\phi^{2}(x-a)\tag{2}.$$ Now by changing variables $x-a=y$, one has $$S[\phi(x)]\mapsto\int d^4y~\phi^2(y)=S[\phi(y)]\tag{3}$$ which readily establishes the invariance of the action. **Question** *I'm a bit confused about step (1). Since the coordinates also change shouldn't we also change $d^4x\to d^4x^\prime$ in step (1)? I know that differentials don't change by adding a constant to a variable. In fact, that's what is used in arriving at step (3) from step (2). But the step (1) looks like $\phi(x)$ is mapped to $\phi^\prime(x-a)$ and $x$ is mapped to $x$. I'm suspicious whether it is $d^4x$ or really $d^4x^\prime$ (which is in turn equal to $d^4x$) in step (1).* --- **$S\_2[\phi]$ of AFT's answer** Using (a) and (b), (when both the intergrand and $dx$ are changed) we get, $$S\_2[\phi]=\int x^2 \phi(x)^2 dx\mapsto \int (x+a)^2\phi(x-a)d(x+a)=\int (x+a)^2\phi(x-a)dx.$$ Changing variable $y=x-a$, I find $$S\_2[\phi]\mapsto \int(y+2a)^2\phi^2(y)dy\neq S\_2[\phi].$$ So it shows that even when $dx$ is changed to $dx^\prime$, the action is not translationally invariant. --- **References** 1. [A Modern Introduction to Quanrum Field Theory](https://books.google.co.in/books?id=yykTDAAAQBAJ&pg=PA47&lpg=PA47&dq=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&source=bl&ots=KAXp1oVaEw&sig=rrhvybZu2vcj1HWgGPNwTEDkYug&hl=en&sa=X&ved=0ahUKEwjG67On-e7aAhUKv48KHapdBzoQ6AEIKDAA#v=onepage&q=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&f=false) Eq. 3.19, 3.20 and 3.21. 2. [Field Quantization-W. Greiner](https://books.google.co.in/books?id=C-DVBAAAQBAJ&pg=PA41&lpg=PA41&dq=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&source=bl&ots=Ul21tFC_26&sig=xA6Ubc1We2KSg6Ou2mv28pc0PgA&hl=en&sa=X&ved=0ahUKEwizsuv37O7aAhUHLY8KHaJQD78Q6AEIKDAA#v=onepage&q=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&f=false) Eq. 2.38, 2.39, and 2.45. 3. [An introduction to Quantum Field theory- Peskin and Schroeder](https://books.google.co.in/books?id=_Q84DgAAQBAJ&pg=PT45&lpg=PT45&dq=noether%27s%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&source=bl&ots=yZmSlt2qi8&sig=eNMrbrc8_kZJuMFvigo4m6ce4vw&hl=en&sa=X&ved=0ahUKEwjC3bqw-u7aAhXIOY8KHYnpDBQQ6AEIKDAA#v=onepage&q=noether's%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&f=false) page 18. 4. [Lectures on Classical Field Theory by Suresh Govindrajan](https://www.youtube.com/watch?v=SY5JILTzYiY&list=PLbMVogVj5nJRYLTwyuusiiFchFU-WvElW) 5. [Lectures on Quantum Field Theory by Ashok Das](https://books.google.co.in/books?id=HFFkDQAAQBAJ&pg=PA212&lpg=PA212&dq=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&source=bl&ots=PFAqZ7q_Zz&sig=UZL_MGocmMLXkC1pFixrwHF1G_E&hl=en&sa=X&ved=0ahUKEwiFy6uF_u7aAhWJK48KHXE8AjQQ6AEIKDAA#v=onepage&q=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&f=false) page 212, Eq. 6.4 6. [Relativistic Quantum Physics-Tommy Ohlsson](https://books.google.co.in/books?id=hRavtAW5EFcC&pg=PA119&lpg=PA119&dq=to%20each%20continuous%20symmetry%20transformation%20of%20a%20local%20lagrangian%20tommy%20ohlsson&source=bl&ots=3ejGdWs9XF&sig=EfpbFY_5pge8wXJn8it_QwDtV9c&hl=en&sa=X&ved=0ahUKEwikxIvM_u7aAhUHTo8KHSBgD5wQ6AEIKDAA#v=onepage&q&f=false) Eq. 5.66, page 119. 7. [A first book on quantum field theory by P. B. Pal](https://books.google.co.in/books?id=_UmPP8Yr5mYC&pg=PA22&lpg=PA22&dq=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&source=bl&ots=tcSydVEb1I&sig=MNz8ili2s71R-ybjbniYP__Iezc&hl=en&sa=X&ved=0ahUKEwjY673x_-7aAhUEMY8KHc7yAQ8Q6AEINjAB#v=onepage&q=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&f=false) Page 22, Eq. 2.38.
2018/04/28
[ "https://physics.stackexchange.com/questions/402579", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/36793/" ]
Perhaps the most clear way to see what's going on is to compare the action $$ S\_1[\phi]=\int\_{\mathbb R^d} \phi(x)^2\mathrm dx\tag1 $$ to the action $$ S\_2[\phi]=\int\_{\mathbb R^d} x^2\phi(x)^2\mathrm dx\tag2 $$ The first one should be invariant under translations, while the second one should not. We define the translation operator $T\_a\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $a\in\mathbb R^d$, as (ref.1) $$ (T\_a\phi)(x):=\phi(x-a)\tag3 $$ With this, an action is invariant under translations if and only if $$ S[T\_a\phi]\equiv S[\phi],\quad\forall a\in\mathbb R^d\tag4 $$ What follows is a standard textbook exercise: $$ S\_1[T\_a\phi]\overset{(1)}=\int\_{\mathbb R^d} (T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} \phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} \phi(y)^2\mathrm dy=S\_1[\phi]\tag5 $$ and $$ S\_2[T\_a\phi]\overset{(2)}=\int\_{\mathbb R^d} x^2(T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} x^2\phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} (y+a)^2\phi(y)^2\mathrm dy\neq S[\phi]\tag6 $$ where in both cases we defined $y:=x-a$. This is the expected result: $S\_1$ is translation invariant, and $S\_2$ is not. Note that a very similar computation shows that both $S\_1$ and $S\_2$ are invariant under *Lorentz transformations* $T\_\Lambda\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $\Lambda\in\mathrm{SO}(1,d-1)$, defined in the obvious way: $(T\_\Lambda\phi)(x):=\phi(\Lambda x)$. Here, and as before, it proves essential that $\mathrm dx$ is Poincaré invariant (indeed, it's the Haar measure of $\mathrm{ISO}(1,d-1)$), and that $x\mapsto \Lambda x+a$ is one-to-one over the integration region, $\mathbb R^d$. But this doesn't mean that $\mathrm dx$ *transforms* under $T\_a,T\_\Lambda$. Symmetry transformations are defined at the level of the field $\phi$, with no reference to $\mathrm dx$. Indeed, the definition of invariance $S[T\phi]=S[\phi]$ is quite general, and it is not limited to local functionals: $S[\phi]$ could be *any* functional, not necessarily given by an integral. The volume form $\mathrm dx$ doesn't transform under symmetry operations1, and neither does $x$. The "arrows and primes" notation $\phi\to\phi'$ can be ambiguous and imprecise. If you stick to well-defined operations, the picture is rather clear. In any case, and not to be mislead to think that invariance of the measure is necessary and/or sufficient for invariance of $S$, the reader should consider other symmetry transformations, such as: internal symmetries (e.g., the $\mathbb Z\_2$ transformation $(T\phi)(x):=-\phi(x)$), and non-isometric external symmetries (i.e., conformal transformations). The simplest example of a conformal transformation is the dilatation $$ (T\_\lambda\phi)(x):=\lambda^\Delta\phi(\lambda x)\tag7 $$ with $\lambda\in\mathbb R$. The canonical example of a dilatation-invariant theory is $$ S\_3[\phi]=\int\_{\mathbb R^d} \frac12(\partial\_x\phi(x))^2-\frac{1}{n!}\phi(x)^n\ \mathrm dx\tag8 $$ which satisfies $$ \begin{aligned} S\_3[T\_\lambda\phi]&\overset{(8)}=\int\_{\mathbb R^d} \frac12(\partial\_x(T\_\lambda\phi)(x))^2-\frac{1}{n!}(T\_\lambda\phi)(x)^n\ \mathrm dx\\ &\overset{(7)}=\int\_{\mathbb R^d} \frac12\lambda^{2(\Delta+1)-d}(\partial\_y\phi(y))^2-\lambda^{n\Delta-d}\frac{1}{n!}\phi(y)^n\ \mathrm dy \end{aligned}\tag9 $$ where I set $y:=\lambda x$. This equals $S\_3[\phi]$ iff $2(\Delta+1)=n\Delta=d$, that is, $\Delta=(d-2)/2$ and $n=2d/(d-2)$ (which, for $d=4$, becomes $\Delta=1$ and $n=4$; i.e., $\phi^4$ theory in four space-time dimensions is scale invariant, as is well-known; more generally, $n$ is an integer only in $d=3,4,6$ space-time dimensions). -- More generally, let $\phi\colon\mathbb R^d\to V$, with $V$ a finite-dimensional vector space. We say $T\in\mathrm{End}(\mathscr C(\mathbb R^d,V))$ is a symmetry of a functional $S\colon\mathscr C(\mathbb R^d,V)\to\mathbb R$ if $$ S[T\phi]=S[\phi],\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{10} $$ It is typically the case that symmetry transformations are coordinatised by some manifold $\mathcal M$, so that $T\colon\mathcal M\to \mathrm{End}(\mathscr C(\mathbb R^d,V))$. Moreover, we assume that $T\_0=1$, with $0\in\mathcal M$ the origin of $\mathcal M$ and $1$ the identity transformation. In this case, there is a weaker notion of symmetry: we say $S$ is quasi-invariant under $T$ if the directional derivative of $S[T\_x\phi]$ vanishes at the origin of $\mathcal M$: $$ \lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}S[T\_{vt}\phi]=0,\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{11} $$ for some $v\in\mathrm T\_0\mathcal M$. The pushforward (differential) of $T$ at the origin is usually denoted by $\delta$: $$ \delta\_v=\lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}T\_{vt}\tag{12} $$ with components $\delta\_v=v^a\delta\_a$, with $a=1,2,\dots,\dim\mathcal M$. Quasi-invariance is therefore equivalent to $$ 0=S[\phi+t\delta\_v\phi]-S[\phi]=tS'[\phi]\cdot\delta\_v\phi+\mathcal O(t^2)\tag{13} $$ where $\cdot$ denotes summation-integration, and $'$ denotes a functional derivative. Noether's first theorem is precisely the statement that there is a current for every quasi-symmetry of $S$, which is divergenceless whenever $\phi$ satisfies $S'[\phi]\equiv 0$. Finally, it bears mentioning that usually $\mathcal M$ is a homogeneous space for some Lie group $G$; in which case we say that $S$ is invariant under $G$. If $G$ is connected and compact, then we can reconstruct it from its algebra $\mathfrak g=\mathrm T\_1G$ by means of the exponential map. This algebra is generated by $\delta$, and therefore quasi-symmetry implies symmetry, and vice-versa. If $\exp$ is not surjective, then quasi-symmetry is truly weaker than symmetry. **References:** 1. Bogolubov, Logunov, Oksak, Todorov - General principles of quantum field theory, §7.1.C. --- 1: Here we are advocating for a *passive* point of view, as opposed to an *active* one. Internal transformations are always passive, so it is convenient to regard external ones as passive to, so as to have a uniform framework. It appears that the books OP is following introduce a mixed point of view, where both the fields *and* the spacetime point are allowed to vary, if somewhat redundantly. The passive point of view is, IMHO, the most general and clear one, and the one most people use nowadays.
If you would change $d^4x$ for $d^4x'$, you would just apply the substitution theorem, and you wouldn't say anything about translation invariance (you could see it as evaluating the same integral after reordering the terms in the Riemann sums). This is true also for non-translation invariant expressions. $\phi$ is your physical state. $\phi'$ is a different state, not the same state written differently. It is related by a translation: the value of $\phi$ at $x$ is the same as the value of $\phi'$ at $x - a$. Now the action for this *different* state $\phi'$ is the same integral expression, but now evaluated in $\phi'$. *Then* you use the explicit relation between $\phi$ and $\phi'$ to express the same expression in terms of $\phi$ and *now* you do use the substitution theorem (which here essentially just is the translation invariance of the volume form $d^4x$) to conclude that the action of $\phi$ and $\phi'$ are the same if they are related by a translation.
402,579
Under a translation in spacetime i.e., $$x\mapsto x^\prime=x+a,\tag{a}$$ a scalar field $\phi(x)$ $$\phi(x)\mapsto\phi^\prime(x)=\phi(x-a).\tag{b}$$ My aim is to verify the invariance of an action of the form $S[\phi(x)]=\int d^4x~ \phi^2(x)$. This [video](https://www.youtube.com/watch?v=8XeHlQcf3fc&t=1679s) by M. Luty shows the invariance (around time 17.40 minuties) as follows. $$\int d^4x~\phi^{2}(x)\mapsto\int d^4x~\phi^{\prime 2}(x)\tag{1}$$ $$=\int d^4x~\phi^{2}(x-a)\tag{2}.$$ Now by changing variables $x-a=y$, one has $$S[\phi(x)]\mapsto\int d^4y~\phi^2(y)=S[\phi(y)]\tag{3}$$ which readily establishes the invariance of the action. **Question** *I'm a bit confused about step (1). Since the coordinates also change shouldn't we also change $d^4x\to d^4x^\prime$ in step (1)? I know that differentials don't change by adding a constant to a variable. In fact, that's what is used in arriving at step (3) from step (2). But the step (1) looks like $\phi(x)$ is mapped to $\phi^\prime(x-a)$ and $x$ is mapped to $x$. I'm suspicious whether it is $d^4x$ or really $d^4x^\prime$ (which is in turn equal to $d^4x$) in step (1).* --- **$S\_2[\phi]$ of AFT's answer** Using (a) and (b), (when both the intergrand and $dx$ are changed) we get, $$S\_2[\phi]=\int x^2 \phi(x)^2 dx\mapsto \int (x+a)^2\phi(x-a)d(x+a)=\int (x+a)^2\phi(x-a)dx.$$ Changing variable $y=x-a$, I find $$S\_2[\phi]\mapsto \int(y+2a)^2\phi^2(y)dy\neq S\_2[\phi].$$ So it shows that even when $dx$ is changed to $dx^\prime$, the action is not translationally invariant. --- **References** 1. [A Modern Introduction to Quanrum Field Theory](https://books.google.co.in/books?id=yykTDAAAQBAJ&pg=PA47&lpg=PA47&dq=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&source=bl&ots=KAXp1oVaEw&sig=rrhvybZu2vcj1HWgGPNwTEDkYug&hl=en&sa=X&ved=0ahUKEwjG67On-e7aAhUKv48KHapdBzoQ6AEIKDAA#v=onepage&q=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&f=false) Eq. 3.19, 3.20 and 3.21. 2. [Field Quantization-W. Greiner](https://books.google.co.in/books?id=C-DVBAAAQBAJ&pg=PA41&lpg=PA41&dq=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&source=bl&ots=Ul21tFC_26&sig=xA6Ubc1We2KSg6Ou2mv28pc0PgA&hl=en&sa=X&ved=0ahUKEwizsuv37O7aAhUHLY8KHaJQD78Q6AEIKDAA#v=onepage&q=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&f=false) Eq. 2.38, 2.39, and 2.45. 3. [An introduction to Quantum Field theory- Peskin and Schroeder](https://books.google.co.in/books?id=_Q84DgAAQBAJ&pg=PT45&lpg=PT45&dq=noether%27s%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&source=bl&ots=yZmSlt2qi8&sig=eNMrbrc8_kZJuMFvigo4m6ce4vw&hl=en&sa=X&ved=0ahUKEwjC3bqw-u7aAhXIOY8KHYnpDBQQ6AEIKDAA#v=onepage&q=noether's%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&f=false) page 18. 4. [Lectures on Classical Field Theory by Suresh Govindrajan](https://www.youtube.com/watch?v=SY5JILTzYiY&list=PLbMVogVj5nJRYLTwyuusiiFchFU-WvElW) 5. [Lectures on Quantum Field Theory by Ashok Das](https://books.google.co.in/books?id=HFFkDQAAQBAJ&pg=PA212&lpg=PA212&dq=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&source=bl&ots=PFAqZ7q_Zz&sig=UZL_MGocmMLXkC1pFixrwHF1G_E&hl=en&sa=X&ved=0ahUKEwiFy6uF_u7aAhWJK48KHXE8AjQQ6AEIKDAA#v=onepage&q=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&f=false) page 212, Eq. 6.4 6. [Relativistic Quantum Physics-Tommy Ohlsson](https://books.google.co.in/books?id=hRavtAW5EFcC&pg=PA119&lpg=PA119&dq=to%20each%20continuous%20symmetry%20transformation%20of%20a%20local%20lagrangian%20tommy%20ohlsson&source=bl&ots=3ejGdWs9XF&sig=EfpbFY_5pge8wXJn8it_QwDtV9c&hl=en&sa=X&ved=0ahUKEwikxIvM_u7aAhUHTo8KHSBgD5wQ6AEIKDAA#v=onepage&q&f=false) Eq. 5.66, page 119. 7. [A first book on quantum field theory by P. B. Pal](https://books.google.co.in/books?id=_UmPP8Yr5mYC&pg=PA22&lpg=PA22&dq=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&source=bl&ots=tcSydVEb1I&sig=MNz8ili2s71R-ybjbniYP__Iezc&hl=en&sa=X&ved=0ahUKEwjY673x_-7aAhUEMY8KHc7yAQ8Q6AEINjAB#v=onepage&q=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&f=false) Page 22, Eq. 2.38.
2018/04/28
[ "https://physics.stackexchange.com/questions/402579", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/36793/" ]
If you would change $d^4x$ for $d^4x'$, you would just apply the substitution theorem, and you wouldn't say anything about translation invariance (you could see it as evaluating the same integral after reordering the terms in the Riemann sums). This is true also for non-translation invariant expressions. $\phi$ is your physical state. $\phi'$ is a different state, not the same state written differently. It is related by a translation: the value of $\phi$ at $x$ is the same as the value of $\phi'$ at $x - a$. Now the action for this *different* state $\phi'$ is the same integral expression, but now evaluated in $\phi'$. *Then* you use the explicit relation between $\phi$ and $\phi'$ to express the same expression in terms of $\phi$ and *now* you do use the substitution theorem (which here essentially just is the translation invariance of the volume form $d^4x$) to conclude that the action of $\phi$ and $\phi'$ are the same if they are related by a translation.
It looks like you are getting too caught up in the *notation* and the *formalism* of it all. In this case the notation is not what is important, what is more important is the concept. The concept may be easier to understand if you think about what the statement regarding the action means in one dimensional space rather than in four dimensional space-time. What is meant is that the total area under a curve in the x-y plane doesn't change if you slide the curve back and forth along the x-axis. In order to show that this is true more formally, you want replace "under the integral sign" a curve $f(x)$ by a different curve $g(x)$, where the curve g looks exactly like the curve f was grabbed and slid over to the right (along the x-axis) by an amount $a$. Well, obviously the two integrals are going to be equal if we are integrating from $x=-\infty$ to $x=+\infty$, right? This is all that is meant by the statement that the action is invariant under this transformation. In the original problem the curve $f$ is called $\phi^2$. The fact that the function is squared does not matter for this proof. If could be any function.
402,579
Under a translation in spacetime i.e., $$x\mapsto x^\prime=x+a,\tag{a}$$ a scalar field $\phi(x)$ $$\phi(x)\mapsto\phi^\prime(x)=\phi(x-a).\tag{b}$$ My aim is to verify the invariance of an action of the form $S[\phi(x)]=\int d^4x~ \phi^2(x)$. This [video](https://www.youtube.com/watch?v=8XeHlQcf3fc&t=1679s) by M. Luty shows the invariance (around time 17.40 minuties) as follows. $$\int d^4x~\phi^{2}(x)\mapsto\int d^4x~\phi^{\prime 2}(x)\tag{1}$$ $$=\int d^4x~\phi^{2}(x-a)\tag{2}.$$ Now by changing variables $x-a=y$, one has $$S[\phi(x)]\mapsto\int d^4y~\phi^2(y)=S[\phi(y)]\tag{3}$$ which readily establishes the invariance of the action. **Question** *I'm a bit confused about step (1). Since the coordinates also change shouldn't we also change $d^4x\to d^4x^\prime$ in step (1)? I know that differentials don't change by adding a constant to a variable. In fact, that's what is used in arriving at step (3) from step (2). But the step (1) looks like $\phi(x)$ is mapped to $\phi^\prime(x-a)$ and $x$ is mapped to $x$. I'm suspicious whether it is $d^4x$ or really $d^4x^\prime$ (which is in turn equal to $d^4x$) in step (1).* --- **$S\_2[\phi]$ of AFT's answer** Using (a) and (b), (when both the intergrand and $dx$ are changed) we get, $$S\_2[\phi]=\int x^2 \phi(x)^2 dx\mapsto \int (x+a)^2\phi(x-a)d(x+a)=\int (x+a)^2\phi(x-a)dx.$$ Changing variable $y=x-a$, I find $$S\_2[\phi]\mapsto \int(y+2a)^2\phi^2(y)dy\neq S\_2[\phi].$$ So it shows that even when $dx$ is changed to $dx^\prime$, the action is not translationally invariant. --- **References** 1. [A Modern Introduction to Quanrum Field Theory](https://books.google.co.in/books?id=yykTDAAAQBAJ&pg=PA47&lpg=PA47&dq=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&source=bl&ots=KAXp1oVaEw&sig=rrhvybZu2vcj1HWgGPNwTEDkYug&hl=en&sa=X&ved=0ahUKEwjG67On-e7aAhUKv48KHapdBzoQ6AEIKDAA#v=onepage&q=of%20course%20a%20local%20symmetry%20gives%20rise%20also%20to%20a%20global%20symmetry%20maggiore&f=false) Eq. 3.19, 3.20 and 3.21. 2. [Field Quantization-W. Greiner](https://books.google.co.in/books?id=C-DVBAAAQBAJ&pg=PA41&lpg=PA41&dq=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&source=bl&ots=Ul21tFC_26&sig=xA6Ubc1We2KSg6Ou2mv28pc0PgA&hl=en&sa=X&ved=0ahUKEwizsuv37O7aAhUHLY8KHaJQD78Q6AEIKDAA#v=onepage&q=many%20of%20the%20following%20results%20are%20only%20valid%20up%20to%20first%20order%20greiner%20field%20quantization&f=false) Eq. 2.38, 2.39, and 2.45. 3. [An introduction to Quantum Field theory- Peskin and Schroeder](https://books.google.co.in/books?id=_Q84DgAAQBAJ&pg=PT45&lpg=PT45&dq=noether%27s%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&source=bl&ots=yZmSlt2qi8&sig=eNMrbrc8_kZJuMFvigo4m6ce4vw&hl=en&sa=X&ved=0ahUKEwjC3bqw-u7aAhXIOY8KHYnpDBQQ6AEIKDAA#v=onepage&q=noether's%20theorem%20can%20also%20be%20applied%20to%20spacetime%20transformations%20such%20as%20translations%20and%20rotations%20peskin%20schroeder&f=false) page 18. 4. [Lectures on Classical Field Theory by Suresh Govindrajan](https://www.youtube.com/watch?v=SY5JILTzYiY&list=PLbMVogVj5nJRYLTwyuusiiFchFU-WvElW) 5. [Lectures on Quantum Field Theory by Ashok Das](https://books.google.co.in/books?id=HFFkDQAAQBAJ&pg=PA212&lpg=PA212&dq=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&source=bl&ots=PFAqZ7q_Zz&sig=UZL_MGocmMLXkC1pFixrwHF1G_E&hl=en&sa=X&ved=0ahUKEwiFy6uF_u7aAhWJK48KHXE8AjQQ6AEIKDAA#v=onepage&q=unprimed%20systems%20would%20remain%20form%20invariant%20ashok%20das&f=false) page 212, Eq. 6.4 6. [Relativistic Quantum Physics-Tommy Ohlsson](https://books.google.co.in/books?id=hRavtAW5EFcC&pg=PA119&lpg=PA119&dq=to%20each%20continuous%20symmetry%20transformation%20of%20a%20local%20lagrangian%20tommy%20ohlsson&source=bl&ots=3ejGdWs9XF&sig=EfpbFY_5pge8wXJn8it_QwDtV9c&hl=en&sa=X&ved=0ahUKEwikxIvM_u7aAhUHTo8KHSBgD5wQ6AEIKDAA#v=onepage&q&f=false) Eq. 5.66, page 119. 7. [A first book on quantum field theory by P. B. Pal](https://books.google.co.in/books?id=_UmPP8Yr5mYC&pg=PA22&lpg=PA22&dq=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&source=bl&ots=tcSydVEb1I&sig=MNz8ili2s71R-ybjbniYP__Iezc&hl=en&sa=X&ved=0ahUKEwjY673x_-7aAhUEMY8KHc7yAQ8Q6AEINjAB#v=onepage&q=Here%20we%20have%20suppressed%20the%20space-time%20index%20Palash%20first%20book%20of%20quantum%20field%20theory&f=false) Page 22, Eq. 2.38.
2018/04/28
[ "https://physics.stackexchange.com/questions/402579", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/36793/" ]
Perhaps the most clear way to see what's going on is to compare the action $$ S\_1[\phi]=\int\_{\mathbb R^d} \phi(x)^2\mathrm dx\tag1 $$ to the action $$ S\_2[\phi]=\int\_{\mathbb R^d} x^2\phi(x)^2\mathrm dx\tag2 $$ The first one should be invariant under translations, while the second one should not. We define the translation operator $T\_a\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $a\in\mathbb R^d$, as (ref.1) $$ (T\_a\phi)(x):=\phi(x-a)\tag3 $$ With this, an action is invariant under translations if and only if $$ S[T\_a\phi]\equiv S[\phi],\quad\forall a\in\mathbb R^d\tag4 $$ What follows is a standard textbook exercise: $$ S\_1[T\_a\phi]\overset{(1)}=\int\_{\mathbb R^d} (T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} \phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} \phi(y)^2\mathrm dy=S\_1[\phi]\tag5 $$ and $$ S\_2[T\_a\phi]\overset{(2)}=\int\_{\mathbb R^d} x^2(T\_a\phi)(x)^2\mathrm dx\overset{(3)}=\int\_{\mathbb R^d} x^2\phi(x-a)^2\mathrm dx=\int\_{\mathbb R^d} (y+a)^2\phi(y)^2\mathrm dy\neq S[\phi]\tag6 $$ where in both cases we defined $y:=x-a$. This is the expected result: $S\_1$ is translation invariant, and $S\_2$ is not. Note that a very similar computation shows that both $S\_1$ and $S\_2$ are invariant under *Lorentz transformations* $T\_\Lambda\in\mathrm{End}(\mathscr C(\mathbb R^d))$, with $\Lambda\in\mathrm{SO}(1,d-1)$, defined in the obvious way: $(T\_\Lambda\phi)(x):=\phi(\Lambda x)$. Here, and as before, it proves essential that $\mathrm dx$ is Poincaré invariant (indeed, it's the Haar measure of $\mathrm{ISO}(1,d-1)$), and that $x\mapsto \Lambda x+a$ is one-to-one over the integration region, $\mathbb R^d$. But this doesn't mean that $\mathrm dx$ *transforms* under $T\_a,T\_\Lambda$. Symmetry transformations are defined at the level of the field $\phi$, with no reference to $\mathrm dx$. Indeed, the definition of invariance $S[T\phi]=S[\phi]$ is quite general, and it is not limited to local functionals: $S[\phi]$ could be *any* functional, not necessarily given by an integral. The volume form $\mathrm dx$ doesn't transform under symmetry operations1, and neither does $x$. The "arrows and primes" notation $\phi\to\phi'$ can be ambiguous and imprecise. If you stick to well-defined operations, the picture is rather clear. In any case, and not to be mislead to think that invariance of the measure is necessary and/or sufficient for invariance of $S$, the reader should consider other symmetry transformations, such as: internal symmetries (e.g., the $\mathbb Z\_2$ transformation $(T\phi)(x):=-\phi(x)$), and non-isometric external symmetries (i.e., conformal transformations). The simplest example of a conformal transformation is the dilatation $$ (T\_\lambda\phi)(x):=\lambda^\Delta\phi(\lambda x)\tag7 $$ with $\lambda\in\mathbb R$. The canonical example of a dilatation-invariant theory is $$ S\_3[\phi]=\int\_{\mathbb R^d} \frac12(\partial\_x\phi(x))^2-\frac{1}{n!}\phi(x)^n\ \mathrm dx\tag8 $$ which satisfies $$ \begin{aligned} S\_3[T\_\lambda\phi]&\overset{(8)}=\int\_{\mathbb R^d} \frac12(\partial\_x(T\_\lambda\phi)(x))^2-\frac{1}{n!}(T\_\lambda\phi)(x)^n\ \mathrm dx\\ &\overset{(7)}=\int\_{\mathbb R^d} \frac12\lambda^{2(\Delta+1)-d}(\partial\_y\phi(y))^2-\lambda^{n\Delta-d}\frac{1}{n!}\phi(y)^n\ \mathrm dy \end{aligned}\tag9 $$ where I set $y:=\lambda x$. This equals $S\_3[\phi]$ iff $2(\Delta+1)=n\Delta=d$, that is, $\Delta=(d-2)/2$ and $n=2d/(d-2)$ (which, for $d=4$, becomes $\Delta=1$ and $n=4$; i.e., $\phi^4$ theory in four space-time dimensions is scale invariant, as is well-known; more generally, $n$ is an integer only in $d=3,4,6$ space-time dimensions). -- More generally, let $\phi\colon\mathbb R^d\to V$, with $V$ a finite-dimensional vector space. We say $T\in\mathrm{End}(\mathscr C(\mathbb R^d,V))$ is a symmetry of a functional $S\colon\mathscr C(\mathbb R^d,V)\to\mathbb R$ if $$ S[T\phi]=S[\phi],\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{10} $$ It is typically the case that symmetry transformations are coordinatised by some manifold $\mathcal M$, so that $T\colon\mathcal M\to \mathrm{End}(\mathscr C(\mathbb R^d,V))$. Moreover, we assume that $T\_0=1$, with $0\in\mathcal M$ the origin of $\mathcal M$ and $1$ the identity transformation. In this case, there is a weaker notion of symmetry: we say $S$ is quasi-invariant under $T$ if the directional derivative of $S[T\_x\phi]$ vanishes at the origin of $\mathcal M$: $$ \lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}S[T\_{vt}\phi]=0,\qquad\forall \phi\in\mathscr C(\mathbb R^d,V)\tag{11} $$ for some $v\in\mathrm T\_0\mathcal M$. The pushforward (differential) of $T$ at the origin is usually denoted by $\delta$: $$ \delta\_v=\lim\_{t\to0}\frac{\mathrm d}{\mathrm dt}T\_{vt}\tag{12} $$ with components $\delta\_v=v^a\delta\_a$, with $a=1,2,\dots,\dim\mathcal M$. Quasi-invariance is therefore equivalent to $$ 0=S[\phi+t\delta\_v\phi]-S[\phi]=tS'[\phi]\cdot\delta\_v\phi+\mathcal O(t^2)\tag{13} $$ where $\cdot$ denotes summation-integration, and $'$ denotes a functional derivative. Noether's first theorem is precisely the statement that there is a current for every quasi-symmetry of $S$, which is divergenceless whenever $\phi$ satisfies $S'[\phi]\equiv 0$. Finally, it bears mentioning that usually $\mathcal M$ is a homogeneous space for some Lie group $G$; in which case we say that $S$ is invariant under $G$. If $G$ is connected and compact, then we can reconstruct it from its algebra $\mathfrak g=\mathrm T\_1G$ by means of the exponential map. This algebra is generated by $\delta$, and therefore quasi-symmetry implies symmetry, and vice-versa. If $\exp$ is not surjective, then quasi-symmetry is truly weaker than symmetry. **References:** 1. Bogolubov, Logunov, Oksak, Todorov - General principles of quantum field theory, §7.1.C. --- 1: Here we are advocating for a *passive* point of view, as opposed to an *active* one. Internal transformations are always passive, so it is convenient to regard external ones as passive to, so as to have a uniform framework. It appears that the books OP is following introduce a mixed point of view, where both the fields *and* the spacetime point are allowed to vary, if somewhat redundantly. The passive point of view is, IMHO, the most general and clear one, and the one most people use nowadays.
It looks like you are getting too caught up in the *notation* and the *formalism* of it all. In this case the notation is not what is important, what is more important is the concept. The concept may be easier to understand if you think about what the statement regarding the action means in one dimensional space rather than in four dimensional space-time. What is meant is that the total area under a curve in the x-y plane doesn't change if you slide the curve back and forth along the x-axis. In order to show that this is true more formally, you want replace "under the integral sign" a curve $f(x)$ by a different curve $g(x)$, where the curve g looks exactly like the curve f was grabbed and slid over to the right (along the x-axis) by an amount $a$. Well, obviously the two integrals are going to be equal if we are integrating from $x=-\infty$ to $x=+\infty$, right? This is all that is meant by the statement that the action is invariant under this transformation. In the original problem the curve $f$ is called $\phi^2$. The fact that the function is squared does not matter for this proof. If could be any function.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You need to know a bit about the server side. Here's what you need to know. If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects. So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it. If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON. I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: <http://www.trailbehind.com/comment_widget/>
It helps to set up a local server and write a few lines of code to service your AJAX calls. You can do a lot of JavaScript learning with just a little back-end learning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
Yes and no. Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML. However, an AJAX call can be made to static resources as well. You could have an XML file or html snippet stored statically on your web server and have it loaded. The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?
If you're new in web development you'd rather wait with Ajax and server-side languages until you've learnt the basics with HTML, CSS and JavaScript, especially if you want to mostly work with the user interface and not the funcionality.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
Yes and no. Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML. However, an AJAX call can be made to static resources as well. You could have an XML file or html snippet stored statically on your web server and have it loaded. The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?
It helps to set up a local server and write a few lines of code to service your AJAX calls. You can do a lot of JavaScript learning with just a little back-end learning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.). As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.
Yes and no. Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML. However, an AJAX call can be made to static resources as well. You could have an XML file or html snippet stored statically on your web server and have it loaded. The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You need to know a bit about the server side. Here's what you need to know. If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects. So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it. If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON. I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: <http://www.trailbehind.com/comment_widget/>
As you said you can let somebody else do the back-end and focus on front-end (JavaScript, HTML, CSS). You would need to communicate with the back-end developer when storing or processing data from the server. As mentioned before back-end development knowledge would be useful but if you have someone doing it, it's not essential for beginning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.). As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.
As you said you can let somebody else do the back-end and focus on front-end (JavaScript, HTML, CSS). You would need to communicate with the back-end developer when storing or processing data from the server. As mentioned before back-end development knowledge would be useful but if you have someone doing it, it's not essential for beginning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.). As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.
You need to know a bit about the server side. Here's what you need to know. If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects. So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it. If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON. I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: <http://www.trailbehind.com/comment_widget/>
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.). As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.
It helps to set up a local server and write a few lines of code to service your AJAX calls. You can do a lot of JavaScript learning with just a little back-end learning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
Yes and no. Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML. However, an AJAX call can be made to static resources as well. You could have an XML file or html snippet stored statically on your web server and have it loaded. The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?
As you said you can let somebody else do the back-end and focus on front-end (JavaScript, HTML, CSS). You would need to communicate with the back-end developer when storing or processing data from the server. As mentioned before back-end development knowledge would be useful but if you have someone doing it, it's not essential for beginning.
930,312
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
2009/05/30
[ "https://Stackoverflow.com/questions/930312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78193/" ]
You need to know a bit about the server side. Here's what you need to know. If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects. So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it. If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON. I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: <http://www.trailbehind.com/comment_widget/>
Yes and no. Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML. However, an AJAX call can be made to static resources as well. You could have an XML file or html snippet stored statically on your web server and have it loaded. The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?
466,077
Does $ax^2+by^2=cz^2$ have positive integer solutions? I know that the solution exists when $(a,b,c)=(1,1,1)$ or $(1,1,n^2+1)$, but I failed to produce a general formula. Any help would be appreciated.
2013/08/12
[ "https://math.stackexchange.com/questions/466077", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90077/" ]
As pointed out by D. Burde, there is a general solution by Legendre which gives the necessary conditions of the solvability of, $$ax^2+by^2+cz^2=0\tag{1}$$ but it is not an instant formula in the sense of, $$(p^2-nq^2)^2+n(2pq)^2 = (p^2+nq^2)^2\tag{2}$$ which, for $n=1$, gives the *Pythagorean triples*. You can find a formula like $(2)$ only for particular cases, and not for all general $a,b,c$. However, to help you out, if $(1)$ has a non-trivial solution $x, y, z$, then an infinite more can be given as, $$x\_i = x(-a p^2 + b q^2 + c r^2) - 2p(b q y + c r z)$$ $$y\_i = y(a p^2 - b q^2 + c r^2) - 2q(a p x + c r z)$$ $$z\_i = z(a p^2 + b q^2 - c r^2) - 2r(a p x + b q y)$$ for arbitrary variables $p,q,r$.
A general solution is due to Legendre, in terms of the Legendre symbol. See for example here: <http://public.csusm.edu/aitken_html/notes/legendre.pdf>, proposition $2$. See also for Hasse principle in corollary 5, 6 and 7. Elliptic curves are not needed, and also no algebraic geometry. Just elementary number theory.
466,077
Does $ax^2+by^2=cz^2$ have positive integer solutions? I know that the solution exists when $(a,b,c)=(1,1,1)$ or $(1,1,n^2+1)$, but I failed to produce a general formula. Any help would be appreciated.
2013/08/12
[ "https://math.stackexchange.com/questions/466077", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90077/" ]
A general solution is due to Legendre, in terms of the Legendre symbol. See for example here: <http://public.csusm.edu/aitken_html/notes/legendre.pdf>, proposition $2$. See also for Hasse principle in corollary 5, 6 and 7. Elliptic curves are not needed, and also no algebraic geometry. Just elementary number theory.
Formula generally look like this: Do not like these formulas. But this does not mean that we should not draw them. To start this equation zayimemsya, well then, and others. $aX^2+bXY+cY^2=jZ^2$ Solutions can be written if even a single root.$\sqrt{j(a+b+c)}$ , $\sqrt{b^2 + 4a(j-c)}$ , $\sqrt{b^2+4c(j-a)}$ Then the solution can be written. $X=(2j(b+2c)^2-(b^2+4c(j-a))(j\pm\sqrt{j(a+b+c)}))s^2+2(b+2c)(\sqrt{j(a+b+c)}\mp{j})sp+(j\mp \sqrt{j(a+b+c)})p^2$ $Y=(2j(2j-b-2a)(b+2c)-(b^2+4c(j-a))(j\pm\sqrt{j(a+b+c)}))s^2+ +2((2j-2a-b)\sqrt{j(a+b+c)}\mp{j(b+2c)})sp+(j\mp\sqrt{j(a+b+c)})p^2$ $Z=(2j(b+2c)^2-(b^2+4c(j-a))(a+b+c\pm\sqrt{j(a+b+c)}))s^2+ +2(b+2c) ( \sqrt{j(a+b+c)} \mp{j})sp + ( a + b + c \mp \sqrt{j(a+b+c)})p^2 $ In the case when the root $\sqrt{b^2+4c(j-a)}$ whole. Solutions have the form. $X=((2j-b-2c)(8ac+2b(2j-b))-(b^2+4a(j-c))(b+2c\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm{(2j-b-2c)}\sqrt{b^2+4c(j-a)})sp+(b+2c\pm\sqrt{b^2+4c(j-a)})p^2$ $Y=((b+2a)(8ac+2b(2j-b))-(b^2+4a(j-c))(2j-b-2a\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm{(b+2a)}\sqrt{b^2+4c(j-a)})sp+(2j-b-2a\pm\sqrt{b^2+4c(j-a)})p^2$ $Z=((b+2a)(8ac+2b(2j-b))-(b^2+4a(j-c))(b+2c\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm {(b+2a)}\sqrt{b^2+4c(j-a)})sp+(b+2c\pm\sqrt{b^2+4c(j-a)})p^2$ In the case when the root $\sqrt{b^2+4a(j-c)}$ whole. Solutions have the form. $X=(2j^2(b+2a)-j(a+b+c)(2j-2c-b\pm\sqrt{b^2+4a(j-c)}))p^2+ +2j(\sqrt{b^2+4a(j-c)}\mp{(b+2a)})ps+(2j-2c-b\mp\sqrt{b^2+4a(j-c)})s^2$ $Y=(2j^2(b+2a)-j(a+b+c)(b+2a\pm\sqrt{b^2+4a(j-c)}))p^2+ +2j(\sqrt{b^2+4a(j-c)}\mp{(b+2a)})ps+(b+2a\mp\sqrt{b^2+4a(j-c)})s^2$ $Z=j(a+b+c)(b+2a\mp\sqrt{b^2+4a(j-c)})p^2+ +2((a+b+c)\sqrt{b^2+4a(j-c)}\mp{j(b+2a)})ps+ (b+2a\mp\sqrt{b^2+4a(j-c)})s^2$ Since these formulas are written in general terms, require a certain specificity calculations.If, after a permutation of the coefficients, no root is not an integer. You need to check whether there is an equivalent quadratic form in which, at least one root of a whole. Is usually sufficient to make the substitution $X\longrightarrow{X+kY}$ or more $Y\longrightarrow{Y+kX}$ In fact, this reduces to determining the existence of solutions in certain Pell's equation. Of course with such an idea can solve more complex equations. If I will not disturb anybody, slowly formula will draw. number $p,s$ integers and set us. I understand that these formulas do not like. And when they draw - or try to ignore or delete. Formulas but there are no bad or good. They either are or they are not. In equation $aX^2+bY^2+cZ^2=qXY+dXZ+tYZ$ $a,b,c,q,d,t$ integer coefficients which specify the conditions of the problem. For a more compact notation, we introduce a replacement. $k=(q+t)^2-4b(a+c-d)$ $j=(d+t)^2-4c(a+b-q)$ $n=t(2a-t-d-q)+(2b-q)(2c-d)$ Then the formula in the general form is: $X=(2n(2c-d-t)+j(q+t-2b\pm\sqrt{k}))p^2+2((d+t-2c)\sqrt{k}\mp{n})ps++(2b-q-t\pm\sqrt{k})s^2$ $Y=(2n(2c-d-t)+j(2(a+c-d)-q-t\pm\sqrt{k}))p^2+2((d+t-2c)\sqrt{k}\mp{ n })ps++(q+t+2(d-a-c)\pm\sqrt{k})s^2$ $Z=(j(q+t-2b\pm\sqrt{k})-2n(2(a+b-q)-d-t))p^2+2((2(a+b-q)-d-t)\sqrt{k}\mp{n})ps+(2b-q-t\pm\sqrt{k})s^2$ And more. $X=(2n(q+t-2b)+k(2c-d-t\pm\sqrt{j}))p^2+2((2b-q-t)\sqrt{j}\mp{n})ps++(d+t-2c\pm\sqrt{j})s^2$ $Y=(2n(2(a+c-d)-q-t)+k(2c-d-t\pm\sqrt{j}))p^2++2((q+t+2(d-a-c))\sqrt{j}\mp{n})ps+(d+t-2c\pm\sqrt{j})s^2$ $Z=(2n(q+t-2b)+k(d+t+2(q-a-b)\pm\sqrt{j}))p^2+2((2b-q-t)\sqrt{j}\mp{n})ps++(2(a+b-q)-d-t\pm\sqrt{j})s^2$ $p,s$ are integers and are given us. Since formulas are written in general terms, in the case where neither the root is not an integer, it is necessary to check whether there is such an equivalent quadratic form in which at least one root of a whole. If not, then the solution in integers of the equation have not.
466,077
Does $ax^2+by^2=cz^2$ have positive integer solutions? I know that the solution exists when $(a,b,c)=(1,1,1)$ or $(1,1,n^2+1)$, but I failed to produce a general formula. Any help would be appreciated.
2013/08/12
[ "https://math.stackexchange.com/questions/466077", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90077/" ]
As pointed out by D. Burde, there is a general solution by Legendre which gives the necessary conditions of the solvability of, $$ax^2+by^2+cz^2=0\tag{1}$$ but it is not an instant formula in the sense of, $$(p^2-nq^2)^2+n(2pq)^2 = (p^2+nq^2)^2\tag{2}$$ which, for $n=1$, gives the *Pythagorean triples*. You can find a formula like $(2)$ only for particular cases, and not for all general $a,b,c$. However, to help you out, if $(1)$ has a non-trivial solution $x, y, z$, then an infinite more can be given as, $$x\_i = x(-a p^2 + b q^2 + c r^2) - 2p(b q y + c r z)$$ $$y\_i = y(a p^2 - b q^2 + c r^2) - 2q(a p x + c r z)$$ $$z\_i = z(a p^2 + b q^2 - c r^2) - 2r(a p x + b q y)$$ for arbitrary variables $p,q,r$.
Formula generally look like this: Do not like these formulas. But this does not mean that we should not draw them. To start this equation zayimemsya, well then, and others. $aX^2+bXY+cY^2=jZ^2$ Solutions can be written if even a single root.$\sqrt{j(a+b+c)}$ , $\sqrt{b^2 + 4a(j-c)}$ , $\sqrt{b^2+4c(j-a)}$ Then the solution can be written. $X=(2j(b+2c)^2-(b^2+4c(j-a))(j\pm\sqrt{j(a+b+c)}))s^2+2(b+2c)(\sqrt{j(a+b+c)}\mp{j})sp+(j\mp \sqrt{j(a+b+c)})p^2$ $Y=(2j(2j-b-2a)(b+2c)-(b^2+4c(j-a))(j\pm\sqrt{j(a+b+c)}))s^2+ +2((2j-2a-b)\sqrt{j(a+b+c)}\mp{j(b+2c)})sp+(j\mp\sqrt{j(a+b+c)})p^2$ $Z=(2j(b+2c)^2-(b^2+4c(j-a))(a+b+c\pm\sqrt{j(a+b+c)}))s^2+ +2(b+2c) ( \sqrt{j(a+b+c)} \mp{j})sp + ( a + b + c \mp \sqrt{j(a+b+c)})p^2 $ In the case when the root $\sqrt{b^2+4c(j-a)}$ whole. Solutions have the form. $X=((2j-b-2c)(8ac+2b(2j-b))-(b^2+4a(j-c))(b+2c\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm{(2j-b-2c)}\sqrt{b^2+4c(j-a)})sp+(b+2c\pm\sqrt{b^2+4c(j-a)})p^2$ $Y=((b+2a)(8ac+2b(2j-b))-(b^2+4a(j-c))(2j-b-2a\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm{(b+2a)}\sqrt{b^2+4c(j-a)})sp+(2j-b-2a\pm\sqrt{b^2+4c(j-a)})p^2$ $Z=((b+2a)(8ac+2b(2j-b))-(b^2+4a(j-c))(b+2c\mp\sqrt{b^2+4c(j-a)}))s^2++2(4ac+b(2j-b)\pm {(b+2a)}\sqrt{b^2+4c(j-a)})sp+(b+2c\pm\sqrt{b^2+4c(j-a)})p^2$ In the case when the root $\sqrt{b^2+4a(j-c)}$ whole. Solutions have the form. $X=(2j^2(b+2a)-j(a+b+c)(2j-2c-b\pm\sqrt{b^2+4a(j-c)}))p^2+ +2j(\sqrt{b^2+4a(j-c)}\mp{(b+2a)})ps+(2j-2c-b\mp\sqrt{b^2+4a(j-c)})s^2$ $Y=(2j^2(b+2a)-j(a+b+c)(b+2a\pm\sqrt{b^2+4a(j-c)}))p^2+ +2j(\sqrt{b^2+4a(j-c)}\mp{(b+2a)})ps+(b+2a\mp\sqrt{b^2+4a(j-c)})s^2$ $Z=j(a+b+c)(b+2a\mp\sqrt{b^2+4a(j-c)})p^2+ +2((a+b+c)\sqrt{b^2+4a(j-c)}\mp{j(b+2a)})ps+ (b+2a\mp\sqrt{b^2+4a(j-c)})s^2$ Since these formulas are written in general terms, require a certain specificity calculations.If, after a permutation of the coefficients, no root is not an integer. You need to check whether there is an equivalent quadratic form in which, at least one root of a whole. Is usually sufficient to make the substitution $X\longrightarrow{X+kY}$ or more $Y\longrightarrow{Y+kX}$ In fact, this reduces to determining the existence of solutions in certain Pell's equation. Of course with such an idea can solve more complex equations. If I will not disturb anybody, slowly formula will draw. number $p,s$ integers and set us. I understand that these formulas do not like. And when they draw - or try to ignore or delete. Formulas but there are no bad or good. They either are or they are not. In equation $aX^2+bY^2+cZ^2=qXY+dXZ+tYZ$ $a,b,c,q,d,t$ integer coefficients which specify the conditions of the problem. For a more compact notation, we introduce a replacement. $k=(q+t)^2-4b(a+c-d)$ $j=(d+t)^2-4c(a+b-q)$ $n=t(2a-t-d-q)+(2b-q)(2c-d)$ Then the formula in the general form is: $X=(2n(2c-d-t)+j(q+t-2b\pm\sqrt{k}))p^2+2((d+t-2c)\sqrt{k}\mp{n})ps++(2b-q-t\pm\sqrt{k})s^2$ $Y=(2n(2c-d-t)+j(2(a+c-d)-q-t\pm\sqrt{k}))p^2+2((d+t-2c)\sqrt{k}\mp{ n })ps++(q+t+2(d-a-c)\pm\sqrt{k})s^2$ $Z=(j(q+t-2b\pm\sqrt{k})-2n(2(a+b-q)-d-t))p^2+2((2(a+b-q)-d-t)\sqrt{k}\mp{n})ps+(2b-q-t\pm\sqrt{k})s^2$ And more. $X=(2n(q+t-2b)+k(2c-d-t\pm\sqrt{j}))p^2+2((2b-q-t)\sqrt{j}\mp{n})ps++(d+t-2c\pm\sqrt{j})s^2$ $Y=(2n(2(a+c-d)-q-t)+k(2c-d-t\pm\sqrt{j}))p^2++2((q+t+2(d-a-c))\sqrt{j}\mp{n})ps+(d+t-2c\pm\sqrt{j})s^2$ $Z=(2n(q+t-2b)+k(d+t+2(q-a-b)\pm\sqrt{j}))p^2+2((2b-q-t)\sqrt{j}\mp{n})ps++(2(a+b-q)-d-t\pm\sqrt{j})s^2$ $p,s$ are integers and are given us. Since formulas are written in general terms, in the case where neither the root is not an integer, it is necessary to check whether there is such an equivalent quadratic form in which at least one root of a whole. If not, then the solution in integers of the equation have not.
22,432,240
I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, `allResult` displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code. my Code... ``` int main(){ int allResult; for( int i = 1; i < 11; i++) { int result = 2*i; cout << 2 << " times " << i << " = " << result << endl; // I want allResult to store results added. so after first loop, result = 2 so allResult = 2 // after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added) // after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added) // I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2. } system("pause"); } ```
2014/03/16
[ "https://Stackoverflow.com/questions/22432240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3424696/" ]
``` int allResult = 0; for( int i = 1; i < 11; i++) { int result = 2*i; cout << "2 times " << i << " = " << result << endl; allResult += result; cout << "allResult: " << allResult << endl; } ```
``` int allResult = 0; for( int i = 1; i < 11; i++) { allResult += 2*i; cout << 2 << " times " << i << " = " << 2*i << endl; } ```
22,432,240
I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, `allResult` displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code. my Code... ``` int main(){ int allResult; for( int i = 1; i < 11; i++) { int result = 2*i; cout << 2 << " times " << i << " = " << result << endl; // I want allResult to store results added. so after first loop, result = 2 so allResult = 2 // after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added) // after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added) // I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2. } system("pause"); } ```
2014/03/16
[ "https://Stackoverflow.com/questions/22432240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3424696/" ]
``` int allResult = 0; for( int i = 1; i < 11; i++) { int result = 2*i; cout << "2 times " << i << " = " << result << endl; allResult += result; cout << "allResult: " << allResult << endl; } ```
``` int main() { int allResult=0; for( int i = 1; i < 11; i++) { int result = 2*i; allResult=allResult+result; /*Initially allResult is 0. After each loop iteration it adds to its previous value. For instance in the first loop it was allResult=0+2, which made allResult equal to 2. In the next loop allResult=2+4=6. Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/ cout << 2 << " times " << i << " = " << result << endl; } system("pause"); } ```
22,432,240
I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, `allResult` displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code. my Code... ``` int main(){ int allResult; for( int i = 1; i < 11; i++) { int result = 2*i; cout << 2 << " times " << i << " = " << result << endl; // I want allResult to store results added. so after first loop, result = 2 so allResult = 2 // after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added) // after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added) // I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2. } system("pause"); } ```
2014/03/16
[ "https://Stackoverflow.com/questions/22432240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3424696/" ]
``` int allResult = 0; for( int i = 1; i < 11; i++) { allResult += 2*i; cout << 2 << " times " << i << " = " << 2*i << endl; } ```
``` int main() { int allResult=0; for( int i = 1; i < 11; i++) { int result = 2*i; allResult=allResult+result; /*Initially allResult is 0. After each loop iteration it adds to its previous value. For instance in the first loop it was allResult=0+2, which made allResult equal to 2. In the next loop allResult=2+4=6. Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/ cout << 2 << " times " << i << " = " << result << endl; } system("pause"); } ```
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
If it is to be discrete, then each one-point set $\{x\}$ should be an open set in $A$. Let $x=\frac{1}{n}$ be a point from your set. Measure the distance to its nearest neighbor: call that distance $\delta$. In fact, the nearest neighbor is $\frac{1}{n+1}$, so finding this distance explicitly isn't hard. Then $$ \{x\} = A \cap (x-\delta, x+\delta) $$ and so $\{x\}$ is open in $A$: we chose $\delta$ so that no one from $A$ (besides $x$) can be within $\delta$ of $x$.
As you noted it suffices by the definition of the subspace topology to find for each point $x\in A$ an open neighborhood $U\_x \subseteq \Bbb R$ such that no other point $y\in A$ lies inside $U\_x$. Then $\{x\}$ is open in the subspace topology and since $x$ was arbitrary $A$ has to be discrete. **Hint**: Let $x = \frac{1}{n}$ for some $n>0$. Let $\varepsilon = \frac{1}{2}(\frac{1}n - \frac{1}{n+1})$ and consider $U\_x=(x-\varepsilon, x+\varepsilon)\subseteq \Bbb R$. Can you show that $\frac{1}{m} \notin U\_x$ for all $m\neq n$?
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
If it is to be discrete, then each one-point set $\{x\}$ should be an open set in $A$. Let $x=\frac{1}{n}$ be a point from your set. Measure the distance to its nearest neighbor: call that distance $\delta$. In fact, the nearest neighbor is $\frac{1}{n+1}$, so finding this distance explicitly isn't hard. Then $$ \{x\} = A \cap (x-\delta, x+\delta) $$ and so $\{x\}$ is open in $A$: we chose $\delta$ so that no one from $A$ (besides $x$) can be within $\delta$ of $x$.
Note that open intervals are open in the Euclidean topology on $\mathbb{R}$. Then $\{1\}=(\frac{1}{2},\infty)\cap A$ is open in the subspace topology on $A$, and for $n\geq2$, we have that $$\left\{\frac{1}{n}\right\}=\left(\frac{1}{n+1},\frac{1}{n-1}\right)\cap A$$ is open in the subspace topology on $A$. So the singletons $\{\frac{1}{n}\}$ in $A$ are all open. Since every subset of $A$ is a union of singletons, and therefore a union of open sets, all subsets of $A$ are open in the subspace topology. Since all subsets are open, the subspace topology is equal to the discrete topology on $A$. --- To get a better feel for how this works, I shall provide a generalisation to arbitrary topological spaces: > > Let $X$ be a topological space with a non-empty subset $A$ and suppose that for each $a\in A$ there exists $U$ open in $X$ with $U\cap A=\{a\}$. Then the subspace topology on $A$ is equal to the discrete topology on $A$. > > > *Proof*: For each $a\in A$, we have that there exists $U$ open in $X$ with $U\cap A=\{a\}$. It follows from the definition of the subspace topology that $\{a\}$ is open in $A$. Since each subset of $A$ is a union of singletons, each of which is open, it follows that every subset of $A$ is open in the subspace topology.
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
If it is to be discrete, then each one-point set $\{x\}$ should be an open set in $A$. Let $x=\frac{1}{n}$ be a point from your set. Measure the distance to its nearest neighbor: call that distance $\delta$. In fact, the nearest neighbor is $\frac{1}{n+1}$, so finding this distance explicitly isn't hard. Then $$ \{x\} = A \cap (x-\delta, x+\delta) $$ and so $\{x\}$ is open in $A$: we chose $\delta$ so that no one from $A$ (besides $x$) can be within $\delta$ of $x$.
In a $T\_1$ first countable space (which is what all metric spaces are) if $x$ is *not* an isolated point of $X$ there is a sequence $z\_n$ of distinct points, all $z\_n \neq x$, so that $z\_n \to x$. So no $\frac{1}{m}$ in $X$ can be a non-isolated point, or such a $z\_n$ would define a subsequence of $(\frac{1}{n})\_n$ that converged to $\frac1m$ while it's clear that $\frac1n \to 0$ in $\Bbb R$ and ditto for all its subsequences. This would contradict the unicity of limits of sequences (which holds in all Hausdorff spaces and so in $\Bbb R$). This is a more "meta" general topology style argument and might be useful to someone. No gory details and more general principles. All convergent sequences in "decent" (Hausdorff is enough) spaces have a unique limit and the other points are isolated in the subspace.
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
As you noted it suffices by the definition of the subspace topology to find for each point $x\in A$ an open neighborhood $U\_x \subseteq \Bbb R$ such that no other point $y\in A$ lies inside $U\_x$. Then $\{x\}$ is open in the subspace topology and since $x$ was arbitrary $A$ has to be discrete. **Hint**: Let $x = \frac{1}{n}$ for some $n>0$. Let $\varepsilon = \frac{1}{2}(\frac{1}n - \frac{1}{n+1})$ and consider $U\_x=(x-\varepsilon, x+\varepsilon)\subseteq \Bbb R$. Can you show that $\frac{1}{m} \notin U\_x$ for all $m\neq n$?
Note that open intervals are open in the Euclidean topology on $\mathbb{R}$. Then $\{1\}=(\frac{1}{2},\infty)\cap A$ is open in the subspace topology on $A$, and for $n\geq2$, we have that $$\left\{\frac{1}{n}\right\}=\left(\frac{1}{n+1},\frac{1}{n-1}\right)\cap A$$ is open in the subspace topology on $A$. So the singletons $\{\frac{1}{n}\}$ in $A$ are all open. Since every subset of $A$ is a union of singletons, and therefore a union of open sets, all subsets of $A$ are open in the subspace topology. Since all subsets are open, the subspace topology is equal to the discrete topology on $A$. --- To get a better feel for how this works, I shall provide a generalisation to arbitrary topological spaces: > > Let $X$ be a topological space with a non-empty subset $A$ and suppose that for each $a\in A$ there exists $U$ open in $X$ with $U\cap A=\{a\}$. Then the subspace topology on $A$ is equal to the discrete topology on $A$. > > > *Proof*: For each $a\in A$, we have that there exists $U$ open in $X$ with $U\cap A=\{a\}$. It follows from the definition of the subspace topology that $\{a\}$ is open in $A$. Since each subset of $A$ is a union of singletons, each of which is open, it follows that every subset of $A$ is open in the subspace topology.
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
As you noted it suffices by the definition of the subspace topology to find for each point $x\in A$ an open neighborhood $U\_x \subseteq \Bbb R$ such that no other point $y\in A$ lies inside $U\_x$. Then $\{x\}$ is open in the subspace topology and since $x$ was arbitrary $A$ has to be discrete. **Hint**: Let $x = \frac{1}{n}$ for some $n>0$. Let $\varepsilon = \frac{1}{2}(\frac{1}n - \frac{1}{n+1})$ and consider $U\_x=(x-\varepsilon, x+\varepsilon)\subseteq \Bbb R$. Can you show that $\frac{1}{m} \notin U\_x$ for all $m\neq n$?
In a $T\_1$ first countable space (which is what all metric spaces are) if $x$ is *not* an isolated point of $X$ there is a sequence $z\_n$ of distinct points, all $z\_n \neq x$, so that $z\_n \to x$. So no $\frac{1}{m}$ in $X$ can be a non-isolated point, or such a $z\_n$ would define a subsequence of $(\frac{1}{n})\_n$ that converged to $\frac1m$ while it's clear that $\frac1n \to 0$ in $\Bbb R$ and ditto for all its subsequences. This would contradict the unicity of limits of sequences (which holds in all Hausdorff spaces and so in $\Bbb R$). This is a more "meta" general topology style argument and might be useful to someone. No gory details and more general principles. All convergent sequences in "decent" (Hausdorff is enough) spaces have a unique limit and the other points are isolated in the subspace.
4,387,813
Say I have $A = \lbrace \frac{1}{n} | n \in \mathbb{N}\_+ \rbrace \subset \mathbb{R}$ **I'm trying to figure out if the subspace topology on $A$ that is inherited from $\mathbb{R}$ is the discrete topology.** For the subset $A$ of $\mathbb{R}$, the subspace topology on $A$ is defined by $\mathcal{T}\_A:=\lbrace A \cap U \mid U \in \mathcal{T}\rbrace$ where $\mathcal{T}$ is the *standard topology* on $\mathbb{R}$. The largest topology on a topological space $X$ contains all subsets as open sets and is called the *discrete topology*. In the discrete topology, every point in $X = \mathbb{R}$ is an open set. In other words, we have to figure out if the subspace topology on $A$ has open set subsets for every point. Disproving the initial statement would be finding a point where this is not true, if one exists. We know $A\subset \mathbb{R}$. Then the standard topology inherited from $\mathbb{R}$ should be the topology whose open sets are the unions of sets of the type $(a,b)\cap A$, with $a,b\in\mathbb{R}$ and $a<b$. The issue I'm having is figuring *what an open set would look like here.* I've been told that some subset $X$ is open in $\mathbb{R}$ if it meets the definition of the topology on $\mathbb{R}$, but $A$ is more than one open interval $(a,b) \subset \mathbb{R}$. Is there a test to apply to $A$ generally?
2022/02/21
[ "https://math.stackexchange.com/questions/4387813", "https://math.stackexchange.com", "https://math.stackexchange.com/users/982631/" ]
In a $T\_1$ first countable space (which is what all metric spaces are) if $x$ is *not* an isolated point of $X$ there is a sequence $z\_n$ of distinct points, all $z\_n \neq x$, so that $z\_n \to x$. So no $\frac{1}{m}$ in $X$ can be a non-isolated point, or such a $z\_n$ would define a subsequence of $(\frac{1}{n})\_n$ that converged to $\frac1m$ while it's clear that $\frac1n \to 0$ in $\Bbb R$ and ditto for all its subsequences. This would contradict the unicity of limits of sequences (which holds in all Hausdorff spaces and so in $\Bbb R$). This is a more "meta" general topology style argument and might be useful to someone. No gory details and more general principles. All convergent sequences in "decent" (Hausdorff is enough) spaces have a unique limit and the other points are isolated in the subspace.
Note that open intervals are open in the Euclidean topology on $\mathbb{R}$. Then $\{1\}=(\frac{1}{2},\infty)\cap A$ is open in the subspace topology on $A$, and for $n\geq2$, we have that $$\left\{\frac{1}{n}\right\}=\left(\frac{1}{n+1},\frac{1}{n-1}\right)\cap A$$ is open in the subspace topology on $A$. So the singletons $\{\frac{1}{n}\}$ in $A$ are all open. Since every subset of $A$ is a union of singletons, and therefore a union of open sets, all subsets of $A$ are open in the subspace topology. Since all subsets are open, the subspace topology is equal to the discrete topology on $A$. --- To get a better feel for how this works, I shall provide a generalisation to arbitrary topological spaces: > > Let $X$ be a topological space with a non-empty subset $A$ and suppose that for each $a\in A$ there exists $U$ open in $X$ with $U\cap A=\{a\}$. Then the subspace topology on $A$ is equal to the discrete topology on $A$. > > > *Proof*: For each $a\in A$, we have that there exists $U$ open in $X$ with $U\cap A=\{a\}$. It follows from the definition of the subspace topology that $\{a\}$ is open in $A$. Since each subset of $A$ is a union of singletons, each of which is open, it follows that every subset of $A$ is open in the subspace topology.
48,492,889
I have a CSV file that I need to read line by line with the help of a `Scanner` and store only country names into an array of strings. Here is my CSV file: ``` World Development Indicators Number of countries,4 Country Name,2005,2006,2007 Bangladesh,6.28776238,13.20573922,23.46762823 "Bahamas,The",69.21279415,75.37855087,109.340767 Brazil,46.31418452,53.11025849,63.67475185 Germany,94.55486999,102.2828888,115.1403608 ``` This is what I have so far: ``` public String[] getCountryNames() throws IOException, FileNotFoundException{ String[] countryNames = new String[3]; int index = 0; BufferedReader br = new BufferedReader(new FileReader(fileName)); br.readLine(); br.readLine(); br.readLine(); String line = br.readLine(); while((br.readLine() != null) && !line.isEmpty()){ String[] countries = line.split(","); countryNames[index] = countries[0]; index++; line = br.readLine(); } System.out.println(Arrays.toString(countryNames)); return countryNames; } ``` Output: ``` [Bangladesh, Brazil, null] ``` For some reason it skips "Bahamas, The" and can't read Germany. Please help me, I have been stuck on this method for hours already. Thanks for your time and effort. The return should be an array of Strings (country names).
2018/01/29
[ "https://Stackoverflow.com/questions/48492889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8735342/" ]
The conventional approach is to build the system using automated build and continuous integration tools like Jenkins, Bitbucket Pipelines, Gitlab-CI etc. (I presume you are using Maven or Gradle already given that you have tagged them in your question). The build will fail if the change (to a newer dependency) changed anything like method signatures or other refactoring. Furthermore, you should also have unit tests ensuring that your functionality is working as expected. If a fundamental behaviour of the underlying libraries changes that affects your functions, you would be able to detect that too. This would help you catch functional changes, not just compilation issues. Finally, you might want to look at the new Java 9 module system. It's still a bit behind with regards to adoption, but it might offer an alternative solution to what you are looking for, especially if you are in control of the dependencies too.
Even if every component in your dependency tree adhere's perfectly to SemVer standards, you still need out-of-band (relevant to SemVer) information to have closure on the transient dependencies. The dependency graph in general and the diamond point dependency problem in particular, are known hard problems. Testing can put a small, but very expensive dent in it, but is generally prohibitive for any non-trivial product running on servers with hundreds or thousands of components. The best that you can do is containerize the environment around your application and test only the interesting combinations of dependent components therein, releasing only those combinations that pass your product's entire test suite. Then you can say "here's a box that has our functional X pre-configured and we make no claims of compatibility with any other products or combinations of component versions". Application specific VM's are the best at reducing the problem space to economically manageable surfaces. Even somewhat leaky environments like app containers can help tame this tiger.
7,976,088
``` gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 c89 ``` Just wondering is there a better way to do this with the code I have provided below. I am building a sdp (session description protocol) string from some parameters. However, I might need to extend the sdp to include other parameters i.e. video codecs. However, I don't really want to have another if else to build the complete string I have done below. I am just wondering is this scalable enough? Is there any technique I could use that is better than what I have done. I have just copied the function that does the sdp building: ``` void create_sdp_string(char *sdp_string, char reinvite) { char session_id[MAX_STRING_LEN]; char session_version[MAX_STRING_LEN]; const char *local_ip_addr = "10.10.10.244"; apr_time_t time_usec = 0; char session_identifier[MAX_STRING_LEN]; char media_transport[MAX_STRING_LEN]; char connection_info[MAX_STRING_LEN]; const char *audio_port = "49152"; /* Required sdp attributes */ #define V_PROTOCOL_VERSION "0" #define USERNAME "JOEBLOGGS" #define NETTYPE "IN" #define ADDR_TYPE "IP4" #define S_SESSION_NAME "SIP_CALL" #define T_TIME_DESCRIPTION "0 0" #define M_MEDIA_NAME_TRANSPORT_ADDR "RTP/AVP 0 8 101" #define A_PCMU "rtpmap:0 PCMU/8000" #define A_PCMA "rtpmap:8 PCMA/8000" #define A_TELEPHONE "rtpmap:101 telephone-event/8000" /* Get the time in micro seconds to create an unique session id */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Get the time in micro seconds to create an unique session version */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_version, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Build session identifier */ apr_snprintf(session_identifier, MAX_STRING_LEN, "o="USERNAME" "NETTYPE" %s %s "ADDR_TYPE" %s\n", session_id, session_version, local_ip_addr); /* Build media transport */ apr_snprintf(media_transport, MAX_STRING_LEN, "m=audio %s "M_MEDIA_NAME_TRANSPORT_ADDR"\n", audio_port); /* Build connection information */ apr_snprintf(connection_info, MAX_STRING_LEN, "c="NETTYPE" "ADDR_TYPE" %s\n", local_ip_addr); if(reinvite == FALSE) { /* Build complete sdp string for cases that are not reinvite */ apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n", session_identifier, connection_info, media_transport); } else if(reinvite == TRUE) { /* Build complete sdp string for cases that are for reinvite 'inactive' */ #define INACTIVE "inactive" apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n" "a="INACTIVE"\n", session_identifier, connection_info, media_transport); } } ```
2011/11/02
[ "https://Stackoverflow.com/questions/7976088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
I consider the `if/else if` statement at the bottom of your code to be pretty ugly because you have copied a lot of code to two different places. You might edit it one place but forget to edit it in another. You should really try to avoid this. One way to do this is to replace the `if/else if` statement with this: ``` apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n" "%s", session_identifier, connection_info, media_transport, reinvite ? "a=inactive\n" : ""); ``` **EDIT1:** Another way to make this code better would be to write your own version of printf adds bytes to sdp\_string, and then call that function once for each different piece of information you want to add to the string.
If there is a performance bottleneck in your code this is not the `if/else` structure, but the fact that you scan all your strings several times. Basically you use your variant of `snprintf` mostly to concatenate strings, this is very unefficient. Switch to a strategy that writes the strings in place just one after another, as you would do with `fputs` if this were a file: * first, for the two numbers that you print, keep track of the resulting string length which is given through the return of `snprintf`. * for all constant strings instead of placing them in `#define` put the in a real array such as `static char const V_PROTOCOL_VERSION = { "0" };`. the size of such an string is a compile time constant that you can optain by `(sizeof V_PROTOCOL_VERSION)-1`. * for the output string, keep a pointer to the actual position to write * write the current string into that position and update your pointer with the known length of the string that you have written This ensures that you touch all those constant strings exactly once per character that you copy.
7,976,088
``` gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 c89 ``` Just wondering is there a better way to do this with the code I have provided below. I am building a sdp (session description protocol) string from some parameters. However, I might need to extend the sdp to include other parameters i.e. video codecs. However, I don't really want to have another if else to build the complete string I have done below. I am just wondering is this scalable enough? Is there any technique I could use that is better than what I have done. I have just copied the function that does the sdp building: ``` void create_sdp_string(char *sdp_string, char reinvite) { char session_id[MAX_STRING_LEN]; char session_version[MAX_STRING_LEN]; const char *local_ip_addr = "10.10.10.244"; apr_time_t time_usec = 0; char session_identifier[MAX_STRING_LEN]; char media_transport[MAX_STRING_LEN]; char connection_info[MAX_STRING_LEN]; const char *audio_port = "49152"; /* Required sdp attributes */ #define V_PROTOCOL_VERSION "0" #define USERNAME "JOEBLOGGS" #define NETTYPE "IN" #define ADDR_TYPE "IP4" #define S_SESSION_NAME "SIP_CALL" #define T_TIME_DESCRIPTION "0 0" #define M_MEDIA_NAME_TRANSPORT_ADDR "RTP/AVP 0 8 101" #define A_PCMU "rtpmap:0 PCMU/8000" #define A_PCMA "rtpmap:8 PCMA/8000" #define A_TELEPHONE "rtpmap:101 telephone-event/8000" /* Get the time in micro seconds to create an unique session id */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Get the time in micro seconds to create an unique session version */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_version, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Build session identifier */ apr_snprintf(session_identifier, MAX_STRING_LEN, "o="USERNAME" "NETTYPE" %s %s "ADDR_TYPE" %s\n", session_id, session_version, local_ip_addr); /* Build media transport */ apr_snprintf(media_transport, MAX_STRING_LEN, "m=audio %s "M_MEDIA_NAME_TRANSPORT_ADDR"\n", audio_port); /* Build connection information */ apr_snprintf(connection_info, MAX_STRING_LEN, "c="NETTYPE" "ADDR_TYPE" %s\n", local_ip_addr); if(reinvite == FALSE) { /* Build complete sdp string for cases that are not reinvite */ apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n", session_identifier, connection_info, media_transport); } else if(reinvite == TRUE) { /* Build complete sdp string for cases that are for reinvite 'inactive' */ #define INACTIVE "inactive" apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n" "a="INACTIVE"\n", session_identifier, connection_info, media_transport); } } ```
2011/11/02
[ "https://Stackoverflow.com/questions/7976088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
If you want something more generic look at this: ``` void append_to_sdp_string(char *sdp_string, char *param) { int size = strlen(sdp_string); apr_snprintf(sdp_string + size, MAX_SDP_STRING_LEN - size, "%s\n", param); } void create_sdp_string(char *sdp_string, char reinvite) { /* Defines and variables here */ apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long) apr_time_usec(apr_time_now()); apr_snprintf(session_version, MAX_STRING_LEN, "%lu", (unsigned long) apr_time_usec(apr_time_now()); apr_snprintf(session_identifier, MAX_STRING_LEN, "o="USERNAME" "NETTYPE" %s %s "ADDR_TYPE" %s", session_id, session_version, local_ip_addr); apr_snprintf(media_transport, MAX_STRING_LEN, "m=audio %s "M_MEDIA_NAME_TRANSPORT_ADDR"", audio_port); apr_snprintf(connection_info, MAX_STRING_LEN, "c="NETTYPE" "ADDR_TYPE" %s", local_ip_addr); append_to_sdp_string(sdp_string, "v="V_PROTOCOL_VERSION); append_to_sdp_string(sdp_string, session_identifier); append_to_sdp_string(sdp_string, "s="S_SESSION_NAME); append_to_sdp_string(sdp_string, connection_info); append_to_sdp_string(sdp_string, "t="T_TIME_DESCRIPTION); append_to_sdp_string(sdp_string, media_transport); append_to_sdp_string(sdp_string, "a="A_PCMU); append_to_sdp_string(sdp_string, "a="A_PCMA); append_to_sdp_string(sdp_string, "a="A_TELEPHONE); if(reinvite == TRUE) append_to_sdp_string(sdp_string, "a="INACTIVE); /* Here you can add as many simple conditional appends as you need */ } ``` This way it's easy to append anything to string which you already created.
I consider the `if/else if` statement at the bottom of your code to be pretty ugly because you have copied a lot of code to two different places. You might edit it one place but forget to edit it in another. You should really try to avoid this. One way to do this is to replace the `if/else if` statement with this: ``` apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n" "%s", session_identifier, connection_info, media_transport, reinvite ? "a=inactive\n" : ""); ``` **EDIT1:** Another way to make this code better would be to write your own version of printf adds bytes to sdp\_string, and then call that function once for each different piece of information you want to add to the string.
7,976,088
``` gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 c89 ``` Just wondering is there a better way to do this with the code I have provided below. I am building a sdp (session description protocol) string from some parameters. However, I might need to extend the sdp to include other parameters i.e. video codecs. However, I don't really want to have another if else to build the complete string I have done below. I am just wondering is this scalable enough? Is there any technique I could use that is better than what I have done. I have just copied the function that does the sdp building: ``` void create_sdp_string(char *sdp_string, char reinvite) { char session_id[MAX_STRING_LEN]; char session_version[MAX_STRING_LEN]; const char *local_ip_addr = "10.10.10.244"; apr_time_t time_usec = 0; char session_identifier[MAX_STRING_LEN]; char media_transport[MAX_STRING_LEN]; char connection_info[MAX_STRING_LEN]; const char *audio_port = "49152"; /* Required sdp attributes */ #define V_PROTOCOL_VERSION "0" #define USERNAME "JOEBLOGGS" #define NETTYPE "IN" #define ADDR_TYPE "IP4" #define S_SESSION_NAME "SIP_CALL" #define T_TIME_DESCRIPTION "0 0" #define M_MEDIA_NAME_TRANSPORT_ADDR "RTP/AVP 0 8 101" #define A_PCMU "rtpmap:0 PCMU/8000" #define A_PCMA "rtpmap:8 PCMA/8000" #define A_TELEPHONE "rtpmap:101 telephone-event/8000" /* Get the time in micro seconds to create an unique session id */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Get the time in micro seconds to create an unique session version */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_version, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); /* Build session identifier */ apr_snprintf(session_identifier, MAX_STRING_LEN, "o="USERNAME" "NETTYPE" %s %s "ADDR_TYPE" %s\n", session_id, session_version, local_ip_addr); /* Build media transport */ apr_snprintf(media_transport, MAX_STRING_LEN, "m=audio %s "M_MEDIA_NAME_TRANSPORT_ADDR"\n", audio_port); /* Build connection information */ apr_snprintf(connection_info, MAX_STRING_LEN, "c="NETTYPE" "ADDR_TYPE" %s\n", local_ip_addr); if(reinvite == FALSE) { /* Build complete sdp string for cases that are not reinvite */ apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n", session_identifier, connection_info, media_transport); } else if(reinvite == TRUE) { /* Build complete sdp string for cases that are for reinvite 'inactive' */ #define INACTIVE "inactive" apr_snprintf(sdp_string, MAX_SDP_STRING_LEN, "v="V_PROTOCOL_VERSION"\n" "%s" "s="S_SESSION_NAME"\n" "%s" "t="T_TIME_DESCRIPTION"\n" "%s" "a="A_PCMU"\n" "a="A_PCMA"\n" "a="A_TELEPHONE"\n" "a="INACTIVE"\n", session_identifier, connection_info, media_transport); } } ```
2011/11/02
[ "https://Stackoverflow.com/questions/7976088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
If you want something more generic look at this: ``` void append_to_sdp_string(char *sdp_string, char *param) { int size = strlen(sdp_string); apr_snprintf(sdp_string + size, MAX_SDP_STRING_LEN - size, "%s\n", param); } void create_sdp_string(char *sdp_string, char reinvite) { /* Defines and variables here */ apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long) apr_time_usec(apr_time_now()); apr_snprintf(session_version, MAX_STRING_LEN, "%lu", (unsigned long) apr_time_usec(apr_time_now()); apr_snprintf(session_identifier, MAX_STRING_LEN, "o="USERNAME" "NETTYPE" %s %s "ADDR_TYPE" %s", session_id, session_version, local_ip_addr); apr_snprintf(media_transport, MAX_STRING_LEN, "m=audio %s "M_MEDIA_NAME_TRANSPORT_ADDR"", audio_port); apr_snprintf(connection_info, MAX_STRING_LEN, "c="NETTYPE" "ADDR_TYPE" %s", local_ip_addr); append_to_sdp_string(sdp_string, "v="V_PROTOCOL_VERSION); append_to_sdp_string(sdp_string, session_identifier); append_to_sdp_string(sdp_string, "s="S_SESSION_NAME); append_to_sdp_string(sdp_string, connection_info); append_to_sdp_string(sdp_string, "t="T_TIME_DESCRIPTION); append_to_sdp_string(sdp_string, media_transport); append_to_sdp_string(sdp_string, "a="A_PCMU); append_to_sdp_string(sdp_string, "a="A_PCMA); append_to_sdp_string(sdp_string, "a="A_TELEPHONE); if(reinvite == TRUE) append_to_sdp_string(sdp_string, "a="INACTIVE); /* Here you can add as many simple conditional appends as you need */ } ``` This way it's easy to append anything to string which you already created.
If there is a performance bottleneck in your code this is not the `if/else` structure, but the fact that you scan all your strings several times. Basically you use your variant of `snprintf` mostly to concatenate strings, this is very unefficient. Switch to a strategy that writes the strings in place just one after another, as you would do with `fputs` if this were a file: * first, for the two numbers that you print, keep track of the resulting string length which is given through the return of `snprintf`. * for all constant strings instead of placing them in `#define` put the in a real array such as `static char const V_PROTOCOL_VERSION = { "0" };`. the size of such an string is a compile time constant that you can optain by `(sizeof V_PROTOCOL_VERSION)-1`. * for the output string, keep a pointer to the actual position to write * write the current string into that position and update your pointer with the known length of the string that you have written This ensures that you touch all those constant strings exactly once per character that you copy.
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In C++, the easiest way of doing it is like this: ``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var(3, std::vector<int>(3)); // code return var; } ``` You need to include `<vector>` in order for this to compile. Unlike Java generic containers, C++ template containers do not incur the cost of wrapping primitives into objects, so they can stay extremely efficient in terms of performance and memory consumption while providing a great deal of additional flexibility. In general, you should prefer C++ - style containers (`std::vector`, `std::set`, `std::map`, and in C++11, `std::array`) to their less flexible built-in alternatives "inherited" from C.
``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var; // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In C++, the easiest way of doing it is like this: ``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var(3, std::vector<int>(3)); // code return var; } ``` You need to include `<vector>` in order for this to compile. Unlike Java generic containers, C++ template containers do not incur the cost of wrapping primitives into objects, so they can stay extremely efficient in terms of performance and memory consumption while providing a great deal of additional flexibility. In general, you should prefer C++ - style containers (`std::vector`, `std::set`, `std::map`, and in C++11, `std::array`) to their less flexible built-in alternatives "inherited" from C.
You wouldn't use C arrays (which notationally look like Java arrays) in C++, you'd use `vector`: ``` typedef std::vector<std::vector<int> > VecType; VecType theFunction() { VecType var(3, std::vector<int>(3)); // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In C++, the easiest way of doing it is like this: ``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var(3, std::vector<int>(3)); // code return var; } ``` You need to include `<vector>` in order for this to compile. Unlike Java generic containers, C++ template containers do not incur the cost of wrapping primitives into objects, so they can stay extremely efficient in terms of performance and memory consumption while providing a great deal of additional flexibility. In general, you should prefer C++ - style containers (`std::vector`, `std::set`, `std::map`, and in C++11, `std::array`) to their less flexible built-in alternatives "inherited" from C.
As others have said, you can return a `std::vector<std::vector<int> >`. It's worth pointing out that this is a case where C++'s [Return Value Optimization](http://en.wikipedia.org/wiki/Return_value_optimization "Return Value Optimization") can be very important -- in particular, just looking at this code, you might think that the entire vector-of-vectors must get copied when the function returns (since C++ functions' return values are returned by value). But this optimization, which is explicitly permitted by C++ and is implemented by almost any compiler, allows the function to allocate the vector in whatever structure it will be returned into.
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In C++, the easiest way of doing it is like this: ``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var(3, std::vector<int>(3)); // code return var; } ``` You need to include `<vector>` in order for this to compile. Unlike Java generic containers, C++ template containers do not incur the cost of wrapping primitives into objects, so they can stay extremely efficient in terms of performance and memory consumption while providing a great deal of additional flexibility. In general, you should prefer C++ - style containers (`std::vector`, `std::set`, `std::map`, and in C++11, `std::array`) to their less flexible built-in alternatives "inherited" from C.
In short, in C (which is the, let's say, dialect you're using from C++ [C++ is a superset of C, with some modifications]) you cannot return a vector nor matrix from a function. You can, though, return a pointer (and probably that's not going to help you very much). In C and C++, the name of the vector (let's simplify it) is a pointer to the first position, so: ``` int v[] = { 1, 2, 3 }; int * ptr = v; ``` A pointer is a memory address, you can use that in order to run over all elements (though it can be dangerous): ``` for( ; ptr < ( v + 3 ); ++ptr) { std::cout << *ptr << stD::endl; } ``` And that pointer can be returned: ``` int * vectorCreator(int max) { int * v = new int[max]; return v; } ``` Beware that, in this case, the caller takes the responsibility of freeing the vector once is done. This is a problem you can solve with `auto_ptr` (which is obsolete with the new standard, you should use `unique_ptr` once your compiler allows it). ``` auto_ptr<int> vectorCreator(int max) { int * v = new int[max]; return auto_ptr<int>( v ); } ``` In this very direction works part of the C++ standard library, in which you can use the `vector<>` template, which is safer, and definitely more comfortable. Hope this helps.
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
As others have said, you can return a `std::vector<std::vector<int> >`. It's worth pointing out that this is a case where C++'s [Return Value Optimization](http://en.wikipedia.org/wiki/Return_value_optimization "Return Value Optimization") can be very important -- in particular, just looking at this code, you might think that the entire vector-of-vectors must get copied when the function returns (since C++ functions' return values are returned by value). But this optimization, which is explicitly permitted by C++ and is implemented by almost any compiler, allows the function to allocate the vector in whatever structure it will be returned into.
``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var; // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In short, in C (which is the, let's say, dialect you're using from C++ [C++ is a superset of C, with some modifications]) you cannot return a vector nor matrix from a function. You can, though, return a pointer (and probably that's not going to help you very much). In C and C++, the name of the vector (let's simplify it) is a pointer to the first position, so: ``` int v[] = { 1, 2, 3 }; int * ptr = v; ``` A pointer is a memory address, you can use that in order to run over all elements (though it can be dangerous): ``` for( ; ptr < ( v + 3 ); ++ptr) { std::cout << *ptr << stD::endl; } ``` And that pointer can be returned: ``` int * vectorCreator(int max) { int * v = new int[max]; return v; } ``` Beware that, in this case, the caller takes the responsibility of freeing the vector once is done. This is a problem you can solve with `auto_ptr` (which is obsolete with the new standard, you should use `unique_ptr` once your compiler allows it). ``` auto_ptr<int> vectorCreator(int max) { int * v = new int[max]; return auto_ptr<int>( v ); } ``` In this very direction works part of the C++ standard library, in which you can use the `vector<>` template, which is safer, and definitely more comfortable. Hope this helps.
``` std::vector<std::vector<int> > theFunction() { std::vector<std::vector<int> > var; // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
As others have said, you can return a `std::vector<std::vector<int> >`. It's worth pointing out that this is a case where C++'s [Return Value Optimization](http://en.wikipedia.org/wiki/Return_value_optimization "Return Value Optimization") can be very important -- in particular, just looking at this code, you might think that the entire vector-of-vectors must get copied when the function returns (since C++ functions' return values are returned by value). But this optimization, which is explicitly permitted by C++ and is implemented by almost any compiler, allows the function to allocate the vector in whatever structure it will be returned into.
You wouldn't use C arrays (which notationally look like Java arrays) in C++, you'd use `vector`: ``` typedef std::vector<std::vector<int> > VecType; VecType theFunction() { VecType var(3, std::vector<int>(3)); // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In short, in C (which is the, let's say, dialect you're using from C++ [C++ is a superset of C, with some modifications]) you cannot return a vector nor matrix from a function. You can, though, return a pointer (and probably that's not going to help you very much). In C and C++, the name of the vector (let's simplify it) is a pointer to the first position, so: ``` int v[] = { 1, 2, 3 }; int * ptr = v; ``` A pointer is a memory address, you can use that in order to run over all elements (though it can be dangerous): ``` for( ; ptr < ( v + 3 ); ++ptr) { std::cout << *ptr << stD::endl; } ``` And that pointer can be returned: ``` int * vectorCreator(int max) { int * v = new int[max]; return v; } ``` Beware that, in this case, the caller takes the responsibility of freeing the vector once is done. This is a problem you can solve with `auto_ptr` (which is obsolete with the new standard, you should use `unique_ptr` once your compiler allows it). ``` auto_ptr<int> vectorCreator(int max) { int * v = new int[max]; return auto_ptr<int>( v ); } ``` In this very direction works part of the C++ standard library, in which you can use the `vector<>` template, which is safer, and definitely more comfortable. Hope this helps.
You wouldn't use C arrays (which notationally look like Java arrays) in C++, you'd use `vector`: ``` typedef std::vector<std::vector<int> > VecType; VecType theFunction() { VecType var(3, std::vector<int>(3)); // code return var; } ```
13,977,737
Being a Java-programmer, I have a hard time getting a function to return a multidimensional array. How would i code this in C++?: ``` int[][] theFunction(){ int[][] var = new int[3][3]; // code return var; } ```
2012/12/20
[ "https://Stackoverflow.com/questions/13977737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919607/" ]
In short, in C (which is the, let's say, dialect you're using from C++ [C++ is a superset of C, with some modifications]) you cannot return a vector nor matrix from a function. You can, though, return a pointer (and probably that's not going to help you very much). In C and C++, the name of the vector (let's simplify it) is a pointer to the first position, so: ``` int v[] = { 1, 2, 3 }; int * ptr = v; ``` A pointer is a memory address, you can use that in order to run over all elements (though it can be dangerous): ``` for( ; ptr < ( v + 3 ); ++ptr) { std::cout << *ptr << stD::endl; } ``` And that pointer can be returned: ``` int * vectorCreator(int max) { int * v = new int[max]; return v; } ``` Beware that, in this case, the caller takes the responsibility of freeing the vector once is done. This is a problem you can solve with `auto_ptr` (which is obsolete with the new standard, you should use `unique_ptr` once your compiler allows it). ``` auto_ptr<int> vectorCreator(int max) { int * v = new int[max]; return auto_ptr<int>( v ); } ``` In this very direction works part of the C++ standard library, in which you can use the `vector<>` template, which is safer, and definitely more comfortable. Hope this helps.
As others have said, you can return a `std::vector<std::vector<int> >`. It's worth pointing out that this is a case where C++'s [Return Value Optimization](http://en.wikipedia.org/wiki/Return_value_optimization "Return Value Optimization") can be very important -- in particular, just looking at this code, you might think that the entire vector-of-vectors must get copied when the function returns (since C++ functions' return values are returned by value). But this optimization, which is explicitly permitted by C++ and is implemented by almost any compiler, allows the function to allocate the vector in whatever structure it will be returned into.
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
`for(var i = 0; i === i; i++) {}`
``` for(let index = 0; true; index++){ console.log(index) } ``` it will work slowly but it will work.
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
``` for(var i = 0; i === i; i++) {} ``` should crash your current window
Simple bookmarklet that crashes your chromebook. If you try to shut down your chromebook and open it again, the screen will stay on for 5 seconds. ``` javascript:while (true) { window.location.reload(true); }; ```
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
```html <!DOCTYPE html> <html> <body> <h2>Crashing Now</h2> <p>Hit Ok To Crash</p> <p id="demo"></p> <script> onbeforeunload = function(){localStorage.x=1}; if(confirm("Do you REALLY want me to crash your browser?")){ setTimeout(function(){ while(1)location.reload(1) }, 1000) } </script> </body> </html> ```
Google Chrome Crashers Websites List 1. chrome://badcastcrash 2. chrome://inducebrowsercrashforrealz 3. chrome://crash 4. chrome://crashdump 5. chrome://kill 6. chrome://hang 7. chrome://shorthang 8. chrome://gpuclean 9. chrome://gpucrash 10. chrome://gpuhang 11. chrome://memory-exhaust 12. chrome://memory-pressure-critical 13. chrome://memory-pressure-moderate 14. chrome://ppapiflashcrash 15. chrome://ppapiflashhang 16. chrome://quit 17. chrome://restart
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
```html <!DOCTYPE html> <html> <body> <h2>Crashing Now</h2> <p>Hit Ok To Crash</p> <p id="demo"></p> <script> onbeforeunload = function(){localStorage.x=1}; if(confirm("Do you REALLY want me to crash your browser?")){ setTimeout(function(){ while(1)location.reload(1) }, 1000) } </script> </body> </html> ```
This link: ```html http://a/%%30%30 ``` will crash chrome because it results in a null character. Try it!
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
Google Chrome Crashers Websites List 1. chrome://badcastcrash 2. chrome://inducebrowsercrashforrealz 3. chrome://crash 4. chrome://crashdump 5. chrome://kill 6. chrome://hang 7. chrome://shorthang 8. chrome://gpuclean 9. chrome://gpucrash 10. chrome://gpuhang 11. chrome://memory-exhaust 12. chrome://memory-pressure-critical 13. chrome://memory-pressure-moderate 14. chrome://ppapiflashcrash 15. chrome://ppapiflashhang 16. chrome://quit 17. chrome://restart
Simple bookmarklet that crashes your chromebook. If you try to shut down your chromebook and open it again, the screen will stay on for 5 seconds. ``` javascript:while (true) { window.location.reload(true); }; ```
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
there is one way... ``` while(true){ var dp = document.getElementByID("spamr"); if(!document.getElementByID("spamr")){ var dp = document.createElementByID("spamr"); dp.innerHTML += ""; } dp.innerHTML += ""; } ```
I don't think there's any way to actually crash a client's browser via JS. However, it's possible to just perform tons of useless calculations rendering a tab useless. ``` while(true) { for(let i = 99; i === i; i *= i) { console.log(i); }; }; ```
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
This works, but slowly, it will make the browser unresponsive immediately though. ``` try { window.location.replace("chrome://quit") //some old browsers support this, if they are useing VERY old chromium. } finally { history.pushState(null, document.title, location.href); window.addEventListener('popstate', function(event) { history.pushState(null, document.title, location.href); }) while(true) { let location = 1 let item = 1 localStorage.setItem(location, item) location = location+1 item = item*2 localStorage.getItem(location) console.log("added and used: "+item+" at "+location) } } if (window.closed) { window.location.replace("run.html") } ```
Simple bookmarklet that crashes your chromebook. If you try to shut down your chromebook and open it again, the screen will stay on for 5 seconds. ``` javascript:while (true) { window.location.reload(true); }; ```
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
**WARNING this will crash ANY browser or the computer using PopUps attack**: If you want to crash somebodies computer or browser **PopUp CODE that CRASHES a browser or computer** ``` <script type="text/javascript"> function CrashAndBurn(url) { popupWindow = window.open( url,'popUpWindow','height=181,width=666,left=3,top=222') } </script> <body onload="JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');"> ``` If you really want to make their browser seriously hang up, you use this popup it will continue to uploading with 2 more and 2 more popup pages for each popup that means 2x2 popups second time 4 popups then 8, 16, 32, 64 and so on popups. It makes **as if was a virus it will spread PopUps in the browser, filling the screen with popups till either the computer or the browser crashes and hangs up and shuts down, just...** **NOTE: You did not hear this from me OKAY... LOL... I ONLY advice this as a piratical joke on a friend and not for an online web page.** If you wish to make it crash faster then just add more `JavaScript:CrashAndBurn(self.location,'_blank');` to onload body like this example x4: ``` <body onload="JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');"> ``` It will load 4 popups for each popup that emans after 4 popups it will load 4x4 meaning 18 popups and then 18x4 that is 72 and then 72x4 that is 288 popups and then 288x4 that is 1152 popups just in 4 rounds of popups in a few seconds. And if you want to be **EXTREME HORRIBLE** then use x10 example: ``` <body onload="JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');JavaScript:CrashAndBurn(self.location,'_blank');"> ``` and you have 8 popups with 10 that is 10x10=100 popups and then 1000 and after that 1 000 000 popups and GUARANTEED crash fast. ***EDIT* You can use a while loop instead of copy-pasting 10 times. It would be much shorter.**
This link: ```html http://a/%%30%30 ``` will crash chrome because it results in a null character. Try it!
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
Works in chrome, edge, IE: ``` while(1)location.reload(1) ``` Continuously hard reload current page (works best over http/https) And to prevent user from closing tab: ``` onbeforeunload = () => true; //only works if the user has interacted with the page ``` Recap: ```js onbeforeunload = () => true; if(confirm("Do you REALLY want to crash your browser?")){ setTimeout(function(){ while(1)location.reload(1) }, 1000) } ``` **WARNING: THIS WILL COMPLETELY AND UTTERLY CRASH ANY INSTANCES OF CHROME and, if you're running on chromebook or any old OS, this will completely crash your entire system!** EDIT: a version that works for safari: ``` window.onload=()=>location.hash="M"+"\u0001".repeat(2**25)+"m"; ```
``` for(let index = 0; true; index++){ console.log(index) } ``` it will work slowly but it will work.
40,367,127
In Rust, a do-while style loop can be written: ``` loop { something(); if !test() { break; } } ``` Note that the purpose of using the do-while form instead of `while test() { something() }`, is that `test()` may need to run *after* `something()`. This works, but when the logic is wrapped in a macro, it's less obvious what happens when `continue` is used. It will skip the test, potentially entering an infinite loop: ``` macro_rules! loop_over_items { ($item:expr, $iter:ident, $code:block) => { { let first = $item.first; let mut $iter = first; loop { $code $iter = $iter.next; if (first != $iter) { break; } } } } } ``` This works in a basic case: ``` loop_over_items!(item, iter_elem, { code_to_run; }); ``` But this may enter an infinite loop which isn't very obvious at first glance: ``` loop_over_items!(item, iter_elem, { if some_test() { continue; } code_to_run; }); ``` What would be a good method in Rust to write a macro that supports use of `continue` skipping the logic after `$code`?
2016/11/01
[ "https://Stackoverflow.com/questions/40367127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432509/" ]
``` for(var i = 0; i === i; i++) {} ``` should crash your current window
``` for(let index = 0; true; index++){ console.log(index) } ``` it will work slowly but it will work.
38,376,724
[enter image description here](http://i.stack.imgur.com/SP7Re.png)I am creating a query of two values, a period number and the corresponding date. The periods are accounting periods that are similar but not identical to our months. The dates are largely correct, but there are a few inconsistencies that I thought I would clean up with a WHERE statement. For example, the date 4/1/2015 belongs in period 3, but it shows up in both period 3 and period 4. To fix this, I thought that I would create a WHERE statement stating: ``` SELECT DISTINCT table1.period, table1.datetime FROM table1 WHERE table1.period <> 4 AND table1.datetime <> '4/1/2015' ``` This took away all of period 4 away instead of just the one I needed. I have also tried the datetime syntax: ``` AND table1.datetime <> '20150401 00:00:00.000' ``` Both syntaxes had the same results. I am fairly inexperienced at SQL and have always hated dealing with datetime values, so any help would be great. -EDIT- Forgot to add single quotations to the first datetime WHERE clause.
2016/07/14
[ "https://Stackoverflow.com/questions/38376724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6489423/" ]
Try following: ``` SELECT DISTINCT table1.period, table1.datetime FROM table1 WHERE CASE WHEN table1.period = 4 AND CONVERT(VARCHAR(8),table1.datetime,112) = '20150401' THEN 1 ELSE 0 END = 0 ``` This only get rid of rows that both has `period=4` and `datetime=20150401`, while your query first get rid of anything that has `period=4`(no matter what [datetime] is), then get rid of anything has `datetime=20150401`.
Did you say that period is a string field ? you mean a varchar ? Also you want to check on the date part only, not the time ? then you can try this ``` SELECT DISTINCT table1.period, table1.datetime FROM table1 WHERE table1.period <> '4' AND convert(date, table1.datetime) <> '20150401' ```
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
I had previously done up #7. It was the first time I used Windbg and so I didn't know what to do with the address to find the references. Here is what I got. ``` Address MT Size 0131c9c0 55cd21d8 84 013479e0 55cd21d8 84 044dabe0 55cd21d8 84 total 3 objects Statistics: MT Count TotalSize Class Name 55cd21d8 3 252 System.Windows.Documents.FlowDocument Total 3 objects 0:011> !gcroot 0131c9c0 Note: Roots found on stacks may be false positives. Run "!help gcroot" for more info. Scan Thread 0 OSTHread 47c Scan Thread 2 OSTHread be8 Scan Thread 4 OSTHread 498 DOMAIN(001657B0):HANDLE(WeakSh):911788:Root:0131ff98(System.EventHandler)-> 0131fcd4(System.Windows.Documents.AdornerLayer)-> 012fad68(MemoryTesting.Window2)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):911cb0:Root:0131ca90(MS.Internal.PtsHost.PtsContext)-> 0131cb14(MS.Internal.PtsHost.PtsContext+HandleIndex[])-> 0133d668(MS.Internal.PtsHost.TextParagraph)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):9124a8:Root:01320a2c(MS.Internal.PtsHost.FlowDocumentPage)-> 0133d5d0(System.Windows.Documents.TextPointer)-> 0131ca14(System.Windows.Documents.TextContainer)-> 0131c9c0(System.Windows.Documents.FlowDocument) ``` (I put it in a code block for easier reading). This is after I closed the window. So it looks like it is being referenced by a few things. Now that I know this how do I go about freeing up these references so they can release the FlowDocument. Thanks for your help. I feel like I am finally gaining some ground.
I tried to reproduce your problem, but it doesn't happen on my machine. Task Manager shows working set size, which isn't an accurate representation of a program's memory usage. Try using perfmon instead. 1. Start -> Run -> perfmon.msc 2. Add .NET CLR Memory/#Bytes in All Heaps for your application Now repeat the experiment and check if that counter keeps going up. If it doesn't, it means you aren't leaking any managed memory.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
If I've confirmed that there's a memory leak, here's what I would do to debug the problem. 1. Install Debugging Tools for Windows from <http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#a> 2. Fire up Windbg from the installation directory. 3. Launch your application and do the operations that leak memory. 4. Attach Windbg to your application (F6). 5. Type `.loadby sos mscorwks` 6. Type `!dumpheap -type FlowDocument` 7. Check the result of the above command. If you see multiple FlowDocuments, for each value of the first column (which contains the address), do Type `!gcroot <value of first column>` That should show you who's holding on to the reference.
I tried to reproduce your problem, but it doesn't happen on my machine. Task Manager shows working set size, which isn't an accurate representation of a program's memory usage. Try using perfmon instead. 1. Start -> Run -> perfmon.msc 2. Add .NET CLR Memory/#Bytes in All Heaps for your application Now repeat the experiment and check if that counter keeps going up. If it doesn't, it means you aren't leaking any managed memory.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
FlowDocument uses System.Windows.Threading.Dispatcher to free all resources. It doesn't use finalizers because finalizers will block current thread until all resources will be free. So the user may see some UI freezings and so on. Dispatchers are running in background thread and have less impact on the UI. So calling GC.WaitForPendingFinalizers(); has no influence on this. You just need to add some code to wait and allow Dispatchers to finish their work. Just try to add something like Thread.CurrentThread.Sleep(2000 /\* 2 secs \*/); EDIT: It seems to me that you found this problem during debugging of some application. I wrote the following very simple test case (console program): ``` static void Main(string[] args) { Console.WriteLine("press enter to start"); Console.ReadLine(); var path = "c:\\1.rtf"; for (var i = 0; i < 20; i++) { using (var stream = new FileStream(path, FileMode.Open)) { var document = new FlowDocument(); var range = new TextRange(document.ContentStart, document.ContentEnd); range.Load(stream, DataFormats.Rtf); } } Console.WriteLine("press enter to run GC."); Console.ReadLine(); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("GC has finished ."); Console.ReadLine(); } ``` I've tried to reproduce the problem. I run it several times and it was working perfectly - there were no leaks (about 3,2Kb all of the time and 36 handles). I couldn't reproduce it until I run this program in debug mode in the VS (just f5 instead of ctrl+f5). I received 20,5Kb at the beginning, 31,7Kb after loading and before GC and 31Kb after GC. It looks similar to your results. So, could you please try to reproduce this problem running in release mode not under the VS?
`GC.Collect()` by itself won't collect everything, you need to run: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` Also, I've found the runtime doesn't always release collected memory right away, you should check the actual heap size instead of relying on task manager.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
If I've confirmed that there's a memory leak, here's what I would do to debug the problem. 1. Install Debugging Tools for Windows from <http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#a> 2. Fire up Windbg from the installation directory. 3. Launch your application and do the operations that leak memory. 4. Attach Windbg to your application (F6). 5. Type `.loadby sos mscorwks` 6. Type `!dumpheap -type FlowDocument` 7. Check the result of the above command. If you see multiple FlowDocuments, for each value of the first column (which contains the address), do Type `!gcroot <value of first column>` That should show you who's holding on to the reference.
FlowDocument uses System.Windows.Threading.Dispatcher to free all resources. It doesn't use finalizers because finalizers will block current thread until all resources will be free. So the user may see some UI freezings and so on. Dispatchers are running in background thread and have less impact on the UI. So calling GC.WaitForPendingFinalizers(); has no influence on this. You just need to add some code to wait and allow Dispatchers to finish their work. Just try to add something like Thread.CurrentThread.Sleep(2000 /\* 2 secs \*/); EDIT: It seems to me that you found this problem during debugging of some application. I wrote the following very simple test case (console program): ``` static void Main(string[] args) { Console.WriteLine("press enter to start"); Console.ReadLine(); var path = "c:\\1.rtf"; for (var i = 0; i < 20; i++) { using (var stream = new FileStream(path, FileMode.Open)) { var document = new FlowDocument(); var range = new TextRange(document.ContentStart, document.ContentEnd); range.Load(stream, DataFormats.Rtf); } } Console.WriteLine("press enter to run GC."); Console.ReadLine(); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("GC has finished ."); Console.ReadLine(); } ``` I've tried to reproduce the problem. I run it several times and it was working perfectly - there were no leaks (about 3,2Kb all of the time and 36 handles). I couldn't reproduce it until I run this program in debug mode in the VS (just f5 instead of ctrl+f5). I received 20,5Kb at the beginning, 31,7Kb after loading and before GC and 31Kb after GC. It looks similar to your results. So, could you please try to reproduce this problem running in release mode not under the VS?
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
We had a similar problem in which we were creating flow document in different thread, i noticed in memory profiler that objects were still there. So far as i know, as described in this [link](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/) "When a FlowDocument is created, relatively expensive formatting context objects are also created for it in its StructuralCache. When you create multiple FlowDocs in a tight loop, a StructuralCache is created for each FlowDoc. Let's you called Gc.Collect at the end of the loop, hoping to recover some memory. StructuralCache has a finalizer releases this formatting context, but not immediately. The finalizer effectively schedules an operation to release contexts at DispatcherPriority.Background." So until the dispatcher operations are completed, Flow document will be in memory. So the idea is to complete the dispatcher operations. If you are in a thread in which Dispatcher is currently running then try code below, it will force all the operations in queue to be completed, as SystemIdle is the lowest priority: ``` Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.SystemIdle, new DispatcherOperationCallback(delegate { return null; }), null); ``` If you are in a thread in which Dispatcher is not running, as in my case only single flow document was created in thread, so i tried something like: ``` var dispatcher = Dispatcher.CurrentDispatcher; dispatcher.BeginInvokeShutdown(DispatcherPriority.SystemIdle); Dispatcher.Run(); ``` this will queue a shut down at very end and then will run the dispatcher to clean the FlowDocument and then in end it will shut down the dispatcher.
I tried to reproduce your problem, but it doesn't happen on my machine. Task Manager shows working set size, which isn't an accurate representation of a program's memory usage. Try using perfmon instead. 1. Start -> Run -> perfmon.msc 2. Add .NET CLR Memory/#Bytes in All Heaps for your application Now repeat the experiment and check if that counter keeps going up. If it doesn't, it means you aren't leaking any managed memory.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
I had previously done up #7. It was the first time I used Windbg and so I didn't know what to do with the address to find the references. Here is what I got. ``` Address MT Size 0131c9c0 55cd21d8 84 013479e0 55cd21d8 84 044dabe0 55cd21d8 84 total 3 objects Statistics: MT Count TotalSize Class Name 55cd21d8 3 252 System.Windows.Documents.FlowDocument Total 3 objects 0:011> !gcroot 0131c9c0 Note: Roots found on stacks may be false positives. Run "!help gcroot" for more info. Scan Thread 0 OSTHread 47c Scan Thread 2 OSTHread be8 Scan Thread 4 OSTHread 498 DOMAIN(001657B0):HANDLE(WeakSh):911788:Root:0131ff98(System.EventHandler)-> 0131fcd4(System.Windows.Documents.AdornerLayer)-> 012fad68(MemoryTesting.Window2)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):911cb0:Root:0131ca90(MS.Internal.PtsHost.PtsContext)-> 0131cb14(MS.Internal.PtsHost.PtsContext+HandleIndex[])-> 0133d668(MS.Internal.PtsHost.TextParagraph)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):9124a8:Root:01320a2c(MS.Internal.PtsHost.FlowDocumentPage)-> 0133d5d0(System.Windows.Documents.TextPointer)-> 0131ca14(System.Windows.Documents.TextContainer)-> 0131c9c0(System.Windows.Documents.FlowDocument) ``` (I put it in a code block for easier reading). This is after I closed the window. So it looks like it is being referenced by a few things. Now that I know this how do I go about freeing up these references so they can release the FlowDocument. Thanks for your help. I feel like I am finally gaining some ground.
Make sure that the Parent of the FlowDocument isn't hanging around, see [here](http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument(VS.85).aspx). "Instantiating a FlowDocument automatically spawns a parent FlowDocumentPageViewer that hosts the content." If that control is hanging around it could be the source of your problem.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
We had a similar problem in which we were creating flow document in different thread, i noticed in memory profiler that objects were still there. So far as i know, as described in this [link](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/) "When a FlowDocument is created, relatively expensive formatting context objects are also created for it in its StructuralCache. When you create multiple FlowDocs in a tight loop, a StructuralCache is created for each FlowDoc. Let's you called Gc.Collect at the end of the loop, hoping to recover some memory. StructuralCache has a finalizer releases this formatting context, but not immediately. The finalizer effectively schedules an operation to release contexts at DispatcherPriority.Background." So until the dispatcher operations are completed, Flow document will be in memory. So the idea is to complete the dispatcher operations. If you are in a thread in which Dispatcher is currently running then try code below, it will force all the operations in queue to be completed, as SystemIdle is the lowest priority: ``` Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.SystemIdle, new DispatcherOperationCallback(delegate { return null; }), null); ``` If you are in a thread in which Dispatcher is not running, as in my case only single flow document was created in thread, so i tried something like: ``` var dispatcher = Dispatcher.CurrentDispatcher; dispatcher.BeginInvokeShutdown(DispatcherPriority.SystemIdle); Dispatcher.Run(); ``` this will queue a shut down at very end and then will run the dispatcher to clean the FlowDocument and then in end it will shut down the dispatcher.
`GC.Collect()` by itself won't collect everything, you need to run: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` Also, I've found the runtime doesn't always release collected memory right away, you should check the actual heap size instead of relying on task manager.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
FlowDocument uses System.Windows.Threading.Dispatcher to free all resources. It doesn't use finalizers because finalizers will block current thread until all resources will be free. So the user may see some UI freezings and so on. Dispatchers are running in background thread and have less impact on the UI. So calling GC.WaitForPendingFinalizers(); has no influence on this. You just need to add some code to wait and allow Dispatchers to finish their work. Just try to add something like Thread.CurrentThread.Sleep(2000 /\* 2 secs \*/); EDIT: It seems to me that you found this problem during debugging of some application. I wrote the following very simple test case (console program): ``` static void Main(string[] args) { Console.WriteLine("press enter to start"); Console.ReadLine(); var path = "c:\\1.rtf"; for (var i = 0; i < 20; i++) { using (var stream = new FileStream(path, FileMode.Open)) { var document = new FlowDocument(); var range = new TextRange(document.ContentStart, document.ContentEnd); range.Load(stream, DataFormats.Rtf); } } Console.WriteLine("press enter to run GC."); Console.ReadLine(); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("GC has finished ."); Console.ReadLine(); } ``` I've tried to reproduce the problem. I run it several times and it was working perfectly - there were no leaks (about 3,2Kb all of the time and 36 handles). I couldn't reproduce it until I run this program in debug mode in the VS (just f5 instead of ctrl+f5). I received 20,5Kb at the beginning, 31,7Kb after loading and before GC and 31Kb after GC. It looks similar to your results. So, could you please try to reproduce this problem running in release mode not under the VS?
I tried to reproduce your problem, but it doesn't happen on my machine. Task Manager shows working set size, which isn't an accurate representation of a program's memory usage. Try using perfmon instead. 1. Start -> Run -> perfmon.msc 2. Add .NET CLR Memory/#Bytes in All Heaps for your application Now repeat the experiment and check if that counter keeps going up. If it doesn't, it means you aren't leaking any managed memory.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
I had previously done up #7. It was the first time I used Windbg and so I didn't know what to do with the address to find the references. Here is what I got. ``` Address MT Size 0131c9c0 55cd21d8 84 013479e0 55cd21d8 84 044dabe0 55cd21d8 84 total 3 objects Statistics: MT Count TotalSize Class Name 55cd21d8 3 252 System.Windows.Documents.FlowDocument Total 3 objects 0:011> !gcroot 0131c9c0 Note: Roots found on stacks may be false positives. Run "!help gcroot" for more info. Scan Thread 0 OSTHread 47c Scan Thread 2 OSTHread be8 Scan Thread 4 OSTHread 498 DOMAIN(001657B0):HANDLE(WeakSh):911788:Root:0131ff98(System.EventHandler)-> 0131fcd4(System.Windows.Documents.AdornerLayer)-> 012fad68(MemoryTesting.Window2)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):911cb0:Root:0131ca90(MS.Internal.PtsHost.PtsContext)-> 0131cb14(MS.Internal.PtsHost.PtsContext+HandleIndex[])-> 0133d668(MS.Internal.PtsHost.TextParagraph)-> 0131c9c0(System.Windows.Documents.FlowDocument) DOMAIN(001657B0):HANDLE(WeakSh):9124a8:Root:01320a2c(MS.Internal.PtsHost.FlowDocumentPage)-> 0133d5d0(System.Windows.Documents.TextPointer)-> 0131ca14(System.Windows.Documents.TextContainer)-> 0131c9c0(System.Windows.Documents.FlowDocument) ``` (I put it in a code block for easier reading). This is after I closed the window. So it looks like it is being referenced by a few things. Now that I know this how do I go about freeing up these references so they can release the FlowDocument. Thanks for your help. I feel like I am finally gaining some ground.
`GC.Collect()` by itself won't collect everything, you need to run: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` Also, I've found the runtime doesn't always release collected memory right away, you should check the actual heap size instead of relying on task manager.
952,985
I am currently attempting to deal with an issue with releasing a FlowDocument resources. I am loading an rtf file and putting it into a FlowDocument with TextRange.Load. I noticed that after it does this it holds onto those resources and GC doesn't collect it. I have ran a memory profiler and have seen that this is true. I have also narrowed it down to were I load actually put the rtf into the FlowDocument. If I dont do that, then everything is ok. So I know this is the issue. I am hoping for some guidance to what how I can solve this problem. Here is the code that loads the rtf and everything. I have commented all of the other code out and even put it in its own scope as well as tried GC.Collect(). Any help is greatly appreciated. EDIT: Here is my code in full at the moment. I have taken out everything else except for the bare essentials to get it running. The problem is still there. As you can see the FlowDocument and TextRange are not referenced anywhere else. ``` public LoadRTFWindow(string file) { InitializeComponent(); using (FileStream reader = new FileStream(file, FileMode.Open)) { FlowDocument doc = new FlowDocument(); TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(reader, System.Windows.DataFormats.Rtf); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } ``` I found [this post](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9cba6b80-c402-4f89-b300-6a9f8e4d7e37/), which I was hoping would help me solve my problem but I had no luck with it. Any type of help is greatly appreciated. Thank you. EDIT: I figure I should mention the major way I am checking this. I have Windows Task Manager open and am watching the memory usage my application's process is using. When I run the above code the application goes from 40,000K to 70,000K while doing the TextRange.Load() (this is a large 400 page RTF) and once that finishes it drops down to 61,000K and stays there. My expectation is that it would drop back down to 40,000K or at least very close to it. As I mentioned earlier I used a memory profiler and saw that there were LOTS of Paragraph, Run..ect. objects still Alive afterwards.
2009/06/04
[ "https://Stackoverflow.com/questions/952985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82896/" ]
If I've confirmed that there's a memory leak, here's what I would do to debug the problem. 1. Install Debugging Tools for Windows from <http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#a> 2. Fire up Windbg from the installation directory. 3. Launch your application and do the operations that leak memory. 4. Attach Windbg to your application (F6). 5. Type `.loadby sos mscorwks` 6. Type `!dumpheap -type FlowDocument` 7. Check the result of the above command. If you see multiple FlowDocuments, for each value of the first column (which contains the address), do Type `!gcroot <value of first column>` That should show you who's holding on to the reference.
`GC.Collect()` by itself won't collect everything, you need to run: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` Also, I've found the runtime doesn't always release collected memory right away, you should check the actual heap size instead of relying on task manager.
948,741
The problem states to prove that if $h$ is a branch of $f^{1/n}$ for integer $n > 0$ (i.e. $h(z)^n = f(z)$ for $z \in G$, $h$ continuous), then $h$ is holomorphic, where $f$ is a holomorphic function on an open connected subset $G$ of $\mathbb{C}$ and $f \neq 0$ on $G$. I'm not sure where to start; the Cauchy-Riemann equations seem to be a bad route. I was thinking of trying to prove by contradiction that if $h$ is not complex differentiable at a point, then $f$ must have a point where it's not complex differentiable, but that hasn't been fruitful. Algebraic manipulation of the limit definition of a derivative doesn't seem to be a good idea either. Any tips?
2014/09/27
[ "https://math.stackexchange.com/questions/948741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/95668/" ]
Hint: try with branch of logarithmic function.
Let $a\in G$. We need to show that $h$ is differentiable at $a$. As $G$ is open there exists a disc $D(a,r)\subset G$. Now as $f$ does not vanish in $G$, and hence in $D(a,r)$, we define the function $$ F(z)=\int\_{[a,z]}\frac{f'}{f}. $$ Then $F$ is holomorphic in $D(a,r)$ and the product $\exp(-F(z))f(z)$ is constant in $D(a,r)$, as $$ \big(\exp(-F(z))f(z)\big)'=-\exp(-F(z))F'(z)f(z)+\exp(-F(z))f'(z)=0. $$ Let $c=\exp(-F(z))f(z)$ or equivalently $f(z)=c\exp(F(z))$. Clearly $c\ne 0$, as $f$ does not vanish. Set now $$ g(z)=c\_1\exp\left(\frac{F(z)}{n}\right). $$ Then $g$ is holomorphic in $D(a,r)$ and choose $c\_1$ so that $\left(g(z)\right)^n=f(z)$ - i.e., $c\_1^n=c$. But $\big(h(z)\big)^n=f(z)$, as well, and therefore $$ \left(\frac{h}{g}\right)^n=1, \quad z\in D(a,r). $$ Thus, for all $z\in D(a,r)$: $$ \frac{h(z)}{g(z)}\in\{\mathrm{e}^{2k\pi i/n}: k=0,\ldots,n-1\}, $$ and as the latter set is discrete and $h/g$ is continuous on the connected set $D(a,r)$, then $f/g$ is constant, and hence $h$ is holomorphic in $D(a,r)$. But $a$ was chosen arbitrarily, and hence $h$ is holomorphic on the whole $G$.
15,811,456
I'm making a sudoku field in a windows form application (c#) I've used a TableLayout to make my boxes to put labels in for the numbers displayed in the sudoku, now I need a thick border around every group of 3x3 cells (like a sudoku)... I'm trying with the CellPaint object but I can't set a border around a group of borders...
2013/04/04
[ "https://Stackoverflow.com/questions/15811456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2244887/" ]
You should add a second type parameter on your `Map` method, along with an appropriate [type constraint](http://msdn.microsoft.com/en-us/library/d5x73970.aspx): ``` public static void Map<TEntityTrack, TEntity>() where TEntityTrack : EntityTrack<TEntity> { var entityType = typeof(TEntity); } ```
If I understood you correctly, you can get the type of the generic parameter using the following statement: ``` Type param = typeof(TEntity); ```
15,811,456
I'm making a sudoku field in a windows form application (c#) I've used a TableLayout to make my boxes to put labels in for the numbers displayed in the sudoku, now I need a thick border around every group of 3x3 cells (like a sudoku)... I'm trying with the CellPaint object but I can't set a border around a group of borders...
2013/04/04
[ "https://Stackoverflow.com/questions/15811456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2244887/" ]
If you want to get the type in runtime you can do the following: ``` Type[] genericTypes = typeof(TEntityTrack).GetGenericArguments(); Type entityType = genericTypes[0]; ``` adding all the proper bounds-checking etc, of course. EDIT: In order to find the generic arguments of the base type. ``` Type type = typeof(TEntityTrack); while (type != typeof(object)) { Type[] genericTypes = type.GetGenericArguments(); if (genericTypes.Length == 0) { type = type.BaseType; } else { Type entityType = genericTypes[0]; return entityType; } } // Throw an exception or other appropriate action throw Exception("Does not have generic argument."); ```
If I understood you correctly, you can get the type of the generic parameter using the following statement: ``` Type param = typeof(TEntity); ```
15,811,456
I'm making a sudoku field in a windows form application (c#) I've used a TableLayout to make my boxes to put labels in for the numbers displayed in the sudoku, now I need a thick border around every group of 3x3 cells (like a sudoku)... I'm trying with the CellPaint object but I can't set a border around a group of borders...
2013/04/04
[ "https://Stackoverflow.com/questions/15811456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2244887/" ]
You should add a second type parameter on your `Map` method, along with an appropriate [type constraint](http://msdn.microsoft.com/en-us/library/d5x73970.aspx): ``` public static void Map<TEntityTrack, TEntity>() where TEntityTrack : EntityTrack<TEntity> { var entityType = typeof(TEntity); } ```
If you want to get the type in runtime you can do the following: ``` Type[] genericTypes = typeof(TEntityTrack).GetGenericArguments(); Type entityType = genericTypes[0]; ``` adding all the proper bounds-checking etc, of course. EDIT: In order to find the generic arguments of the base type. ``` Type type = typeof(TEntityTrack); while (type != typeof(object)) { Type[] genericTypes = type.GetGenericArguments(); if (genericTypes.Length == 0) { type = type.BaseType; } else { Type entityType = genericTypes[0]; return entityType; } } // Throw an exception or other appropriate action throw Exception("Does not have generic argument."); ```
362,729
A nice little oddity which I thought I'd ask about. I stumbled across the delightful word 'Boustrophedon' in relation to the scanning actions of some printers (inkjet/dot matrix). I believe that this roughly derives from the notion of 'As the ox ploughs the field'. I mentioned this to a colleague who had a farming background. He stated that in older times, this isn't actually how an ox would have ploughed the field, owing to the direction the plough would have turned the earth. Apparently, the field would have been ploughed in spiral pattern to ensure that meeting edges of the plough lines would have their earth turned in the same direction, or 'like the spider builds its web'. Which got me thinking. Is there a colourful noun of some sort that describes this sort of pattern/action?
2016/12/09
[ "https://english.stackexchange.com/questions/362729", "https://english.stackexchange.com", "https://english.stackexchange.com/users/3477/" ]
Perhaps you'll find it easier to read when it's formatted as: > > The construction ***the number of + plural noun*** is used with a > singular verb (as in *the number of people affected remains small*). > Thus it is the noun *number* rather than the noun *people* which is > taken to agree with the verb (and which is therefore functioning as > the head noun). > > > By contrast, the apparently similar construction ***a number of + > plural noun*** is used with a plural verb (as in *a number of people > remain to be contacted*). In this case it is the noun *people* which > acts as the head noun and with which the verb agrees. In the latter > case, ***a number of*** works as if it were a single word, such as > *some* or *several*. > > >
The excerpt from the OED describes the situation like this: * [**the number of X**] is a singular noun phrase which takes singular agreement. The Head noun here according to the OED is the singular noun *number*: > > The number of applicants **has** increased. > > > --- * [**a number of X**] is a plural noun phrase which takes plural agreement. The Head of this noun phrase is the plural noun, *X*: > > A number of applicants **have** applied for the position. > > >
38,274,955
I'm trying to make a script that takes in an answer and appends it to a new list, then checks to see if the new list is the same as the other list. When these lists are the same, the while loop should break. **NOTE**: Each question should not repeat. Here's my **code**: ``` import random questions = ['a','b','c','d','e'] answered_q = [] while len(answered_q) < len(questions): question = random.choice(questions) answered_q.append(question) raw_input = str(input(question + ": ")) if sorted(questions) == sorted(answered_q): break ``` When executed I am still getting random questions but the code does not **break** when the lists have the same contents. **output** : `['b','c','b,'d','d']` If anyone can help it would be great! Thanks in advance!
2016/07/08
[ "https://Stackoverflow.com/questions/38274955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6412913/" ]
You have to add `position: relative` to your list items: ``` .buttons li { display: inline; font-size: 48px; margin: 5px; position: relative; } .count { z-index: 1; position: absolute; right: 0; bottom: 0; background-color: #d9534f; } ``` [JSFIDDLE](https://jsfiddle.net/ag1vgnqt/6/) --------------------------------------------
Something like this should work for your needs: ``` .count { z-index:1; position:relative; top:5px; right:18px; margin-right:-25px; background-color:#d9534f; } ``` Just changed position to `relative`, added a negative `margin-right` and slightly adjusted the other variables. The `.badge` not floats at the bottom right of the `.list` icon. [JSFiddle](https://jsfiddle.net/ag1vgnqt/4/)
4,961,117
I cannot figure this out! I am trying to get a list of a products attributes into an array on the list.phtml page. I have tried everything. I have seen a lot of solutions that use ``` $attributes = $product->getAttributes(); ``` but I cannot get this to work, it just brings up a blank page. Any help would be greatly appreciated, I have spent hours and hours on this so far... I am using Magento version 1.4.2.0 UPDATE: Here is exactly what I am trying to do: ``` $neededAttributes = Mage::helper('mymodule')->getNeededAttributes(); $attributes = $product->getAttributes(); foreach ($attributes as $attribute) { if(in_array($attribute->getAttributeCode(), $neededAttributes)) { $attributename = $attribute->getAttributeCode(); echo $attributename; } } ``` this is in the file gallery.phtml in design/adminhtml/default/default/catalog/product/helper/ For some reason, I cannot get the getAttributeCode function to return anything.
2011/02/10
[ "https://Stackoverflow.com/questions/4961117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/574480/" ]
I'm guessing you need a list of only visible values. I say "values" because attributes are not the actual values, they are descriptors. The following is the salient parts from `Mage_Mage_Catalog_Block_Product_View_Attributes`: ``` $attributes = $product->getAttributes(); foreach ($attributes as $attribute) { if ($attribute->getIsVisibleOnFront()) { $value = $attribute->getFrontend()->getValue($product); // do something with $value here } } ``` You don't really need to duplicate this though since you can alter/use the template `catalog/product/view/attributes.phtml` which is already declared on the product view page as `attributes` block.
It's rather easy and gives you an array of available product attribute names ``` $product = Mage::getModel('catalog/product')->load('product_id'); $attributeNames = array_keys($product->getData()); print_r($attributeNames); ``` If you need a attribute object collection you can call ``` $product->getAttributes(); ``` If you need a product collection and after that you can perform the previously mentioned ways on each collection member ``` Mage::getModel('catalog/product')->getCollection(); ```
4,961,117
I cannot figure this out! I am trying to get a list of a products attributes into an array on the list.phtml page. I have tried everything. I have seen a lot of solutions that use ``` $attributes = $product->getAttributes(); ``` but I cannot get this to work, it just brings up a blank page. Any help would be greatly appreciated, I have spent hours and hours on this so far... I am using Magento version 1.4.2.0 UPDATE: Here is exactly what I am trying to do: ``` $neededAttributes = Mage::helper('mymodule')->getNeededAttributes(); $attributes = $product->getAttributes(); foreach ($attributes as $attribute) { if(in_array($attribute->getAttributeCode(), $neededAttributes)) { $attributename = $attribute->getAttributeCode(); echo $attributename; } } ``` this is in the file gallery.phtml in design/adminhtml/default/default/catalog/product/helper/ For some reason, I cannot get the getAttributeCode function to return anything.
2011/02/10
[ "https://Stackoverflow.com/questions/4961117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/574480/" ]
According to your question, you should be using `Mage::getResourceModel('catalog/product_attribute_collection')` instead: ``` $productAttrs = Mage::getResourceModel('catalog/product_attribute_collection'); foreach ($productAttrs as $productAttr) { /** @var Mage_Catalog_Model_Resource_Eav_Attribute $productAttr */ var_dump($productAttr->getAttributeCode()); } ``` You don't always have attributes in the `_data` (`getData()`) storage and you don't always need to load a product to get its attributes.
It's rather easy and gives you an array of available product attribute names ``` $product = Mage::getModel('catalog/product')->load('product_id'); $attributeNames = array_keys($product->getData()); print_r($attributeNames); ``` If you need a attribute object collection you can call ``` $product->getAttributes(); ``` If you need a product collection and after that you can perform the previously mentioned ways on each collection member ``` Mage::getModel('catalog/product')->getCollection(); ```
4,961,117
I cannot figure this out! I am trying to get a list of a products attributes into an array on the list.phtml page. I have tried everything. I have seen a lot of solutions that use ``` $attributes = $product->getAttributes(); ``` but I cannot get this to work, it just brings up a blank page. Any help would be greatly appreciated, I have spent hours and hours on this so far... I am using Magento version 1.4.2.0 UPDATE: Here is exactly what I am trying to do: ``` $neededAttributes = Mage::helper('mymodule')->getNeededAttributes(); $attributes = $product->getAttributes(); foreach ($attributes as $attribute) { if(in_array($attribute->getAttributeCode(), $neededAttributes)) { $attributename = $attribute->getAttributeCode(); echo $attributename; } } ``` this is in the file gallery.phtml in design/adminhtml/default/default/catalog/product/helper/ For some reason, I cannot get the getAttributeCode function to return anything.
2011/02/10
[ "https://Stackoverflow.com/questions/4961117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/574480/" ]
I'm guessing you need a list of only visible values. I say "values" because attributes are not the actual values, they are descriptors. The following is the salient parts from `Mage_Mage_Catalog_Block_Product_View_Attributes`: ``` $attributes = $product->getAttributes(); foreach ($attributes as $attribute) { if ($attribute->getIsVisibleOnFront()) { $value = $attribute->getFrontend()->getValue($product); // do something with $value here } } ``` You don't really need to duplicate this though since you can alter/use the template `catalog/product/view/attributes.phtml` which is already declared on the product view page as `attributes` block.
According to your question, you should be using `Mage::getResourceModel('catalog/product_attribute_collection')` instead: ``` $productAttrs = Mage::getResourceModel('catalog/product_attribute_collection'); foreach ($productAttrs as $productAttr) { /** @var Mage_Catalog_Model_Resource_Eav_Attribute $productAttr */ var_dump($productAttr->getAttributeCode()); } ``` You don't always have attributes in the `_data` (`getData()`) storage and you don't always need to load a product to get its attributes.
16,097,031
Alright, let's say my MySQL table is set up with entries similar to: ``` id code sold 1 JKDA983J1KZMN49 0 2 JZMA093KANZB481 1 3 KZLMMA98309Z874 0 ``` I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it. Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going.
2013/04/19
[ "https://Stackoverflow.com/questions/16097031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297714/" ]
How about using a WHERE and ORDER BY RAND() ``` SELECT id, code FROM tablename WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```
Have you tried ``` SELECT * FROM myTable WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```
16,097,031
Alright, let's say my MySQL table is set up with entries similar to: ``` id code sold 1 JKDA983J1KZMN49 0 2 JZMA093KANZB481 1 3 KZLMMA98309Z874 0 ``` I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it. Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going.
2013/04/19
[ "https://Stackoverflow.com/questions/16097031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297714/" ]
How about using a WHERE and ORDER BY RAND() ``` SELECT id, code FROM tablename WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```
Adding `ORDER BY RAND()` to the rest of your `SELECT` query is the most straightforward way to accomplish this.
16,097,031
Alright, let's say my MySQL table is set up with entries similar to: ``` id code sold 1 JKDA983J1KZMN49 0 2 JZMA093KANZB481 1 3 KZLMMA98309Z874 0 ``` I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it. Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going.
2013/04/19
[ "https://Stackoverflow.com/questions/16097031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297714/" ]
How about using a WHERE and ORDER BY RAND() ``` SELECT id, code FROM tablename WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```
If you don't need the random, then don't use it. It can affect performance very negatively. Since you mentioned in your post that it wasn't necessary, I would recomment using Ezequiel's answer above and dropping the rand. See [Most Efficient Way To Retrieve MYSQL data in random order PHP](https://stackoverflow.com/questions/2564780/most-efficient-way-to-retrieve-mysql-data-in-random-order-php) for more info.
16,097,031
Alright, let's say my MySQL table is set up with entries similar to: ``` id code sold 1 JKDA983J1KZMN49 0 2 JZMA093KANZB481 1 3 KZLMMA98309Z874 0 ``` I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it. Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going.
2013/04/19
[ "https://Stackoverflow.com/questions/16097031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297714/" ]
How about using a WHERE and ORDER BY RAND() ``` SELECT id, code FROM tablename WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```
It seems that your codes are already random, so why not just take the first item; if you have many unsold records in your database, doing the typical `ORDER BY RAND()` will hurt the database performance. ``` SELECT * FROM codes WHERE sold = 0 LIMIT 1 FOR UPDATE; ``` I've also added `FOR UPDATE` to avoid race conditions, assuming that you're using transactions, as you update the record later (to actually sell it).
16,097,031
Alright, let's say my MySQL table is set up with entries similar to: ``` id code sold 1 JKDA983J1KZMN49 0 2 JZMA093KANZB481 1 3 KZLMMA98309Z874 0 ``` I'd like it to pick a random ID within the ranges already in the database (or just go from 1-X) and then just assign it to a variable for my own action to be taken. So let's say we want to pick **a** code that isn't sold (marked as 0 and not 1), then we'd pick it. Now, it doesn't have to be 100% random, it could check if the first one is sold, if not, keep going. But I'm not 100% sure on how to go by this. Snippets would be appreciated because I can work out things easily on my own, I just need an example to see where I am going.
2013/04/19
[ "https://Stackoverflow.com/questions/16097031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297714/" ]
If you don't need the random, then don't use it. It can affect performance very negatively. Since you mentioned in your post that it wasn't necessary, I would recomment using Ezequiel's answer above and dropping the rand. See [Most Efficient Way To Retrieve MYSQL data in random order PHP](https://stackoverflow.com/questions/2564780/most-efficient-way-to-retrieve-mysql-data-in-random-order-php) for more info.
Have you tried ``` SELECT * FROM myTable WHERE sold = 0 ORDER BY RAND() LIMIT 1 ```