qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
7,677,924
I'm new to Git and I'm a little confused how to use "git fetch" I have a central repository that I access using SSH, I have created a repository using git clone, just like this: ``` $ cd /my/local/repotest $ git clone ssh://[email protected]/var/github/repotest . ``` Now other developer have pushed some new files to the central repo in "somedomain.com" My question is, how can I fetch the new files and changes via command line?
2011/10/06
[ "https://Stackoverflow.com/questions/7677924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488735/" ]
From the C99 standard (§6.3.2.3/6): > > Any pointer type may be converted to an integer type. Except as previously specified, **the > result is implementation-defined**. If the result cannot be represented in the integer type, > the behavior is undefined. The result need not be in the range of values of any integer > type. > > > So you'll need to find your compiler's documentation that talks about that.
Integer constants (e.g, `0x00000000FFFFFFFF`) are signed integers by default, and hence may experience sign extension when assigned to a 64-bit variable. Try replacing the value on line 3 with: ``` 0x00000000FFFFFFFFULL ```
7,677,924
I'm new to Git and I'm a little confused how to use "git fetch" I have a central repository that I access using SSH, I have created a repository using git clone, just like this: ``` $ cd /my/local/repotest $ git clone ssh://[email protected]/var/github/repotest . ``` Now other developer have pushed some new files to the central repo in "somedomain.com" My question is, how can I fetch the new files and changes via command line?
2011/10/06
[ "https://Stackoverflow.com/questions/7677924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488735/" ]
From the C99 standard (§6.3.2.3/6): > > Any pointer type may be converted to an integer type. Except as previously specified, **the > result is implementation-defined**. If the result cannot be represented in the integer type, > the behavior is undefined. The result need not be in the range of values of any integer > type. > > > So you'll need to find your compiler's documentation that talks about that.
Use this to avoid the sign extension: ``` unsigned __int64 a = 0x00000000FFFFFFFFLL; ``` Note the L on the end. Without this it is interpreted as a 32-bit signed number (-1) and then cast.
7,677,924
I'm new to Git and I'm a little confused how to use "git fetch" I have a central repository that I access using SSH, I have created a repository using git clone, just like this: ``` $ cd /my/local/repotest $ git clone ssh://[email protected]/var/github/repotest . ``` Now other developer have pushed some new files to the central repo in "somedomain.com" My question is, how can I fetch the new files and changes via command line?
2011/10/06
[ "https://Stackoverflow.com/questions/7677924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488735/" ]
Converting a pointer to/from an integer is implementation defined. [Here](http://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-implementation.html) is how gcc does it, i.e. it sign extends if the integer type is larger than the pointer type(this'll happen regardless of the integer being signed or unsigned, just because that's how gcc decided to implement it). Presumably msvc behaves similar. Edit, the closest thing I can find on MSDN is [this](http://msdn.microsoft.com/en-us/library/aa983399.aspx)/[this](http://msdn.microsoft.com/en-us/library/aa384242%28v=vs.85%29.aspx), suggesting that converting 32 bit pointers to 64 bit also sign extends.
Integer constants (e.g, `0x00000000FFFFFFFF`) are signed integers by default, and hence may experience sign extension when assigned to a 64-bit variable. Try replacing the value on line 3 with: ``` 0x00000000FFFFFFFFULL ```
7,677,924
I'm new to Git and I'm a little confused how to use "git fetch" I have a central repository that I access using SSH, I have created a repository using git clone, just like this: ``` $ cd /my/local/repotest $ git clone ssh://[email protected]/var/github/repotest . ``` Now other developer have pushed some new files to the central repo in "somedomain.com" My question is, how can I fetch the new files and changes via command line?
2011/10/06
[ "https://Stackoverflow.com/questions/7677924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488735/" ]
Converting a pointer to/from an integer is implementation defined. [Here](http://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-implementation.html) is how gcc does it, i.e. it sign extends if the integer type is larger than the pointer type(this'll happen regardless of the integer being signed or unsigned, just because that's how gcc decided to implement it). Presumably msvc behaves similar. Edit, the closest thing I can find on MSDN is [this](http://msdn.microsoft.com/en-us/library/aa983399.aspx)/[this](http://msdn.microsoft.com/en-us/library/aa384242%28v=vs.85%29.aspx), suggesting that converting 32 bit pointers to 64 bit also sign extends.
Use this to avoid the sign extension: ``` unsigned __int64 a = 0x00000000FFFFFFFFLL; ``` Note the L on the end. Without this it is interpreted as a 32-bit signed number (-1) and then cast.
47,020,089
I've designed a login form in MS Access. I've different user roles and want to display different controls to at different user logins. For instance, if an admin is logged in, the controls should be different and a normal user should be able to use different controls. The vba code I've written for SignIn button on click is as follows (this code is for `Login_Form`): ``` Private Sub Btn_SignIn_Click() IF Me.Txt_UserID.Value = "admin" AND Me.Txt_Password = "123admin" AND Me.Cmbo_UserRole.Value = "DBA" THEN MsgBox "Welcome to RMS", vbOKOnly, "Logged in as Admin!" DoCmd.OpenForm "Main_Form" --How can I show/hide controls here at Main_Form End If ``` `Main_Form` has different controls, but I'm unable to access `Main_Form` controls inside `Btn_SignIn_Click()` function. So that, I might be able to show or hide controls.
2017/10/30
[ "https://Stackoverflow.com/questions/47020089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643351/" ]
You can require fs on client side using the following code in webpack.config.js ``` var fs = require('fs'); var nodeModules = {}; fs.readdirSync('node_modules') .filter(function(x) { return ['.bin'].indexOf(x) === -1; }) .forEach(function(mod) { nodeModules[mod] = 'commonjs ' + mod; }); ``` also add inside module.exports ``` externals: nodeModules, target: 'node', ``` this would help you to require fs inside client side.
In case with Webpack 4 i got same error: ``` Module not found: Error: Can't resolve 'fs' in ... ``` I fixed this error by adding section to root of `webpack.config.js` file: ```js ... node: { fs: "empty", }, ... ```
47,020,089
I've designed a login form in MS Access. I've different user roles and want to display different controls to at different user logins. For instance, if an admin is logged in, the controls should be different and a normal user should be able to use different controls. The vba code I've written for SignIn button on click is as follows (this code is for `Login_Form`): ``` Private Sub Btn_SignIn_Click() IF Me.Txt_UserID.Value = "admin" AND Me.Txt_Password = "123admin" AND Me.Cmbo_UserRole.Value = "DBA" THEN MsgBox "Welcome to RMS", vbOKOnly, "Logged in as Admin!" DoCmd.OpenForm "Main_Form" --How can I show/hide controls here at Main_Form End If ``` `Main_Form` has different controls, but I'm unable to access `Main_Form` controls inside `Btn_SignIn_Click()` function. So that, I might be able to show or hide controls.
2017/10/30
[ "https://Stackoverflow.com/questions/47020089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643351/" ]
You can require fs on client side using the following code in webpack.config.js ``` var fs = require('fs'); var nodeModules = {}; fs.readdirSync('node_modules') .filter(function(x) { return ['.bin'].indexOf(x) === -1; }) .forEach(function(mod) { nodeModules[mod] = 'commonjs ' + mod; }); ``` also add inside module.exports ``` externals: nodeModules, target: 'node', ``` this would help you to require fs inside client side.
At some point, I had used this include: ``` import { TRUE } from "node-sass"; ``` I simply commented it out. I was running all over the place trying to figure out what changed! Moral: sometimes it's not about chasing the error ONLY (because I was getting all kinds of suggestions). It's also about reviewing what you've done! Here is the FULL error with the uncommented code: ``` `WARNING in ./node_modules/node-sass/lib/binding.js 19:9-37 Critical dependency: the request of a dependency is an expression @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/fs.realpath/index.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\fs.realpath' @ ./node_modules/fs.realpath/index.js 8:9-22 @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/fs.realpath/old.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\fs.realpath' @ ./node_modules/fs.realpath/old.js 24:9-22 @ ./node_modules/fs.realpath/index.js @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/glob/glob.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\glob' @ ./node_modules/glob/glob.js 43:9-22 @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/glob/sync.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\glob' @ ./node_modules/glob/sync.js 4:9-22 @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/mkdirp/index.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\mkdirp' @ ./node_modules/mkdirp/index.js 2:9-22 @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/node-sass/lib/extensions.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\node-sass\lib' @ ./node_modules/node-sass/lib/extensions.js 6:7-20 @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js i 「wdm」: Failed to compile.` ```
47,020,089
I've designed a login form in MS Access. I've different user roles and want to display different controls to at different user logins. For instance, if an admin is logged in, the controls should be different and a normal user should be able to use different controls. The vba code I've written for SignIn button on click is as follows (this code is for `Login_Form`): ``` Private Sub Btn_SignIn_Click() IF Me.Txt_UserID.Value = "admin" AND Me.Txt_Password = "123admin" AND Me.Cmbo_UserRole.Value = "DBA" THEN MsgBox "Welcome to RMS", vbOKOnly, "Logged in as Admin!" DoCmd.OpenForm "Main_Form" --How can I show/hide controls here at Main_Form End If ``` `Main_Form` has different controls, but I'm unable to access `Main_Form` controls inside `Btn_SignIn_Click()` function. So that, I might be able to show or hide controls.
2017/10/30
[ "https://Stackoverflow.com/questions/47020089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643351/" ]
You can require fs on client side using the following code in webpack.config.js ``` var fs = require('fs'); var nodeModules = {}; fs.readdirSync('node_modules') .filter(function(x) { return ['.bin'].indexOf(x) === -1; }) .forEach(function(mod) { nodeModules[mod] = 'commonjs ' + mod; }); ``` also add inside module.exports ``` externals: nodeModules, target: 'node', ``` this would help you to require fs inside client side.
``` // Add somewhere close to the bottom directly above devtool: options.devtool ... node: { fs: 'empty' }, // This will cause the webpack to ignore fs dependencies. i.e. resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, node: { fs: 'empty' }, devtool: options.devtool, }); ```
47,020,089
I've designed a login form in MS Access. I've different user roles and want to display different controls to at different user logins. For instance, if an admin is logged in, the controls should be different and a normal user should be able to use different controls. The vba code I've written for SignIn button on click is as follows (this code is for `Login_Form`): ``` Private Sub Btn_SignIn_Click() IF Me.Txt_UserID.Value = "admin" AND Me.Txt_Password = "123admin" AND Me.Cmbo_UserRole.Value = "DBA" THEN MsgBox "Welcome to RMS", vbOKOnly, "Logged in as Admin!" DoCmd.OpenForm "Main_Form" --How can I show/hide controls here at Main_Form End If ``` `Main_Form` has different controls, but I'm unable to access `Main_Form` controls inside `Btn_SignIn_Click()` function. So that, I might be able to show or hide controls.
2017/10/30
[ "https://Stackoverflow.com/questions/47020089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643351/" ]
In case with Webpack 4 i got same error: ``` Module not found: Error: Can't resolve 'fs' in ... ``` I fixed this error by adding section to root of `webpack.config.js` file: ```js ... node: { fs: "empty", }, ... ```
At some point, I had used this include: ``` import { TRUE } from "node-sass"; ``` I simply commented it out. I was running all over the place trying to figure out what changed! Moral: sometimes it's not about chasing the error ONLY (because I was getting all kinds of suggestions). It's also about reviewing what you've done! Here is the FULL error with the uncommented code: ``` `WARNING in ./node_modules/node-sass/lib/binding.js 19:9-37 Critical dependency: the request of a dependency is an expression @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/fs.realpath/index.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\fs.realpath' @ ./node_modules/fs.realpath/index.js 8:9-22 @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/fs.realpath/old.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\fs.realpath' @ ./node_modules/fs.realpath/old.js 24:9-22 @ ./node_modules/fs.realpath/index.js @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/glob/glob.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\glob' @ ./node_modules/glob/glob.js 43:9-22 @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/glob/sync.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\glob' @ ./node_modules/glob/sync.js 4:9-22 @ ./node_modules/glob/glob.js @ ./node_modules/true-case-path/index.js @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/mkdirp/index.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\mkdirp' @ ./node_modules/mkdirp/index.js 2:9-22 @ ./node_modules/node-sass/lib/extensions.js @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js ERROR in ./node_modules/node-sass/lib/extensions.js Module not found: Error: Can't resolve 'fs' in 'D:\dev\xyz.io.1\node_modules\node-sass\lib' @ ./node_modules/node-sass/lib/extensions.js 6:7-20 @ ./node_modules/node-sass/lib/index.js @ ./src/components/form/Form.js @ ./src/components/app/App.js @ ./src/index.js i 「wdm」: Failed to compile.` ```
47,020,089
I've designed a login form in MS Access. I've different user roles and want to display different controls to at different user logins. For instance, if an admin is logged in, the controls should be different and a normal user should be able to use different controls. The vba code I've written for SignIn button on click is as follows (this code is for `Login_Form`): ``` Private Sub Btn_SignIn_Click() IF Me.Txt_UserID.Value = "admin" AND Me.Txt_Password = "123admin" AND Me.Cmbo_UserRole.Value = "DBA" THEN MsgBox "Welcome to RMS", vbOKOnly, "Logged in as Admin!" DoCmd.OpenForm "Main_Form" --How can I show/hide controls here at Main_Form End If ``` `Main_Form` has different controls, but I'm unable to access `Main_Form` controls inside `Btn_SignIn_Click()` function. So that, I might be able to show or hide controls.
2017/10/30
[ "https://Stackoverflow.com/questions/47020089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643351/" ]
In case with Webpack 4 i got same error: ``` Module not found: Error: Can't resolve 'fs' in ... ``` I fixed this error by adding section to root of `webpack.config.js` file: ```js ... node: { fs: "empty", }, ... ```
``` // Add somewhere close to the bottom directly above devtool: options.devtool ... node: { fs: 'empty' }, // This will cause the webpack to ignore fs dependencies. i.e. resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, node: { fs: 'empty' }, devtool: options.devtool, }); ```
793,691
[Circle packing theorem](http://en.wikipedia.org/wiki/Circle_packing_theorem) states: *For every connected simple planar graph G there is a circle packing in the plane whose intersection graph is (isomorphic to) G.* Paper [Collins, Stephenson: A circle packing algorithm](https://www.google.rs/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&ved=0CHAQFjAG&url=http://www.researchgate.net/publication/222403200_A_circle_packing_algorithm/file/50463521dfbd4a3c58.pdf&ei=aTRxU5_GD8ec0QW6x4DoCQ&usg=AFQjCNEEp_EJyMyfmDTikDCOnWdlNAm-ig&sig2=pU0zLPnoVh_U1GP868ln2A&bvm=bv.66330100,d.d2k&cad=rja) describes an algorithm for obtaining circle pack corresponding to a given planar graph. However, I tried searching internet for images of resulting circle packs, and I could hardly find just a few. Those that I found had some unusual beauty in them. I suspect whole beauty of such circle packs is still not discovered. I would like to know if somebody tried to generate circle packs corresponding to some known classes of planar graphs, like these: ![enter image description here](https://i.stack.imgur.com/msFdt.png) ![enter image description here](https://i.stack.imgur.com/VEaGD.png) ![enter image description here](https://i.stack.imgur.com/S8b4m.png) or similar? --- Some rare visual examples that I found on internet.: --- ![enter image description here](https://i.stack.imgur.com/omIfc.png) --- ![enter image description here](https://i.stack.imgur.com/gSPBW.png) --- ![enter image description here](https://i.stack.imgur.com/2Z7pz.jpg)
2014/05/13
[ "https://math.stackexchange.com/questions/793691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/121158/" ]
I have computed circle packings in various special cases taking advantage of symmetry. However, I have not implemented circle packing in full generality. ![enter image description here](https://i.stack.imgur.com/MlZjk.png) The US graph is featured in a review of [Hyperbolic Geometry](http://www.math.brown.edu/~rkenyon/papers/cannon.pdf) by Cannon, Floyed, Kenyon and Parry. Square tilings are another geometric object associated with planar graphs. ![enter image description here](https://i.stack.imgur.com/ktscE.png) --- It's hard to find good implementations of circle packing. Even we had some, the software is slowly going out of date. At least, a theory is pinned down in some papers: * [The convergence of circle packings to the Riemann mapping](http://projecteuclid.org/euclid.jdg/1214441375) that any graph has circle packings leads to a proof of the Riemann Mapping theorem * [On the convergence of circle packings to the Riemann Map](http://www.cs.jhu.edu/~misha/Fall09/He96.pdf) * [Approximation of Conformal Structures via Circle Packing](http://www.cs.jhu.edu/~misha/Fall09/Stephenson97.pdf) * [Wikipedia](https://en.wikipedia.org/wiki/Circle_packing_theorem) has many interesting references as well.
If you read the very last item in the paper that you linked, you will see that the authors of that paper give a [link to software that computes circle packings](http://www.math.utk.edu/~kens/).
29,316,318
I actually need a mysql query like ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, '%h:%i %p') ``` and as I use codeigniter i wrote query as below ``` $this->db->select("*,CONCAT(pri_hours,':', pri_minutes,' ',IF(pri_ampm = 1,'am','pm')) as hr",FALSE); $this->db->from('sms_primary'); $this->db->order_by("STR_TO_DATE(hr,'%h:%i %p')"); ``` But i am not getting the expected query i get it as below ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, `'%h:%i` %p') ``` I hope you spot out the difference in the generated query. Its a injection off some unwanted operator `. I just want to remove it.How to do that? Change ``` STR_TO_DATE(hr, `'%h:%i` %p') ``` to ``` STR_TO_DATE(hr, '%h:%i %p') ```
2015/03/28
[ "https://Stackoverflow.com/questions/29316318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531600/" ]
It should be simpler : ``` f.list((File a1, String a2) -> {return false;}); ``` or even : ``` f.list((a1,a2) -> {return false;}); ``` The lambda expression replaces the instantiation of the abstract class instance.
You don't have to put the class name, if you use a lambda-expression: ``` f.list( (File a1, String a2) -> { return false; } ); ``` In fact, in your first example, you omit `new Runnable()`.
29,316,318
I actually need a mysql query like ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, '%h:%i %p') ``` and as I use codeigniter i wrote query as below ``` $this->db->select("*,CONCAT(pri_hours,':', pri_minutes,' ',IF(pri_ampm = 1,'am','pm')) as hr",FALSE); $this->db->from('sms_primary'); $this->db->order_by("STR_TO_DATE(hr,'%h:%i %p')"); ``` But i am not getting the expected query i get it as below ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, `'%h:%i` %p') ``` I hope you spot out the difference in the generated query. Its a injection off some unwanted operator `. I just want to remove it.How to do that? Change ``` STR_TO_DATE(hr, `'%h:%i` %p') ``` to ``` STR_TO_DATE(hr, '%h:%i %p') ```
2015/03/28
[ "https://Stackoverflow.com/questions/29316318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531600/" ]
First things first, your formatting is **horrible**, sort it out! Now, lambda syntax; to convert the anonymous class: ``` final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return false; } }; ``` We start by replacing the anonymous class with an equivalent lambda for the single method `accept(File dir, String name)`: ``` final FilenameFilter filter = (File dir, String name) -> { return false; }; ``` But we can do better, we don't need to define the types - the compiler can work those out: ``` final FilenameFilter filter = (dir, name) -> { return false; }; ``` And we can do better still, as the method return a `boolean`; if we have a single statement that evaluates to a `boolean` we can skip the `return` and the braces: ``` final FilenameFilter filter = (dir, name) -> false; ``` This can be any statement, for example: ``` final FilenameFilter filter = (dir, name) -> !dir.isDirectory() && name.toLowerCase().endsWith(".txt"); ``` However, the `File` API is **very** old, so don't use it. Use the [`nio API`](http://docs.oracle.com/javase/tutorial/essential/io/pathClass.html). This has been around since Java 7 in 2011 so there is really **no** excuse: ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final DirectoryStream.Filter<Path> f = path -> false; try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, f)) { stream.forEach(System.out::println); } ``` And in fact your example has a specific method built into `Files` that [takes a Glob](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newDirectoryStream-java.nio.file.Path-java.lang.String-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, "*.txt")) { stream.forEach(System.out::println); } ``` Or, using the more modern [`Files.list`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#list-java.nio.file.Path-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final PathMatcher filter = p.getFileSystem().getPathMatcher("glob:*.txt"); try (final Stream<Path> stream = Files.list(p)) { stream.filter(filter::matches) .forEach(System.out::println); } ``` Here `filter::matches` is a method reference because the method `PathMatcher.matches` can be used to implement the functional interface `Predicate<Path>` as it takes a `Path` and returns a `boolean`. --- As an aside: ``` f.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { name.endsWith(".txt"); return false; } }); ``` This makes no sense...
You don't have to put the class name, if you use a lambda-expression: ``` f.list( (File a1, String a2) -> { return false; } ); ``` In fact, in your first example, you omit `new Runnable()`.
29,316,318
I actually need a mysql query like ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, '%h:%i %p') ``` and as I use codeigniter i wrote query as below ``` $this->db->select("*,CONCAT(pri_hours,':', pri_minutes,' ',IF(pri_ampm = 1,'am','pm')) as hr",FALSE); $this->db->from('sms_primary'); $this->db->order_by("STR_TO_DATE(hr,'%h:%i %p')"); ``` But i am not getting the expected query i get it as below ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, `'%h:%i` %p') ``` I hope you spot out the difference in the generated query. Its a injection off some unwanted operator `. I just want to remove it.How to do that? Change ``` STR_TO_DATE(hr, `'%h:%i` %p') ``` to ``` STR_TO_DATE(hr, '%h:%i %p') ```
2015/03/28
[ "https://Stackoverflow.com/questions/29316318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531600/" ]
`FileNameFilter` is a functional interface. You don't need to instantiate it explicitly. ``` f.list((dir, name) -> name.endsWith(".txt")); ``` Note also, that `f` should be a directory, not a file as in your example. Your example where `f1` is a file will return `null` with the specified filter.
You don't have to put the class name, if you use a lambda-expression: ``` f.list( (File a1, String a2) -> { return false; } ); ``` In fact, in your first example, you omit `new Runnable()`.
29,316,318
I actually need a mysql query like ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, '%h:%i %p') ``` and as I use codeigniter i wrote query as below ``` $this->db->select("*,CONCAT(pri_hours,':', pri_minutes,' ',IF(pri_ampm = 1,'am','pm')) as hr",FALSE); $this->db->from('sms_primary'); $this->db->order_by("STR_TO_DATE(hr,'%h:%i %p')"); ``` But i am not getting the expected query i get it as below ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, `'%h:%i` %p') ``` I hope you spot out the difference in the generated query. Its a injection off some unwanted operator `. I just want to remove it.How to do that? Change ``` STR_TO_DATE(hr, `'%h:%i` %p') ``` to ``` STR_TO_DATE(hr, '%h:%i %p') ```
2015/03/28
[ "https://Stackoverflow.com/questions/29316318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531600/" ]
First things first, your formatting is **horrible**, sort it out! Now, lambda syntax; to convert the anonymous class: ``` final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return false; } }; ``` We start by replacing the anonymous class with an equivalent lambda for the single method `accept(File dir, String name)`: ``` final FilenameFilter filter = (File dir, String name) -> { return false; }; ``` But we can do better, we don't need to define the types - the compiler can work those out: ``` final FilenameFilter filter = (dir, name) -> { return false; }; ``` And we can do better still, as the method return a `boolean`; if we have a single statement that evaluates to a `boolean` we can skip the `return` and the braces: ``` final FilenameFilter filter = (dir, name) -> false; ``` This can be any statement, for example: ``` final FilenameFilter filter = (dir, name) -> !dir.isDirectory() && name.toLowerCase().endsWith(".txt"); ``` However, the `File` API is **very** old, so don't use it. Use the [`nio API`](http://docs.oracle.com/javase/tutorial/essential/io/pathClass.html). This has been around since Java 7 in 2011 so there is really **no** excuse: ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final DirectoryStream.Filter<Path> f = path -> false; try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, f)) { stream.forEach(System.out::println); } ``` And in fact your example has a specific method built into `Files` that [takes a Glob](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newDirectoryStream-java.nio.file.Path-java.lang.String-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, "*.txt")) { stream.forEach(System.out::println); } ``` Or, using the more modern [`Files.list`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#list-java.nio.file.Path-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final PathMatcher filter = p.getFileSystem().getPathMatcher("glob:*.txt"); try (final Stream<Path> stream = Files.list(p)) { stream.filter(filter::matches) .forEach(System.out::println); } ``` Here `filter::matches` is a method reference because the method `PathMatcher.matches` can be used to implement the functional interface `Predicate<Path>` as it takes a `Path` and returns a `boolean`. --- As an aside: ``` f.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { name.endsWith(".txt"); return false; } }); ``` This makes no sense...
It should be simpler : ``` f.list((File a1, String a2) -> {return false;}); ``` or even : ``` f.list((a1,a2) -> {return false;}); ``` The lambda expression replaces the instantiation of the abstract class instance.
29,316,318
I actually need a mysql query like ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, '%h:%i %p') ``` and as I use codeigniter i wrote query as below ``` $this->db->select("*,CONCAT(pri_hours,':', pri_minutes,' ',IF(pri_ampm = 1,'am','pm')) as hr",FALSE); $this->db->from('sms_primary'); $this->db->order_by("STR_TO_DATE(hr,'%h:%i %p')"); ``` But i am not getting the expected query i get it as below ``` SELECT *, CONCAT(pri_hours, ':', pri_minutes, ' ', IF(pri_ampm = 1, 'am', 'pm')) as hr FROM (`sms_primary`) ORDER BY STR_TO_DATE(hr, `'%h:%i` %p') ``` I hope you spot out the difference in the generated query. Its a injection off some unwanted operator `. I just want to remove it.How to do that? Change ``` STR_TO_DATE(hr, `'%h:%i` %p') ``` to ``` STR_TO_DATE(hr, '%h:%i %p') ```
2015/03/28
[ "https://Stackoverflow.com/questions/29316318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531600/" ]
First things first, your formatting is **horrible**, sort it out! Now, lambda syntax; to convert the anonymous class: ``` final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return false; } }; ``` We start by replacing the anonymous class with an equivalent lambda for the single method `accept(File dir, String name)`: ``` final FilenameFilter filter = (File dir, String name) -> { return false; }; ``` But we can do better, we don't need to define the types - the compiler can work those out: ``` final FilenameFilter filter = (dir, name) -> { return false; }; ``` And we can do better still, as the method return a `boolean`; if we have a single statement that evaluates to a `boolean` we can skip the `return` and the braces: ``` final FilenameFilter filter = (dir, name) -> false; ``` This can be any statement, for example: ``` final FilenameFilter filter = (dir, name) -> !dir.isDirectory() && name.toLowerCase().endsWith(".txt"); ``` However, the `File` API is **very** old, so don't use it. Use the [`nio API`](http://docs.oracle.com/javase/tutorial/essential/io/pathClass.html). This has been around since Java 7 in 2011 so there is really **no** excuse: ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final DirectoryStream.Filter<Path> f = path -> false; try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, f)) { stream.forEach(System.out::println); } ``` And in fact your example has a specific method built into `Files` that [takes a Glob](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newDirectoryStream-java.nio.file.Path-java.lang.String-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(p, "*.txt")) { stream.forEach(System.out::println); } ``` Or, using the more modern [`Files.list`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#list-java.nio.file.Path-): ``` final Path p = Paths.get("/", "home", "text", "xyz.txt"); final PathMatcher filter = p.getFileSystem().getPathMatcher("glob:*.txt"); try (final Stream<Path> stream = Files.list(p)) { stream.filter(filter::matches) .forEach(System.out::println); } ``` Here `filter::matches` is a method reference because the method `PathMatcher.matches` can be used to implement the functional interface `Predicate<Path>` as it takes a `Path` and returns a `boolean`. --- As an aside: ``` f.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { name.endsWith(".txt"); return false; } }); ``` This makes no sense...
`FileNameFilter` is a functional interface. You don't need to instantiate it explicitly. ``` f.list((dir, name) -> name.endsWith(".txt")); ``` Note also, that `f` should be a directory, not a file as in your example. Your example where `f1` is a file will return `null` with the specified filter.
18,606,960
Can someone help me with a simple AJAX pagination in Codeigniter using JQuery? With the paginated list queryed from the database. I searched the web but all the exemples are very complex... Thank you in advance and sorry for my bad english...
2013/09/04
[ "https://Stackoverflow.com/questions/18606960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2728329/" ]
just use codeigniter pagination simple and use following code for pagination through jquery: ``` <script> $(function(){ $("#pagination-div-id a").click(function(){ $.ajax({ type: "POST", url: $(this).attr("href"), data:"q=<?php echo $searchString; ?>", success: function(res){ $("#containerid").html(res); } }); return false; }); }); </script> ``` Here pagination div id is the id of pagination container and containerid is simple the container id where you showing the result.
just use codeigniter pagination library and add the following function in the library after create links function ``` function create_links_ajax() { // If our item count or per-page total is zero there is no need to continue. if ($this->total_rows == 0 OR $this->per_page == 0) { return ''; } // Calculate the total number of pages $num_pages = ceil($this->total_rows / $this->per_page); // Is there only one page? Hm... nothing more to do here then. if ($num_pages == 1) { return ''; } // Set the base page index for starting page number if ($this->use_page_numbers) { $base_page = 1; } else { $base_page = 0; } // Determine the current page number. $CI =& get_instance(); if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) { if ($CI->input->get($this->query_string_segment) != $base_page) { $this->cur_page = $CI->input->get($this->query_string_segment); // Prep the current page - no funny business! $this->cur_page = (int) $this->cur_page; } } else { if ($CI->uri->segment($this->uri_segment) != $base_page) { $this->cur_page = $CI->uri->segment($this->uri_segment); // Prep the current page - no funny business! $this->cur_page = (int) $this->cur_page; } } // Set current page to 1 if using page numbers instead of offset if ($this->use_page_numbers AND $this->cur_page == 0) { $this->cur_page = $base_page; } $this->num_links = (int)$this->num_links; if ($this->num_links < 1) { show_error('Your number of links must be a positive number.'); } if ( ! is_numeric($this->cur_page)) { $this->cur_page = $base_page; } // Is the page number beyond the result range? // If so we show the last page if ($this->use_page_numbers) { if ($this->cur_page > $num_pages) { $this->cur_page = $num_pages; } } else { if ($this->cur_page > $this->total_rows) { $this->cur_page = ($num_pages - 1) * $this->per_page; } } $uri_page_number = $this->cur_page; if ( ! $this->use_page_numbers) { $this->cur_page = floor(($this->cur_page/$this->per_page) + 1); } // Calculate the start and end numbers. These determine // which number to start and end the digit links with $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1; $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages; // Is pagination being used over GET or POST? If get, add a per_page query // string. If post, add a trailing slash to the base URL if needed if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) { $this->base_url = rtrim($this->base_url).'&amp;'.$this->query_string_segment.'='; } else { $this->base_url = rtrim($this->base_url, '/') .'/'; } // And here we go... $output = ''; // Render the "First" link if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1)) { $first_url = ($this->first_url == '') ? $this->base_url : $this->first_url; $output .= $this->first_tag_open.'<a id="'.$first_url.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$this->first_link.'</a>'.$this->first_tag_close; } // Render the "previous" link if ($this->prev_link !== FALSE AND $this->cur_page != 1) { if ($this->use_page_numbers) { $i = $uri_page_number - 1; } else { $i = $uri_page_number - $this->per_page; } if ($i == 0 && $this->first_url != '') { $output .= $this->prev_tag_open.'<a id="'.$this->first_url.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->prev_link.'</a>'.$this->prev_tag_close; } else { $i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix; $output .= $this->prev_tag_open.'<a id="'.$this->base_url.$i.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->prev_link.'</a>'.$this->prev_tag_close; } } // Render the pages if ($this->display_pages !== FALSE) { // Write the digit links for ($loop = $start -1; $loop <= $end; $loop++) { if ($this->use_page_numbers) { $i = $loop; } else { $i = ($loop * $this->per_page) - $this->per_page; } if ($i >= $base_page) { if ($this->cur_page == $loop) { // $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page // $output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close; } else { $n = ($i == $base_page) ? '' : $i; if ($n == '' && $this->first_url != '') { $output .= $this->num_tag_open.'<a id="'.$this->first_url.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$loop.'</a>'.$this->num_tag_close; } else { $n = ($n == '') ? '' : $this->prefix.$n.$this->suffix; $output .= $this->num_tag_open.'<a id="'.$this->base_url.$n.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$loop.'</a>'.$this->num_tag_close; } } } } } // Render the "next" link if ($this->next_link !== FALSE AND $this->cur_page < $num_pages) { if ($this->use_page_numbers) { $i = $this->cur_page + 1; } else { $i = ($this->cur_page * $this->per_page); } $output .= $this->next_tag_open.'<a id="'.$this->base_url.$this->prefix.$i.$this->suffix.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->next_link.'</a>'.$this->next_tag_close; } // Render the "Last" link if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages) { if ($this->use_page_numbers) { $i = $num_pages; } else { $i = (($num_pages * $this->per_page) - $this->per_page); } $output .= $this->last_tag_open.'<a id="'.$this->base_url.$this->prefix.$i.$this->suffix.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)"'.$this->last_link.'</a>'.$this->last_tag_close; } // Kill double slashes. Note: Sometimes we can end up with a double slash // in the penultimate link so we'll kill all double slashes. $output = preg_replace("#([^:])//+#", "\\1/", $output); // Add the wrapper HTML if exists $output = $this->full_tag_open.$output.$this->full_tag_close; return $output; } ``` **and in the view create a function that will look like this** ``` function show_ajax_cards(obj) { var baseurl = obj.id; $.ajax({ url: baseurl, data:"baseurl="+baseurl, type: 'POST', success: function(html) { $('#cardReplace').html(html); } }); } ```
18,606,960
Can someone help me with a simple AJAX pagination in Codeigniter using JQuery? With the paginated list queryed from the database. I searched the web but all the exemples are very complex... Thank you in advance and sorry for my bad english...
2013/09/04
[ "https://Stackoverflow.com/questions/18606960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2728329/" ]
just use codeigniter pagination simple and use following code for pagination through jquery: ``` <script> $(function(){ $("#pagination-div-id a").click(function(){ $.ajax({ type: "POST", url: $(this).attr("href"), data:"q=<?php echo $searchString; ?>", success: function(res){ $("#containerid").html(res); } }); return false; }); }); </script> ``` Here pagination div id is the id of pagination container and containerid is simple the container id where you showing the result.
Apply Live click, if you are returning data from controller as follows: ``` jQuery("#pagination a").live('click',function(e){ e.preventDefault(); jQuery.ajax({ type: "POST", url: jQuery(this).attr("href"), success: function(res){ jQuery('#multiple_selection_data').html(res); } }); return false; }); ```
18,606,960
Can someone help me with a simple AJAX pagination in Codeigniter using JQuery? With the paginated list queryed from the database. I searched the web but all the exemples are very complex... Thank you in advance and sorry for my bad english...
2013/09/04
[ "https://Stackoverflow.com/questions/18606960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2728329/" ]
just use codeigniter pagination library and add the following function in the library after create links function ``` function create_links_ajax() { // If our item count or per-page total is zero there is no need to continue. if ($this->total_rows == 0 OR $this->per_page == 0) { return ''; } // Calculate the total number of pages $num_pages = ceil($this->total_rows / $this->per_page); // Is there only one page? Hm... nothing more to do here then. if ($num_pages == 1) { return ''; } // Set the base page index for starting page number if ($this->use_page_numbers) { $base_page = 1; } else { $base_page = 0; } // Determine the current page number. $CI =& get_instance(); if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) { if ($CI->input->get($this->query_string_segment) != $base_page) { $this->cur_page = $CI->input->get($this->query_string_segment); // Prep the current page - no funny business! $this->cur_page = (int) $this->cur_page; } } else { if ($CI->uri->segment($this->uri_segment) != $base_page) { $this->cur_page = $CI->uri->segment($this->uri_segment); // Prep the current page - no funny business! $this->cur_page = (int) $this->cur_page; } } // Set current page to 1 if using page numbers instead of offset if ($this->use_page_numbers AND $this->cur_page == 0) { $this->cur_page = $base_page; } $this->num_links = (int)$this->num_links; if ($this->num_links < 1) { show_error('Your number of links must be a positive number.'); } if ( ! is_numeric($this->cur_page)) { $this->cur_page = $base_page; } // Is the page number beyond the result range? // If so we show the last page if ($this->use_page_numbers) { if ($this->cur_page > $num_pages) { $this->cur_page = $num_pages; } } else { if ($this->cur_page > $this->total_rows) { $this->cur_page = ($num_pages - 1) * $this->per_page; } } $uri_page_number = $this->cur_page; if ( ! $this->use_page_numbers) { $this->cur_page = floor(($this->cur_page/$this->per_page) + 1); } // Calculate the start and end numbers. These determine // which number to start and end the digit links with $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1; $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages; // Is pagination being used over GET or POST? If get, add a per_page query // string. If post, add a trailing slash to the base URL if needed if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) { $this->base_url = rtrim($this->base_url).'&amp;'.$this->query_string_segment.'='; } else { $this->base_url = rtrim($this->base_url, '/') .'/'; } // And here we go... $output = ''; // Render the "First" link if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1)) { $first_url = ($this->first_url == '') ? $this->base_url : $this->first_url; $output .= $this->first_tag_open.'<a id="'.$first_url.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$this->first_link.'</a>'.$this->first_tag_close; } // Render the "previous" link if ($this->prev_link !== FALSE AND $this->cur_page != 1) { if ($this->use_page_numbers) { $i = $uri_page_number - 1; } else { $i = $uri_page_number - $this->per_page; } if ($i == 0 && $this->first_url != '') { $output .= $this->prev_tag_open.'<a id="'.$this->first_url.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->prev_link.'</a>'.$this->prev_tag_close; } else { $i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix; $output .= $this->prev_tag_open.'<a id="'.$this->base_url.$i.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->prev_link.'</a>'.$this->prev_tag_close; } } // Render the pages if ($this->display_pages !== FALSE) { // Write the digit links for ($loop = $start -1; $loop <= $end; $loop++) { if ($this->use_page_numbers) { $i = $loop; } else { $i = ($loop * $this->per_page) - $this->per_page; } if ($i >= $base_page) { if ($this->cur_page == $loop) { // $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page // $output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close; } else { $n = ($i == $base_page) ? '' : $i; if ($n == '' && $this->first_url != '') { $output .= $this->num_tag_open.'<a id="'.$this->first_url.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$loop.'</a>'.$this->num_tag_close; } else { $n = ($n == '') ? '' : $this->prefix.$n.$this->suffix; $output .= $this->num_tag_open.'<a id="'.$this->base_url.$n.'" onclick="show_ajax_cards(this)" '.$this->anchor_class.'href="javascript:void(0)">'.$loop.'</a>'.$this->num_tag_close; } } } } } // Render the "next" link if ($this->next_link !== FALSE AND $this->cur_page < $num_pages) { if ($this->use_page_numbers) { $i = $this->cur_page + 1; } else { $i = ($this->cur_page * $this->per_page); } $output .= $this->next_tag_open.'<a id="'.$this->base_url.$this->prefix.$i.$this->suffix.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)">'.$this->next_link.'</a>'.$this->next_tag_close; } // Render the "Last" link if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages) { if ($this->use_page_numbers) { $i = $num_pages; } else { $i = (($num_pages * $this->per_page) - $this->per_page); } $output .= $this->last_tag_open.'<a id="'.$this->base_url.$this->prefix.$i.$this->suffix.'" onclick="show_ajax_cards(this)"'.$this->anchor_class.'href="javascript:void(0)"'.$this->last_link.'</a>'.$this->last_tag_close; } // Kill double slashes. Note: Sometimes we can end up with a double slash // in the penultimate link so we'll kill all double slashes. $output = preg_replace("#([^:])//+#", "\\1/", $output); // Add the wrapper HTML if exists $output = $this->full_tag_open.$output.$this->full_tag_close; return $output; } ``` **and in the view create a function that will look like this** ``` function show_ajax_cards(obj) { var baseurl = obj.id; $.ajax({ url: baseurl, data:"baseurl="+baseurl, type: 'POST', success: function(html) { $('#cardReplace').html(html); } }); } ```
Apply Live click, if you are returning data from controller as follows: ``` jQuery("#pagination a").live('click',function(e){ e.preventDefault(); jQuery.ajax({ type: "POST", url: jQuery(this).attr("href"), success: function(res){ jQuery('#multiple_selection_data').html(res); } }); return false; }); ```
60,006,520
``` <ul id="sortable"> <li class="ui-state-default editor-sortable-moveable" id="123"> <div class="d-flex"> <div class="p-2 flex-fill li-content-grid"></div> <div class="p-2 flex-fill li-content-grid">Text</div> <div class="p-2 flex-fill li-content-grid icon-flow"><i class="fas fa-edit" id="editor_click_icon_edit"></i></div> </div> </li> </ul> ``` When clicking the icon, i need to get the id of the parent `<li>`. I'm using the following click listener: ``` $("#sortable").click("#editor_click_icon_edit",function(e) { console.log($(this).text()); }); ``` This will return "Text". By using ``` $(this).children().attr('id'); ``` I just returns the id of the first `<li>` entry. So it looks like "this" points to the `<ul>`.
2020/01/31
[ "https://Stackoverflow.com/questions/60006520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372316/" ]
You have two issues here. Firstly you're not using `click()` correctly. The first argument in your case is the additional data you want to include in the event, but that's not relevant to your use case. Instead it appears you're trying to create a delegated event handler, but you need to use `on()` for that. Secondly, you need to traverse the DOM to find the parent `li` from the clicked element. `closest()` will achieve this for you. ```js $("#sortable").on('click', "#editor_click_icon_edit", function(e) { console.log($(this).closest('li').prop('id')); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js"></script> <ul id="sortable"> <li class="ui-state-default editor-sortable-moveable" id="123"> <div class="d-flex"> <div class="p-2 flex-fill li-content-grid"></div> <div class="p-2 flex-fill li-content-grid">Text</div> <div class="p-2 flex-fill li-content-grid icon-flow"> <i class="fas fa-edit" id="editor_click_icon_edit"></i> </div> </div> </li> </ul> ```
fyi, if you use a snippet its easier for us to run and see whats up. Below in the snippet i switched it from adding the listener to the ul. now it adds the listener to the lis nested inside your ul. ```js //#sortable is the id of the ul //.editor-sortable-movable grabs the li $(document).ready(function () { $("#sortable > li").on("click",function(e) { console.log($(this).attr('id')); }); }); ``` ```css .editor-sortable-moveable { background-color: yellow; } .editor-sortable-moveable:hover { background-color: red; cursor: pointer; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="sortable"> <li class="ui-state-default editor-sortable-moveable" id="123"> <div class="d-flex"> <div class="p-2 flex-fill li-content-grid"></div> <div class="p-2 flex-fill li-content-grid">Text</div> <div class="p-2 flex-fill li-content-grid icon-flow"><i class="fas fa-edit" id="editor_click_icon_edit"></i></div> </div> </li> <li class="ui-state-default editor-sortable-moveable" id="456"> <div class="d-flex"> <div class="p-2 flex-fill li-content-grid"></div> <div class="p-2 flex-fill li-content-grid">Next</div> <div class="p-2 flex-fill li-content-grid icon-flow"><i class="fas fa-edit" id="editor_click_icon_edit"></i></div> </div> </li> </ul> ```
8,181,121
I have compiled a list of db object names, one name per line, in a text file. I want to know for each names, where it is being used. The target search is a group of folders containing sub-folders of source codes. Before I give up looking for a tool to do this and start creating my own, perhaps you can help to point to me an existing one. Ideally, it should be a Windows desktop application. I have not used grep before.
2011/11/18
[ "https://Stackoverflow.com/questions/8181121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54908/" ]
use `grep` (there are tons of port of this command to windows, search the web). eventually, use [`AgentRansack`](http://mythicsoft.com/page.aspx?type=agentransack&page=home).
See our [Source Code Search Engine](http://www.semanticdesigns.com/Products/SearchEngine). It indexes a large code base according to the atoms (tokens) of the language(s) of interest, and then uses that index to quickly execute structured queries stated in terms of language elememnts. It is a kind of super-grep, but it isn't fooled by comments or string literals, and it automatically ignores whitespace. This means you get a lot fewer false positive hits than you get with grep. If you had an identifier "foo", the following query would find all mentions: ``` I=foo ``` For C and Java, you can constrain the types of identifier accesses to Use, Read, Write or Defines. ``` D=bar* ``` would find only *declarations* of identifiers which started with the letters "bar". You can write more complex queries using sequences of language tokens: ``` 'int' I=*baz* '[' ``` for C, would find declarations of any variable name that contained the letters "baz" and apparantly declared an array. You can see the hits in a GUI, and one-click navigate to a source code view of any hit. It is a Windows application. It handles a wide variety of languages: C#, C++, Java, ... and many more.
8,181,121
I have compiled a list of db object names, one name per line, in a text file. I want to know for each names, where it is being used. The target search is a group of folders containing sub-folders of source codes. Before I give up looking for a tool to do this and start creating my own, perhaps you can help to point to me an existing one. Ideally, it should be a Windows desktop application. I have not used grep before.
2011/11/18
[ "https://Stackoverflow.com/questions/8181121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54908/" ]
use `grep` (there are tons of port of this command to windows, search the web). eventually, use [`AgentRansack`](http://mythicsoft.com/page.aspx?type=agentransack&page=home).
I had created an SSIS package to load my 500+ source code files that is distributed into some depth of folders belongs to several projects, into a table, with 1 row as 1 line from the files (total is 10K+ lines). I then made a select statement against it, by cross-applying the table that keeps the list of 5K+ keywords of db objects, with the help of RegEx for MS-SQL, <http://www.simple-talk.com/sql/t-sql-programming/clr-assembly-regex-functions-for-sql-server-by-example/>. The query took almost 1.5 hr to complete. I know it's a long winded, but this is exactly what I need. I thank you for your efforts in guiding me. I would be happy to explain the details further, should anyone gets interested using my method. ![enter image description here](https://i.stack.imgur.com/fVJGZ.png) ``` insert dbo.DbObjectUsage select do.Id as DbObjectId, fl.Id as FileLineId from dbo.FileLine as fl -- 10K+ cross apply dbo.DbObject as do -- 5K+ where dbo.RegExIsMatch('\b' + do.name + '\b', fl.Line, 0) != 0 ```
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
**Potential Solution** I think at least a little hackery is required no matter how you optimize it - protractor doesn't give you this out of the box. However would a small helper function like this suit your needs? What else do you need to speed up sides `text` `input`s with `ng-model`s? ``` function setNgModelToString(element, value) { return element.getAttribute('ng-model').then(function (ngModel) { element.evaluate('$eval("' + ngModel + ' = \'' + value + '\'") && $digest()'); }); } ``` **Solution Example:** ``` describe('angularjs homepage', function() { it('should have a title', function() { browser.get('http://juliemr.github.io/protractor-demo/'); var inputString1 = ''; var inputString2 = ''; for (var i = 0; i < 1000; i++) { inputString1 += '1'; inputString2 += '2'; } /* Uncomment this to see it runs much much slower when you enter each key. */ //element(by.model('second')).sendKeys(inputString1); setNgModelToString(element(by.model('second')), inputString2); expect(element(by.model('second')).getAttribute('value')).toEqual(inputString2); }); }); ``` **Why does the solution work?** You need to use `$eval` to wrap the assignment and not just assignment as `evaluate` does not evaluate side effects (a nested evaluation, though... heh). Assuming that's truthy in angular expressions then `$digest()` is called from the `&&`; this causes a digest to happen, which you need to update everything since you set a value from outside the digest cycle. **Thoughts about the solution:** The whole idea behind an E2E test is to "emulate" an end-user using your app. This arguably doesn't do that as well as sending the keys one-by-one, or copy-and-paste (since pasting into elements is a valid way of entering input; it's just hard to set up due to flash, etc., see below). **Other Potential Solutions:** * *Copy and Paste:* Create an element, enter text, copy it, paste the text sending Ctrl + V to the target element. This may require doing a bunch of fancy footwork, like using Flash (exposing the system clipboard is a security risk) and having "copy it" click an invisible flash player. See [`executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) to evaluate functions on the target so that you have access to variables like `window` if you need that. * *Parallelizing your tests.* Read the official doc [here](https://github.com/angular/protractor/blob/master/docs/referenceConf.js) and search for "shard" and then "multiple". If you're mainly worried about the duration of your entire test collection and not individual tests, scaling out your browser count is probably the way to go. However there's a good chance you are TDD-ing or something, hence needing each test to run faster.
You can do following - ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { var arr=[ {id:this.modalExamName, text:'Test Exam ' + modifier}, {id:this.modalExamVersionId, text:'Test exam version ' + modifier }, {id:this.modalExamProductVersionId, text:'Test exam product version ' + modifier}, {id:this.modalExamAudienceId,text:'Test exam audience ' + modifier}, {id:this.modalExamPublishedId, text:'2014-06-1' + modifier}, {id:this.modalExamPriceId, text:'100' + modifier}, {this.modalExamDurationId, text:'6' + modifier} ]; var Q = require('q'), promises = []; for (var i = 0; i < arr.length; i++) { promises.push(page.sendKeys(arr[i].id, arr[i].text)); } Q.all(promises).done(function () { //do here whatever you want }); }; ``` sendKeys returns promise by default. See here -<https://github.com/angular/protractor/blob/master/docs/api.md#api-webdriver-webelement-prototype-sendkeys> ``` sendKeys(id: string, text: string) { return element(by.id(id)).sendKeys(text); } ```
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
You can do following - ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { var arr=[ {id:this.modalExamName, text:'Test Exam ' + modifier}, {id:this.modalExamVersionId, text:'Test exam version ' + modifier }, {id:this.modalExamProductVersionId, text:'Test exam product version ' + modifier}, {id:this.modalExamAudienceId,text:'Test exam audience ' + modifier}, {id:this.modalExamPublishedId, text:'2014-06-1' + modifier}, {id:this.modalExamPriceId, text:'100' + modifier}, {this.modalExamDurationId, text:'6' + modifier} ]; var Q = require('q'), promises = []; for (var i = 0; i < arr.length; i++) { promises.push(page.sendKeys(arr[i].id, arr[i].text)); } Q.all(promises).done(function () { //do here whatever you want }); }; ``` sendKeys returns promise by default. See here -<https://github.com/angular/protractor/blob/master/docs/api.md#api-webdriver-webelement-prototype-sendkeys> ``` sendKeys(id: string, text: string) { return element(by.id(id)).sendKeys(text); } ```
I also used `browser.executeScript`. But I didn't need to use $apply `waitForAngular` I add a script when E2E tests are running, and put a function on global scope, don't worry it's only during E2E tests, and you can namespace if you want to. ``` 'use strict'; function fastSendKeys(testId, value) { //test id is just an attribute we add in our elements //you can use whatever selector you want, test-id is just easy and repeatable var element = jQuery('[test-id=' + '"' + testId + '"' + ']'); element.val(value); element.trigger('input'); } ``` Then in your protractor test something like this (in a page object): ``` this.enterText = function (testId, value) { var call = 'fastSendKeys(' + '"' + testId + '"' + ',' + '"' + value + '"' + ')'; console.log('call is ', call); browser.executeScript(call); }; ```
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
You can do following - ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { var arr=[ {id:this.modalExamName, text:'Test Exam ' + modifier}, {id:this.modalExamVersionId, text:'Test exam version ' + modifier }, {id:this.modalExamProductVersionId, text:'Test exam product version ' + modifier}, {id:this.modalExamAudienceId,text:'Test exam audience ' + modifier}, {id:this.modalExamPublishedId, text:'2014-06-1' + modifier}, {id:this.modalExamPriceId, text:'100' + modifier}, {this.modalExamDurationId, text:'6' + modifier} ]; var Q = require('q'), promises = []; for (var i = 0; i < arr.length; i++) { promises.push(page.sendKeys(arr[i].id, arr[i].text)); } Q.all(promises).done(function () { //do here whatever you want }); }; ``` sendKeys returns promise by default. See here -<https://github.com/angular/protractor/blob/master/docs/api.md#api-webdriver-webelement-prototype-sendkeys> ``` sendKeys(id: string, text: string) { return element(by.id(id)).sendKeys(text); } ```
The following worked for me when testing an angular 2 application ``` await browser.executeScript("arguments[0].value='" + inputText + "';", await element.by.css("#cssID")) ``` inspired by <https://stackoverflow.com/a/43404924/6018757>
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
**Potential Solution** I think at least a little hackery is required no matter how you optimize it - protractor doesn't give you this out of the box. However would a small helper function like this suit your needs? What else do you need to speed up sides `text` `input`s with `ng-model`s? ``` function setNgModelToString(element, value) { return element.getAttribute('ng-model').then(function (ngModel) { element.evaluate('$eval("' + ngModel + ' = \'' + value + '\'") && $digest()'); }); } ``` **Solution Example:** ``` describe('angularjs homepage', function() { it('should have a title', function() { browser.get('http://juliemr.github.io/protractor-demo/'); var inputString1 = ''; var inputString2 = ''; for (var i = 0; i < 1000; i++) { inputString1 += '1'; inputString2 += '2'; } /* Uncomment this to see it runs much much slower when you enter each key. */ //element(by.model('second')).sendKeys(inputString1); setNgModelToString(element(by.model('second')), inputString2); expect(element(by.model('second')).getAttribute('value')).toEqual(inputString2); }); }); ``` **Why does the solution work?** You need to use `$eval` to wrap the assignment and not just assignment as `evaluate` does not evaluate side effects (a nested evaluation, though... heh). Assuming that's truthy in angular expressions then `$digest()` is called from the `&&`; this causes a digest to happen, which you need to update everything since you set a value from outside the digest cycle. **Thoughts about the solution:** The whole idea behind an E2E test is to "emulate" an end-user using your app. This arguably doesn't do that as well as sending the keys one-by-one, or copy-and-paste (since pasting into elements is a valid way of entering input; it's just hard to set up due to flash, etc., see below). **Other Potential Solutions:** * *Copy and Paste:* Create an element, enter text, copy it, paste the text sending Ctrl + V to the target element. This may require doing a bunch of fancy footwork, like using Flash (exposing the system clipboard is a security risk) and having "copy it" click an invisible flash player. See [`executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) to evaluate functions on the target so that you have access to variables like `window` if you need that. * *Parallelizing your tests.* Read the official doc [here](https://github.com/angular/protractor/blob/master/docs/referenceConf.js) and search for "shard" and then "multiple". If you're mainly worried about the duration of your entire test collection and not individual tests, scaling out your browser count is probably the way to go. However there's a good chance you are TDD-ing or something, hence needing each test to run faster.
If you really want to speed up the process of manipulating DOM in any way (including filling up data forms) one option to consider is to use: [`browser.executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) or [`browser.executeAsyncScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeAsyncScript). In such a case the `webdriver` let the browser execute the script on its own -- the only overhead is to send the script body to the browser, so I do not think there may be anything faster. From what I see, you identify DOM elements by `id`s so it should smoothly work with the approach I propose. Here is a scaffold of it -- tested it and it works fine: ``` browser.get('someUrlToBeTested'); browser.waitForAngular(); browser.executeScript(function(param1, param2, param3){ // form doc: arguments may be a boolean, number, string, or webdriver.WebElement // here all are strings: param1 = "someClass", param2 = "someId", param3 = "someModifier" var el1 = document.getElementsByClassName(param1)[0]; var el2 = document.getElementById(param2); el1.setAttribute('value', 'yoohoo ' + param3); el2.setAttribute('value', 'hooyoo ' + param3); // depending on your context it will probably // be needed to manually digest the changes window.angular.element(el1).scope().$apply(); },'someClass', 'someId', 'someModifier') ``` *small remark*: If you pass `webdriver.WebElement` as one of your argument it will be cast down to the corresponding `DOM element`.
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
**Potential Solution** I think at least a little hackery is required no matter how you optimize it - protractor doesn't give you this out of the box. However would a small helper function like this suit your needs? What else do you need to speed up sides `text` `input`s with `ng-model`s? ``` function setNgModelToString(element, value) { return element.getAttribute('ng-model').then(function (ngModel) { element.evaluate('$eval("' + ngModel + ' = \'' + value + '\'") && $digest()'); }); } ``` **Solution Example:** ``` describe('angularjs homepage', function() { it('should have a title', function() { browser.get('http://juliemr.github.io/protractor-demo/'); var inputString1 = ''; var inputString2 = ''; for (var i = 0; i < 1000; i++) { inputString1 += '1'; inputString2 += '2'; } /* Uncomment this to see it runs much much slower when you enter each key. */ //element(by.model('second')).sendKeys(inputString1); setNgModelToString(element(by.model('second')), inputString2); expect(element(by.model('second')).getAttribute('value')).toEqual(inputString2); }); }); ``` **Why does the solution work?** You need to use `$eval` to wrap the assignment and not just assignment as `evaluate` does not evaluate side effects (a nested evaluation, though... heh). Assuming that's truthy in angular expressions then `$digest()` is called from the `&&`; this causes a digest to happen, which you need to update everything since you set a value from outside the digest cycle. **Thoughts about the solution:** The whole idea behind an E2E test is to "emulate" an end-user using your app. This arguably doesn't do that as well as sending the keys one-by-one, or copy-and-paste (since pasting into elements is a valid way of entering input; it's just hard to set up due to flash, etc., see below). **Other Potential Solutions:** * *Copy and Paste:* Create an element, enter text, copy it, paste the text sending Ctrl + V to the target element. This may require doing a bunch of fancy footwork, like using Flash (exposing the system clipboard is a security risk) and having "copy it" click an invisible flash player. See [`executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) to evaluate functions on the target so that you have access to variables like `window` if you need that. * *Parallelizing your tests.* Read the official doc [here](https://github.com/angular/protractor/blob/master/docs/referenceConf.js) and search for "shard" and then "multiple". If you're mainly worried about the duration of your entire test collection and not individual tests, scaling out your browser count is probably the way to go. However there's a good chance you are TDD-ing or something, hence needing each test to run faster.
I also used `browser.executeScript`. But I didn't need to use $apply `waitForAngular` I add a script when E2E tests are running, and put a function on global scope, don't worry it's only during E2E tests, and you can namespace if you want to. ``` 'use strict'; function fastSendKeys(testId, value) { //test id is just an attribute we add in our elements //you can use whatever selector you want, test-id is just easy and repeatable var element = jQuery('[test-id=' + '"' + testId + '"' + ']'); element.val(value); element.trigger('input'); } ``` Then in your protractor test something like this (in a page object): ``` this.enterText = function (testId, value) { var call = 'fastSendKeys(' + '"' + testId + '"' + ',' + '"' + value + '"' + ')'; console.log('call is ', call); browser.executeScript(call); }; ```
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
**Potential Solution** I think at least a little hackery is required no matter how you optimize it - protractor doesn't give you this out of the box. However would a small helper function like this suit your needs? What else do you need to speed up sides `text` `input`s with `ng-model`s? ``` function setNgModelToString(element, value) { return element.getAttribute('ng-model').then(function (ngModel) { element.evaluate('$eval("' + ngModel + ' = \'' + value + '\'") && $digest()'); }); } ``` **Solution Example:** ``` describe('angularjs homepage', function() { it('should have a title', function() { browser.get('http://juliemr.github.io/protractor-demo/'); var inputString1 = ''; var inputString2 = ''; for (var i = 0; i < 1000; i++) { inputString1 += '1'; inputString2 += '2'; } /* Uncomment this to see it runs much much slower when you enter each key. */ //element(by.model('second')).sendKeys(inputString1); setNgModelToString(element(by.model('second')), inputString2); expect(element(by.model('second')).getAttribute('value')).toEqual(inputString2); }); }); ``` **Why does the solution work?** You need to use `$eval` to wrap the assignment and not just assignment as `evaluate` does not evaluate side effects (a nested evaluation, though... heh). Assuming that's truthy in angular expressions then `$digest()` is called from the `&&`; this causes a digest to happen, which you need to update everything since you set a value from outside the digest cycle. **Thoughts about the solution:** The whole idea behind an E2E test is to "emulate" an end-user using your app. This arguably doesn't do that as well as sending the keys one-by-one, or copy-and-paste (since pasting into elements is a valid way of entering input; it's just hard to set up due to flash, etc., see below). **Other Potential Solutions:** * *Copy and Paste:* Create an element, enter text, copy it, paste the text sending Ctrl + V to the target element. This may require doing a bunch of fancy footwork, like using Flash (exposing the system clipboard is a security risk) and having "copy it" click an invisible flash player. See [`executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) to evaluate functions on the target so that you have access to variables like `window` if you need that. * *Parallelizing your tests.* Read the official doc [here](https://github.com/angular/protractor/blob/master/docs/referenceConf.js) and search for "shard" and then "multiple". If you're mainly worried about the duration of your entire test collection and not individual tests, scaling out your browser count is probably the way to go. However there's a good chance you are TDD-ing or something, hence needing each test to run faster.
The following worked for me when testing an angular 2 application ``` await browser.executeScript("arguments[0].value='" + inputText + "';", await element.by.css("#cssID")) ``` inspired by <https://stackoverflow.com/a/43404924/6018757>
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
If you really want to speed up the process of manipulating DOM in any way (including filling up data forms) one option to consider is to use: [`browser.executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) or [`browser.executeAsyncScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeAsyncScript). In such a case the `webdriver` let the browser execute the script on its own -- the only overhead is to send the script body to the browser, so I do not think there may be anything faster. From what I see, you identify DOM elements by `id`s so it should smoothly work with the approach I propose. Here is a scaffold of it -- tested it and it works fine: ``` browser.get('someUrlToBeTested'); browser.waitForAngular(); browser.executeScript(function(param1, param2, param3){ // form doc: arguments may be a boolean, number, string, or webdriver.WebElement // here all are strings: param1 = "someClass", param2 = "someId", param3 = "someModifier" var el1 = document.getElementsByClassName(param1)[0]; var el2 = document.getElementById(param2); el1.setAttribute('value', 'yoohoo ' + param3); el2.setAttribute('value', 'hooyoo ' + param3); // depending on your context it will probably // be needed to manually digest the changes window.angular.element(el1).scope().$apply(); },'someClass', 'someId', 'someModifier') ``` *small remark*: If you pass `webdriver.WebElement` as one of your argument it will be cast down to the corresponding `DOM element`.
I also used `browser.executeScript`. But I didn't need to use $apply `waitForAngular` I add a script when E2E tests are running, and put a function on global scope, don't worry it's only during E2E tests, and you can namespace if you want to. ``` 'use strict'; function fastSendKeys(testId, value) { //test id is just an attribute we add in our elements //you can use whatever selector you want, test-id is just easy and repeatable var element = jQuery('[test-id=' + '"' + testId + '"' + ']'); element.val(value); element.trigger('input'); } ``` Then in your protractor test something like this (in a page object): ``` this.enterText = function (testId, value) { var call = 'fastSendKeys(' + '"' + testId + '"' + ',' + '"' + value + '"' + ')'; console.log('call is ', call); browser.executeScript(call); }; ```
25,689,090
I have code similar to this: ``` ExamPage.prototype.enterDetailsInputData = function (modifier) { page.sendKeys(this.modalExamName, 'Test Exam ' + modifier); page.sendKeys(this.modalExamVersionId, 'Test exam version ' + modifier); page.sendKeys(this.modalExamProductVersionId, 'Test exam product version ' + modifier); page.sendKeys(this.modalExamAudienceId, 'Test exam audience ' + modifier); page.sendKeys(this.modalExamPublishedId, '2014-06-1' + modifier); page.sendKeys(this.modalExamPriceId, '100' + modifier); page.sendKeys(this.modalExamDurationId, '6' + modifier); }; ``` Here's the page.sendKeys function. Note that currently this is not doing any return of promises or anything like that. If the function is not coded well then I welcome comments: ``` // page.sendkeys function sendKeys(id: string, text: string) { element(by.id(id)).sendKeys(text); } ``` I watch as it slowly fills out each field on my screen and then repeats it again and again in more tests that follow. Is there any way that this could be optimized or do I have to wait for one field after the other to fill and have to live with tests that take a long time to run? I assume sendKeys is promise based. Could I for example use **AngularJS $q** to issue all the sendKeys at the same time and then use $q to wait for them to complete?
2014/09/05
[ "https://Stackoverflow.com/questions/25689090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975566/" ]
If you really want to speed up the process of manipulating DOM in any way (including filling up data forms) one option to consider is to use: [`browser.executeScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeScript) or [`browser.executeAsyncScript`](http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.prototype.executeAsyncScript). In such a case the `webdriver` let the browser execute the script on its own -- the only overhead is to send the script body to the browser, so I do not think there may be anything faster. From what I see, you identify DOM elements by `id`s so it should smoothly work with the approach I propose. Here is a scaffold of it -- tested it and it works fine: ``` browser.get('someUrlToBeTested'); browser.waitForAngular(); browser.executeScript(function(param1, param2, param3){ // form doc: arguments may be a boolean, number, string, or webdriver.WebElement // here all are strings: param1 = "someClass", param2 = "someId", param3 = "someModifier" var el1 = document.getElementsByClassName(param1)[0]; var el2 = document.getElementById(param2); el1.setAttribute('value', 'yoohoo ' + param3); el2.setAttribute('value', 'hooyoo ' + param3); // depending on your context it will probably // be needed to manually digest the changes window.angular.element(el1).scope().$apply(); },'someClass', 'someId', 'someModifier') ``` *small remark*: If you pass `webdriver.WebElement` as one of your argument it will be cast down to the corresponding `DOM element`.
The following worked for me when testing an angular 2 application ``` await browser.executeScript("arguments[0].value='" + inputText + "';", await element.by.css("#cssID")) ``` inspired by <https://stackoverflow.com/a/43404924/6018757>
29,247,089
When I insert a new field in my users collection, several of the attributes disappear. Initially, my collection looked like this: ``` { "_id": "myfi3E4YTf9z6tdgS", "createdAt": ISODate("2015-03-20T16:25:06.978Z"), "emails": { "address": "[email protected]", "verified": true }, "profile": { "companyName": "Company1", "markup": "5", "phoneNum": "555-555-5555" }, "services": { "password": { "bcrypt": "$2a$10$EsecJJz.PA/qgupHzknYBuGQRW4c6S9hFScc4GesOcO7pixOna1AG" }, "resume": { "loginTokens": [ { "when": ISODate("2015-03-23T20:58:48.642Z"), "hashedToken": "dlPlzU7KtVhMW1JPDgCQWPYgqIc825ao2bnR84q9NQI=" } ] } }, } ``` I then added an admin flag field by typing the following command in the terminal: ``` db.users.update({_id: 'myfi3E4YTf9z6tdgS'}, {$set: {profile{ admin: true}} ``` I checked the collection's attributes again and found: ``` { "_id": "myfi3E4YTf9z6tdgS", "createdAt": ISODate("2015-03-20T16:25:06.978Z"), "emails": { "address": "[email protected]", "verified": true }, "profile": { "admin": true }, "services": { "password": { "bcrypt": "$2a$10$EsecJJz.PA/qgupHzknYBuGQRW4c6S9hFScc4GesOcO7pixOna1AG" }, "resume": { "loginTokens": [ { "when": ISODate("2015-03-23T20:58:48.642Z"), "hashedToken": "dlPlzU7KtVhMW1JPDgCQWPYgqIc825ao2bnR84q9NQI=" }, { "when": ISODate("2015-03-25T03:32:37.172Z"), "hashedToken": "xrojAUw7VwQvbjMtDwaexFEtQprMgl85b+0SY18z58c=" } ] } }, } ``` The profile.companyName, profile.markup, and profile.phoneNum disappeared. Does anyone know what's going on? Please help!
2015/03/25
[ "https://Stackoverflow.com/questions/29247089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1547174/" ]
Use dot notation to update individual fields within an embedded object like `profile` instead of replacing the whole embedded object: ```js db.users.update({_id: 'myfi3E4YTf9z6tdgS'}, {$set: {'profile.admin': true}}) ```
Why don't you use db.users.save() function The syntax probably looks like ``` db.users.save({_id: 'myfi3E4YTf9z6tdgS', 'profile.admin': true}) ```
3,355,641
I"m looking to read the contents of a Word file on an application running on a webserver - without having word installed. Does a native .net solution for this exist?
2010/07/28
[ "https://Stackoverflow.com/questions/3355641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280746/" ]
Aspose makes a paid solution for doing just about anything with any Office format: <http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx>
There are commercial options too, but that's what [OpenXML](http://openxmldeveloper.org/) is all about as long as you are dealing with docx files only. If you need doc files, you will probably need to purchase [Aspose's Aspose.Words for .NET](http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx).
3,355,641
I"m looking to read the contents of a Word file on an application running on a webserver - without having word installed. Does a native .net solution for this exist?
2010/07/28
[ "https://Stackoverflow.com/questions/3355641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280746/" ]
There are commercial options too, but that's what [OpenXML](http://openxmldeveloper.org/) is all about as long as you are dealing with docx files only. If you need doc files, you will probably need to purchase [Aspose's Aspose.Words for .NET](http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx).
i have used several SDK, for now, the best is Aspose.words, the openxml sdk 2.5 is also a nice choice, but the api is too low, so if you use openxml sdk that means will be writing more code, and remenber user openxml sdk tool together, it is a nice tool can make coding simple. you can look this video for a overview: [how to use openxml sdk tool](http://www.youtube.com/watch?v=KSSMLR19JWA) another choice: [GemBox.Document](http://www.gemboxsoftware.com/), a commercial option, cheaper than aspose.words.
3,355,641
I"m looking to read the contents of a Word file on an application running on a webserver - without having word installed. Does a native .net solution for this exist?
2010/07/28
[ "https://Stackoverflow.com/questions/3355641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280746/" ]
Aspose makes a paid solution for doing just about anything with any Office format: <http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx>
i have used several SDK, for now, the best is Aspose.words, the openxml sdk 2.5 is also a nice choice, but the api is too low, so if you use openxml sdk that means will be writing more code, and remenber user openxml sdk tool together, it is a nice tool can make coding simple. you can look this video for a overview: [how to use openxml sdk tool](http://www.youtube.com/watch?v=KSSMLR19JWA) another choice: [GemBox.Document](http://www.gemboxsoftware.com/), a commercial option, cheaper than aspose.words.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
Try [TACO HTML Edit](http://tacosw.com/) or [JEdit](http://www.jedit.org/) (Freeware) Bye.
I use [BBEdit](http://www.barebones.com/) for this.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
Try using [tidy](http://www.w3.org/People/Raggett/tidy/). I think it is included in OSX (at least the command is there on my system) so you won't need to install anything to use it.
I use [BBEdit](http://www.barebones.com/) for this.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
[TextMate](http://macromates.com/) is a really cool app. There are hundreds of bundles for all possible languages.
I use [BBEdit](http://www.barebones.com/) for this.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
Try [TACO HTML Edit](http://tacosw.com/) or [JEdit](http://www.jedit.org/) (Freeware) Bye.
Try using [tidy](http://www.w3.org/People/Raggett/tidy/). I think it is included in OSX (at least the command is there on my system) so you won't need to install anything to use it.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
Try [TACO HTML Edit](http://tacosw.com/) or [JEdit](http://www.jedit.org/) (Freeware) Bye.
Textmate will do a nice job. If you are a java or ruby programmer, [Intellj](http://www.jetbrains.com/idea/) or [Rubymine](http://www.jetbrains.com/ruby/index.html) does an excellent job of auto-formatting code(including HTML).
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
[TextMate](http://macromates.com/) is a really cool app. There are hundreds of bundles for all possible languages.
Try using [tidy](http://www.w3.org/People/Raggett/tidy/). I think it is included in OSX (at least the command is there on my system) so you won't need to install anything to use it.
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
Try using [tidy](http://www.w3.org/People/Raggett/tidy/). I think it is included in OSX (at least the command is there on my system) so you won't need to install anything to use it.
Textmate will do a nice job. If you are a java or ruby programmer, [Intellj](http://www.jetbrains.com/idea/) or [Rubymine](http://www.jetbrains.com/ruby/index.html) does an excellent job of auto-formatting code(including HTML).
1,316,485
Does anyone know of an application (for mac) which will format a page of html code nicely? ie Open the html file and indent all of the code/blocks, put character returns in and format it into sections so that it is readable rather than being just a big block of code. Then also give the ability to minimize/collapse sections of the code to make it more readable. I've been trying Coda and Expresso - Expresso has the feature to minimize/collapse code but does not seem to be able to format code. Please help?
2009/08/22
[ "https://Stackoverflow.com/questions/1316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159366/" ]
[TextMate](http://macromates.com/) is a really cool app. There are hundreds of bundles for all possible languages.
Textmate will do a nice job. If you are a java or ruby programmer, [Intellj](http://www.jetbrains.com/idea/) or [Rubymine](http://www.jetbrains.com/ruby/index.html) does an excellent job of auto-formatting code(including HTML).
78,245
Do contemporary logicians generally claim, as [Wikipedia does](https://en.wikipedia.org/wiki/Classical_logic#Characteristics), that classical logic can be simply reduced to the 5 logical principles below? Or is it more complex than that and are there principles not included? > > 1. [Law of excluded middle](https://en.wikipedia.org/wiki/Law_of_excluded_middle) and [double negation](https://en.wikipedia.org/wiki/Double_negation) elimination > 2. [Law of noncontradiction](https://en.wikipedia.org/wiki/Law_of_noncontradiction), and the [principle of explosion](https://en.wikipedia.org/wiki/Principle_of_explosion) > 3. [Monotonicity of entailment](https://en.wikipedia.org/wiki/Monotonicity_of_entailment) and [idempotency of entailment](https://en.wikipedia.org/wiki/Idempotency_of_entailment) > 4. [Commutativity of conjunction](https://en.wikipedia.org/wiki/Logical_conjunction#Properties) > 5. [De Morgan duality](https://en.wikipedia.org/wiki/De_Morgan%27s_laws): every logical operator is dual to another > > >
2020/12/28
[ "https://philosophy.stackexchange.com/questions/78245", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/49667/" ]
I take your question to be, are the listed features sufficient to precisely and completely distinguish classical logic from all non-classical logics? There are certainly lots of other things one would need to specify in order for classical logic to qualify as a logic at all. And there are many other distinguishing features of classical logic not listed that follow from the ones that are listed. The problem with giving a definitive answer to this question is that it is a matter of disagreement over exactly what constitutes a classical logic. Some use the term in a limited fashion to include only elementary first-order predicate logic. Others use it in a more extended way to include any logic that has the property that all theorems of elementary classical logic are theorems of that logic. These come apart in a number of ways, some of which are: 1. The standard semantics of classical logic is bivalent, which is to say it is the logic of pairs of opposite values, usually true/false, such that every proposition has one and only one value. But some accounts allow that multi-valued logics can be classical, as long as these logics are strictly extensions of bivalent classical logic and do not conflict with it. 2. Modal logics are commonly treated as non-classical in modern textbooks, but usually they extend classical logic and so would count as classical logics in the extended sense. 3. The identity relation is often treated as part of the logic, rather than as a predicate that can be interpreted as part of a theory. One speaks of first-order predicate logic *with* or *without* identity. 4. There are standard rules for handling variables, quantifiers and domains in classical logic. These can be extended in various ways, e.g. with plural quantification, branching quantifiers, typed variables, etc. Some of these extensions might be considered classical, but others, such as the ability in free logics to quantify over non-existent objects, are usually considered non-classical. 5. First order logic can be extended to second order and higher orders. Some logicians (famously Quine) do not consider these to qualify as logic at all. The listed features do not stipulate bivalence, do not exclude non-truth-functional modal operators, do not specify any identity relationships, do not place any restrictions on quantification, and do not specify first-order, so they are obviously intended to characterise classical logic in an extended sense.
Short Answer ------------ The answer to your question is at the start of the article you cited: > > Each logical system in this class shares [these 5] characteristic properties... **While not entailed by the preceding conditions** [emphasis mine], contemporary discussions of classical logic normally only include propositional and first-order logics. Classical logic generally entails the majority of the Western tradition of philosophy and logic since the [pre-Socratics](https://en.wikipedia.org/wiki/Pre-Socratic_philosophy), but particularly starting with [Aristotle](https://en.wikipedia.org/wiki/Aristotle). > > > "While not entailed by the preceding conditions" means that 'there is more than these 5 conditions to describe classical logical study'. Five sentences would hardly be enough to describe classical logic. Long Answer ----------- What is classical logic? According to the [*Encyclopedia of Philosophy*](https://en.wikipedia.org/wiki/Encyclopedia_of_Philosophy) and it's entry 'Logic, Non-Classical': > > [C]lassical logic [is] the theory of validity concerning truth functions and first-order quantifiers likely to be found in introductory textbooks of formal logic at the end of the twentieth century. > > > One way to define what classic logic is is to define it as what non-classic logic is not. (See PhilSE: [In how many and which ways can a logic be non-classical? Are there systems for organizing them?](https://philosophy.stackexchange.com/questions/77449/in-how-many-and-which-ways-can-a-logic-be-non-classical-are-there-systems-for-o) for a list of systems and their characteristics.) This is why the principles are featured prominently in this article because what non-classic logic is about is deviation from some of these principles. For instance, [sequent calculus](https://en.wikipedia.org/wiki/Sequent_calculus) and its extensions such as display calculi, nested sequent systems, and labeled sequent systems are metalogical and go beyond classic-logic as [metalogical theory](https://en.wikipedia.org/wiki/Metalogic). But it's much more informative to describe some of the features of classic logic and some of their historical origin. Is there more than the principles? Well as the WP article concedes, yes. In fact, of the three generally acknowledged [Laws of Thought](https://en.wikipedia.org/wiki/Law_of_thought), one is not mentioned in the list of principles above: the [Law of Identity](https://en.wikipedia.org/wiki/Law_of_identity). So, immediately, the moment discussion starts about classic logic, the Law of Identity is an important topic; the famous [philosopher of language](https://en.wikipedia.org/wiki/Philosophy_of_language), [John Searle](https://en.wikipedia.org/wiki/John_Searle), for instance, challenged the Law of Identity as a law arguing it is only a convention in his paper *Proper Names*. (See PhilSE: [On Searle's \_Proper Names\_ (1958)](https://philosophy.stackexchange.com/questions/77338/on-searles-proper-names-1958/77470#77470) for an explanation how he invokes the conventions of cryptography to challenge it.) From Volume 5 of the *Encyclopedia of Philosophy*, the entry "Logic, Traditional" begins with this: > > In logic, as in other fields, whenever there have been spectacular changes and advances, the logic that was current in the preceding period has been described as "old" or "traditional"...In every case, the logic termed "old" or "traditional" has been essentially Aristotelian, but with a certain concentration on the central portion of the Aristotelian *corpus*, the theory of categorical syllogism... especially of the sixteenth to the nineteenth century. > > > In fact, WP's entry on the [History of Logic has a subsection on traditional logic](https://en.wikipedia.org/wiki/History_of_logic#Traditional_logic): > > Other works in the textbook tradition include [Isaac Watts's](https://en.wikipedia.org/wiki/Isaac_Watts) *Logick: Or, the Right Use of Reason* (1725), [Richard Whately's](https://en.wikipedia.org/wiki/Richard_Whately) *Logic* (1826), and [John Stuart Mill's](https://en.wikipedia.org/wiki/John_Stuart_Mill) *A System of Logic* (1843). Although the latter was one of the last great works in the tradition, Mill's view that the foundations of logic lie in introspection[87] influenced the view that logic is best understood as a branch of psychology, a view which dominated the next fifty years of its development, especially in Germany.[88] > > > So, besides missing the Law of Identity, here are some additional topics: [categorical syllogism](https://en.wikipedia.org/wiki/Syllogism), the [logic of propositions](https://en.wikipedia.org/wiki/Propositional_calculus), [equipollence](https://en.wikipedia.org/wiki/Equinumerosity), and [Euler's diagrams](https://en.wikipedia.org/wiki/Euler_diagram), as well as the [history of classical logic](https://en.wikipedia.org/wiki/Classical_logic#History) more generally to understand the context of their development and relations. In fact, two of the most important works are from three heavyweights of the [analytical tradition](https://en.wikipedia.org/wiki/Analytic_philosophy). According to that WP article: > > Classical logic reached fruition in Bertrand Russell and A. N. Whitehead's [*Principia Mathematica*](https://en.wikipedia.org/wiki/Principia_Mathematica), and Ludwig Wittgenstein's [*Tractatus Logico Philosophicus*](http://Classical%20logic%20reached%20fruition%20in%20Bertrand%20Russell%20and%20A.%20N.%20Whitehead%27s%20Principia%20Mathematica,%20and%20Ludwig%20Wittgenstein%27s%20Tractatus%20Logico%20Philosophicus.). > > > A more technical overview can be found at [SEP: *Classical Logic*](https://plato.stanford.edu/entries/logic-classical/).
78,245
Do contemporary logicians generally claim, as [Wikipedia does](https://en.wikipedia.org/wiki/Classical_logic#Characteristics), that classical logic can be simply reduced to the 5 logical principles below? Or is it more complex than that and are there principles not included? > > 1. [Law of excluded middle](https://en.wikipedia.org/wiki/Law_of_excluded_middle) and [double negation](https://en.wikipedia.org/wiki/Double_negation) elimination > 2. [Law of noncontradiction](https://en.wikipedia.org/wiki/Law_of_noncontradiction), and the [principle of explosion](https://en.wikipedia.org/wiki/Principle_of_explosion) > 3. [Monotonicity of entailment](https://en.wikipedia.org/wiki/Monotonicity_of_entailment) and [idempotency of entailment](https://en.wikipedia.org/wiki/Idempotency_of_entailment) > 4. [Commutativity of conjunction](https://en.wikipedia.org/wiki/Logical_conjunction#Properties) > 5. [De Morgan duality](https://en.wikipedia.org/wiki/De_Morgan%27s_laws): every logical operator is dual to another > > >
2020/12/28
[ "https://philosophy.stackexchange.com/questions/78245", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/49667/" ]
Short Answer ------------ The answer to your question is at the start of the article you cited: > > Each logical system in this class shares [these 5] characteristic properties... **While not entailed by the preceding conditions** [emphasis mine], contemporary discussions of classical logic normally only include propositional and first-order logics. Classical logic generally entails the majority of the Western tradition of philosophy and logic since the [pre-Socratics](https://en.wikipedia.org/wiki/Pre-Socratic_philosophy), but particularly starting with [Aristotle](https://en.wikipedia.org/wiki/Aristotle). > > > "While not entailed by the preceding conditions" means that 'there is more than these 5 conditions to describe classical logical study'. Five sentences would hardly be enough to describe classical logic. Long Answer ----------- What is classical logic? According to the [*Encyclopedia of Philosophy*](https://en.wikipedia.org/wiki/Encyclopedia_of_Philosophy) and it's entry 'Logic, Non-Classical': > > [C]lassical logic [is] the theory of validity concerning truth functions and first-order quantifiers likely to be found in introductory textbooks of formal logic at the end of the twentieth century. > > > One way to define what classic logic is is to define it as what non-classic logic is not. (See PhilSE: [In how many and which ways can a logic be non-classical? Are there systems for organizing them?](https://philosophy.stackexchange.com/questions/77449/in-how-many-and-which-ways-can-a-logic-be-non-classical-are-there-systems-for-o) for a list of systems and their characteristics.) This is why the principles are featured prominently in this article because what non-classic logic is about is deviation from some of these principles. For instance, [sequent calculus](https://en.wikipedia.org/wiki/Sequent_calculus) and its extensions such as display calculi, nested sequent systems, and labeled sequent systems are metalogical and go beyond classic-logic as [metalogical theory](https://en.wikipedia.org/wiki/Metalogic). But it's much more informative to describe some of the features of classic logic and some of their historical origin. Is there more than the principles? Well as the WP article concedes, yes. In fact, of the three generally acknowledged [Laws of Thought](https://en.wikipedia.org/wiki/Law_of_thought), one is not mentioned in the list of principles above: the [Law of Identity](https://en.wikipedia.org/wiki/Law_of_identity). So, immediately, the moment discussion starts about classic logic, the Law of Identity is an important topic; the famous [philosopher of language](https://en.wikipedia.org/wiki/Philosophy_of_language), [John Searle](https://en.wikipedia.org/wiki/John_Searle), for instance, challenged the Law of Identity as a law arguing it is only a convention in his paper *Proper Names*. (See PhilSE: [On Searle's \_Proper Names\_ (1958)](https://philosophy.stackexchange.com/questions/77338/on-searles-proper-names-1958/77470#77470) for an explanation how he invokes the conventions of cryptography to challenge it.) From Volume 5 of the *Encyclopedia of Philosophy*, the entry "Logic, Traditional" begins with this: > > In logic, as in other fields, whenever there have been spectacular changes and advances, the logic that was current in the preceding period has been described as "old" or "traditional"...In every case, the logic termed "old" or "traditional" has been essentially Aristotelian, but with a certain concentration on the central portion of the Aristotelian *corpus*, the theory of categorical syllogism... especially of the sixteenth to the nineteenth century. > > > In fact, WP's entry on the [History of Logic has a subsection on traditional logic](https://en.wikipedia.org/wiki/History_of_logic#Traditional_logic): > > Other works in the textbook tradition include [Isaac Watts's](https://en.wikipedia.org/wiki/Isaac_Watts) *Logick: Or, the Right Use of Reason* (1725), [Richard Whately's](https://en.wikipedia.org/wiki/Richard_Whately) *Logic* (1826), and [John Stuart Mill's](https://en.wikipedia.org/wiki/John_Stuart_Mill) *A System of Logic* (1843). Although the latter was one of the last great works in the tradition, Mill's view that the foundations of logic lie in introspection[87] influenced the view that logic is best understood as a branch of psychology, a view which dominated the next fifty years of its development, especially in Germany.[88] > > > So, besides missing the Law of Identity, here are some additional topics: [categorical syllogism](https://en.wikipedia.org/wiki/Syllogism), the [logic of propositions](https://en.wikipedia.org/wiki/Propositional_calculus), [equipollence](https://en.wikipedia.org/wiki/Equinumerosity), and [Euler's diagrams](https://en.wikipedia.org/wiki/Euler_diagram), as well as the [history of classical logic](https://en.wikipedia.org/wiki/Classical_logic#History) more generally to understand the context of their development and relations. In fact, two of the most important works are from three heavyweights of the [analytical tradition](https://en.wikipedia.org/wiki/Analytic_philosophy). According to that WP article: > > Classical logic reached fruition in Bertrand Russell and A. N. Whitehead's [*Principia Mathematica*](https://en.wikipedia.org/wiki/Principia_Mathematica), and Ludwig Wittgenstein's [*Tractatus Logico Philosophicus*](http://Classical%20logic%20reached%20fruition%20in%20Bertrand%20Russell%20and%20A.%20N.%20Whitehead%27s%20Principia%20Mathematica,%20and%20Ludwig%20Wittgenstein%27s%20Tractatus%20Logico%20Philosophicus.). > > > A more technical overview can be found at [SEP: *Classical Logic*](https://plato.stanford.edu/entries/logic-classical/).
No. The Principle of explosion is absurd, i.e. illogical. And then the fact that Monotonicity of entailment is false follows from the absurdity of the Principle of Explosion. The so-called "classical Logic" part of mathematical logic is in contradiction to Aristotle's logic, which is the only logic which can be properly called "classical".
78,245
Do contemporary logicians generally claim, as [Wikipedia does](https://en.wikipedia.org/wiki/Classical_logic#Characteristics), that classical logic can be simply reduced to the 5 logical principles below? Or is it more complex than that and are there principles not included? > > 1. [Law of excluded middle](https://en.wikipedia.org/wiki/Law_of_excluded_middle) and [double negation](https://en.wikipedia.org/wiki/Double_negation) elimination > 2. [Law of noncontradiction](https://en.wikipedia.org/wiki/Law_of_noncontradiction), and the [principle of explosion](https://en.wikipedia.org/wiki/Principle_of_explosion) > 3. [Monotonicity of entailment](https://en.wikipedia.org/wiki/Monotonicity_of_entailment) and [idempotency of entailment](https://en.wikipedia.org/wiki/Idempotency_of_entailment) > 4. [Commutativity of conjunction](https://en.wikipedia.org/wiki/Logical_conjunction#Properties) > 5. [De Morgan duality](https://en.wikipedia.org/wiki/De_Morgan%27s_laws): every logical operator is dual to another > > >
2020/12/28
[ "https://philosophy.stackexchange.com/questions/78245", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/49667/" ]
I take your question to be, are the listed features sufficient to precisely and completely distinguish classical logic from all non-classical logics? There are certainly lots of other things one would need to specify in order for classical logic to qualify as a logic at all. And there are many other distinguishing features of classical logic not listed that follow from the ones that are listed. The problem with giving a definitive answer to this question is that it is a matter of disagreement over exactly what constitutes a classical logic. Some use the term in a limited fashion to include only elementary first-order predicate logic. Others use it in a more extended way to include any logic that has the property that all theorems of elementary classical logic are theorems of that logic. These come apart in a number of ways, some of which are: 1. The standard semantics of classical logic is bivalent, which is to say it is the logic of pairs of opposite values, usually true/false, such that every proposition has one and only one value. But some accounts allow that multi-valued logics can be classical, as long as these logics are strictly extensions of bivalent classical logic and do not conflict with it. 2. Modal logics are commonly treated as non-classical in modern textbooks, but usually they extend classical logic and so would count as classical logics in the extended sense. 3. The identity relation is often treated as part of the logic, rather than as a predicate that can be interpreted as part of a theory. One speaks of first-order predicate logic *with* or *without* identity. 4. There are standard rules for handling variables, quantifiers and domains in classical logic. These can be extended in various ways, e.g. with plural quantification, branching quantifiers, typed variables, etc. Some of these extensions might be considered classical, but others, such as the ability in free logics to quantify over non-existent objects, are usually considered non-classical. 5. First order logic can be extended to second order and higher orders. Some logicians (famously Quine) do not consider these to qualify as logic at all. The listed features do not stipulate bivalence, do not exclude non-truth-functional modal operators, do not specify any identity relationships, do not place any restrictions on quantification, and do not specify first-order, so they are obviously intended to characterise classical logic in an extended sense.
No. The Principle of explosion is absurd, i.e. illogical. And then the fact that Monotonicity of entailment is false follows from the absurdity of the Principle of Explosion. The so-called "classical Logic" part of mathematical logic is in contradiction to Aristotle's logic, which is the only logic which can be properly called "classical".
50,946,572
There is this big solution I'm working on, where I turned a lot of the projects into NuGet packages. The packages were created via a .nuproj file in a separate solution in VS. Everything works fine, except for the following: At bootstrap I load some catalogs for MEF to be able to import them, which worked perfectly when I worked with the original projects, but now the needed DLLs (which come from the a package) don't make it to the bin\Debug\Modules folder. Is there a way to make NuGet copy its content to the Modules folder? (and not to the root path) I tried using the different kinds of sub-folders inside the package with no success.
2018/06/20
[ "https://Stackoverflow.com/questions/50946572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7986337/" ]
I found that the best solution for this matter is the following: Take the files that need to be loaded and put them on the content folder. This can be done simply: ``` <ItemGroup> <Content Include=" {here go the needed files} " /> </ItemGroup> ``` The content folder just holds the files, but it **does not** copy them to the output folder on the client project. In order to copy them to the desired output, a .targets file can be used, just like the following: ``` <?xml version="1.0" encoding="utf-8" ?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="CopyToOutput" AfterTargets="Build"> <ItemGroup> <FilesToCopy Include="$(MSBuildThisFileDirectory)..\content\**\*.*"/> </ItemGroup> <Copy SourceFiles="@(FilesToCopy)" DestinationFiles="@(FilesToCopy->'$(OutDir)/%(RecursiveDir)%(FileName)%(Extension)')"/> </Target> </Project> ``` **Keep in mind that the targets file name and the ID of the NuGet have to be equal for the targets file to be added to the project.**
You should be able to use a target of `content/Modules`. Anything in the `content` directory is copied in to the `bin` directory on build. If you were trying to use the special "convention based" folders, like `lib/net45`, those are directories that cause Visual Studio to automatically create an assembly reference when the package is installed. You shouldn't use those for regular content files. See the [documentation](https://learn.microsoft.com/en-us/nuget/reference/nuspec#including-content-files) for more details.
66,196,473
I have to delete all the files in azure blob storage(specific container) automatically via azure release pipelines. So I have configured a task to get the IP address of Microsoft agent dynamically and add the IP address into blob Firewall. Below script working successfully sometimes, but I'm not able to see the IP in the Firewall list. Also same script is failing many times and throwing a error like > > The request may be blocked by network rules of storage account. Please > check network rule set using 'az storage account show -n accountname > --query networkRuleSet'.If you want to change the default action to apply when no rule matches, please use > 'az storage account update'. > > > ``` IP=`curl -s http://ipinfo.io/json | jq -r '.ip'` echo "Opening firewall for the IP : $IP" az storage account network-rule add -g custom-web --account-name "customwebapp" --ip-address $IP ``` I'm not sure on this , Any one able to advise me a best way to achieve this or Another alternate secure way for connecting the azure blob via Microsoft hosted agent ? **References** <https://learn.microsoft.com/en-us/cli/azure/storage/account/network-rule?view=azure-cli-latest>
2021/02/14
[ "https://Stackoverflow.com/questions/66196473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6814764/" ]
Work around is to temporary enable public access: ``` az storage account update --resource-group "$ResourceGroupName" --name "$Name" --default-action Allow ``` And after you are done with your operation you can turn it off again.
Communication between microsoft hosted agents and storage account behind firewall is always a troublesome one, even with the above work around of dynamically opening the storage firewall for that specific microsoft hosted agents IP address. This is mainly due to limitations on the storage account side. **1. Each storage account supports up to 200 IP network rules.** So we cannot add the entire IP ranges of hosted agents that spin up from any of your ADO orgs geographical region. If organization is hosted in West Europe, then hosted agents can come up from North and West Europe. So the no. of IP ranges that should be whitelisted will be more than 200. Due to this, users go with the above work around of allowing the particular hosted agent IP address. however the following limitations will not make the above workaround fool proof. When the hosted agent spin up in the same region as your storage account, workaround does not work. **2. Services deployed in the same region as the storage account use private Azure IP addresses for communication.** **3. IP network rules have no effect on requests originating from the same Azure region as the storage account**
49,059,664
I created [this very complex regular expression(RegEx101)](https://regex101.com/r/5cBm5a/1/) for IPv4 and IPv6 ``` ((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))|(^\*$) ``` Below are three examples of data that can be checked by this regular expression. ``` 2001:db8:abcd:0012:0000:0000:0000:0000 (ipv6) 0000:0000:2001:DB8:ABCD:12:: (condensed notation) 255.255.255.0 (ipv4) ``` but this regular expression does not work for IPv6 addresses with prefix. For example: ``` 2001:db8:abcd:0012::0/112 ``` does not work. How can this problem be fixed?
2018/03/01
[ "https://Stackoverflow.com/questions/49059664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9290438/" ]
And if anybody in the future wants optional subnet masks for ipv4 as well as ipv6. ``` /((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*(\/(\d|1\d|2\d|3[0-2]))?$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3}(\/(\d{1,2}|1[0-1]\d|12[0-8]))?)|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))|(^\*$)/g ``` <https://regex101.com/r/lS4Cjo/1>
My understanding is that you want to optionally match a 'prefix'(a number at the end of the address which is always preceded by a forward slash) *p* such that `1≤p≤128`. Let's try breaking this up. Optionally match the following block: * Match a forward slash `/` * Either match a two digit number * Or match a number between `100` and `119` (inclusive) * Or match a number a number between `120` and `128` (inclusive) The above is equivalent to this regex: `(\/(\d{1,2}|1[0-1]\d|12[0-8]))?`. <https://regex101.com/r/5cBm5a/3>
51,261,320
I'm new with editing app.config. I'd like to have this section in app.config: ``` <name1> <name2> <name3 att="something1">value1</name3> <name3 att="something2">value2</name3> ... </name2> </name1> ``` How to create it and access it from code? I want to get `something1`, `something2`, `value1` and `value2`. I found [this tutorial](https://www.codeproject.com/Articles/1173468/Four-Ways-to-Read-Configuration-Setting-in-Csharp), but it shows only how to get `something1`, not `something2`, `value1` and `value2` (Approach Four in tutorial). Thank you for any help.
2018/07/10
[ "https://Stackoverflow.com/questions/51261320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7871876/" ]
You should break your tests up more, both for your sake with debugging and to mitigate issues with the protractor control flow. Changing your tests to the following works: ``` import { browser, element, by } from 'protractor'; describe('protractor-test-project App', () => { it('goes to google', () => { browser.waitForAngularEnabled(false); browser.get('https://www.google.com'); expect(browser.getCurrentUrl()).toEqual('https://www.google.com/'); }); it('enters a search', () => { const inputEl = element(by.id('lst-ib')); browser.wait(() => inputEl.isPresent(), 10000, 'too long'); inputEl.sendKeys("protractor issue waitForAngularEnabled"); expect(inputEl.getAttribute('value')).toEqual('protractor issue waitForAngularEnabled'); }); it('returns to angular page', () => { browser.get('/'); browser.waitForAngularEnabled(true); const titleElement = element(by.id("title")); expect(titleElement.isPresent()); }); }); ``` Can't say for sure why the control flow wouldn't be handling this properly, but this seems to be caused by having two `waitForAngularEnabled` in the same spec (also might be because of navigating twice). If you disable your second one (where you re-enable it), your test works. So you can either use my solution above which breaks them out into multiple steps, or you can nest the call under `browser.get` which also seems to work i.e. ``` browser.get('/').then(() => { browser.waitForAngularEnabled(true); }); ``` Again, not sure why exactly that would happen. The control flow *should* be synchronizing these steps so using `.then()` shouldnt be necessary... but apparently it is. Breaking tests out into multiple `it` blocks also helps protractor synchronize things in the proper order
Using `waitForAngularEnabled` multiple times in the same test can be done, but requires a non-obvious addition of `browser.get`. Intuitively, most people think that setting `waitForAngularEnabled(true)` waits for protractor to pick up Angular tasks again but this returns a promise. Most people use it in a way where they can disable it on non-Angular pages and re-enable it on Angular pages, aka in a synchronous way. To solve this, you can use the following: ``` // do things on your Angular application waitForAngularEnabled(false) // do things on non-angular page waitForAngularEnabled(true) browser.get('/home') // this is a page from your Angular application ``` The `browser.get` function blocks until the Angular page is loaded.
36,446,144
I see load more button all the time, why do I need that?also what happens if I don't have a pagination? just keep lettings the post being displayed without pagination? I don't need a footer anyway. ``` {% for post in Posts %} <div class='col-sm-4'> {{post.content}} </div> {% endfor %} ``` the above simple code would do it, without load more or pagination, will my webpage downgrade itself?..I really don't see the need for pagination and load more feature for my site....the reason I don't want is because I'm not sure how to write them...
2016/04/06
[ "https://Stackoverflow.com/questions/36446144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5792491/" ]
First off, with djangos generic views (ListView), pagination is literally one line to implement in a view and then the code for the template is given to you in the documentation (the bootstrap docs also have pagination example code snippets). Your current loop is essentially the same as ``` for i in range(n): print i ``` As `n` increases, the more information will be printed to the screen and that leads to too much information for one person to take in. Even if they could take it all in, the majority of it they won't care about and only need the first couple results. Therefore, without pagination, you'd have just made your user wait additional time for your server to generate the content, and for their browser to display that content (even longer with images/media). Humans don't like waiting, don't make them when they don't need to.
Every post you add will have a certain weight, especially if it also has images or other media. Your users will have to load everything you have on the load of your page. This will make your page slow to load. Slow loading pages have poorer performance because people give up on loading. When the loading happens bit by bit as requested by the user it won't have such impact.
36,446,144
I see load more button all the time, why do I need that?also what happens if I don't have a pagination? just keep lettings the post being displayed without pagination? I don't need a footer anyway. ``` {% for post in Posts %} <div class='col-sm-4'> {{post.content}} </div> {% endfor %} ``` the above simple code would do it, without load more or pagination, will my webpage downgrade itself?..I really don't see the need for pagination and load more feature for my site....the reason I don't want is because I'm not sure how to write them...
2016/04/06
[ "https://Stackoverflow.com/questions/36446144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5792491/" ]
First off, with djangos generic views (ListView), pagination is literally one line to implement in a view and then the code for the template is given to you in the documentation (the bootstrap docs also have pagination example code snippets). Your current loop is essentially the same as ``` for i in range(n): print i ``` As `n` increases, the more information will be printed to the screen and that leads to too much information for one person to take in. Even if they could take it all in, the majority of it they won't care about and only need the first couple results. Therefore, without pagination, you'd have just made your user wait additional time for your server to generate the content, and for their browser to display that content (even longer with images/media). Humans don't like waiting, don't make them when they don't need to.
While @Haroen Viaene is correct, that is only one side of the matter. Also a big collection of posts would be very hard to navigate through if a user wants to find a certain old post he's read already for example. Also another way to go (without "load more" or pagination) is to use a search box and/or categories to separate your posts in.
60,360,478
I am trying to return the images for each row in my database through the controller ``` public function getEmotions() { $emotionsList = Emotions::all(); $images = DB::table('emotions')->select('image')->get(); return $images; } ``` This returns the error Malformed UTF-8 characters, possibly incorrectly encoded I have tried this as a solution ``` public function getEmotions() { $emotionsList = Emotions::all(); $images = DB::table('emotions')->select('image')->get(); return utf8_encode($images); } ``` But this then returns the error Method Illuminate\Support\Collection::\_\_toString() must return a string value I'm a but stuck with it now, can anyone see where I'm going wrong? This data is also being passed to a Vue file where I want to display the images from. Could I add this as {{ emotion.image }}? ``` <label v-for="emotion in emotions" class="cb-container">{{ emotion.em_name }} <input name="emotions[]" type="checkbox" :value="emotion.id"> <span class="checkmark"></span> </label> ```
2020/02/23
[ "https://Stackoverflow.com/questions/60360478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11170995/" ]
> > $images = DB::table('emotions')->select('image')**->get()**; > > > The `get()` method provided by Laravel **return an instance of** `Illuminate\Support\Collection` class. By definition an > > Illuminate\Support\Collection class provides a fluent, convenient > wrapper for working with **arrays** of data. > > > [Documentation](https://laravel.com/docs/5.8/collections) The point is: you need to loop through your $images var and `utf8_encode` each row separately like ``` foreach($images as $image) { ... } ``` **Edit** You may use ``` public function getEmotions() { $emotionsList = Emotions::all(); foreach($emotionsList as $emotion) { $emotion->image = 'data:image/jpeg;base64,' . base64_encode( $emotion->image); } return $emotionsList; } ``` **Usage** ``` ... v-for="emotion in emotions" ... <img src="$emotion->image"/> ```
You must return a response: ``` return response($images->toArray()); ``` Or if you want it encoded in json: ``` return response()->json($images); ```
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
Yes you can When you reach the “Let’s Connect You To A Network” page, hit “Shift” and “F10” on the keyboard at the same time. This will bring up the Command Prompt In this new cmd window, type in “taskmgr” and press “Enter” on the keyboard. This will bring up the Task Manager window so you can see all running processes. Expand the Task Manager by clicking the “More Details” button, and then find “Network Connection Flow.” Select this process and then hit the “End Task” button. Now you can close the cmd and taskmgr windows and return to the Windows 11 setup, where you will enter a name for a local account. \*\*\*I found a slightly faster way, once cmd prompt is open type in > > OOBE\BYPASSNRO > > > hit enter and close cmd window, now you can enter a local user account name
* Use the email address `[email protected]`. * Type any password (e.g. `123456`). * The wizard says "Oops, something went wrong". * Click `Next` to open a screen that allows you to create a local account. [![enter image description here](https://i.stack.imgur.com/tfBhg.jpg)](https://i.stack.imgur.com/tfBhg.jpg)
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
* Use the email address `[email protected]`. * Type any password (e.g. `123456`). * The wizard says "Oops, something went wrong". * Click `Next` to open a screen that allows you to create a local account. [![enter image description here](https://i.stack.imgur.com/tfBhg.jpg)](https://i.stack.imgur.com/tfBhg.jpg)
One option is to proceed and log in with a Microsoft account or create a new one. Once you're in Windows then you can create a local admin account, log in to the local account, and delete the Microsoft account.
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
* Use the email address `[email protected]`. * Type any password (e.g. `123456`). * The wizard says "Oops, something went wrong". * Click `Next` to open a screen that allows you to create a local account. [![enter image description here](https://i.stack.imgur.com/tfBhg.jpg)](https://i.stack.imgur.com/tfBhg.jpg)
Below is not for updating from Windows 10/11, but for installing 22H2 from scratch, or performing clean install. First, download the Windows 11 22H2's iso and [rufus](https://rufus.ie/en/) that make a USB memory a bootable Windows installer. That sounds as same as just making it by yourself, but there's reason I recommend using rufus - It allows you to bypass the requirements of network and Microsoft account by just clicking one box. When you start rufus, it shows the UI of the software. Pick your USB memory, and once you've selected your USB memory, then hit `SELECT` to select Windows 11's iso. Once it's done, rufus automatically assumes you've selected Windows' iso. Hit `START`, and after that a box will show up.[![enter image description here](https://i.stack.imgur.com/5s1vg.png)](https://i.stack.imgur.com/5s1vg.png) Tick the box that says **Remove requirement for an online Microsoft account**, and then hit `OK` (**Disable data collection** is optional, if you don't like the data collection then tick it). That's it. When rufus completed flashing iso to the USB memory, restart your PC, boot from USB memory, start installing Windows normally. It will ask you to connect internet, but ignore it, and voila it won't ask you to login to Microsoft account.
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
Yes you can When you reach the “Let’s Connect You To A Network” page, hit “Shift” and “F10” on the keyboard at the same time. This will bring up the Command Prompt In this new cmd window, type in “taskmgr” and press “Enter” on the keyboard. This will bring up the Task Manager window so you can see all running processes. Expand the Task Manager by clicking the “More Details” button, and then find “Network Connection Flow.” Select this process and then hit the “End Task” button. Now you can close the cmd and taskmgr windows and return to the Windows 11 setup, where you will enter a name for a local account. \*\*\*I found a slightly faster way, once cmd prompt is open type in > > OOBE\BYPASSNRO > > > hit enter and close cmd window, now you can enter a local user account name
One option is to proceed and log in with a Microsoft account or create a new one. Once you're in Windows then you can create a local admin account, log in to the local account, and delete the Microsoft account.
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
Yes you can When you reach the “Let’s Connect You To A Network” page, hit “Shift” and “F10” on the keyboard at the same time. This will bring up the Command Prompt In this new cmd window, type in “taskmgr” and press “Enter” on the keyboard. This will bring up the Task Manager window so you can see all running processes. Expand the Task Manager by clicking the “More Details” button, and then find “Network Connection Flow.” Select this process and then hit the “End Task” button. Now you can close the cmd and taskmgr windows and return to the Windows 11 setup, where you will enter a name for a local account. \*\*\*I found a slightly faster way, once cmd prompt is open type in > > OOBE\BYPASSNRO > > > hit enter and close cmd window, now you can enter a local user account name
Below is not for updating from Windows 10/11, but for installing 22H2 from scratch, or performing clean install. First, download the Windows 11 22H2's iso and [rufus](https://rufus.ie/en/) that make a USB memory a bootable Windows installer. That sounds as same as just making it by yourself, but there's reason I recommend using rufus - It allows you to bypass the requirements of network and Microsoft account by just clicking one box. When you start rufus, it shows the UI of the software. Pick your USB memory, and once you've selected your USB memory, then hit `SELECT` to select Windows 11's iso. Once it's done, rufus automatically assumes you've selected Windows' iso. Hit `START`, and after that a box will show up.[![enter image description here](https://i.stack.imgur.com/5s1vg.png)](https://i.stack.imgur.com/5s1vg.png) Tick the box that says **Remove requirement for an online Microsoft account**, and then hit `OK` (**Disable data collection** is optional, if you don't like the data collection then tick it). That's it. When rufus completed flashing iso to the USB memory, restart your PC, boot from USB memory, start installing Windows normally. It will ask you to connect internet, but ignore it, and voila it won't ask you to login to Microsoft account.
1,744,970
I'm using Windows 11 Insider Preview 10.0.22622.290 on my Lenovo [Flex 5i 15](https://www.lenovo.com/il/en/laptops/ideapad/ideapad-flex-series/IdeaPad-Flex-5-15ITL-05/p/88IPF501454?orgRef=https%253A%252F%252Fwww.google.com%252F). The pen I'm using is the Lenovo [Active Pen 2](https://support.lenovo.com/us/en/solutions/acc100370). It has 2 side buttons and up until about two months ago, the upper button, when used, would function as '**[barrel button](https://support.lenovo.com/us/en/solutions/ht508862-how-to-use-the-buttons-from-your-lenovo-digital-pen)**' which would function as right click on most things. In some apps such as OneNote (and Microsoft Whiteboard) it would activate *lasso select* and this is the important part for me as I use OneNote as my notebook app for university. ### What I think happend: It seems to me as this functionality was broken by some Windows update not long ago but I can't figure out which one and sadly I cannot roll back windows far enough to find out since my laptop had a bios update and doesn't want me to roll back windows to before it. ### What I've tried: In the Lenovo pen software the settings the button is mapped as 'barrel button' by default and I double checked it still is. I would be good to mention that I have **another Active Pen 2** (for emergencies) and that the problem happens on both of them and that every other part of the pen still works the same: * The bluetooth button on the top of the pen. * The lower side button still functions as eraser. * The pen itself works. I tried disabling its software and tried to update it but nothing changed. Tried to mp the barrel button function to the lower side button and nothing. It almost feels like the '*barrel button*' was removed from Windows. Setting the button to function as right click does not solve the problem since it turns to a mouse cursor when doing so and does not work as lasso select in onenote It seems like pressing the button just registers as a normal click. I uploaded this to Microsoft feedback hub too: <https://aka.ms/AAi701h>
2022/09/29
[ "https://superuser.com/questions/1744970", "https://superuser.com", "https://superuser.com/users/1675522/" ]
Below is not for updating from Windows 10/11, but for installing 22H2 from scratch, or performing clean install. First, download the Windows 11 22H2's iso and [rufus](https://rufus.ie/en/) that make a USB memory a bootable Windows installer. That sounds as same as just making it by yourself, but there's reason I recommend using rufus - It allows you to bypass the requirements of network and Microsoft account by just clicking one box. When you start rufus, it shows the UI of the software. Pick your USB memory, and once you've selected your USB memory, then hit `SELECT` to select Windows 11's iso. Once it's done, rufus automatically assumes you've selected Windows' iso. Hit `START`, and after that a box will show up.[![enter image description here](https://i.stack.imgur.com/5s1vg.png)](https://i.stack.imgur.com/5s1vg.png) Tick the box that says **Remove requirement for an online Microsoft account**, and then hit `OK` (**Disable data collection** is optional, if you don't like the data collection then tick it). That's it. When rufus completed flashing iso to the USB memory, restart your PC, boot from USB memory, start installing Windows normally. It will ask you to connect internet, but ignore it, and voila it won't ask you to login to Microsoft account.
One option is to proceed and log in with a Microsoft account or create a new one. Once you're in Windows then you can create a local admin account, log in to the local account, and delete the Microsoft account.
15,396,895
Quite a strange problem I have here, I am trying to run the DXUT DirectX 10/11 tutorials from DirectX sample browser. They build fine, but cannot be run in Debug mode, as this triggers the error warning "Failed to create the Direct3D device". This is strange as I can run them in release mode. The strangest thing however is that they use to run in Debug mode, and I swear I changed nothing in the day it ran, and the next day that it didn't. A friend also has the same exact problem, which happened around the same time. Has anyone ran into this problem and know of a solution, or perhaps know why its happening beyond the obvious, I have a DirectX 11 capable card if you didn't pick that up. Thanks.
2013/03/13
[ "https://Stackoverflow.com/questions/15396895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800303/" ]
I literally just spent all day trying to fix this exact same problem. Here is the solution which should hopefully fix yours too... I managed to find this article explaining that a recent update, *(26th February 2013 to be exact)*, caused the older version to mess up: <http://blogs.msdn.com/b/chuckw/archive/2013/02/26/directx-11-1-and-windows-7-update.aspx> That explains why it was working fine a few weeks ago, and now it just suddenly stopped working I guess! Following their advice, **I downloaded a trial version of Visual Studio 2012**, and after an hour and a half of installation time, and a system restart, you should have all the new DirectX SDK files that you need. NOTE: You don't even have to use Visual Studio 2012. The new files should fix your issues for Visual Studio 2010 and older versions I presume! (Before doing this **I also installed all the latest drivers**, but I don't think that did anything to help, but it's worth upgrading drivers whenever you can, as that has fixed a similar issue I had before). Hope this helps!!! :)
Somewhere in your code you probably have something along the line of this ``` #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif ``` If you do take a look at the `D3D10_CREATE_DEVICE_DEBUG;` on the [msdn](http://msdn.microsoft.com/en-us/library/windows/desktop/bb204909%28v=vs.85%29.aspx) you will see this > > To use this flag, you must have D3D11\_1SDKLayers.dll installed; > otherwise, device creation fails. > > > You should check that you do have that `dll` in your system or you should reinstall the DirectX SDK.
15,396,895
Quite a strange problem I have here, I am trying to run the DXUT DirectX 10/11 tutorials from DirectX sample browser. They build fine, but cannot be run in Debug mode, as this triggers the error warning "Failed to create the Direct3D device". This is strange as I can run them in release mode. The strangest thing however is that they use to run in Debug mode, and I swear I changed nothing in the day it ran, and the next day that it didn't. A friend also has the same exact problem, which happened around the same time. Has anyone ran into this problem and know of a solution, or perhaps know why its happening beyond the obvious, I have a DirectX 11 capable card if you didn't pick that up. Thanks.
2013/03/13
[ "https://Stackoverflow.com/questions/15396895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800303/" ]
I literally just spent all day trying to fix this exact same problem. Here is the solution which should hopefully fix yours too... I managed to find this article explaining that a recent update, *(26th February 2013 to be exact)*, caused the older version to mess up: <http://blogs.msdn.com/b/chuckw/archive/2013/02/26/directx-11-1-and-windows-7-update.aspx> That explains why it was working fine a few weeks ago, and now it just suddenly stopped working I guess! Following their advice, **I downloaded a trial version of Visual Studio 2012**, and after an hour and a half of installation time, and a system restart, you should have all the new DirectX SDK files that you need. NOTE: You don't even have to use Visual Studio 2012. The new files should fix your issues for Visual Studio 2010 and older versions I presume! (Before doing this **I also installed all the latest drivers**, but I don't think that did anything to help, but it's worth upgrading drivers whenever you can, as that has fixed a similar issue I had before). Hope this helps!!! :)
The automatic IE10 update is what caused my issue of automatic non support of directx development. Simplest solution is downloading standalone win8 sdk at... <http://msdn.microsoft.com/en-us/windows/desktop/hh852363> The directx debug layer dll has to be updated.
181,859
> > **Possible Duplicate:** > > [Best alternative to Windows Live Messenger](https://superuser.com/questions/80465/best-alternative-to-windows-live-messenger) > > > I'm looking for alternative programs other then the offical client to use with Yahoo messenger on Windows. What options are there? Preferably free and with no ads/spyware.
2010/08/28
[ "https://superuser.com/questions/181859", "https://superuser.com", "https://superuser.com/users/555/" ]
You can try [Digsby](http://Digsby.com). Direct download here: <http://update.digsby.com/install/digsby_setup.exe> Or [Trillian](http://www.trillian.im/), though there is the option of a paid version of this one.
I suggest that you have a look at Pidgin. It's an open source messaging client which support a wide range of protocols. (Open Source programs are usually free for ads and malware, and this applies to Pidgin as well) * [Pidgin](http://pidgin.im/) For a more comprehensive list of the alternatives out there, check out this article on Wikipedia: <http://en.wikipedia.org/wiki/Comparison_of_instant_messaging_clients>
181,859
> > **Possible Duplicate:** > > [Best alternative to Windows Live Messenger](https://superuser.com/questions/80465/best-alternative-to-windows-live-messenger) > > > I'm looking for alternative programs other then the offical client to use with Yahoo messenger on Windows. What options are there? Preferably free and with no ads/spyware.
2010/08/28
[ "https://superuser.com/questions/181859", "https://superuser.com", "https://superuser.com/users/555/" ]
I know that @Force Flow already mentioned Trillian, but I'm going to expand on this... [Trillian](http://www.trillian.im/) is the best all-in-one solution I have ever seen. It handles Yahoo Messenger and your contacts, etc *extremely* well. From Wikipedia: > > It can connect to multiple IM services, such as AIM, ICQ, Windows Live Messenger, Yahoo! Messenger, IRC, Novell GroupWise Messenger, Bonjour, XMPP, and Skype networks; as well as Social Networks, such as Facebook, Twitter and MySpace; and email services, such as POP3, IMAP, Gmail, Hotmail and Yahoo! Mail. > > > I have used Trillian myself (the free version), which works extremely well, and does what I need it to do... If you decide to accept Trillian as your accepted answer, **give the checkmark to @Force Flow, since he mentioned it first.**
I suggest that you have a look at Pidgin. It's an open source messaging client which support a wide range of protocols. (Open Source programs are usually free for ads and malware, and this applies to Pidgin as well) * [Pidgin](http://pidgin.im/) For a more comprehensive list of the alternatives out there, check out this article on Wikipedia: <http://en.wikipedia.org/wiki/Comparison_of_instant_messaging_clients>
181,859
> > **Possible Duplicate:** > > [Best alternative to Windows Live Messenger](https://superuser.com/questions/80465/best-alternative-to-windows-live-messenger) > > > I'm looking for alternative programs other then the offical client to use with Yahoo messenger on Windows. What options are there? Preferably free and with no ads/spyware.
2010/08/28
[ "https://superuser.com/questions/181859", "https://superuser.com", "https://superuser.com/users/555/" ]
You can try [Digsby](http://Digsby.com). Direct download here: <http://update.digsby.com/install/digsby_setup.exe> Or [Trillian](http://www.trillian.im/), though there is the option of a paid version of this one.
[Pidgin](http://pidgin.im/) - multi-platform, multi-protocol. Works flawlessly under Windows/Linux.
181,859
> > **Possible Duplicate:** > > [Best alternative to Windows Live Messenger](https://superuser.com/questions/80465/best-alternative-to-windows-live-messenger) > > > I'm looking for alternative programs other then the offical client to use with Yahoo messenger on Windows. What options are there? Preferably free and with no ads/spyware.
2010/08/28
[ "https://superuser.com/questions/181859", "https://superuser.com", "https://superuser.com/users/555/" ]
I know that @Force Flow already mentioned Trillian, but I'm going to expand on this... [Trillian](http://www.trillian.im/) is the best all-in-one solution I have ever seen. It handles Yahoo Messenger and your contacts, etc *extremely* well. From Wikipedia: > > It can connect to multiple IM services, such as AIM, ICQ, Windows Live Messenger, Yahoo! Messenger, IRC, Novell GroupWise Messenger, Bonjour, XMPP, and Skype networks; as well as Social Networks, such as Facebook, Twitter and MySpace; and email services, such as POP3, IMAP, Gmail, Hotmail and Yahoo! Mail. > > > I have used Trillian myself (the free version), which works extremely well, and does what I need it to do... If you decide to accept Trillian as your accepted answer, **give the checkmark to @Force Flow, since he mentioned it first.**
[Pidgin](http://pidgin.im/) - multi-platform, multi-protocol. Works flawlessly under Windows/Linux.
181,859
> > **Possible Duplicate:** > > [Best alternative to Windows Live Messenger](https://superuser.com/questions/80465/best-alternative-to-windows-live-messenger) > > > I'm looking for alternative programs other then the offical client to use with Yahoo messenger on Windows. What options are there? Preferably free and with no ads/spyware.
2010/08/28
[ "https://superuser.com/questions/181859", "https://superuser.com", "https://superuser.com/users/555/" ]
You can try [Digsby](http://Digsby.com). Direct download here: <http://update.digsby.com/install/digsby_setup.exe> Or [Trillian](http://www.trillian.im/), though there is the option of a paid version of this one.
I know that @Force Flow already mentioned Trillian, but I'm going to expand on this... [Trillian](http://www.trillian.im/) is the best all-in-one solution I have ever seen. It handles Yahoo Messenger and your contacts, etc *extremely* well. From Wikipedia: > > It can connect to multiple IM services, such as AIM, ICQ, Windows Live Messenger, Yahoo! Messenger, IRC, Novell GroupWise Messenger, Bonjour, XMPP, and Skype networks; as well as Social Networks, such as Facebook, Twitter and MySpace; and email services, such as POP3, IMAP, Gmail, Hotmail and Yahoo! Mail. > > > I have used Trillian myself (the free version), which works extremely well, and does what I need it to do... If you decide to accept Trillian as your accepted answer, **give the checkmark to @Force Flow, since he mentioned it first.**
9,929,735
I am using the ExpanderView of WindowsPhone Toolkit and on first load my expanded Expander will always look like the second picture. It seems, that its always at the same Height of all Items together. If I goto another page and go back, everything will be fine and the Layout look quiet correct - except that stopping line of the Expander (Pic 1). Either this.UpdatedLayout();(current Page) nor ExpanderView.UpdateLayout(); resolved anything. Items which doesn't show up are fully loaded in that list. ![part 1](https://i.stack.imgur.com/Eew3O.png) ![part 2](https://i.imgur.com/ULq3a.png) ``` <ItemsControl ItemsSource="{Binding EpisodeList}" Margin="20,0,0,0" Grid.Row="1" Grid.ColumnSpan="2"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <toolkit:ExpanderView ItemsSource="{Binding Value}" > <toolkit:ExpanderView.Header> <TextBlock Margin="0,0,10,0"> <Run Text="Season "/> <Run Text="{Binding Key}" /> </TextBlock> </toolkit:ExpanderView.Header> <toolkit:ExpanderView.ItemTemplate> <DataTemplate> <Border BorderBrush="White" BorderThickness="1" Margin="5"> <Grid MouseLeftButtonUp="Grid_MouseLeftButtonUp"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition /> </Grid.ColumnDefinitions> <Image Height="40" Source="{Binding ScreenCap}" Margin="5,0,0,0"/> <TextBlock x:Name="t" Margin="10" Text="{Binding Title}" TextWrapping="Wrap" Grid.Column="1" /> </Grid> </Border> </DataTemplate> </toolkit:ExpanderView.ItemTemplate> </toolkit:ExpanderView> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` EpisodeList is type of Dictionary(int,ObservableCollection(myClass)) and implements INotifyPropertyChanged If anyone got any plan whats going wrong here, I really would appreciate your help, i just did not found any bugreport on that list on google nor a similar Bug. (Debugged on Device as well as on Emulator)
2012/03/29
[ "https://Stackoverflow.com/questions/9929735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1021605/" ]
I managed to solve this by using a listbox as the itemcontainer, and binding the expander items to it: ``` <Controls:ExpanderView Expanded="ExpanderView_Expanded" Header="{Binding}" HeaderTemplate="{StaticResource HeaderTemplate}" NonExpandableHeader="{Binding}" ExpanderTemplate="{StaticResource ExpanderTemplate}" NonExpandableHeaderTemplate="{StaticResource NonExpandableHeaderTemplate}" Expander="{Binding}" > <ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Items}" /> </Controls:ExpanderView> ```
I had similar problem with the ExpanderView. I think it could be a bug in the view, somehow related to the 2048px limitation. Basically when I added lot of items to an expanded ExpanderView everything was fine untill I collapsed the view and expanded it again. After expanding the ExpanderView, any items after the 2048 pixel where not shown unless i tapped them or scrolled it and even then they were shown only for as long as they were on the move (the tap animation of the item was running or the list was on the move). I noticed that if I added an item to the ExpanderView or removed one from it while it was expanded, the glitch went away until the next time I collapsed and expanded the item, so I made a quick work around to add and remove a dummy item to the view when ever it was expanded by using the Expanded- and LayoutUpdated- events of the ExpanderView. Basically this is what I did: * Set state to indicate that expanding is in progress and store the view being expanded for later use. (in Expanded event handler) * Wait untill all the Expanderviews' layouts are updated (use LayoutUpdated event handler to keep track on this) * Add dummy item to the ExpanderView that was expanded (in LayoutUpdated event handler) * Wait untill all the Expanderviews' layouts are updated * Remove the dummy item (in LayoutUpdated event handler) Ugly solution perhaps but best I could come up with. Hope it's some help in your problem. Edit: Doesn't help on that stopping line of the Expander thing. Just couldn't get that one to work..
263,902
It is often claimed that the only tensors invariant under the orthogonal transformations (rotations) are the Kronecker delta $\delta\_{ij}$, the Levi-Civita epsilon $\epsilon\_{ijk}$ and various combinations of their tensor products. While it is easy to check that $\delta\_{ij}$ and $\epsilon\_{ijk}$ are indeed invariant under rotations, I would like to know if there exist any proof by construction that they are the **only** (irreducible) tensors with this property.
2012/12/22
[ "https://math.stackexchange.com/questions/263902", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
This is somewhat late in the day / year, but I suspect the author is asking about representations of isotropic Cartesian tensors, where "isotropic" means "invariant under the action of proper orthogonal transformations" and "Cartesian" means the underlying space is Euclidean $R^n$ ($R^3$ is a case of great practical interest). The proofs for the two cases asked here are non-trivial, and given in Weyl, H., The Classical Groups, Princeton University Press, 1939 Constructions for higher-order isotropic Cartesian tensors are also given there.
> > Harold Jeffreys (1973). On isotropic tensors. Mathematical Proceedings of the Cambridge Philosophical Society, 73, pp 173-176. > > > The proof given is a lot more concrete and "hands on" than Weyl's proof linked to by user\_of\_math.
263,902
It is often claimed that the only tensors invariant under the orthogonal transformations (rotations) are the Kronecker delta $\delta\_{ij}$, the Levi-Civita epsilon $\epsilon\_{ijk}$ and various combinations of their tensor products. While it is easy to check that $\delta\_{ij}$ and $\epsilon\_{ijk}$ are indeed invariant under rotations, I would like to know if there exist any proof by construction that they are the **only** (irreducible) tensors with this property.
2012/12/22
[ "https://math.stackexchange.com/questions/263902", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
This is somewhat late in the day / year, but I suspect the author is asking about representations of isotropic Cartesian tensors, where "isotropic" means "invariant under the action of proper orthogonal transformations" and "Cartesian" means the underlying space is Euclidean $R^n$ ($R^3$ is a case of great practical interest). The proofs for the two cases asked here are non-trivial, and given in Weyl, H., The Classical Groups, Princeton University Press, 1939 Constructions for higher-order isotropic Cartesian tensors are also given there.
$\mathtt{Definition:}$ $T$ is an isotropic tensor of type $(0,n)$ if $\;T\_{i\_1i\_2...i\_n}=R\_{i\_1j\_1}R\_{i\_2j\_2}...R\_{i\_nj\_n}T\_{j\_1j\_2...j\_n}$ whenever $R$ is an orthogonal matrix i.e $R^TR=RR^T=I$. $\mathtt{n=2:}$[See my answer here](https://math.stackexchange.com/questions/881571/how-to-prove-that-the-kronecker-delta-is-the-unique-isotropic-tensor-of-order-2/1314269?noredirect=1#comment2669792_1314269). $\mathtt{n=3:}$For tensors of type $(0,3)$ we can mimick the proof for $n=2$ to deduce skew-symmetricness. Suppose $T\_{pqr}$ is an isotropic tensor. Let $R$ be a diagonal matrix whose diagonal entries are $1$ except for $R\_{ii}$ and $R\_{ii}=-1$. $R$ is diagonal and its own inverse hence it's orthogonal. $$T\_{ijj}=\sum\_{p,q,r}R\_{ip}R\_{jq}R\_{kj}T\_{pqr}=R\_{ii}R\_{jj}R\_{jj}T\_{ijj}\text{( using the fact that R is diagonal)}\\ \Rightarrow T\_{ijj}=-T\_{ijj}=0$$ Using the symmetry of this argument we can show that the only nonzero components of $T$ are those whose indices are a permutation of $(1,2,3)$. Suppose $i\neq j$. Define $$R\_{lm}=\begin{cases} -\delta\_{jm} & \text{if } l=i\\ \delta\_{im} & \text{if } l=j\\ \delta\_{lm} & \text{otherwise} \end{cases}\\ (R^TR)\_{lm}=\sum\_{n}R\_{nl}R\_{nm}=\sum\_{n\neq i,j}R\_{nl}R\_{nm}+(-\delta\_{jl})(-\delta\_{jm})+\delta\_{il}\delta\_{im}\\ =\sum\_{n\neq i,j}\delta\_{nl}\delta\_{nm}+\delta\_{jl}\delta\_{jm}+\delta\_{il}\delta\_{im}=\sum\_{n}\delta\_{nl}\delta\_{nm}=\delta\_{lm}\\$$ So $R$ is orthogonal. Suppose $k\neq i,j$. $$T\_{ijk}=\sum\_{p,q,r}R\_{ip}R\_{jq}R\_{kr}T\_{pqr}=\sum\_{p,q,r}-\delta\_{jp}\delta\_{iq}\delta\_{kr}T\_{pqr}=-T\_{jik}$$ So $T$ is skew-symmetric in its $1$st two indices. Symmetry of this argument shows that $T$ is fully skew-symmetric. Therefore $T$ is a multiple of the Levi-Civita tensor.
263,902
It is often claimed that the only tensors invariant under the orthogonal transformations (rotations) are the Kronecker delta $\delta\_{ij}$, the Levi-Civita epsilon $\epsilon\_{ijk}$ and various combinations of their tensor products. While it is easy to check that $\delta\_{ij}$ and $\epsilon\_{ijk}$ are indeed invariant under rotations, I would like to know if there exist any proof by construction that they are the **only** (irreducible) tensors with this property.
2012/12/22
[ "https://math.stackexchange.com/questions/263902", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
> > Harold Jeffreys (1973). On isotropic tensors. Mathematical Proceedings of the Cambridge Philosophical Society, 73, pp 173-176. > > > The proof given is a lot more concrete and "hands on" than Weyl's proof linked to by user\_of\_math.
$\mathtt{Definition:}$ $T$ is an isotropic tensor of type $(0,n)$ if $\;T\_{i\_1i\_2...i\_n}=R\_{i\_1j\_1}R\_{i\_2j\_2}...R\_{i\_nj\_n}T\_{j\_1j\_2...j\_n}$ whenever $R$ is an orthogonal matrix i.e $R^TR=RR^T=I$. $\mathtt{n=2:}$[See my answer here](https://math.stackexchange.com/questions/881571/how-to-prove-that-the-kronecker-delta-is-the-unique-isotropic-tensor-of-order-2/1314269?noredirect=1#comment2669792_1314269). $\mathtt{n=3:}$For tensors of type $(0,3)$ we can mimick the proof for $n=2$ to deduce skew-symmetricness. Suppose $T\_{pqr}$ is an isotropic tensor. Let $R$ be a diagonal matrix whose diagonal entries are $1$ except for $R\_{ii}$ and $R\_{ii}=-1$. $R$ is diagonal and its own inverse hence it's orthogonal. $$T\_{ijj}=\sum\_{p,q,r}R\_{ip}R\_{jq}R\_{kj}T\_{pqr}=R\_{ii}R\_{jj}R\_{jj}T\_{ijj}\text{( using the fact that R is diagonal)}\\ \Rightarrow T\_{ijj}=-T\_{ijj}=0$$ Using the symmetry of this argument we can show that the only nonzero components of $T$ are those whose indices are a permutation of $(1,2,3)$. Suppose $i\neq j$. Define $$R\_{lm}=\begin{cases} -\delta\_{jm} & \text{if } l=i\\ \delta\_{im} & \text{if } l=j\\ \delta\_{lm} & \text{otherwise} \end{cases}\\ (R^TR)\_{lm}=\sum\_{n}R\_{nl}R\_{nm}=\sum\_{n\neq i,j}R\_{nl}R\_{nm}+(-\delta\_{jl})(-\delta\_{jm})+\delta\_{il}\delta\_{im}\\ =\sum\_{n\neq i,j}\delta\_{nl}\delta\_{nm}+\delta\_{jl}\delta\_{jm}+\delta\_{il}\delta\_{im}=\sum\_{n}\delta\_{nl}\delta\_{nm}=\delta\_{lm}\\$$ So $R$ is orthogonal. Suppose $k\neq i,j$. $$T\_{ijk}=\sum\_{p,q,r}R\_{ip}R\_{jq}R\_{kr}T\_{pqr}=\sum\_{p,q,r}-\delta\_{jp}\delta\_{iq}\delta\_{kr}T\_{pqr}=-T\_{jik}$$ So $T$ is skew-symmetric in its $1$st two indices. Symmetry of this argument shows that $T$ is fully skew-symmetric. Therefore $T$ is a multiple of the Levi-Civita tensor.
169,136
I am trying to figure out the problem stated in the title. Every image/photo I upload to my wordpress site gets slightly blurry. I format them according to my wp theme requirements, however after the image is processed by wordpress and I open the site in a browser I is slightly blurry. This is specially noticeable in Firefox browser. What am I doing wrong? I use photoshop to export images for web and on my computer they look just fine. I tried exporting them directly from Illustrator and the same scenario occurs. So I believe its on wordpress side. Thank you!
2014/11/21
[ "https://wordpress.stackexchange.com/questions/169136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63837/" ]
Actually WordPress reduce quality of image when you upload it via media uploader. WordPress has built in compression for JPG images. Whenever you upload an JPG/JPEG image to WordPress media library, WordPress will automatically compress your images to 90% of the original quality, this is intended to help your pages load faster and keep file sizes smaller. You can disable image compression and force WordPress to keep maximum quality images with this function. ``` // Set image quality function my_image_quality( $quality ) { return 100; } add_filter( 'jpeg_quality', 'my_image_quality' ); add_filter( 'wp_editor_set_quality', 'my_image_quality' ); ```
Normally this might due to some discrepancy from default set values for image in functions.php in wordpress and check whether any default values is set for the images in that file. You also can set it manually in function.php file as below. ``` add_theme_support('post-thumbnails'); update_option('thumbnail_size_w', 200); update_option('thumbnail_size_h', 200); update_option('large_size_w', 650); add_image_size( 'my-thumb', 400, 8888 ); and add_image_size( 'my-thumb', 250); ```
169,136
I am trying to figure out the problem stated in the title. Every image/photo I upload to my wordpress site gets slightly blurry. I format them according to my wp theme requirements, however after the image is processed by wordpress and I open the site in a browser I is slightly blurry. This is specially noticeable in Firefox browser. What am I doing wrong? I use photoshop to export images for web and on my computer they look just fine. I tried exporting them directly from Illustrator and the same scenario occurs. So I believe its on wordpress side. Thank you!
2014/11/21
[ "https://wordpress.stackexchange.com/questions/169136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63837/" ]
Actually WordPress reduce quality of image when you upload it via media uploader. WordPress has built in compression for JPG images. Whenever you upload an JPG/JPEG image to WordPress media library, WordPress will automatically compress your images to 90% of the original quality, this is intended to help your pages load faster and keep file sizes smaller. You can disable image compression and force WordPress to keep maximum quality images with this function. ``` // Set image quality function my_image_quality( $quality ) { return 100; } add_filter( 'jpeg_quality', 'my_image_quality' ); add_filter( 'wp_editor_set_quality', 'my_image_quality' ); ```
For us the problem was with **plugins**, we **disabled all** unused or unwanted **plugins** and then tried to upload, image uploads are fine.
15,774,548
I am writing linux kernel code. I am in VFS and I want to modify it. I want to add a check to see whether or not the user is root and based on that make a decision. How do I do this? Is there a kernel version of getuid() ? Or does any structure like "current->" contain info on which user it is for the current process?
2013/04/02
[ "https://Stackoverflow.com/questions/15774548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2237826/" ]
You can use `current_cred()` as defined in `include/linux/cred.h`, which will give you a pointer to a `struct cred` itself defined in the same header. Something like ``` if (current_cred()->uid != 0) return -EPERM; ```
As mentioned `current_cred()->uid` now returns a `struct kuid_t`. To get the value you need `current_cred()->uid.val` & a final type cast to get rid of the warnings. ``` if ((int)current_cred()->uid.val != 0) return -EPERM; ```
61,621,551
I am trying to grab video panel in google result for example I am searching ---> "great+castles" <-- and in that search result, it has a panel that contains videos when I scrape it I get HTML but with different values of attributes I am not able to grab video panel ``` text="great+castles" url = f'https://google.com/search?q={text}' response = requests.get(url) print(url) soup = BeautifulSoup(response.text,'html.parser') a=soup.findAll('div',{'id':'main'}) a ``` I do get output response but attributes are not same as on google chrome
2020/05/05
[ "https://Stackoverflow.com/questions/61621551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12004786/" ]
Firstly, you can always write that HTML response in HTML file and check what actually you're getting by opening in the browser. Secondly, you cannot **scrape** data from google that easily, you need proxies for that but even with elite proxies you may face number of challenges like reCaptcha etc.
You have 2 options to check source code returned by requests: 1. Save response as `html` file locally and open it in browser. 2. Get [Scrapy](https://scrapy.org/) framework and use `view(response)` from `Scrapy Shell`. The Scrapy option is handy but requires installation of the framework that can be an overkill for a one-time project. There is also another(more robust) way to get results from Google Search by using [`Google Search API][2]` from SerpApi. It's a paid API with a free plan. For example, your request will return handy json including the `inline video` section: ``` > "inline_videos": > [ > { > "position": > 1, > "title": > "A Thousand Years of European Castles", > "link": > "https://www.youtube.com/watch?v=uXSFt-zey84", > "thumbnail": > "https://i.ytimg.com/vi/uXSFt-zey84/mqdefault.jpg?sqp=-oaymwEECHwQRg&rs=AMzJL3n1trdIa7_n5X-kJf8pq70OYoY47w", > "channel": > "Best Documentary", > "duration": > "53:59", > "platform": > "YouTube", > "date": > "Jan 25, 2022" > }, > { > "position": > 2, > "title": > "The Most Beautiful Castles in the World", > "link": > "https://www.youtube.com/watch?v=ln-v2ibnWHU", > "thumbnail": > "https://i.ytimg.com/vi/ln-v2ibnWHU/mqdefault.jpg?sqp=-oaymwEECHwQRg&rs=AMzJL3kHM2n3_vkRLM_stMr0XuiFs5uaCQ", > "channel": > "Luxury Homes", > "duration": > "4:58", > "platform": > "YouTube", > "date": > "Mar 29, 2020" > }, > { > "position": > 3, > "title": > "Great Castles of Europe: Neuschwanstein (Part 1 of 3)", > "link": > "https://www.youtube.com/watch?v=R_uFzANW2Xo", > "thumbnail": > "https://i.ytimg.com/vi/R_uFzANW2Xo/mqdefault.jpg?sqp=-oaymwEECHwQRg&rs=AMzJL3nYdSY5YW2QU1pijXo3xx7ObrILdg", > "channel": > "trakehnen", > "duration": > "8:51", > "platform": > "YouTube", > "date": > "Sep 24, 2009" > } > ], ``` > > Disclaimer, I work for SerpApi. > > > .
61,621,551
I am trying to grab video panel in google result for example I am searching ---> "great+castles" <-- and in that search result, it has a panel that contains videos when I scrape it I get HTML but with different values of attributes I am not able to grab video panel ``` text="great+castles" url = f'https://google.com/search?q={text}' response = requests.get(url) print(url) soup = BeautifulSoup(response.text,'html.parser') a=soup.findAll('div',{'id':'main'}) a ``` I do get output response but attributes are not same as on google chrome
2020/05/05
[ "https://Stackoverflow.com/questions/61621551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12004786/" ]
Firstly, you can always write that HTML response in HTML file and check what actually you're getting by opening in the browser. Secondly, you cannot **scrape** data from google that easily, you need proxies for that but even with elite proxies you may face number of challenges like reCaptcha etc.
You can scrape Google Search Video Panel Results using [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) web scraping library. To get to the tab we need, you need to register it in the [`parameters`](https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls), like this: ```py # this URL params is taken from the actual Google search URL # and transformed to a more readable format params = { "q": "great castles", # query "tbm" : "vid", # video panel "gl": "us", # contry of the search "hl": "en" # language of the search } ``` To get the required data, you need to get a "container", which is a CSS selector called [class selector](https://serpapi.com/blog/web-scraping-with-css-selectors-using-python/#class_selector) that contains all the information about video results i.e title, link, channel name and so on. In our case, this is the "video-voyager" selector which contains data about the title, channel name, video link, description and so on. Have a look at the [SelectorGadget](https://selectorgadget.com/) Chrome extension to easily pick selectors by clicking on the desired element in your browser (*not always work perfectly if the website is rendered via JavaScript*). [Check code in online IDE](https://replit.com/@denisskopa/stackoverflow-scrape-google-search-video-panel#main.py). ```py from bs4 import BeautifulSoup import requests, lxml, json headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36" } params = { "q": "great castles", # query "tbm" : "vid", # video panel "gl": "us", # contry of the search "hl": "en" # language of the search } # by default it will scrape video page results but can be truned off def scrape_google_videos(inline_videos=False, video_page=True): if inline_videos: data_inline_video = [] params.pop("tbm", None) # deletes tbm: vid html = requests.get("https://www.google.com/search", headers=headers, params=params, timeout=30) soup = BeautifulSoup(html.text, "lxml") print("Inline video data:\n") for result in soup.select(".WZIVy"): title = result.select_one(".cHaqb").text platform = result.select_one("cite").text chanel = result.select_one(".pcJO7e span").text.replace(" · ", "") date = result.select_one(".hMJ0yc span").text data_inline_video.append({ "title" : title, "platform" : platform, "chanel" : chanel, "date" : date }) print(json.dumps(data_inline_video, indent=2, ensure_ascii=False)) if video_page: data_video_panel = [] html = requests.get("https://www.google.com/search", headers=headers, params=params, timeout=30) soup = BeautifulSoup(html.text, "lxml") print("Video panel data:\n") for products in soup.select("video-voyager"): title = products.select_one(".DKV0Md").text description = products.select_one(".Uroaid").text link = products.select_one(".ct3b9e a")["href"] chanel = products.select_one(".Zg1NU+ span").text duration = products.select_one(".J1mWY div").text date = products.select_one(".P7xzyf span span").text data_video_panel.append({ "title" : title, "description" : description, "link" : link, "chanel" : chanel, "duration" : duration, "date" : date }) print(json.dumps(data_video_panel, indent=2, ensure_ascii=False)) scrape_google_videos(video_page=True, inline_videos=False) ``` ```json Inline video data: [ { "title": "A Thousand Years of European Castles", "platform": "YouTube", "chanel": "Best Documentary", "date": "Jan 25, 2022" }, { "title": "MOST BEAUTIFUL Castles on Earth", "platform": "YouTube", "chanel": "Top Fives", "date": "Feb 2, 2022" }, { "title": "Great Castles of Europe: Neuschwanstein (Part 1 of 3)", "platform": "YouTube", "chanel": "trakehnen", "date": "Sep 24, 2009" } ] ```
20,363,959
Hi I'm fairly new to c# and have been trying to access my list of cards from another class and get it to display a picture on form but all i really need is the way to instantiate or reference or whatever the list from my deck class. How would i go about my list of cards in a different class? ``` namespace aGameOf21 { //adds deck class to Ideck interface public class Deck : IDeck { //default deck call public Deck() { Reset(); } // creates list from the card class with get and set accessors public List<Card> Cards { get; set; } //resets the decks to unshuffled values default when calling class public void Reset() { // using a LINQ statement takes each enumerable from cards list and combines them Cards = Enumerable.Range(1, 4) .SelectMany(s => Enumerable.Range(1, 13) .Select(c => new Card() { Suit = (Suit)s, CardNumber = (CardNumber)c })) .ToList(); /* foreach(Card c in Cards) { Console.WriteLine("Number = {0}, Suit = {1}", c.CardNumber , c.Suit); }*/ } public void Shuffle() { Cards = Cards.OrderBy(c => Guid.NewGuid()) .ToList(); } public ICard TakeCard() { var card = Cards.FirstOrDefault(); Cards.Remove(card); return card; } public IEnumerable<ICard> TakeCards(int numberOfCards) { var cards = Cards.Take(numberOfCards); var takeCards = cards as Card[] ?? cards.ToArray(); Cards.RemoveAll(takeCards.Contains); return takeCards; } } } ```
2013/12/03
[ "https://Stackoverflow.com/questions/20363959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1840510/" ]
I'm not quite clear what you're asking, but if you create your deck using: ``` var deck = new Deck(); ``` the you can access your list of cards as: ``` var cardList = deck.Cards; ``` You can then pass this list wherever you want.
Per my comment about adding a variable and passing int he list via the constructor. ``` //adds deck class to Ideck interface public class Deck : IDeck { private List _list; //default deck call public Deck(List list) { _list = list; Reset(); } } ```
27,014
I read an article on CNN titled [My grocery bill will skyrocket if military stores close](http://money.cnn.com/2013/12/13/news/economy/military-grocery-stores/) about the possibility of cutting back funding to military grocery stores due to government spending cuts. I was then struck with the following question and I hope somebody here can clear it up. Is it the case that commercial entities (retail stores, restaurants, etc) in the U.S. are compensated by the government (say by tax breaks) if they offer military discounts?
2013/12/25
[ "https://money.stackexchange.com/questions/27014", "https://money.stackexchange.com", "https://money.stackexchange.com/users/-1/" ]
Company X located outside a military base offer discounts to military as a form of marketing. They want to encourage a group of potential customers to use their store/service. In some cases they are competing with subsidized store on the base. In other cases their only competition is other stores outside the base. The smart ones also understand the pay structure of military pay to make it easier for enlisted to stretch their money for the entire month. The government doesn't offer compensation to the business near bases. The businesses see their offer and discount as advertising expenses, and are figured into the prices they have to charge all customers. You will also see these types of discounts offered by some businesses in college towns. They are competing with the services on the campus and with other off-campus businesses. Some also allow the use of campus dollars to make it easier for the student to spend money.
This story is about *military* grocery stores - i.e.: grocery stores for military personnel on military bases. There are no discounts for military personnel in a *regular* grocery store. But they may have subsidised prices in grocery stores located *inside* a military installation, and these are those stores that the story is talking about.
27,014
I read an article on CNN titled [My grocery bill will skyrocket if military stores close](http://money.cnn.com/2013/12/13/news/economy/military-grocery-stores/) about the possibility of cutting back funding to military grocery stores due to government spending cuts. I was then struck with the following question and I hope somebody here can clear it up. Is it the case that commercial entities (retail stores, restaurants, etc) in the U.S. are compensated by the government (say by tax breaks) if they offer military discounts?
2013/12/25
[ "https://money.stackexchange.com/questions/27014", "https://money.stackexchange.com", "https://money.stackexchange.com/users/-1/" ]
Company X located outside a military base offer discounts to military as a form of marketing. They want to encourage a group of potential customers to use their store/service. In some cases they are competing with subsidized store on the base. In other cases their only competition is other stores outside the base. The smart ones also understand the pay structure of military pay to make it easier for enlisted to stretch their money for the entire month. The government doesn't offer compensation to the business near bases. The businesses see their offer and discount as advertising expenses, and are figured into the prices they have to charge all customers. You will also see these types of discounts offered by some businesses in college towns. They are competing with the services on the campus and with other off-campus businesses. Some also allow the use of campus dollars to make it easier for the student to spend money.
Nope, only base commissaries or BX/PX's are subsidized. The rest is just done for goodwill/marketing purposes.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
You can write VBS, JS (using cscript, which is built in with every Windows) to modify the MSI, the syntax is pretty much SQL like. [Here is a MSDN page that shows various examples.](http://msdn.microsoft.com/en-us/library/aa368562.aspx)
You can use perl script to modify the installer msi package. You can use [Win32 OLE](http://www.perl.com/pub/a/2005/04/21/win32ole.html) for this. Open the MSI using `Win32::OLE->new` API. Open the MSI database and execute the SQL queries to do the update. This perl script can be used in builds. This [link](http://cpansearch.perl.org/src/PMAREK/Win32-MSI-DB-1.06/DB.pm) might help you to write the required one.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
I just had to do this too - here is my VBScript file (in case it's useful to anyone)... ``` Dim msiInstaller Dim msiDatabase Dim msiView Dim msiRecord Dim pathToMsiFile Dim pathToIconFile If WScript.Arguments.Count <> 2 Then WScript.Echo "Usage:" & vbCrLf & " " & WScript.ScriptName & " <path-to-msi> <path-to-icon>" WScript.Quit End If Dim pathToMsi, pathToIcon pathToMsi = WScript.Arguments(0) pathToIcon = WScript.Arguments(1) Set msiInstaller = CreateObject("WindowsInstaller.Installer") Set msiRecord = msiInstaller.CreateRecord(1) msiRecord.SetStream 1, pathToIcon Set msiDatabase = msiInstaller.OpenDatabase(pathToMsi, 1) Set msiView = msiDatabase.OpenView("UPDATE Icon SET Data = ? WHERE Name <> ''") msiView.Execute msiRecord msiDatabase.Commit ``` This script replaces all shortcut icons in the MSI database with a single icon - if you need to be selective then you have some more work to do.
You can use perl script to modify the installer msi package. You can use [Win32 OLE](http://www.perl.com/pub/a/2005/04/21/win32ole.html) for this. Open the MSI using `Win32::OLE->new` API. Open the MSI database and execute the SQL queries to do the update. This perl script can be used in builds. This [link](http://cpansearch.perl.org/src/PMAREK/Win32-MSI-DB-1.06/DB.pm) might help you to write the required one.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
Possibly the easiest solution that I found for this was to create a new "Transform" inside of Orca, and then to apply the transform as a part of my post-build steps. 1) Open the MSI file using ORCA for editing. 2) Click on "New transform" 3) Make all of the applicable changes to your MSI tables using the Orca editor. 4) Click on "Generate transform", and save the file. 5) Edit your build events to execute msitran during the post-build step. like this... msitran -a (path to transform file) (path to MSI file) More information about MSITran.exe can be found at the following location... [MSITran](http://msdn.microsoft.com/en-us/library/aa370495%28VS.85%29.aspx) This will automatically apply your edits to the MSI file once your installer build has completed, eliminating the need for custom VBScript.
You can use perl script to modify the installer msi package. You can use [Win32 OLE](http://www.perl.com/pub/a/2005/04/21/win32ole.html) for this. Open the MSI using `Win32::OLE->new` API. Open the MSI database and execute the SQL queries to do the update. This perl script can be used in builds. This [link](http://cpansearch.perl.org/src/PMAREK/Win32-MSI-DB-1.06/DB.pm) might help you to write the required one.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
You can write VBS, JS (using cscript, which is built in with every Windows) to modify the MSI, the syntax is pretty much SQL like. [Here is a MSDN page that shows various examples.](http://msdn.microsoft.com/en-us/library/aa368562.aspx)
Since you're used to work with Orca, just save the modifications as a transform file using Orca and then applying it with 'msitran' in the post build event of your setup project. I'm using this in a setup project and it works just great.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
You can write VBS, JS (using cscript, which is built in with every Windows) to modify the MSI, the syntax is pretty much SQL like. [Here is a MSDN page that shows various examples.](http://msdn.microsoft.com/en-us/library/aa368562.aspx)
I just had to do this too - here is my VBScript file (in case it's useful to anyone)... ``` Dim msiInstaller Dim msiDatabase Dim msiView Dim msiRecord Dim pathToMsiFile Dim pathToIconFile If WScript.Arguments.Count <> 2 Then WScript.Echo "Usage:" & vbCrLf & " " & WScript.ScriptName & " <path-to-msi> <path-to-icon>" WScript.Quit End If Dim pathToMsi, pathToIcon pathToMsi = WScript.Arguments(0) pathToIcon = WScript.Arguments(1) Set msiInstaller = CreateObject("WindowsInstaller.Installer") Set msiRecord = msiInstaller.CreateRecord(1) msiRecord.SetStream 1, pathToIcon Set msiDatabase = msiInstaller.OpenDatabase(pathToMsi, 1) Set msiView = msiDatabase.OpenView("UPDATE Icon SET Data = ? WHERE Name <> ''") msiView.Execute msiRecord msiDatabase.Commit ``` This script replaces all shortcut icons in the MSI database with a single icon - if you need to be selective then you have some more work to do.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
I just had to do this too - here is my VBScript file (in case it's useful to anyone)... ``` Dim msiInstaller Dim msiDatabase Dim msiView Dim msiRecord Dim pathToMsiFile Dim pathToIconFile If WScript.Arguments.Count <> 2 Then WScript.Echo "Usage:" & vbCrLf & " " & WScript.ScriptName & " <path-to-msi> <path-to-icon>" WScript.Quit End If Dim pathToMsi, pathToIcon pathToMsi = WScript.Arguments(0) pathToIcon = WScript.Arguments(1) Set msiInstaller = CreateObject("WindowsInstaller.Installer") Set msiRecord = msiInstaller.CreateRecord(1) msiRecord.SetStream 1, pathToIcon Set msiDatabase = msiInstaller.OpenDatabase(pathToMsi, 1) Set msiView = msiDatabase.OpenView("UPDATE Icon SET Data = ? WHERE Name <> ''") msiView.Execute msiRecord msiDatabase.Commit ``` This script replaces all shortcut icons in the MSI database with a single icon - if you need to be selective then you have some more work to do.
Since you're used to work with Orca, just save the modifications as a transform file using Orca and then applying it with 'msitran' in the post build event of your setup project. I'm using this in a setup project and it works just great.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
Possibly the easiest solution that I found for this was to create a new "Transform" inside of Orca, and then to apply the transform as a part of my post-build steps. 1) Open the MSI file using ORCA for editing. 2) Click on "New transform" 3) Make all of the applicable changes to your MSI tables using the Orca editor. 4) Click on "Generate transform", and save the file. 5) Edit your build events to execute msitran during the post-build step. like this... msitran -a (path to transform file) (path to MSI file) More information about MSITran.exe can be found at the following location... [MSITran](http://msdn.microsoft.com/en-us/library/aa370495%28VS.85%29.aspx) This will automatically apply your edits to the MSI file once your installer build has completed, eliminating the need for custom VBScript.
Since you're used to work with Orca, just save the modifications as a transform file using Orca and then applying it with 'msitran' in the post build event of your setup project. I'm using this in a setup project and it works just great.
886,842
I'm using Visual Studio 2008 and have created a setup project for my application. The application has a high-resolution icon (for Vista). There's a bug in Visual Studio, and the installer creates a desktop shortcut with a low resolution icon. I logged this bug in Microsoft Connect (<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338258>) and finally got an answer, which is to use Orca to edit the msi file and replace the icon. That solutions works fine. Now I want to automate that process, so I can include it in my build script. Is there a way to do that?
2009/05/20
[ "https://Stackoverflow.com/questions/886842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106908/" ]
Possibly the easiest solution that I found for this was to create a new "Transform" inside of Orca, and then to apply the transform as a part of my post-build steps. 1) Open the MSI file using ORCA for editing. 2) Click on "New transform" 3) Make all of the applicable changes to your MSI tables using the Orca editor. 4) Click on "Generate transform", and save the file. 5) Edit your build events to execute msitran during the post-build step. like this... msitran -a (path to transform file) (path to MSI file) More information about MSITran.exe can be found at the following location... [MSITran](http://msdn.microsoft.com/en-us/library/aa370495%28VS.85%29.aspx) This will automatically apply your edits to the MSI file once your installer build has completed, eliminating the need for custom VBScript.
I just had to do this too - here is my VBScript file (in case it's useful to anyone)... ``` Dim msiInstaller Dim msiDatabase Dim msiView Dim msiRecord Dim pathToMsiFile Dim pathToIconFile If WScript.Arguments.Count <> 2 Then WScript.Echo "Usage:" & vbCrLf & " " & WScript.ScriptName & " <path-to-msi> <path-to-icon>" WScript.Quit End If Dim pathToMsi, pathToIcon pathToMsi = WScript.Arguments(0) pathToIcon = WScript.Arguments(1) Set msiInstaller = CreateObject("WindowsInstaller.Installer") Set msiRecord = msiInstaller.CreateRecord(1) msiRecord.SetStream 1, pathToIcon Set msiDatabase = msiInstaller.OpenDatabase(pathToMsi, 1) Set msiView = msiDatabase.OpenView("UPDATE Icon SET Data = ? WHERE Name <> ''") msiView.Execute msiRecord msiDatabase.Commit ``` This script replaces all shortcut icons in the MSI database with a single icon - if you need to be selective then you have some more work to do.
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I get the same error and I don´t know how to figure out this problem. It took me many hours to notice that I have a init.py at the same direcory as the manage.py from django. Before: ``` |-- myproject |-- __init__.py <--- |-- manage.py |-- myproject |-- ... |-- app1 |-- models.py |-- app2 |-- models.py ``` After: ``` |-- myproject |-- manage.py |-- myproject |-- ... |-- app1 |-- models.py |-- app2 |-- models.py ``` It is quite confused that you get this "doesn't declare an explicit app\_label" error. But deleting this **init** file solved my problem.
For PyCharm users: I had an error using not "clean" project structure. Was: ``` project_root_directory └── src ├── chat │   ├── migrations │   └── templates ├── django_channels └── templates ``` Now: ``` project_root_directory ├── chat │ ├── migrations │ └── templates │ └── chat ├── django_channels └── templates ``` Here is a lot of good solutions, but I think, first of all, you should clean your project structure or tune PyCharm Django settings before setting `DJANGO_SETTINGS_MODULE` variables and so on. Hope it'll help someone. Cheers.
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
In my case I was getting this error when trying to run `python manage.py runserver` when not connected to my project's virtual environment.
The issue is that: 1. You have made modifications to your models file, but not addedd them yet to the DB, but you are trying to run Python manage.py runserver. 2. Run Python manage.py makemigrations 3. Python manage.py migrate 4. Now Python manage.py runserver and all should be fine.
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
In my case, I was trying the same import in `manage.py shell`. The shell was messed up with the updated db. I mean, I forgot to restart my shell after updating the DB. To resolve the issue, I had to stop the shell by the following command: ```sh >>> exit() ``` then restart the shell by the following command: ``` $ python3 manage.py shell ``` Hope this will help somebody like me.
If you have got all the config right, it might just be an import mess. keep an eye on how you are importing the offending model. The following won't work `from .models import Business`. Use full import path instead: `from myapp.models import Business`
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I had exactly the same error when running tests with PyCharm. I've fixed it by explicitly setting `DJANGO_SETTINGS_MODULE` environment variable. If you're using PyCharm, just hit *Edit Configurations* button and choose *Environment Variables*. Set the variable to `your_project_name.settings` and that should fix the thing. It seems like this error occurs, because PyCharm runs tests with its own `manage.py`.
I got this error while trying to upgrade my [Django Rest Framework](http://www.django-rest-framework.org/) app to DRF 3.6.3 and Django 1.11.1. For anyone else in this situation, I found my solution [in a GitHub issue](https://github.com/encode/django-rest-framework/issues/3262#issuecomment-147541598), which was to unset the `UNAUTHENTICATED_USER` setting in the [DRF settings](http://www.django-rest-framework.org/api-guide/settings/): ``` # webapp/settings.py ... REST_FRAMEWORK = { ... 'UNAUTHENTICATED_USER': None ... } ```
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
Are you missing putting in your application name into the settings file? The `myAppNameConfig` is the default class generated at apps.py by the `.manage.py createapp myAppName` command. Where `myAppName` is the name of your app. settings.py ``` INSTALLED_APPS = [ 'myAppName.apps.myAppNameConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` This way, the settings file finds out what you want to call your application. You can change how it looks later in the apps.py file by adding the following code in myAppName/apps.py ``` class myAppNameConfig(AppConfig): name = 'myAppName' verbose_name = 'A Much Better Name' ```
If all else fails, and if you are seeing this error while trying to import in a PyCharm "Python console" (or "Django console"): **Try restarting the console.** This is pretty embarassing, but it took me a while before I realized I had forgotten to do that. Here's what happened: Added a fresh app, then added a minimal model, then tried to import the model in the Python/Django console (PyCharm pro 2019.2). This raised the `doesn't declare an explicit app_label` error, because I had not added the new app to `INSTALLED_APPS`. So, I added the app to `INSTALLED_APPS`, tried the import again, but still got the same error. Came here, read all the other answers, but nothing seemed to fit. Finally it hit me that I had not yet restarted the Python console after adding the new app to `INSTALLED_APPS`. Note: failing to restart the PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing `ImportError: Cannot import name ...`
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I got this error while trying to upgrade my [Django Rest Framework](http://www.django-rest-framework.org/) app to DRF 3.6.3 and Django 1.11.1. For anyone else in this situation, I found my solution [in a GitHub issue](https://github.com/encode/django-rest-framework/issues/3262#issuecomment-147541598), which was to unset the `UNAUTHENTICATED_USER` setting in the [DRF settings](http://www.django-rest-framework.org/api-guide/settings/): ``` # webapp/settings.py ... REST_FRAMEWORK = { ... 'UNAUTHENTICATED_USER': None ... } ```
in my case I was able to find a fix and by looking at the everyone else's code it may be the same issue.. I simply just had to add 'django.contrib.sites' to the list of installed apps in the settings.py file. hope this helps someone. this is my first contribution to the coding community
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I had exactly the same error when running tests with PyCharm. I've fixed it by explicitly setting `DJANGO_SETTINGS_MODULE` environment variable. If you're using PyCharm, just hit *Edit Configurations* button and choose *Environment Variables*. Set the variable to `your_project_name.settings` and that should fix the thing. It seems like this error occurs, because PyCharm runs tests with its own `manage.py`.
After keep on running into this issue and keep on coming back to this question I thought I'd share what my problem was. Everything that @Xeberdee is correct so follow that and see if that solves the issue, if not this was my issue: In my apps.py this is what I had: ``` class AlgoExplainedConfig(AppConfig): name = 'algo_explained' verbose_name = "Explain_Algo" .... ``` And all I did was I added the project name in front of my app name like this: ``` class AlgoExplainedConfig(AppConfig): name = '**algorithms_explained**.algo_explained' verbose_name = "Explain_Algo" ``` and that solved my problem and I was able to run the makemigrations and migrate command after that! good luck
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I had this error today trying to run Django tests because I was using the shorthand `from .models import *` syntax in one of my files. The issue was that I had a file structure like so: ``` apps/ myapp/ models/ __init__.py foo.py bar.py ``` and in `models/__init__.py` I was importing my models using the shorthand syntax: ``` from .foo import * from .bar import * ``` In my application I was importing models like so: ``` from myapp.models import Foo, Bar ``` This caused the `Django model doesn't declare an explicit app_label` when running `./manage.py test`. To fix the problem, I had to explicitly import from the full path in `models/__init__.py`: ``` from myapp.models.foo import * from myapp.models.bar import * ``` That took care of the error. H/t <https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a>
I ran into this error when I tried generating migrations for a single app which had existing malformed migrations due to a git merge. e.g. ``` manage.py makemigrations myapp ``` When I deleted it's migrations and then ran: ``` manage.py makemigrations ``` the error did not occur and the migrations generated successfully.
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I get the same error and I don´t know how to figure out this problem. It took me many hours to notice that I have a init.py at the same direcory as the manage.py from django. Before: ``` |-- myproject |-- __init__.py <--- |-- manage.py |-- myproject |-- ... |-- app1 |-- models.py |-- app2 |-- models.py ``` After: ``` |-- myproject |-- manage.py |-- myproject |-- ... |-- app1 |-- models.py |-- app2 |-- models.py ``` It is quite confused that you get this "doesn't declare an explicit app\_label" error. But deleting this **init** file solved my problem.
I got this error also today. The Message referenced to some specific app of **my apps** in **INSTALLED\_APPS**. But in fact it had nothing to do with this specific App. I used a new virtual Environment and forgot to install some Libraries, that i used in this project. After i installed the additional Libraries, it worked.
40,206,569
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: ``` Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label ``` There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: ``` INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` And my apps.py files look like this: ``` from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' ``` and ``` from django.apps import AppConfig class LibrarysyncConfig(AppConfig): name = 'LibrarySync' ```
2016/10/23
[ "https://Stackoverflow.com/questions/40206569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6025788/" ]
I just ran into this issue and figured out what was going wrong. Since no previous answer described the issue as it happened to me, I though I would post it for others: * the issue came from using `python migrate.py startapp myApp` from my project root folder, then move myApp to a child folder with `mv myApp myFolderWithApps/`. * I wrote myApp.models and ran `python migrate.py makemigrations`. All went well. * then I did the same with another app that was importing models from myApp. Kaboom! I ran into this error, while performing makemigrations. That was because I had to use `myFolderWithApps.myApp` to reference my app, but I had forgotten to update MyApp/apps.py. So I corrected myApp/apps.py, settings/INSTALLED\_APPS and my import path in my second app. * but then the error kept happening: the reason was that I had migrations trying to import the models from myApp with the wrong path. I tried to correct the migration file, but I went at the point where it was easier to reset the DB and delete the migrations to start from scratch. So to make a long story short: - the issue was initially coming from the wrong app name in apps.py of myApp, in settings and in the import path of my second app. - but it was not enough to correct the paths in these three places, as migrations had been created with imports referencing the wrong app name. Therefore, the same error kept happening while migrating (except this time from migrations). So... check your migrations, and good luck!
In my case, there was an issue with BASE\_DIR in settings.py This is the structure of the packages: ``` project_root_directory └── service_package └── db_package ├── my_django_package │ └── my_django_package │    ├── settings.py │    └── ... └── my_django_app ├── migrations ├── models.py └── ... ``` It worked when updated the settings.py with: ``` INSTALLED_APPS = [ 'some_django_stuff_here...', 'some_django_stuff_here....', ... 'service_package.db_package.my_django_app' ] ``` And BASE\_DIR pointing to the project root ``` BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent.parent ``` Came to this after running django in debug, with breakpoint in registry.py -> def get\_containing\_app\_config(self, object\_name)
52,071,501
Got a simple question I guess. I have like a form in HTML which has multiple selectors that can be selected. In these selectors I have data attributes which can be selected (only one). If clicked, the data-attr must be stored into a hiddenfield. My HTML: ```js function styleChoice() { var productHandler = $('.styleChoiceButton'); var setDataVal = $('#plantChoiceSelection'); productHandler.bind('click', function (e) { var productDataStyle = productHandler.data('style'); console.log('clicked'); console.log(productDataStyle); console.log(e); productHandler.removeClass("is-selected"); setDataVal.attr(productDataStyle); $(this).addClass("is-selected"); }); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-one"> <figure> <strong>Stijl 1</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-two"> <figure> <strong>Stijl 2</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-three"> <figure> <strong>Stijl 3</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-four"> <figure> <strong>Stijl 4</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> ``` As you mentioned, which options I clicked, the only data-id i've get it style-one. Appreciate your help, thanks!
2018/08/29
[ "https://Stackoverflow.com/questions/52071501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7167791/" ]
You can try something like this: ``` function styleChoice() { var productHandler = $('.styleChoiceButton'); var setDataVal = $('#plantChoiceSelection'); productHandler.bind('click', function (e) { var elem = $(this); var productDataStyle = elem.data('style'); console.log('clicked'); console.log(productDataStyle); productHandler.removeClass("is-selected"); setDataVal.attr('data-selected', productDataStyle); elem.addClass("is-selected"); }); } ```
You should create listener for **each** `.styleChoiceButton` ```js styleChoice(); function styleChoice() { var productHandler = $('.styleChoiceButton'); var setDataVal = $('#plantChoiceSelection'); productHandler.each(function() { $(this).bind('click', function (e) { var productDataStyle = $(this).data('style'); console.log('clicked'); console.log(productDataStyle); // console.log(e); productHandler.removeClass("is-selected"); setDataVal.attr(productDataStyle); $(this).addClass("is-selected"); }); }); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-one"> <figure> <strong>Stijl 1</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-two"> <figure> <strong>Stijl 2</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-three"> <figure> <strong>Stijl 3</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-four"> <figure> <strong>Stijl 4</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> ```
52,071,501
Got a simple question I guess. I have like a form in HTML which has multiple selectors that can be selected. In these selectors I have data attributes which can be selected (only one). If clicked, the data-attr must be stored into a hiddenfield. My HTML: ```js function styleChoice() { var productHandler = $('.styleChoiceButton'); var setDataVal = $('#plantChoiceSelection'); productHandler.bind('click', function (e) { var productDataStyle = productHandler.data('style'); console.log('clicked'); console.log(productDataStyle); console.log(e); productHandler.removeClass("is-selected"); setDataVal.attr(productDataStyle); $(this).addClass("is-selected"); }); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-one"> <figure> <strong>Stijl 1</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-two"> <figure> <strong>Stijl 2</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-three"> <figure> <strong>Stijl 3</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> <div class="column"> <button class="styleChoiceButton" type="button" data-style="style-four"> <figure> <strong>Stijl 4</strong> <img src="https://via.placeholder.com/600x400" width="600" height="400" alt="productafbeeldingen" /> </figure> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula nulla, consequat laoreet vulputate ac, dictum ac dui. Nunc placerat tincidunt sollicitudin. Integer at libero leo. Praesent enim dolor, rhoncus consequat sapien vitae, maximus bibendum nunc. In consectetur leo vehicula porta vehicula. </p> </article> </button> </div> ``` As you mentioned, which options I clicked, the only data-id i've get it style-one. Appreciate your help, thanks!
2018/08/29
[ "https://Stackoverflow.com/questions/52071501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7167791/" ]
You can try something like this: ``` function styleChoice() { var productHandler = $('.styleChoiceButton'); var setDataVal = $('#plantChoiceSelection'); productHandler.bind('click', function (e) { var elem = $(this); var productDataStyle = elem.data('style'); console.log('clicked'); console.log(productDataStyle); productHandler.removeClass("is-selected"); setDataVal.attr('data-selected', productDataStyle); elem.addClass("is-selected"); }); } ```
Ok, you should be able to do all this in simple JQuery: ``` $('.StyleChoiceButton').on('click', function(e) { if ($(this)[0].hasAttribute('data-style')) { myhiddenfield = this.attributes['data-style'].value; } }); ```
54,507,395
Assume that I have a big float numpy array: How to save this float numpy array to a binary file with less storage using numpy.save? ``` np.save(nucleosomenpyOutputFilePath,averageSignalArray) ```
2019/02/03
[ "https://Stackoverflow.com/questions/54507395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291993/" ]
A schema belongs to a user. You can list all available users from [the **sysusers** system catalog](https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.sqlr.doc/ids_sqr_077.htm) : ``` SELECT username FROM "informix".sysusers; ``` Since only `DBA`s and `Resource` privilieges allow a user to issue a [`CREATE SCHEMA` statement](https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_0483.htm), we could restrict the query like : ``` SELECT username FROM "informix".sysusers WHERE usertype IN ('D', 'R'); ``` --- Another solution is to list only users that actually have created tables ; for that, you can query [the **systables** system catalog](https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.sqlr.doc/ids_sqr_072.htm) and list distinct owners. ``` SELECT DISTINCT owner FROM FROM "informix".systables ``` As commented by @JonathanLeffler, a user could have been granted `RESOURCE` privileges and have created a table, and then be 'demoted' to `CONNECT` privileges. The user would still own the table. Hence the second solution is the most accurate.
Schemas are not commonly used in Informix databases and have very little trackability within a database. The CREATE SCHEMA notation is supported because it was part of SQL-89. The AUTHORIZATION clause is used to determine the (default) 'owner' of the objects created with the CREATE SCHEMA statement. There is nothing to stop a single user running the CREATE SCHEMA statement multiple times, either consecutively or at widely different times (in any given database within an Informix instance). ``` CREATE SCHEMA AUTHORIZATION "pokemon" CREATE TABLE gizmo (s SERIAL NOT NULL PRIMARY KEY, v VARCHAR(20) NOT NULL) CREATE TABLE widget(t SERIAL NOT NULL PRIMARY KEY, d DATETIME YEAR TO SECOND NOT NULL) ; CREATE SCHEMA AUTHORIZATION "pokemon" CREATE TABLE object (u SERIAL NOT NULL PRIMARY KEY, i INTEGER NOT NULL) CREATE TABLE "pikachu".complain (C SERIAL NOT NULL PRIMARY KEY, v VARCHAR(255) NOT NULL) ; ``` After the CREATE SCHEMA statement executes, there is no way of tracking that either pair of these tables were created together as part of the same schema; there's no way to know that `"pikachu".complain` was part of a CREATE SCHEMA statement executed on behalf of `"pokemon"`. There is no DROP SCHEMA statement that would necessitate such support.
63,228,428
I am getting error while writing this line of code: ```cs double h = model.WorkHours.Value>=0 ? model.WorkHours.Value : ""; ``` I want to check if the value is equal and greater than `0` then get that value or else get blank or null.
2020/08/03
[ "https://Stackoverflow.com/questions/63228428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12721544/" ]
What happens when the condition is `false`? This: ``` double h = ""; ``` A `string` value can't be set to a `double`. The default for a `double` would be a `0` instead: ``` double h = model.WorkHours.Value >= 0 ? model.WorkHours.Value : 0; ``` Or, as specifically as possible: ``` double h = model.WorkHours.Value >= 0 ? model.WorkHours.Value : 0.0d; ``` You could also rely on `default` if you like: ``` double h = model.WorkHours.Value >= 0 ? model.WorkHours.Value : default(double); ``` If you want the value to truly be *empty* then you might consider using a `double?` (shorthand for `Nullable<double>`): ``` double? h = model.WorkHours.Value >= 0 ? model.WorkHours.Value : new Nullable<double>(); ```
Because a double doesnt have `null` or blank string as an allowable value, if you really want the default value to be a `null` or blank string, you will need to do one of the following. Use an optional type along with an explicit type conversion: ``` double? h = model.WorkHours.Value >= 0 ? (double?) model.WorkHours.Value : null; ``` Use a string: ``` string h = model.WorkHours.Value >= 0 ? model.WorkHours.Value.ToString() : ""; ```
37,891,443
EDIT: I never figured this out - I refactored the code to be pretty much identical to a Boost sample, and still had the problem. If anyone else has this problem, yours may be the more common shared\_from\_this() being called when no shared\_ptr exists (or in the constructor). Otherwise, I recommend just rebuilding from the boost asio samples. I'm trying to do something that I think is pretty common, but I am having some issues. I'm using boost asio, and trying to create a TCP server. I accept connections with async\_accept, and I create shared pointers. I have a long lived object (like a connection manager), that inserts the shared\_ptr into a set. Here is a snippet: ``` std::shared_ptr<WebsocketClient> ptr = std::make_shared<WebsocketClient>(std::move(s)); directory.addPending(ptr); ptr->onConnect(std::bind(&Directory::addClient, &directory, std::placeholders::_1)); ptr->onDisconnect(std::bind(&Directory::removeClient, &directory, std::placeholders::_1)); ptr->onMessage(std::bind(&Directory::onMessage, &directory, std::placeholders::_1, std::placeholders::_2)); ptr->start(); ``` The Directory has `std::set<std::shared_ptr<WebsocketClient>> pendingClients;` The function for adding a client is: ``` void Directory::addPending(std::shared_ptr<WebsocketClient> ptr){ std::cout << "Added pending client: " << ptr->getName() << std::endl; pendingClients.insert(ptr); } ``` Now, when the WebsocketClient starts, it tries to create a shared\_ptr using shared\_from\_this() and then initiates an async\_read\_until ("\r\n\r\n"), and passes that shared\_ptr to the lambda to keep ownership. It crashes before actually invoking the asio function, on shared\_from\_this(). Call stack looks like this: ``` server.exe!WebsocketClient::start() server.exe!Server::acceptConnection::__l2::<lambda>(boost::system::error_code ec) server.exe!boost::asio::asio_handler_invoke<boost::asio::detail::binder1<void <lambda>(boost::system::error_code),boost::system::error_code> >(boost::asio::detail::binder1<void <lambda>(boost::system::error_code),boost::system::error_code> & function, ...) server.exe!boost::asio::detail::win_iocp_socket_accept_op<boost::asio::basic_socket<boost::asio::ip::tcp,boost::asio::stream_socket_service<boost::asio::ip::tcp> >,boost::asio::ip::tcp,void <lambda>(boost::system::error_code) ::do_complete(boost::asio::detail::win_iocp_io_service * owner, boost::asio::detail::win_iocp_operation * base, const boost::system::error_code & result_ec, unsigned __int64 __formal) Line 142 C++ server.exe!boost::asio::detail::win_iocp_io_service::do_one(bool ec, boost::system::error_code &) server.exe!boost::asio::detail::win_iocp_io_service::run(boost::system::error_code & ec) server.exe!Server::run() server.exe!main(int argc, char * * argv) ``` However, I get a bad\_weak\_ptr when I call shared\_from\_this. I thought that was thrown when no shared\_ptr owned this object, but when I call the addPending, I insert "ptr" into a set, so there should still be a reference to it. Any ideas? If you need more details please ask, and I'll provide them. This is my first post on StackOverflow, so let me know what I can improve.
2016/06/17
[ "https://Stackoverflow.com/questions/37891443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5515465/" ]
This is just a 'this' binding issue. Put a console.log inside of your mouseOver and mouseOut methods and you'll notice that your state isn't changing. There are many ways to bind the 'this' context in your class methods. I'll show you three ways to do it in this example (DO NOT do all three methods, just choose one). ``` import React from 'react'; import Eyecon from '../../static/eye.svg'; class Item extends React.Component { constructor(props) { super(props); this.displayName = 'Item'; // 1. bind your functions in the constructor. this.mouseOver = this.mouseOver.bind(this); this.mouseOut = this.mouseOut.bind(this); this.state = { hover: false }; } // 2. bind it with fat arrows. mouseOver = () => { this.setState({hover: true}); } mouseOut() { this.setState({hover: false}); } render() { const { item, i } = this.props; // 3. bind them in the render method (not recommended for performance reasons) return ( <div className="grid-box" onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)}> {this.state.hover ? (<img src={Eyecon}/>) : null} </div> ) } } export default Item; ``` Here's an explanation of different ways to bind your 'this' context in react using ES6 classes: <http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html>
Maybe it's because you have to bind `mouseOver` and `mouseOut` calls in order to use `this.setState` inside them. Replace: ``` <div className="grid-box" onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}> ``` with: ``` <div className="grid-box" onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)}> ```
37,891,443
EDIT: I never figured this out - I refactored the code to be pretty much identical to a Boost sample, and still had the problem. If anyone else has this problem, yours may be the more common shared\_from\_this() being called when no shared\_ptr exists (or in the constructor). Otherwise, I recommend just rebuilding from the boost asio samples. I'm trying to do something that I think is pretty common, but I am having some issues. I'm using boost asio, and trying to create a TCP server. I accept connections with async\_accept, and I create shared pointers. I have a long lived object (like a connection manager), that inserts the shared\_ptr into a set. Here is a snippet: ``` std::shared_ptr<WebsocketClient> ptr = std::make_shared<WebsocketClient>(std::move(s)); directory.addPending(ptr); ptr->onConnect(std::bind(&Directory::addClient, &directory, std::placeholders::_1)); ptr->onDisconnect(std::bind(&Directory::removeClient, &directory, std::placeholders::_1)); ptr->onMessage(std::bind(&Directory::onMessage, &directory, std::placeholders::_1, std::placeholders::_2)); ptr->start(); ``` The Directory has `std::set<std::shared_ptr<WebsocketClient>> pendingClients;` The function for adding a client is: ``` void Directory::addPending(std::shared_ptr<WebsocketClient> ptr){ std::cout << "Added pending client: " << ptr->getName() << std::endl; pendingClients.insert(ptr); } ``` Now, when the WebsocketClient starts, it tries to create a shared\_ptr using shared\_from\_this() and then initiates an async\_read\_until ("\r\n\r\n"), and passes that shared\_ptr to the lambda to keep ownership. It crashes before actually invoking the asio function, on shared\_from\_this(). Call stack looks like this: ``` server.exe!WebsocketClient::start() server.exe!Server::acceptConnection::__l2::<lambda>(boost::system::error_code ec) server.exe!boost::asio::asio_handler_invoke<boost::asio::detail::binder1<void <lambda>(boost::system::error_code),boost::system::error_code> >(boost::asio::detail::binder1<void <lambda>(boost::system::error_code),boost::system::error_code> & function, ...) server.exe!boost::asio::detail::win_iocp_socket_accept_op<boost::asio::basic_socket<boost::asio::ip::tcp,boost::asio::stream_socket_service<boost::asio::ip::tcp> >,boost::asio::ip::tcp,void <lambda>(boost::system::error_code) ::do_complete(boost::asio::detail::win_iocp_io_service * owner, boost::asio::detail::win_iocp_operation * base, const boost::system::error_code & result_ec, unsigned __int64 __formal) Line 142 C++ server.exe!boost::asio::detail::win_iocp_io_service::do_one(bool ec, boost::system::error_code &) server.exe!boost::asio::detail::win_iocp_io_service::run(boost::system::error_code & ec) server.exe!Server::run() server.exe!main(int argc, char * * argv) ``` However, I get a bad\_weak\_ptr when I call shared\_from\_this. I thought that was thrown when no shared\_ptr owned this object, but when I call the addPending, I insert "ptr" into a set, so there should still be a reference to it. Any ideas? If you need more details please ask, and I'll provide them. This is my first post on StackOverflow, so let me know what I can improve.
2016/06/17
[ "https://Stackoverflow.com/questions/37891443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5515465/" ]
This is just a 'this' binding issue. Put a console.log inside of your mouseOver and mouseOut methods and you'll notice that your state isn't changing. There are many ways to bind the 'this' context in your class methods. I'll show you three ways to do it in this example (DO NOT do all three methods, just choose one). ``` import React from 'react'; import Eyecon from '../../static/eye.svg'; class Item extends React.Component { constructor(props) { super(props); this.displayName = 'Item'; // 1. bind your functions in the constructor. this.mouseOver = this.mouseOver.bind(this); this.mouseOut = this.mouseOut.bind(this); this.state = { hover: false }; } // 2. bind it with fat arrows. mouseOver = () => { this.setState({hover: true}); } mouseOut() { this.setState({hover: false}); } render() { const { item, i } = this.props; // 3. bind them in the render method (not recommended for performance reasons) return ( <div className="grid-box" onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)}> {this.state.hover ? (<img src={Eyecon}/>) : null} </div> ) } } export default Item; ``` Here's an explanation of different ways to bind your 'this' context in react using ES6 classes: <http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html>
The other solutions suggested are perfectly valid, however you can solve this easily by just converting your functions to [**ES6 arrow functions**](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions). > > An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. > > > Like so: ``` mouseOver = () => { this.setState({hover: true}); } mouseOut = () => { this.setState({hover: false}); } ``` Simple.