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
5,388,194
Is there a Java Web Framework, with mvc, thrid-party integration APIs, libraries and tools? Something like Zend Framework for PHP?
2011/03/22
[ "https://Stackoverflow.com/questions/5388194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268912/" ]
Using Zend for a while, I found the transition to Spring fairly easy. Spring does come with more bells and whistles (Dependancy injection, AOP etc)
There are a lot of Java web Frameworks, here you have a list with lots of them: <http://java-source.net/open-source/web-frameworks> The most "famous" would be Struts, JSF or Spring mvc framework (not in that particular order).
5,388,194
Is there a Java Web Framework, with mvc, thrid-party integration APIs, libraries and tools? Something like Zend Framework for PHP?
2011/03/22
[ "https://Stackoverflow.com/questions/5388194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268912/" ]
[Play Framework](http://www.playframework.org/) is more light weight compared to Spring , JSF or Struts. More close to Zend in some sense. and has scala support :)
You also have [AppFuse](http://appfuse.org/display/APF/Home) > > **AppFuse** is an open source project and > application that uses open source > tools built on the Java platform to > help you develop Web applications > quickly and efficiently. It was > originally developed to eliminate the > ramp-up time found when building new > web applications for customers. At its > core, AppFuse is a project skeleton, > similar to the one that's created by > your IDE when you click through a > wizard to create a new web project. > > > AppFuse 2.x is a restructuring of > AppFuse 1.x to use Maven 2 and JDK 5 > and annotations. The major reasons we > use Maven 2 are: > > > > ``` > Dependency downloading > Easier maintenance (everything can be compiled at once) > Easier upgrading for end-users > > ``` > > If you'd like to help out or ask > questions about AppFuse 2.0, please do > so on the user mailing list. If you'd > like to use AppFuse 2.0, see the Demos > and Videos and use the QuickStart > Guide to get started. > > >
5,388,194
Is there a Java Web Framework, with mvc, thrid-party integration APIs, libraries and tools? Something like Zend Framework for PHP?
2011/03/22
[ "https://Stackoverflow.com/questions/5388194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268912/" ]
Using Zend for a while, I found the transition to Spring fairly easy. Spring does come with more bells and whistles (Dependancy injection, AOP etc)
[Play Framework](http://www.playframework.org/) is more light weight compared to Spring , JSF or Struts. More close to Zend in some sense. and has scala support :)
5,388,194
Is there a Java Web Framework, with mvc, thrid-party integration APIs, libraries and tools? Something like Zend Framework for PHP?
2011/03/22
[ "https://Stackoverflow.com/questions/5388194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268912/" ]
Using Zend for a while, I found the transition to Spring fairly easy. Spring does come with more bells and whistles (Dependancy injection, AOP etc)
You also have [AppFuse](http://appfuse.org/display/APF/Home) > > **AppFuse** is an open source project and > application that uses open source > tools built on the Java platform to > help you develop Web applications > quickly and efficiently. It was > originally developed to eliminate the > ramp-up time found when building new > web applications for customers. At its > core, AppFuse is a project skeleton, > similar to the one that's created by > your IDE when you click through a > wizard to create a new web project. > > > AppFuse 2.x is a restructuring of > AppFuse 1.x to use Maven 2 and JDK 5 > and annotations. The major reasons we > use Maven 2 are: > > > > ``` > Dependency downloading > Easier maintenance (everything can be compiled at once) > Easier upgrading for end-users > > ``` > > If you'd like to help out or ask > questions about AppFuse 2.0, please do > so on the user mailing list. If you'd > like to use AppFuse 2.0, see the Demos > and Videos and use the QuickStart > Guide to get started. > > >
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
After viewing your provided tutorial, I would like to suggest you the following: * First follow the standard renaming technique that you got in another post * Now if you have enough time and patience, then it'd be best to start over from the section `Installing Your First Dependency` If you don't do that, then you may follow the next steps, but I can't guarantee for success. * `Replace` all the occurrence of `CocoaPodsExample.xcworkspace` with `<NEW_PROJ_NAME>.xcworkspace` in the `Pods` folder and possible places * Close the Xcode project (if you had it open) and open `<NEW_PROJ_NAME>.xcworkspace` to continue and test if it worked * Now, switch to `ViewController.m` and replace `CocoaPodsExample` with `<NEW_PROJ_NAME>` if exists Thats it! The project should now build successfully.
I had this issue and used Wassif's answer, however it didn't work until I also selected the new executable (.app) file in Products > Scheme > Edit Scheme > Info Also I couldn't find "Installing Your First Dependency" on CocoaPods.
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
After viewing your provided tutorial, I would like to suggest you the following: * First follow the standard renaming technique that you got in another post * Now if you have enough time and patience, then it'd be best to start over from the section `Installing Your First Dependency` If you don't do that, then you may follow the next steps, but I can't guarantee for success. * `Replace` all the occurrence of `CocoaPodsExample.xcworkspace` with `<NEW_PROJ_NAME>.xcworkspace` in the `Pods` folder and possible places * Close the Xcode project (if you had it open) and open `<NEW_PROJ_NAME>.xcworkspace` to continue and test if it worked * Now, switch to `ViewController.m` and replace `CocoaPodsExample` with `<NEW_PROJ_NAME>` if exists Thats it! The project should now build successfully.
I removed all cocoapods from my project with this GEM <https://github.com/kylef/cocoapods-deintegrate> then renamed my app in standard way and after fixing this issue with tests: <https://stackoverflow.com/a/27558736/1237542> everything worked OK.
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
After viewing your provided tutorial, I would like to suggest you the following: * First follow the standard renaming technique that you got in another post * Now if you have enough time and patience, then it'd be best to start over from the section `Installing Your First Dependency` If you don't do that, then you may follow the next steps, but I can't guarantee for success. * `Replace` all the occurrence of `CocoaPodsExample.xcworkspace` with `<NEW_PROJ_NAME>.xcworkspace` in the `Pods` folder and possible places * Close the Xcode project (if you had it open) and open `<NEW_PROJ_NAME>.xcworkspace` to continue and test if it worked * Now, switch to `ViewController.m` and replace `CocoaPodsExample` with `<NEW_PROJ_NAME>` if exists Thats it! The project should now build successfully.
I have just written a [blog post](http://h4ckish.com/2015/01/22/renaming-your-cocoapods-ios-project/) on how to go about this. The most sure-fire procedure looks like: 1. remove CocoaPods 2. rename project 3. re-add CocoaPods to your project Consult the post for details.
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
After viewing your provided tutorial, I would like to suggest you the following: * First follow the standard renaming technique that you got in another post * Now if you have enough time and patience, then it'd be best to start over from the section `Installing Your First Dependency` If you don't do that, then you may follow the next steps, but I can't guarantee for success. * `Replace` all the occurrence of `CocoaPodsExample.xcworkspace` with `<NEW_PROJ_NAME>.xcworkspace` in the `Pods` folder and possible places * Close the Xcode project (if you had it open) and open `<NEW_PROJ_NAME>.xcworkspace` to continue and test if it worked * Now, switch to `ViewController.m` and replace `CocoaPodsExample` with `<NEW_PROJ_NAME>` if exists Thats it! The project should now build successfully.
I found the easy way to do it: 1. change inside podfile project name. 2. pod install 3. open generated file xcworkspace reload red files Done!
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
I removed all cocoapods from my project with this GEM <https://github.com/kylef/cocoapods-deintegrate> then renamed my app in standard way and after fixing this issue with tests: <https://stackoverflow.com/a/27558736/1237542> everything worked OK.
I had this issue and used Wassif's answer, however it didn't work until I also selected the new executable (.app) file in Products > Scheme > Edit Scheme > Info Also I couldn't find "Installing Your First Dependency" on CocoaPods.
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
I have just written a [blog post](http://h4ckish.com/2015/01/22/renaming-your-cocoapods-ios-project/) on how to go about this. The most sure-fire procedure looks like: 1. remove CocoaPods 2. rename project 3. re-add CocoaPods to your project Consult the post for details.
I had this issue and used Wassif's answer, however it didn't work until I also selected the new executable (.app) file in Products > Scheme > Edit Scheme > Info Also I couldn't find "Installing Your First Dependency" on CocoaPods.
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
I found the easy way to do it: 1. change inside podfile project name. 2. pod install 3. open generated file xcworkspace reload red files Done!
I had this issue and used Wassif's answer, however it didn't work until I also selected the new executable (.app) file in Products > Scheme > Edit Scheme > Info Also I couldn't find "Installing Your First Dependency" on CocoaPods.
21,916,516
I'm working on an AngularJS app that uses a custom directive. I'm also trying to use unit testing in my app. So, I'm trying to leverage Jasmine for that. Currently, My unit test is the problem. Currently, it looks like the following: **myDirective.spec.js** ``` describe('Directive: myDirective', function () { describe('Function: myProcedure', function () { it('should word', function ($rootScope, $compile) { var e = angular.element('<div><br /></div>'); console.log($compile); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` This test is throwing an exception. When the console.log line is ran, it prints: 'undefined'. The next line throws an error to Jasmine that says: 'TypeError: undefined is not a function'. Its like I'm not injecting the $compile service. However, I believe I'm doing so. My test runner looks like the following: ``` <html ng-app="testApp"> <head> <title></title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script> <script type="text/javascript" src="index.html.js"></script> <script type="text/javascript" src="directives/myDirective.js"></script> <script type="text/javascript" src="tests/unit/myDirective.spec.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" /> </head> <body> <a href="#" onclick="env.execute()">run tests</a> </body> </html> ``` Why cannot I not run this basic test? What am I doing wrong?
2014/02/20
[ "https://Stackoverflow.com/questions/21916516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3284007/" ]
First you must add angular mocks: ``` <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-mocks.js"> </script> ``` then load the modules and inject $compile/$rootScope in `beforeEach` blocks: ``` describe('Directive: myDirective', function () { var $compile; var $rootScope; beforeEach(module('testApp')); beforeEach(inject(function(_$compile_, _$rootScope_){ $compile = _$compile_; $rootScope = _$rootScope_; })); describe('Function: myProcedure', function () { it('should word', function () { var e = angular.element('<div><br /></div>'); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` Check unit testing docs: <http://docs.angularjs.org/guide/dev_guide.unit-testing#directives>
The it() function provided by jasmine won't do any injection for you, so you need to inject your angular components into your tests. Modify your test as follows: ``` describe('Directive: myDirective', function () { describe('Function: myProcedure', function () { it('should word', function () { inject(function ($rootScope, $compile) { var e = angular.element('<div><br /></div>'); //rest of code goes here }); ``` You also need a reference to the [angular.mocks library](http://docs.angularjs.org/api/ngMock).
21,916,516
I'm working on an AngularJS app that uses a custom directive. I'm also trying to use unit testing in my app. So, I'm trying to leverage Jasmine for that. Currently, My unit test is the problem. Currently, it looks like the following: **myDirective.spec.js** ``` describe('Directive: myDirective', function () { describe('Function: myProcedure', function () { it('should word', function ($rootScope, $compile) { var e = angular.element('<div><br /></div>'); console.log($compile); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` This test is throwing an exception. When the console.log line is ran, it prints: 'undefined'. The next line throws an error to Jasmine that says: 'TypeError: undefined is not a function'. Its like I'm not injecting the $compile service. However, I believe I'm doing so. My test runner looks like the following: ``` <html ng-app="testApp"> <head> <title></title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script> <script type="text/javascript" src="index.html.js"></script> <script type="text/javascript" src="directives/myDirective.js"></script> <script type="text/javascript" src="tests/unit/myDirective.spec.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" /> </head> <body> <a href="#" onclick="env.execute()">run tests</a> </body> </html> ``` Why cannot I not run this basic test? What am I doing wrong?
2014/02/20
[ "https://Stackoverflow.com/questions/21916516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3284007/" ]
First you must add angular mocks: ``` <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-mocks.js"> </script> ``` then load the modules and inject $compile/$rootScope in `beforeEach` blocks: ``` describe('Directive: myDirective', function () { var $compile; var $rootScope; beforeEach(module('testApp')); beforeEach(inject(function(_$compile_, _$rootScope_){ $compile = _$compile_; $rootScope = _$rootScope_; })); describe('Function: myProcedure', function () { it('should word', function () { var e = angular.element('<div><br /></div>'); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` Check unit testing docs: <http://docs.angularjs.org/guide/dev_guide.unit-testing#directives>
I have come across this problem just now and this is what made my day (in the very end of it actually).just add "module('ng');" along with module('yourAppModule'). It should work.
6,275,246
I have two tables, Subject and Content, where Content references Subject with foreign key. I want to display how many times each subject appears in Content table (0, if it does not appear). But the query below only gives me the rows with count > 0 and ignores the others: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id WHERE type = @type GROUP BY Subject.id; ``` I checked and tried to follow [this](https://stackoverflow.com/questions/3855678/mysql-include-zero-rows-when-using-count-with-group-by), [this](https://stackoverflow.com/questions/1478384/mysql-select-count-group-by-not-returning-rows-where-the-count-is-zero) and [this](https://stackoverflow.com/questions/743456/displaying-rows-with-count-0-with-mysql-group-by) post but for some reason the code above does not work. Any ideas? Edit: the type field is in the Content table and that was causing the the problem as "Will A" pointed out
2011/06/08
[ "https://Stackoverflow.com/questions/6275246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705972/" ]
Which table is `type` a column in? I'm supposing that it's Content - and by including the field in the WHERE clause, you're forcing the Content table on the right-hand side of the LEFT JOIN to have data in it (which means the LEFT JOIN is actually then just an INNER JOIN). Try: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id AND type = @type GROUP BY Subject.id; ```
Do an outer join instead. Replace the null with a 0. Replace non null with a 1. Instead of count, do a sum of this column. Hope this helps
6,275,246
I have two tables, Subject and Content, where Content references Subject with foreign key. I want to display how many times each subject appears in Content table (0, if it does not appear). But the query below only gives me the rows with count > 0 and ignores the others: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id WHERE type = @type GROUP BY Subject.id; ``` I checked and tried to follow [this](https://stackoverflow.com/questions/3855678/mysql-include-zero-rows-when-using-count-with-group-by), [this](https://stackoverflow.com/questions/1478384/mysql-select-count-group-by-not-returning-rows-where-the-count-is-zero) and [this](https://stackoverflow.com/questions/743456/displaying-rows-with-count-0-with-mysql-group-by) post but for some reason the code above does not work. Any ideas? Edit: the type field is in the Content table and that was causing the the problem as "Will A" pointed out
2011/06/08
[ "https://Stackoverflow.com/questions/6275246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705972/" ]
Which table does column `type` belong to? If `type` is in `subject`, your left join should work. So I assume that `type` is in `Content`. Then the problem is that your WHERE clause won't match the cases where there are no matching lines in `Content`. Use ``` WHERE (type = @type) OR (type IS NULL) ```
Do an outer join instead. Replace the null with a 0. Replace non null with a 1. Instead of count, do a sum of this column. Hope this helps
6,275,246
I have two tables, Subject and Content, where Content references Subject with foreign key. I want to display how many times each subject appears in Content table (0, if it does not appear). But the query below only gives me the rows with count > 0 and ignores the others: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id WHERE type = @type GROUP BY Subject.id; ``` I checked and tried to follow [this](https://stackoverflow.com/questions/3855678/mysql-include-zero-rows-when-using-count-with-group-by), [this](https://stackoverflow.com/questions/1478384/mysql-select-count-group-by-not-returning-rows-where-the-count-is-zero) and [this](https://stackoverflow.com/questions/743456/displaying-rows-with-count-0-with-mysql-group-by) post but for some reason the code above does not work. Any ideas? Edit: the type field is in the Content table and that was causing the the problem as "Will A" pointed out
2011/06/08
[ "https://Stackoverflow.com/questions/6275246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705972/" ]
Which table is `type` a column in? I'm supposing that it's Content - and by including the field in the WHERE clause, you're forcing the Content table on the right-hand side of the LEFT JOIN to have data in it (which means the LEFT JOIN is actually then just an INNER JOIN). Try: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id AND type = @type GROUP BY Subject.id; ```
Which table does column `type` belong to? If `type` is in `subject`, your left join should work. So I assume that `type` is in `Content`. Then the problem is that your WHERE clause won't match the cases where there are no matching lines in `Content`. Use ``` WHERE (type = @type) OR (type IS NULL) ```
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
You can copy queries to create tables or modify tables from the generated room database file. Just double tap shift and look for \_Impl. Your problem is related to `NON NULL` data types in your tables you need to specify these fields as `NON NULL` and handle `DEFAULT` values that need to be assigned during your Room Migration.
You dont need crate new table create an method like: ``` private static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `WordTable` ADD COLUMN ref STRING"); } }; ``` and call Database create method like: ``` Room.databaseBuilder(/*parameter want */).addMigrations(MIGRATION_1_2).allowMainThreadQueries().build(); ```
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
You can copy queries to create tables or modify tables from the generated room database file. Just double tap shift and look for \_Impl. Your problem is related to `NON NULL` data types in your tables you need to specify these fields as `NON NULL` and handle `DEFAULT` values that need to be assigned during your Room Migration.
You can use the `ALTER TABLE` Query and simply provide migration ``` private static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `table_name` ADD COLUMN `column_name` {type} DEFAULT {defaultValue} NOT NULL"); } }; ``` When you try to Alter Table, then you should provide default values to all other records that are already present in the table.
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
You can copy queries to create tables or modify tables from the generated room database file. Just double tap shift and look for \_Impl. Your problem is related to `NON NULL` data types in your tables you need to specify these fields as `NON NULL` and handle `DEFAULT` values that need to be assigned during your Room Migration.
The differences between Expected and Found in your error message are the not null constraints in your table. If you want the rows to be nullable, define their variables as objects without default values and make a constructor that defines the required rows. Do not instantiate row values at the same time as you instantiate the variables! If you want the rows to never accept Null, add NOT NULL to the end of the rows in your SQLite query, and you don't have to change your model class.
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
You can use the `ALTER TABLE` Query and simply provide migration ``` private static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `table_name` ADD COLUMN `column_name` {type} DEFAULT {defaultValue} NOT NULL"); } }; ``` When you try to Alter Table, then you should provide default values to all other records that are already present in the table.
You dont need crate new table create an method like: ``` private static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `WordTable` ADD COLUMN ref STRING"); } }; ``` and call Database create method like: ``` Room.databaseBuilder(/*parameter want */).addMigrations(MIGRATION_1_2).allowMainThreadQueries().build(); ```
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
The differences between Expected and Found in your error message are the not null constraints in your table. If you want the rows to be nullable, define their variables as objects without default values and make a constructor that defines the required rows. Do not instantiate row values at the same time as you instantiate the variables! If you want the rows to never accept Null, add NOT NULL to the end of the rows in your SQLite query, and you don't have to change your model class.
You dont need crate new table create an method like: ``` private static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `WordTable` ADD COLUMN ref STRING"); } }; ``` and call Database create method like: ``` Room.databaseBuilder(/*parameter want */).addMigrations(MIGRATION_1_2).allowMainThreadQueries().build(); ```
3,472
I am working on [this code](https://github.com/nfmcclure/tensorflow_cookbook/blob/master/09_Recurrent_Neural_Networks/02_Implementing_RNN_for_Spam_Prediction/02_implementing_rnn.py) for spam detection using recurrent neural networks. Question 1. I am wondering whether this field (using RNNs for email spam detection) worths more researches or it is a closed research field. Question 2. What is the oldest published paper in this field? Quesiton 3. What are the pros and cons of using RNNs for email spam detection over other classification methods?
2017/06/10
[ "https://ai.stackexchange.com/questions/3472", "https://ai.stackexchange.com", "https://ai.stackexchange.com/users/6050/" ]
There's a strong sentiment towards the idea that medical diagnosis is largely [Abductive Reasoning](https://en.wikipedia.org/wiki/Abductive_reasoning). See [this presentation](https://blogs.kent.ac.uk/jonw/files/2015/04/Aliseda2012.pdf) for additional details. One approach to automated abductive reasoning is [parsimonious covering theory](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2244953/). If you want a relatively in-depth look at all of this, check out the book [Abductive Inference Models for Diagnostic Problem-Solving](http://rads.stackoverflow.com/amzn/click/0387973435) . Expert systems have also been shown to work very well for medical diagnosis. As far back as the 1970's, systems like [MYCIN](https://en.wikipedia.org/wiki/Mycin) could beat human experts in terms of diagnosis and treatment plans. From what I can tell, there doesn't seem to be any reason in principle to think that AI/ML can't be used across the board for medical diagnosis, mental health or otherwise.
You may infer some mental problems using text processing. Any text written by an individual contains a lot of clues about their mental state, probably including any health problems. However, I believe pursuing this would prove to be difficult due to lack of ground truth. Not many people makes it public that they have mental problems and without a reliable database it is quite difficult to make research on the field.
3,472
I am working on [this code](https://github.com/nfmcclure/tensorflow_cookbook/blob/master/09_Recurrent_Neural_Networks/02_Implementing_RNN_for_Spam_Prediction/02_implementing_rnn.py) for spam detection using recurrent neural networks. Question 1. I am wondering whether this field (using RNNs for email spam detection) worths more researches or it is a closed research field. Question 2. What is the oldest published paper in this field? Quesiton 3. What are the pros and cons of using RNNs for email spam detection over other classification methods?
2017/06/10
[ "https://ai.stackexchange.com/questions/3472", "https://ai.stackexchange.com", "https://ai.stackexchange.com/users/6050/" ]
There's a strong sentiment towards the idea that medical diagnosis is largely [Abductive Reasoning](https://en.wikipedia.org/wiki/Abductive_reasoning). See [this presentation](https://blogs.kent.ac.uk/jonw/files/2015/04/Aliseda2012.pdf) for additional details. One approach to automated abductive reasoning is [parsimonious covering theory](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2244953/). If you want a relatively in-depth look at all of this, check out the book [Abductive Inference Models for Diagnostic Problem-Solving](http://rads.stackoverflow.com/amzn/click/0387973435) . Expert systems have also been shown to work very well for medical diagnosis. As far back as the 1970's, systems like [MYCIN](https://en.wikipedia.org/wiki/Mycin) could beat human experts in terms of diagnosis and treatment plans. From what I can tell, there doesn't seem to be any reason in principle to think that AI/ML can't be used across the board for medical diagnosis, mental health or otherwise.
It's already being done, and apparently with very good results. See: [Predicting Risk of Suicide Attempts Over Time Through Machine Learning](http://journals.sagepub.com/doi/abs/10.1177/2167702617691560?journalCode=cpxa&), Walsh, Ribiero, Franklin Here is the abstract from the paper: > > Traditional approaches to the prediction of suicide attempts have limited the accuracy and scale of risk detection for these dangerous behaviors. We sought to overcome these limitations by applying machine learning to electronic health records within a large medical database. Participants were 5,167 adult patients with a claim code for self-injury (i.e., ICD-9, E95x); expert review of records determined that 3,250 patients made a suicide attempt (i.e., cases), and 1,917 patients engaged in self-injury that was nonsuicidal, accidental, or nonverifiable (i.e., controls). We developed machine learning algorithms that accurately predicted future suicide attempts (AUC = 0.84, precision = 0.79, recall = 0.95, Brier score = 0.14). Moreover, accuracy improved from 720 days to 7 days before the suicide attempt, and predictor importance shifted across time. These findings represent a step toward accurate and scalable risk detection and provide insight into how suicide attempt risk shifts over time. > > > This has gotten national press attention quite recently. Here are a couple of prior articles on the result and endeavor: [Artificial Intelligence is Learning to Predict and Prevent Suicide](https://www.wired.com/2017/03/artificial-intelligence-learning-predict-prevent-suicide/) (Wired) [Artificial intelligence can now predict suicide with remarkable accuracy](https://qz.com/1001968/artificial-intelligence-can-now-predict-suicide-with-remarkable-accuracy/) (Quartz) Is strongly suspect ML can be used in an array of application related to human mental health. For instance, it is entirely possible a app would be able to discern the mood swings in people with bipolar disorder based on activity or lack thereof.
3,472
I am working on [this code](https://github.com/nfmcclure/tensorflow_cookbook/blob/master/09_Recurrent_Neural_Networks/02_Implementing_RNN_for_Spam_Prediction/02_implementing_rnn.py) for spam detection using recurrent neural networks. Question 1. I am wondering whether this field (using RNNs for email spam detection) worths more researches or it is a closed research field. Question 2. What is the oldest published paper in this field? Quesiton 3. What are the pros and cons of using RNNs for email spam detection over other classification methods?
2017/06/10
[ "https://ai.stackexchange.com/questions/3472", "https://ai.stackexchange.com", "https://ai.stackexchange.com/users/6050/" ]
It's already being done, and apparently with very good results. See: [Predicting Risk of Suicide Attempts Over Time Through Machine Learning](http://journals.sagepub.com/doi/abs/10.1177/2167702617691560?journalCode=cpxa&), Walsh, Ribiero, Franklin Here is the abstract from the paper: > > Traditional approaches to the prediction of suicide attempts have limited the accuracy and scale of risk detection for these dangerous behaviors. We sought to overcome these limitations by applying machine learning to electronic health records within a large medical database. Participants were 5,167 adult patients with a claim code for self-injury (i.e., ICD-9, E95x); expert review of records determined that 3,250 patients made a suicide attempt (i.e., cases), and 1,917 patients engaged in self-injury that was nonsuicidal, accidental, or nonverifiable (i.e., controls). We developed machine learning algorithms that accurately predicted future suicide attempts (AUC = 0.84, precision = 0.79, recall = 0.95, Brier score = 0.14). Moreover, accuracy improved from 720 days to 7 days before the suicide attempt, and predictor importance shifted across time. These findings represent a step toward accurate and scalable risk detection and provide insight into how suicide attempt risk shifts over time. > > > This has gotten national press attention quite recently. Here are a couple of prior articles on the result and endeavor: [Artificial Intelligence is Learning to Predict and Prevent Suicide](https://www.wired.com/2017/03/artificial-intelligence-learning-predict-prevent-suicide/) (Wired) [Artificial intelligence can now predict suicide with remarkable accuracy](https://qz.com/1001968/artificial-intelligence-can-now-predict-suicide-with-remarkable-accuracy/) (Quartz) Is strongly suspect ML can be used in an array of application related to human mental health. For instance, it is entirely possible a app would be able to discern the mood swings in people with bipolar disorder based on activity or lack thereof.
You may infer some mental problems using text processing. Any text written by an individual contains a lot of clues about their mental state, probably including any health problems. However, I believe pursuing this would prove to be difficult due to lack of ground truth. Not many people makes it public that they have mental problems and without a reliable database it is quite difficult to make research on the field.
33,170,820
I have x86 C++ application which using ImageMagic++ library. I also have machine with CentOS 7 x86\_64. I need to build my application on this machine. I have installed i686 ImageMagick library: ``` [dvoryankin@testsuitel]$ yum list installed | grep Magick ImageMagick.i686 6.7.8.9-10.el7 @base ImageMagick-c++.i686 6.7.8.9-10.el7 @base ImageMagick-c++-devel.i686 6.7.8.9-10.el7 @base ImageMagick-devel.i686 6.7.8.9-10.el7 @base ``` When I try to build my application I have an error: ``` /usr/include/ImageMagick/magick/magick-config.h:9:31: fatal error: magick-config-64.h: No such file or directory #include "magick-config-64.h" ``` It's happened becuase file */usr/include/ImageMagick/magick/magick-config.h* use macro definition `__WORDSIZE` to determine which file must be included *magick-config-64.h* or *magick-config-32.h*. On my machine with CentOS 7 x86\_64 this macro is equal 64 and ImageMagick try to include *magick-config-64.h* but i686 library doesn't have this, only *magick-config-32.h*. How I can build x86 application with x86 ImageMagick library on CentOS 7 x86\_64 machine without change any library files?
2015/10/16
[ "https://Stackoverflow.com/questions/33170820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3844730/" ]
I added this : ``` // Add timeZone Date.prototype.addTimeZone = function () { if(this.getTimezoneOffset() > 0){ this.setMinutes(this.getTimezoneOffset()); } return this; }; ``` And this on my controller/model : ``` new Date(myDate).addTimeZone(); ``` **To resume :** **extend-date-prototype.js** ``` // Add timeZone Date.prototype.addTimeZone = function () { if(this.getTimezoneOffset() > 0){ this.setMinutes(this.getTimezoneOffset()); } return this; }; // Remove TimeZone Date.prototype.toJSON = function(){ return moment(this).format('YYYY-MM-DD') + 'T00:00:00.000Z'; }; ``` **view.html** ``` <p ng-bind="(myDate | date:'dd/MM/yyyy')"></p> ``` **controller.js** ``` new Date(myDate).addTimeZone(); ``` I use [moment.js](http://momentjs.com/)
You can use [`getTimezoneOffset`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset) to get the offset of the client, then simple math ``` var dateToTranslate = new Date("2015-10-16T00:00:00.000Z"); var timezoneOffset = dateToTranslate.getTimezoneOffset() * 60000; var newDate = new Date(+dateToTranslate+timezoneOffset); // Fri Oct 16 2015 00:00:00 GMT+0200 (CEST) in my browser ```
57,927,197
I have a dictionary like below. ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} ``` I want to grab key names (where the value of the key is either match or match2) under heading "match" and unmatch ones under "not match" heading. ``` match key1 key2 not match key3 key4 ``` I tried the below code but it doesn't return anything: ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} print(*[k for k in d if 'match' in d[k] or 'match2' in d[k]], sep='\n') ---only prints the matched values ```
2019/09/13
[ "https://Stackoverflow.com/questions/57927197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8340881/" ]
You can do a list comprehension to get the match using `any` and membership check and non-match using set difference: ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} to_look = {'match', 'match2'} match = [k for k, v in d.items() if any(x in to_look for x in v)] not_match = set(d).difference(match) print('match') print(*match, sep='\n') print('\nnot match') print(*not_match, sep='\n') ``` **Output**: ``` match key1 key2 not match key3 key4 ```
You can iterate through the dict items and test if `match` or `match2` is in any of the keys of the sub-dicts: ``` print(*(k for k, s in d.items() if any(w in s for w in ('match', 'match2'))), sep='\n') ``` This outputs: ``` key1 key2 ``` Similarly, you can get the non-matching keys by testing if both `match1` and `match2` are not in any of the keys of the sub-dicts: ``` print(*(k for k, s in d.items() if all(w not in s for w in ('match', 'match2'))), sep='\n') ``` This outputs: ``` key3 key4 ```
22,184
Assuming that there are no known complete graph invariants in the spirit of [Harrsion's question](https://mathoverflow.net/questions/11631/complete-graph-invariants) that do not depend on any labelling (see [graph property](http://en.wikipedia.org/wiki/Graph_invariant) at Wikipedia), I wonder if there are graph invariants that are * almost complete, i.e. discriminating almost all finite graphs up to isomorphism * almost complete in a weaker sense, i.e. discriminating all finite graphs except for a small, but finite fraction (the smaller the fraction the greater the invariant's discriminating power) * probably complete, i.e. not proven to be incomplete yet (e.g. by counterexamples) Can anyone provide examples or references?
2010/04/22
[ "https://mathoverflow.net/questions/22184", "https://mathoverflow.net", "https://mathoverflow.net/users/2672/" ]
I'm not sure I understand the question well enough to know whether this is a reasonable answer. But a standard observation concerning the graph isomorphism problem is that there is an approach that feels as though it almost works: work out the eigenvalues and eigenvectors of the adjacency matrix. There is a small technical problem that you can't do this exactly, and a more fundamental problem that if you have eigenvalues of multiplicity greater than 1 then you don't distinguish all graphs. But I would guess that almost all graphs have adjacency matrices with distinct eigenvalues. Can anyone confirm this? And if that is the case, does it answer your question?
Though painfully slow to compute, I've yet to find a counterexample to the first invariant proposed in [this](http://arxiv.org/abs/math/0503316) paper by Mehendale: a vector of integers counting, for each n, the number of labeled subgraphs of G which are trees on n vertices. Update: I've since discovered several counterexamples, perhaps the simplest being S3 U P2 U P2 and P4 U P3 U P1 both of which yield the signature (8,5,3,1)
16,454,723
How to Make a Game Like Cut the Rope using vrope class ??? my game is on cocos2d for iphone >> cut the rope
2013/05/09
[ "https://Stackoverflow.com/questions/16454723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2372875/" ]
Using **NSURLConnection** ,Try this ``` // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [[NSMutableData data] retain]; } else { // Inform the user that the connection failed. } ``` For more info on NSURLConnection Refer this :[URL Loading System Programming Guide](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html) **EDIT** Here `recievedData` is the instance variable of type `NSMutableData` ``` -(void)downloadWithNsurlconnection { NSURL *url = [NSURL URLWithString:currentURL]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; receivedData = [[NSMutableData alloc] initWithLength:0]; NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; } - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [receivedData setLength:0]; } - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]]; NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [receivedData writeToFile:pdfPath atomically:YES]; } ```
Without using `NSURLConnection` you can easily download files, then no need to overhead delegate calls. Simply try this. ``` NSString *url = @"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"; NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentdirectory = [path objectAtIndex:0]; NSString *dataPath = [documentdirectory stringByAppendingPathComponent:@"Pictures"]; NSString *localFileURL = [NSString stringWithFormat:@"%@/%@",dataPath,[url lastPathComponent]]; if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; if([data writeToFile:localFileURL atomically:YES]) { NSLog(@"Downloaded File"); } ```
16,454,723
How to Make a Game Like Cut the Rope using vrope class ??? my game is on cocos2d for iphone >> cut the rope
2013/05/09
[ "https://Stackoverflow.com/questions/16454723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2372875/" ]
Using **NSURLConnection** ,Try this ``` // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [[NSMutableData data] retain]; } else { // Inform the user that the connection failed. } ``` For more info on NSURLConnection Refer this :[URL Loading System Programming Guide](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html) **EDIT** Here `recievedData` is the instance variable of type `NSMutableData` ``` -(void)downloadWithNsurlconnection { NSURL *url = [NSURL URLWithString:currentURL]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; receivedData = [[NSMutableData alloc] initWithLength:0]; NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; } - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [receivedData setLength:0]; } - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]]; NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [receivedData writeToFile:pdfPath atomically:YES]; } ```
It would be good to do it asynchronously with NSURLConnection with blocks. ``` - (NSString *)documentsDirectoryPath{ NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return directories[0]; } - (void)downloadImage{ NSString *urlPath = @"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg"; NSURL *url = [NSURL URLWithString:urlPath]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData *responseData, NSError *error) { if (responseData) { NSString *imageName = [urlPath lastPathComponent]; NSString *imagePath = [[self documentsDirectoryPath]stringByAppendingPathComponent:imageName]; [responseData writeToFile:imagePath atomically:YES]; } }]; } ```
74,556,541
i am not experienced working with docker and docker-compose, but atleast i know how to get a container running, below is my compose file of a simple react app boiler plate. my intention was to assign an IP to it so that i can ping it from the external network, and also to access it without any port mapping to the host ``` version: "3.9" services: front-web: build: context: . dockerfile: Dockerfile args: buildno: 1.0.0 container_name: web-front domainname: fontend dns: 8.8.8.8 network_mode: "host" hostname: alpha restart: unless-stopped stop_grace_period: 1m expose: - 4000 tty: true pid: host stdin_open: true ports: - target: 4000 published: 4000 protocol: tcp mode: host networks: web-net: ipv4_address: 192.168.1.195 volumes: - web-front:/app/data networks: web-net: name: web-net driver: bridge driver_opts: enable_ipv4: 1 enable_ipv6: 1 ipam: driver: default config: - subnet: 192.168.1.1/24 ip_range: 192.168.1.195/24 gateway: 192.168.1.195/24 volumes: web-front: ``` the docker file of the app is below ``` FROM node:alpine3.16 # RUN addgroup app && adduser -SG app app # USER app WORKDIR /app RUN mkdir data EXPOSE 4000 COPY package* . RUN npm install COPY . . CMD [ "npm", "start" ] ``` ignore the "adduser" although it also failed to workout. whenever i run docker-compose up, i get an error saying: ``` Attaching to web-front Error response from daemon: failed to add interface vethcf21a7d to sandbox: error setting interface "vethcf21a7d" IP to 192.168.1.195/24: cannot program address 192.168.1.195/24 in sandbox interface because it conflicts with existing route {Ifindex: 31 Dst: 192.168.1.0/24 Src: 192.168.1.1 Gw: <nil> Flags: [] Table: 254} ``` i am not sure how to go about this, kindly assist I tried changing the driver part in the Networks section from brigde to macvlan, the build would pass but again i could not ping the the container with its ip. adding external:true, makes the whole thing fail
2022/11/24
[ "https://Stackoverflow.com/questions/74556541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569584/" ]
Here is a one liner that will do the trick using `gsub()` ``` gsub(".*def.*(\\d+)\\)%ile.*%ile", "\\1", x, perl = TRUE) ``` Here's an approach that will work with any number of "%ile"s. Based on `str_split()` ``` x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile" x %>% str_split("def", simplify = TRUE) %>% subset(TRUE, 2) %>% str_split("%ile", simplify = TRUE) %>% subset(TRUE, 1) %>% str_replace(".*(\\d+)\\)$", "\\1") ```
``` sub(".*?def.*?(\\d)\\)%ile.*", "\\1", x) [1] "4" ```
74,556,541
i am not experienced working with docker and docker-compose, but atleast i know how to get a container running, below is my compose file of a simple react app boiler plate. my intention was to assign an IP to it so that i can ping it from the external network, and also to access it without any port mapping to the host ``` version: "3.9" services: front-web: build: context: . dockerfile: Dockerfile args: buildno: 1.0.0 container_name: web-front domainname: fontend dns: 8.8.8.8 network_mode: "host" hostname: alpha restart: unless-stopped stop_grace_period: 1m expose: - 4000 tty: true pid: host stdin_open: true ports: - target: 4000 published: 4000 protocol: tcp mode: host networks: web-net: ipv4_address: 192.168.1.195 volumes: - web-front:/app/data networks: web-net: name: web-net driver: bridge driver_opts: enable_ipv4: 1 enable_ipv6: 1 ipam: driver: default config: - subnet: 192.168.1.1/24 ip_range: 192.168.1.195/24 gateway: 192.168.1.195/24 volumes: web-front: ``` the docker file of the app is below ``` FROM node:alpine3.16 # RUN addgroup app && adduser -SG app app # USER app WORKDIR /app RUN mkdir data EXPOSE 4000 COPY package* . RUN npm install COPY . . CMD [ "npm", "start" ] ``` ignore the "adduser" although it also failed to workout. whenever i run docker-compose up, i get an error saying: ``` Attaching to web-front Error response from daemon: failed to add interface vethcf21a7d to sandbox: error setting interface "vethcf21a7d" IP to 192.168.1.195/24: cannot program address 192.168.1.195/24 in sandbox interface because it conflicts with existing route {Ifindex: 31 Dst: 192.168.1.0/24 Src: 192.168.1.1 Gw: <nil> Flags: [] Table: 254} ``` i am not sure how to go about this, kindly assist I tried changing the driver part in the Networks section from brigde to macvlan, the build would pass but again i could not ping the the container with its ip. adding external:true, makes the whole thing fail
2022/11/24
[ "https://Stackoverflow.com/questions/74556541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569584/" ]
Here is a one liner that will do the trick using `gsub()` ``` gsub(".*def.*(\\d+)\\)%ile.*%ile", "\\1", x, perl = TRUE) ``` Here's an approach that will work with any number of "%ile"s. Based on `str_split()` ``` x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile" x %>% str_split("def", simplify = TRUE) %>% subset(TRUE, 2) %>% str_split("%ile", simplify = TRUE) %>% subset(TRUE, 1) %>% str_replace(".*(\\d+)\\)$", "\\1") ```
You can use ```r x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile" library(stringr) result <- str_match(x, "\\bdef(?:\\((\\d+)\\))+%ile") result[,2] ``` See the [R demo online](https://ideone.com/lFnbgg) and the [regex demo](https://regex101.com/r/YBxCtZ/1). *Details*: * `\b` - word boundary * `def` - a `def` string * `(?:\((\d+)\))+` - zero or more occurrences of `(` + one or more digits (captured into Group 1) + `)` and the last one captured is saved in Group 1 * `%ile` - an `%ile` string.
74,556,541
i am not experienced working with docker and docker-compose, but atleast i know how to get a container running, below is my compose file of a simple react app boiler plate. my intention was to assign an IP to it so that i can ping it from the external network, and also to access it without any port mapping to the host ``` version: "3.9" services: front-web: build: context: . dockerfile: Dockerfile args: buildno: 1.0.0 container_name: web-front domainname: fontend dns: 8.8.8.8 network_mode: "host" hostname: alpha restart: unless-stopped stop_grace_period: 1m expose: - 4000 tty: true pid: host stdin_open: true ports: - target: 4000 published: 4000 protocol: tcp mode: host networks: web-net: ipv4_address: 192.168.1.195 volumes: - web-front:/app/data networks: web-net: name: web-net driver: bridge driver_opts: enable_ipv4: 1 enable_ipv6: 1 ipam: driver: default config: - subnet: 192.168.1.1/24 ip_range: 192.168.1.195/24 gateway: 192.168.1.195/24 volumes: web-front: ``` the docker file of the app is below ``` FROM node:alpine3.16 # RUN addgroup app && adduser -SG app app # USER app WORKDIR /app RUN mkdir data EXPOSE 4000 COPY package* . RUN npm install COPY . . CMD [ "npm", "start" ] ``` ignore the "adduser" although it also failed to workout. whenever i run docker-compose up, i get an error saying: ``` Attaching to web-front Error response from daemon: failed to add interface vethcf21a7d to sandbox: error setting interface "vethcf21a7d" IP to 192.168.1.195/24: cannot program address 192.168.1.195/24 in sandbox interface because it conflicts with existing route {Ifindex: 31 Dst: 192.168.1.0/24 Src: 192.168.1.1 Gw: <nil> Flags: [] Table: 254} ``` i am not sure how to go about this, kindly assist I tried changing the driver part in the Networks section from brigde to macvlan, the build would pass but again i could not ping the the container with its ip. adding external:true, makes the whole thing fail
2022/11/24
[ "https://Stackoverflow.com/questions/74556541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569584/" ]
``` sub(".*?def.*?(\\d)\\)%ile.*", "\\1", x) [1] "4" ```
You can use ```r x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile" library(stringr) result <- str_match(x, "\\bdef(?:\\((\\d+)\\))+%ile") result[,2] ``` See the [R demo online](https://ideone.com/lFnbgg) and the [regex demo](https://regex101.com/r/YBxCtZ/1). *Details*: * `\b` - word boundary * `def` - a `def` string * `(?:\((\d+)\))+` - zero or more occurrences of `(` + one or more digits (captured into Group 1) + `)` and the last one captured is saved in Group 1 * `%ile` - an `%ile` string.
473,455
Just wondering if there is any way to put emacs and shell in the same window. Like split the shell in to two parts, one for shell it self, the other one for emacs. Or is there any way to switch the shell window and emacs window quickly? The reason I am asking this is: sometimes I need to run my program with shell command, that I have to close the emacs and go back to the shell window. It is a little waste of time to switch back and forth. Thank you
2012/09/11
[ "https://superuser.com/questions/473455", "https://superuser.com", "https://superuser.com/users/100570/" ]
Try enabling the `discard` mount option for an Ext4 filesystem and running a recent Linux kernel. This option is being used for SSDs mainly. At the same time it is being currently supported by [`zram`](https://www.kernel.org/doc/Documentation/blockdev/zram.txt) too.
Use fstrim command: `fstrim -v /tmp`
145,215
Which is the real one? What is the other one? How did I get it? ![screenshot](https://i.stack.imgur.com/rG0D8.jpg)
2014/09/14
[ "https://apple.stackexchange.com/questions/145215", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/3044/" ]
TL;DR: keep the one that looks like a bag, it is now a universal app. The cart one was the iPad specific one. Looks like the one of the left (with the shopping cart icon) is the old one. Launching it now directs me to the new one, but it didn't when I was trying to figure this out before. Here's what I get when launching the old one now.![enter image description here](https://i.stack.imgur.com/VLuRy.jpg) EDIT-20140917: It appears that Apple may have had a separate iPad app that they have since deprecated and made their iPhone/iPod Touch app a universal app and that's why this app is now defunct.
The old iPad Store APP is obsolete and has been updated and replaced with this new one.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Your compassion is admirable but is not unique. Other answers have provided more detailed answers about grading, content prep and presentation, students 'earning' their grade and that is all true. Responsibility vs Accountability -------------------------------- With my answer I want to add to the discussion the point that the economic situation of a student may seem dire it is still the students responsibility and not yours. Them making you aware of their situation (even innocently) can have the effect of shifting that responsibility unfairly to one who is not accountable for it (you). It's Not Life or Death, Until It Is ----------------------------------- When I was in college there was a professor who would comment about students complaining about difficult tests or mounds of homework by recalling how different it was in the 1970's when a male student failing out of college made them eligible for the draft with a likely outcome of being sent to Vietnam; which carried with it a very real risk to their health or lifespan. He wasn't saying that he failed people in order to send them to be drafted, he was saying the motivation of students facing such risks were much higher in those days. It wasn't him that decided who was born male, who would be drafted, who would be given a gun and sent out into the jungle. Guilt, party of 2 ----------------- Did the student confer with you before choosing their major? Did they ask your opinion about which school to attend? Did they check with you before taking out those loans? You are neither responsible nor accountable for their choices. Advice ------ While I would not ask you to stop feeling compassion, you should not allow their predicament to turn into guilt on your part. Should you turn your back on these students? Absolutely not, but what then? Either add something in your syllabus or to your first lecture something to effect of, "I know some of you may be relying on financial aid (loans, scholarships) which carry an eligibility component which may be affected by how well you do in this class. If that applies to you, I would suggest you get with me early in the semester so I can assist however I can to point you to resources to improve your chances of success in this class." To effect, you are saying "I can point you to water but I can't make you drink". That is the most that can be reasonably be asked of you since you can't do the work for them or make them attend class, etc.
I generally design my exams so that even a student with relatively limited understanding of the course can pass. I would really only consider a student who has achieved the highest grade (> 80%) to have a good understanding of the material, and I often see just-passing exams (50-60%) where I think that the student really had no idea, but somehow managed to scrape together enough marks to get over the line. Armed with that viewpoint, when I see a student who fails, I think they must have really deserved it! So I don't feel too bad about failing them; they need to put in some effort to fail my course!
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
**You are responsible for teaching the students to the best of your ability, and to judge their capacities to use what they have learned**. That judgment is made based on their grades. So you have several things to think about here. 1. **Are you teaching the best you can?** Teaching does not mean "downloading facts", as I'm sure you're aware. It means "transferring knowledge, skills, and attitudes". That "transfer" part is the important bit — transfer means that the student is able to reproduce and use what they've learned. Is your teaching enhancing this transfer? This is a tough nut to crack — how do you know? Are you planning your assessments so that you can really tease out the nuances and to see which students really understand, or are they just assessments because you need to assign a grade somehow? Your institution might have a center for teaching how to teach, and if you feel that you aren't teaching your best class then start there. Otherwise, lots of books and resources exist, which I'm sure we can all provide. 2. **Are you assessing fairly?** Fairly doesn't mean easily. It means that you are creating assessments that actually test understanding and that a student with reasonable ability will be able to succeed at. It also means to understand their context. It's easy to make a "really good" assessment that everyone fails because they also have three projects and two midterms in their other courses. Are your expectations clearly communicated, and are you ensuring that you only assess what you've asked for? (that doesn't mean that you can't expect students to go above and beyond, just that you need to tell them you expect them to) 3. **Are you assessing accurately?** I'm distinguishing this from "fair", but you can treat "fair" and "accurate" as two sides of the same coin. Accurate means that your assessments are set up so that appropriate weight is given to appropriate topics, and that your tests actually enable students to display their understanding and capacities, rather than whether they memorized the example or found the answer on stack exchange. Creating fair assessments is challenging, but there is a lot of research and resources available. 4. **Are you giving every student the chance to seek help?** I often find that if students are slipping through the cracks, setting up a regular meeting with them to keep them on track can do wonders. However, I am in a job in which I'm required to work with students like this, so it's easy for me to do. If you are a busy research professor who is teaching two courses per semester while juggling other things, it's a lot harder. Ultimately, the final exam is not when a student should find out they failed the course. They should know that they are on a bad path long before then, and should have opportunities to get on track. If you are doing these things, then **you** are not causing them financial ruin. It's similarly not fair to say that the students are causing this — you don't know their context and can't make the judgment. Perhaps they went to a bad high school that just didn't prepare them, or perhaps they are always on the train to another city because their parents are sick and they can't attend classes. It is not your responsibility to help them in this way unless you are capable of providing everyone the same help. Which brings me to the most unfortunate reality of post-secondary education: **Not everyone can make it**. For whatever reason, some students simply will not demonstrate that their abilities are up to the standard that has been set. Notice the wording I used there — I didn't say that they don't have those abilities, but that they will not **demonstrate** that they have those abilities. Provided you are assessing them fairly/accurately, teaching the best you can, and giving the help they pay for, then you are providing them with every opportunity to demonstrate those abilities. If they are unable to do so, then it would be unethical to let them pass regardless of the reason.
Being put on academic probation was one of the best things that ever happened to me. I switched to community college, took art, music, and math classes, learned who I **really** was instead of who I **thought** I was, and eventually graduated with a Bachelor's and have had a lovely career doing things that are truly meaningful to me. The bad grades I "earned" in my first two years at a university were trying to tell me several things: I was not at the right school. I was not in the right major. I was not in the right place in my life mentally and emotionally. But the grades alone didn't help me understand. The letter I got that said I was on probation was what I needed to get to understand that I was doing the wrong things. If professors had just passed me because they felt for me, I would probably be far less happy with my life right now. I would argue that students are paying you to give them the feedback they need on their work and views, they are not paying you for credits and/or a degree.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Being put on academic probation was one of the best things that ever happened to me. I switched to community college, took art, music, and math classes, learned who I **really** was instead of who I **thought** I was, and eventually graduated with a Bachelor's and have had a lovely career doing things that are truly meaningful to me. The bad grades I "earned" in my first two years at a university were trying to tell me several things: I was not at the right school. I was not in the right major. I was not in the right place in my life mentally and emotionally. But the grades alone didn't help me understand. The letter I got that said I was on probation was what I needed to get to understand that I was doing the wrong things. If professors had just passed me because they felt for me, I would probably be far less happy with my life right now. I would argue that students are paying you to give them the feedback they need on their work and views, they are not paying you for credits and/or a degree.
Here in Germany universities are quite strict. After my daughter failed the very last maths exam three times, she was out. However, strict does not mean heartless or planless. Her uni had an arrangement with the tech unis; one of them agreed to accept the exams she had already passed and enrol her in a similar course, for the third year. She was not alone in this. This way all that time and investment was not lost. You could organise a similar scheme with nearby polys or tech colleges, to take up your students, who didn't quite manage, but are still worthy of education. So everybody wins.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
The other answers are great, but I want to stress one thing not really mentioned in other answers: **if you are concerned, talk to them before they fail**. Don't single them out for help because again it won't be fair, but still: tell them explicitly that if they continue performing as they have, they are going to fail the class. Point them to the various resources that are available (e.g. undergraduate tutors, office hours). If they still fail, as the proverb goes, you can lead a horse to water, but you can't make it drink.
Here in Germany universities are quite strict. After my daughter failed the very last maths exam three times, she was out. However, strict does not mean heartless or planless. Her uni had an arrangement with the tech unis; one of them agreed to accept the exams she had already passed and enrol her in a similar course, for the third year. She was not alone in this. This way all that time and investment was not lost. You could organise a similar scheme with nearby polys or tech colleges, to take up your students, who didn't quite manage, but are still worthy of education. So everybody wins.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Take the example of a medical student. Do you want to pass someone who does not have the necessary knowledge to treat patients correctly? It is your duty to make sure that only the ones who know what they are doing will pass. This may be less strict in other subjects but the principle is the same. --- EDIT --- Another example where this becomes clear would be an airplane engineer or pilot that does not have the necessary knowledge (thanks to Mike's comment below!).
Here's an added perspective: If you start passing students for non-academic reasons (or really even just start spending mental energy considering that), there is *no lower bound* to that concern. Wherever you decide to set your threshold, there will always be students further down academically. There will always be some students to be "ruined", and the more your institution lowers standards, the further-down your population will drift over time, in like response to the lowered expectations. This is notably coming from my position as a faculty member at a (large, urban, northeast US) community college. Nationally, [community colleges only have a 22% graduation rate after 3 years](https://www.communitycollegereview.com/blog/the-catch-22-of-community-college-graduation-rates) (our is somewhat higher than that). I've routinely witnessed courses from remedial level up with 50%-60% failure rates. (In contrast, 4-year colleges only have 60% graduation rates after six years.) Many of our students cannot read or write at an elementary level, handle the simplest elementary arithmetic, have emotional/intellectual disabilities, etc. There is no threshold we could possibly set that would serve to pass all or most of these students. Example 1: I've had students ask whether they were guaranteed a passing grade as long as they physically attended every class session, and were incredulous when the answer was "no". (Apparently that's fairly common in some courses now.) Example 2: A few years ago we had a university-wide remedial algebra exam for all students (e.g, at the 8th-9th grade level). I attended a central planning meeting where someone asserted something like, "Our goal was to make an exam that no one could possibly fail. We have not succeeded, because 50% of the students are still failing." (This was given as a positive argument for further reducing the standard of the exam.) Ultimately this was found to be an impossible endeavor, so the college has now abandoned the exam and the basic-algebra requirement entirely. Example 3: In light of budget and enrollment pressures, among the university's new endeavors is to more widely expand advertising and enrollment to even more severely learning-disabled and intellectually-disabled prospective students. The OP identifies a keenly-felt and significant problem. But granted my perspective, I might suggest that there is *no solution* to this problem. No matter where you set the threshold or cutoff, there are more (many more) students lined up further down (arbitrarily further down) the skill and intellectual ladder hoping for the same judgement. It's a cycle that has no hypothetical end.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Take the example of a medical student. Do you want to pass someone who does not have the necessary knowledge to treat patients correctly? It is your duty to make sure that only the ones who know what they are doing will pass. This may be less strict in other subjects but the principle is the same. --- EDIT --- Another example where this becomes clear would be an airplane engineer or pilot that does not have the necessary knowledge (thanks to Mike's comment below!).
All things in life can cause you economic ruin these days. House mortgages, car loans, hacking, frauds. It is basically a society based on debt-based servitude where the banks are our overlords. You are likely just one well-meaning person in this huge mess and likely cannot affect this fact. As far as I know you also can not affect what these students future employers will base their decisions on. It is not your moral obligation (nor is it even within your power) to try and steer where these students end up. It is the privilege of these debt overlords to do. Your job is to teach and to grade. Do your job, peasant.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Some of the discussion surrounding this question demonstrates that people are viewing it through two different implicit lenses, and I'd like to make them explicit. * **Considered as an act in isolation** A single decision to give a student a "kindly" mark has quite diffuse negative consequences. As long as we assume that the rest of the student's record is accurate, the harm to students who have legitimately passed the course, to the institution awarding the credential, and to the organizations that will later trust that credential as a mark of suitability are all very modest. Down in the weeds, really. * **Considered as a pattern** If we assume that "give the poor kid a break" is a social norm that could be applied over and over again to a single student, then the picture is different. Some subset of students will be awarded credentials that don't mean what they say on the label, their subsequent failure in work environments will drag down the reputation of the institution and with it the value of degrees *earned* by students who didn't get a bunch of soft passes. And the damage starts even earlier than that, because professors in second year and later courses will have classes coming in less prepared than they should be and will have to give time over to remedial explanations and hand-holding to the detriment of progress in their course. Several times during my career I've agonized over the kind of decision facing John, and I'm hugely sympathetic. I feel for students who have gotten themselves into a financial bind they don't have the where-with-all to haul themselves out of. But by the time a student is standing in my office explaining that if they don't pass my class they won't graduate and, and, and ... they have already have years of warning signs. That can't be on one professors' head. More than once I discretely (no names) sounded out some of my colleagues about a student only to come away reasonably convinced that the subject had already been given a break; probably more than once. --- As an aside I'm convinced that a significant amount of blame for the binds the students get into in the US lies with a financing system that "just grew that way" through a serious of short-sighted and frankly stupid decisions made by politicians who were personally isolated from the consequences. Both major parties have been vastly wrongheaded in their own ways, but the damage is worse because of they ways they have compromised; the old joke about bipartisanship leading to stupid-evil legislation applies.
Going to college in a country with high tuition fees is a risk. A potentially very huge risk. I think it is important to establish a scheme that makes sure that weak students notice this immediately. This means that in the very first year, it should become clear to the students whether they will make it or not.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
I think you are trying to assume too much responsibility. The way you grade your students (assuming no malicious intent on your part) is not what is (possibly) causing their ruin. What might be causing it (besides, perhaps, some bad decisions of their own) is the system which forces them to go into debt or does not provide them with sufficient opportunities to study properly (e.g. by having them go to bad schools, or forcing them to work long hours in a part-time job). You are not directly responsible for any of this. Indirectly, you can try to change the system. I can think of a couple of ways to do it: 1. You can support (or even start) political initiatives which aim to change what you consider to be unfair. 2. If you think your job is part of the problem, you could quit, and look for a different job which would have less of a bad impact (e.g. a worse paid job at a place with lower fees). 3. You could do something to actively sabotage the system. I think your suggestion (passing students who don't really merit a passing grade) falls under the sabotage category. Indeed, by passing students regardless of their merit, you undermine the whole system --- the more teachers at your institution do that, the less value a passing grade will have. At the logical conclusion, the whole higher education system would collapse, and something better could come up from the ruins. Maybe (but probably not). Either way, in the interim, this would harm all the *other* students (who do merit a passing grade) by diminishing their accomplishments, other people (when the "passed" ones get a job they are not competent for, perhaps instead of someone more qualified), and possibly the ones you wanted to help (by pushing them to an ill-chosen career path). I think ideally, the first solution I have mentioned should be the best, and sabotage should only be used as a last resort.
All things in life can cause you economic ruin these days. House mortgages, car loans, hacking, frauds. It is basically a society based on debt-based servitude where the banks are our overlords. You are likely just one well-meaning person in this huge mess and likely cannot affect this fact. As far as I know you also can not affect what these students future employers will base their decisions on. It is not your moral obligation (nor is it even within your power) to try and steer where these students end up. It is the privilege of these debt overlords to do. Your job is to teach and to grade. Do your job, peasant.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Something other answers did not yet address - by giving unfairly good grades to undeserving students, ***you are dramatically, and unfairly, penalizing good students***. Students - in large part - choose to attend a university based on its academic reputation. Perhaps, paying premium. If your lax grading methods graduate unfit students instead of failing them, this will materially affect the successful student's reputations as graduates of your school, since the employers or graduate schools would have no way of knowing if someone graduated your program because they were a good student, OR, because you took pity on them. So, everyone will be tarred with the bad reputation and that would negatively affect their lives and careers.
I generally design my exams so that even a student with relatively limited understanding of the course can pass. I would really only consider a student who has achieved the highest grade (> 80%) to have a good understanding of the material, and I often see just-passing exams (50-60%) where I think that the student really had no idea, but somehow managed to scrape together enough marks to get over the line. Armed with that viewpoint, when I see a student who fails, I think they must have really deserved it! So I don't feel too bad about failing them; they need to put in some effort to fail my course!
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
Take the example of a medical student. Do you want to pass someone who does not have the necessary knowledge to treat patients correctly? It is your duty to make sure that only the ones who know what they are doing will pass. This may be less strict in other subjects but the principle is the same. --- EDIT --- Another example where this becomes clear would be an airplane engineer or pilot that does not have the necessary knowledge (thanks to Mike's comment below!).
You're not failing the students. Assuming you performed your teaching job well, and you're grading them fairly, the students are failing themselves. They didn't study well enough to pass the class, or maybe they just don't have a talent for this material. Giving someone a passing grade when they haven't earned it is not fair to them, and it dilutes the value of passing grades for all the other students. If they need to use what you're teaching them in their career, they're not going to be as successful. The passing grade you gave them doesn't actually make them competent. When you go to college, you're not buying a degree. No matter how much debt you get yourself into, you're not entitled to the diploma, you still have to do the work and pass the classes. And as a teacher, it's your responsibility to make sure they've done that before passing them.
8,411,466
I am using a way to insert some javascript code in the page which works with all browsers but not with IE. Here is a sample: <http://boxfly.free.fr/tmp/innerjs.html> The line which does not work properly with IE is: ``` ele.text = document.getElementById('DIV_js').innerHTML ; ``` If I change this line to: ``` ele.text = 'alert("Hello")' ; ``` It works. But I need to be able to insert code which is on a lot of lines, not only one line for displaying an alert, that's why I am using a DIV to contain the Javascript code... ;) Does anyone know how to make this script work with IE: ``` <body> <div id="DIV_js" style="display:none;"> var i = 'here' ; function hello() { alert('toto says ' + i) ; } </div> <script> var ele = document.createElement("script") ; ele.type = 'text/javascript' ; ele.text = document.getElementById('DIV_js').innerHTML ; document.body.insertBefore(ele, (document.getElementsByTagName("div"))[0]); </script> <span onClick="hello();">Click to display alert</span> </body> ```
2011/12/07
[ "https://Stackoverflow.com/questions/8411466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073500/" ]
The problem was that the example constructor needs this line at the top ``` parent::__construct ``` That should fix the issues you were having. So your constructor should look like: ``` public function __construct() { parent::__construct(); $this->load->library('session'); } ``` There is no need to store CodeIgniter in a private variable. Just use the constructor as outline in the CodeIgniter documentation. I have updated the GIT repo to fix this issue.
I had a very similar problem, you have to configure it as an object, in your \_construct as follow : ``` class Example extends CI_Controller { private $CI; public function __construct() { parent::__construct(); $this->CI =& get_instance(); $this->CI->load->library('session'); $oauth = array(); $oauth['oauth_token_secret']=''; $oauth['oauth_token']=''; } ``` see here for a very similar subject: [YouTube API Request : How could I get the Right token ( about Jim S.' code )](https://stackoverflow.com/questions/8399738/youtube-api-request-how-could-i-get-the-right-token-about-jim-s-code/8399975#8399975) and [Google Oauth for YouTube : Why do I get "Undefined index: oauth\_token" ( Jim S.' code )](https://stackoverflow.com/questions/8428547/google-oauth-for-youtube-why-do-i-get-undefined-index-oauth-token-jim-s/8429071#8429071) let me know if that solved your pb
39,149,713
I'm writing a UI where the user can type in a search term and a list get continuously updated offering suggestions. My first though was that the Rx primitive Throttle was a perfect match but it gets me half there. The suggestions take a while to fetch so I get them asynchronously on not on the UI thread. The problem is that I want to discard/skip/throw away a result if the user types af the throttle time span again. For example: * Time starts and the user presses a key : 0ms * The throttle is set to 100ms. * The fetch takes 200ms. * At 150ms the user pressed another key Now with Throttle the first fetch will still go ahead an populate the gui suggestion list. What I like to learn is how can I cancel that first fetch as it is not relevant anymore? Only the second keypress should trigger an update to the gui. Here is what I tried (I use ReactiveUI but the Q is about Rx) ``` public IEnumerable<usp_getOpdrachtgevers_Result> Results { get; set; } // [Reactive] pu public SearchOpdrachtgeverVM() { this.WhenAnyValue(x => x.FirstName, x => x.LastName ) .Throttle(TimeSpan.FromMilliseconds(200)) .Subscribe(async vm => Results = await PopulateGrid()); } private async Task<IEnumerable<usp_getOpdrachtgevers_Result>> PopulateGrid() { return await Task.Run( () => _opdrachtgeversCache .Where(x => x.vNaam.Contains(FirstName) && x.vLastName.Contains(LastName) ) ); } ```
2016/08/25
[ "https://Stackoverflow.com/questions/39149713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381995/" ]
If you turn your async Task into an Observable, this looks like a classic use for `Switch`: ``` this.WhenAnyValue(x => x.FirstName, x => x.LastName ) .Throttle(TimeSpan.FromMilliseconds(100)) .Select(l => PopulateGrid().ToObservable()) .Switch() .Subscribe(vm => Results = vm); ``` `Throttle` should be used to suppress calls while the user is typing. So adjust that TimeSpan as you like.
If I understand what you want correctly, this can be done in a quite straight forward manner and clean if you refactor your code slightly. Firstly, make the first name and last name triggers into observables. In the code below, I have used subjects but it is better if you're able to use static Observable methods to 'convert' them into observables; e.g. `Observable.FromEvent`. Then turn the code to fetch results into an observable. In the code below I have used `Observable.Create` to return a stream of `IEnumerable<string>`. Finally, you can use the Switch operator to subscribe to each new GetResults call and cancel the previous call to GetResults. Sounds complicated but the code is quite straight forward: ``` private Subject<string> _firstName = new Subject<string>(); private Subject<string> _lastName = new Subject<string>(); private Task<IEnumerable<string>> FetchResults(string firstName, string lastName, CancellationToken cancellationToken) { // Fetch the results, respecting the cancellation token at the earliest opportunity return Task.FromResult(Enumerable.Empty<string>()); } private IObservable<IEnumerable<string>> GetResults(string firstName, string lastName) { return Observable.Create<IEnumerable<string>>( async observer => { // Use a cancellation disposable to provide a cancellation token the the asynchronous method // When the subscription to this observable is disposed, the cancellation token will be cancelled. CancellationDisposable disposable = new CancellationDisposable(); IEnumerable<string> results = await FetchResults(firstName, lastName, disposable.Token); if (!disposable.IsDisposed) { observer.OnNext(results); observer.OnCompleted(); } return disposable; } ); } private void UpdateGrid(IEnumerable<string> results) { // Do whatever } private IDisposable ShouldUpdateGridWhenFirstOrLastNameChanges() { return Observable // Whenever the first or last name changes, create a tuple of the first and last name .CombineLatest(_firstName, _lastName, (firstName, lastName) => new { FirstName = firstName, LastName = lastName }) // Throttle these tuples so we only get a value after it has settled for 100ms .Throttle(TimeSpan.FromMilliseconds(100)) // Select the results as an observable .Select(tuple => GetResults(tuple.FirstName, tuple.LastName)) // Subscribe to the new results and cancel any previous subscription .Switch() // Use the new results to update the grid .Subscribe(UpdateGrid); } ``` Quick tip: you should really pass an explicit scheduler into the Throttle so that you can effectively unit test this code using the TestScheduler. Hope it helps.
58,206,823
In my `ClientController@index`, I have a form with a select input to list every client in the database. After submitting the form to list detailed client information, the `URL` is like `/clients?client_id=id`. The routes are the defult with `route::resource()`. ``` <form name="show_client" id="show_client"> <div class="form-group"> <label for="branch"><b>Selectione o Cliente</b></label> <select class="form-control select2" name="client_id" id="client_id" required> <option value="">Selecione o Cliente</option> @foreach ($list as $client) <option value="{{ $client->client_id }}">{{ $client->name }} </option> @endforeach </select> </div> <hr /> <div class="form-group"> <button type="submit" class="btn btn-primary btn-rounded">Listar Cliente</button> </div> </form> ``` ``` <script> $(function() { $('#show_client').submit(function(){ var client_id = $('#client_id').val(); $(this).attr('action', "/clients/" + client_id); }); }); </script> ``` Is there any way to work the url to be /clients/id? I accomplish that by using an js function but it's clearly not the solution.
2019/10/02
[ "https://Stackoverflow.com/questions/58206823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742421/" ]
Assuming `search` is in your `methods` it should not be using an arrow function as that will give you the wrong `this` binding. Instead use: ```js methods: { search: throttle(function (live) { // ... }, 500) } ``` Here I'm also assuming that `throttle` will preserve the `this` value, which would be typical for implementations of throttling.
Like I said in my comment, I suspect this is a scoping issue. Perhaps if you return the throttle function with the Vue component passed in, you might see better results: ``` search: function() { let vm = this; return throttle(live => { console.log("entered!!!"); console.log("this", this); console.log("vm", vm); if (typeof live == "undefined") { live = true; } if (!live) { // We are on the search page, we need to update the results if (vm.$route.name != "search") { vm.$router.push({ name: "search" }); } } vm.$store.dispatch("search/get", { type: vm.searchType, query: vm.searchQuery }); }, 500) } ```
401,773
Let $a\_1,\dots,a\_n$ be real numbers, and set $a\_{ij} = a\_ia\_j$. Consider the $n \times n$ matrix $A=(a\_{ij})$. Then 1. It is possible to choose $a\_1.\dots,a\_n$ such that $A$ is non-singular 2. matrix $A$ is positive definite if $(a\_1,\dots,a\_n)$ is nonzero vector 3. matrix $A$ is positive semi definite for all $(a\_1,\dots,a\_n)$ 4. for all $(a\_1,\dots,a\_n)$, $0$ is an eigen value of $A$ I have calculated upto $3\times 3$ that determimant is $0$ but I have no idea how to conclude rigoriously. please help?
2013/05/25
[ "https://math.stackexchange.com/questions/401773", "https://math.stackexchange.com", "https://math.stackexchange.com/users/24690/" ]
It depends. With $a=(a\_1,\ldots,a\_n)$, we can more conveniently write $v\mapsto \langle a,v\rangle a$ instead of $v\mapsto Av$, which simplifies computations. 1. If $n=1$, then $a\_1=1$ is a valid choice and makes $A$ regular (the identity). For $n>1$, there exists nonzero $v$ with $\langle a,v\rangle = 0$, hence $A$ is singular. (To be explicit, either some $a\_i$ is $=0$ and then the $i$th standard base vector $e\_i$ is in the kernel; or $a\_1,a\_2$ are nonzero and $a\_1e\_2-a\_2e\_1$ is in the kernel. That is: Such a choice is possible if and only if $n=1$. 2. $\langle Av,v\rangle = \langle \langle a,v\rangle a,v\rangle = \langle a,v\rangle^2\ge 0$, so we see that $A$ is positive *semi*-definite. But if $n>1$ or $a=0$, it is defnitely not positive definite, as follows from 1. Hence the claim is true only for $n=1$ 3. As shown in 2, this is correct 4. As shown in 1, this is correct only if $n>1$. So the only claim that is unrestrictedly correct, is 3.
Here are a few comments: First, 4. implies that $A$ is always singular, answering 1. Follow Gerry Myerson's advice to prove 4 (basically, you are trying to show that the first two columns are linearly dependent). Now 2. cannot be true since 0 is an eigenvalue. Also, it may be helpful to think of $A$ as the product $a a^T$ where $a$ is the column vector of the $a\_i's$. Edit: you can use this to show 3.
5,371,869
**Please note:** While the bounty is no longer available, I'm still keen for anyone with an answer to this question to contribute; I'm still watching it, and I'm waiting to see if there is a better answer. Thanks, and please read on... --- I am looking for a way to convert an arbitrary set of [RCC](http://en.wikipedia.org/wiki/Region_connection_calculus)-like spatial relations (or similar) describing a constraint network into Venn-diagram-like images. For example, the constraint network as expressed in RCC8: `W {EC} Y`, `X {TPP} Y`, `Z {NTPP} Y`, `Z {PO} X`. ..could be represented by the following diagram with circular or square regions: ![Example 1: Venn diagram representing constraint network using circular regions.](https://i.stack.imgur.com/QYE9H.png) ..alternatively:   ![Venn diagram representing constraint network using square regions.](https://i.stack.imgur.com/pjAMA.png) Is anyone aware of software that can at least generate such diagrams programmatically (via an API) from a specification of RCC-like constraints? I am aware that such a constraint network could be underspecified, precluding a match to any single such diagram (many solutions may exist). Ideally, I would like to deal with this by being able to generate possible alternatives, but can resort to none (and raising an error) for now. Just to be clear, in this question I am specifically asking for software which can calculate a ***diagram layout*** based on RCC-like constraints in a ***declarative manner***. I am not concerned with tools to turn a DSL for RCC into some other syntax, nor am I interested in particular image serialization formats or methods. I am hoping to find an algorithm to do this for dealing with an arbitrary number of constraints for up to six unique sets. ***Notes:*** [Graphviz](http://www.graphviz.org/) (as @vickirk mentioned below) is an example of a **diagram layout software package**, which is akin to what I'm after. Unfortunately, it seems that Graphviz itself cannot help with this problem (but I'd be very happy to be proven wrong!). It seems this is a very hard problem.
2011/03/20
[ "https://Stackoverflow.com/questions/5371869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't know of any software that can generate such diagrams. However, If I had to tackle your problem I would probably explore the possibility of using [Scalable Vector Graphics (SVG)](http://en.wikipedia.org/wiki/Scalable_Vector_Graphics). I think you can translate your DSL for RCC into SVG XML, and then you can render it (maybe in a Web browser). You can easily find examples on the Web by searching for "svg venn diagram". A nice one is [here](http://jura.wi.mit.edu/bioc/tools/venn.php): here's a diagram that I generate from that website ![enter image description here](https://i.stack.imgur.com/S0Nan.png) and here's the corresponding SVG code (also from the website): ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg height="150" width="200" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title >WIBR Venn diagram</title> <ellipse cx="141.795128105731" cy="75" id="circle2" rx="58.2048718942687" ry="58.2048718942687" style="fill: gray; fill-opacity: 0.5; stroke: black; stroke-width: 1; stroke-opacity: 1" /> <ellipse cx="67.2091969126074" cy="75" id="circle1" rx="67.2091969126074" ry="67.2091969126074" style="fill: darkgray; fill-opacity: 0.5; stroke: black; stroke-width: 1; stroke-opacity: 1"/> </svg> ``` There's also an Apache toolkit for SVG called [Batik](http://xmlgraphics.apache.org/batik/), which should support display, generation or manipulation of SVGs. Another option is to use [TikZ & PGF](http://pgf.sourceforge.net/) with LaTeX: there you have powerful macros that let you programmatically place shapes, and the rendering is done by LaTeX. Here's an example: ``` \documentclass[a4paper,10pt]{article} \usepackage{tikz} \usetikzlibrary{shapes,calc} \begin{document} \pagestyle{empty} \begin{tikzpicture} \node (TPP) {X TPP Y}; \node [ circle, draw, minimum width=2cm, label={[label distance=-0.7cm]145:X}, ] (X) [right of=TPP,xshift=1cm] {}; \node [ circle, draw, minimum width=1cm, anchor=south east, ] (Y) at (X.south east) {Y}; \end{tikzpicture} \end{document} ``` which produces the following (i.e. the RCC8 TPP relation): ![enter image description here](https://i.stack.imgur.com/XfnLY.jpg) You can see from the LaTeX code that you can draw the Y circle at south west of X (`X.south west`) saying that Y's anchor is also at south west (`anchor=south west`). You can find a more complex example [here](http://www.texample.net/tikz/examples/venn-diagram/), and some additional discussion [here](https://tex.stackexchange.com/questions/9681/how-to-draw-venn-diagrams-especially-complements-in-latex). Although this is not yet a layout algorithm that draws RCC8 relation for you, I think you can define LaTeX macro that translate RCC8 relations into PGF/TikZ macros. The drawback is that you must then compile the LaTeX code. I hope this helps and good luck!
Have you evaluated antlr, You could define an EBNF grammar for RCC8. Use antlr to generate an item list. This item list can be used as an input to software like [VennMaster](http://www.informatik.uni-ulm.de/ni/mitarbeiter/HKestler/vennm/doc.html "VennMaster") for drawing diagrams. Other options are Goolge Charts , <http://bioinfogp.cnb.csic.es/tools/venny/index.html>
5,371,869
**Please note:** While the bounty is no longer available, I'm still keen for anyone with an answer to this question to contribute; I'm still watching it, and I'm waiting to see if there is a better answer. Thanks, and please read on... --- I am looking for a way to convert an arbitrary set of [RCC](http://en.wikipedia.org/wiki/Region_connection_calculus)-like spatial relations (or similar) describing a constraint network into Venn-diagram-like images. For example, the constraint network as expressed in RCC8: `W {EC} Y`, `X {TPP} Y`, `Z {NTPP} Y`, `Z {PO} X`. ..could be represented by the following diagram with circular or square regions: ![Example 1: Venn diagram representing constraint network using circular regions.](https://i.stack.imgur.com/QYE9H.png) ..alternatively:   ![Venn diagram representing constraint network using square regions.](https://i.stack.imgur.com/pjAMA.png) Is anyone aware of software that can at least generate such diagrams programmatically (via an API) from a specification of RCC-like constraints? I am aware that such a constraint network could be underspecified, precluding a match to any single such diagram (many solutions may exist). Ideally, I would like to deal with this by being able to generate possible alternatives, but can resort to none (and raising an error) for now. Just to be clear, in this question I am specifically asking for software which can calculate a ***diagram layout*** based on RCC-like constraints in a ***declarative manner***. I am not concerned with tools to turn a DSL for RCC into some other syntax, nor am I interested in particular image serialization formats or methods. I am hoping to find an algorithm to do this for dealing with an arbitrary number of constraints for up to six unique sets. ***Notes:*** [Graphviz](http://www.graphviz.org/) (as @vickirk mentioned below) is an example of a **diagram layout software package**, which is akin to what I'm after. Unfortunately, it seems that Graphviz itself cannot help with this problem (but I'd be very happy to be proven wrong!). It seems this is a very hard problem.
2011/03/20
[ "https://Stackoverflow.com/questions/5371869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Who need's a backend? Here's a **working prototype** using HTML/CSS/JS: <http://jsfiddle.net/RuvE6/6/> Just enter the RCC8 code syntax in the field and hit the button! ![HTML/CSS/JS RCC8 Diagram Builder](https://i.stack.imgur.com/owghs.png) Some current limitations: * Doesn't handle ambiguity * There's no error handling if syntax is off * Probably breaks in some valid cases (I haven't tested very much) * Didn't implement any inverse cases (yet?) **Edit: How it works** Basically, there are two *families* of relationships shown with these diagrams: * **A *contains* B** * **A *is adjacent to* B**. There are then sub-types or variations, like: * **A *contains* B** and **B *is tangential to* A** * **A *is adjacent to* B** and **A *overlaps with* to B** Both of the basic concepts are *kind of* baked into the HTML rendering world: * containment --> nested HTML elements: `<div class="region"><div class="region"></div></div>` * adjacency --> sibling HTML elements: `<div class="region"></div><div class="region"></div>` I handle the variations with special classes that (rather crudely) wiggle margins around to accomplish the desired layout: * **containment, with tangent:** `<div class="region"><div class="region touches-parent"></div></div>` (child has negative top margin to touch parent) * **adjacency, with overlap:** `<div class="ven"><div class="region"></div><div class="region touches-parent"></div></div>` (a wrapper is added to trigger CSS on the children - the second element has negative left margin to overlap the first.) There is some static markup commented out in the jsfiddle showing the structure I started with. To complete the functional loop, there is a bit of code that parses the RCC8 statement into A {XX} B parts, and attempts to render the necessary markup for each part. It checks as it goes to not duplicate regions. I also go through afterwards and set the heights of all sibling the same, which ensures they will overlap and/or abut properly. This code is really just a start, and it has it's conceits. It's basically a *linear* diagram, which means it doesn't, for instance, handle cases where there are complicated adjacencies, like this: `A {EC} B, C {EC} B, D {EC} B` These might be handled be smarted JS parsing and more complicated CSS, but probably quickly venture into the realm of more force-directed layouts (a *smarter* [bubble chart](http://vis.stanford.edu/protovis/ex/bubble.html), for instance).
Have you evaluated antlr, You could define an EBNF grammar for RCC8. Use antlr to generate an item list. This item list can be used as an input to software like [VennMaster](http://www.informatik.uni-ulm.de/ni/mitarbeiter/HKestler/vennm/doc.html "VennMaster") for drawing diagrams. Other options are Goolge Charts , <http://bioinfogp.cnb.csic.es/tools/venny/index.html>
5,371,869
**Please note:** While the bounty is no longer available, I'm still keen for anyone with an answer to this question to contribute; I'm still watching it, and I'm waiting to see if there is a better answer. Thanks, and please read on... --- I am looking for a way to convert an arbitrary set of [RCC](http://en.wikipedia.org/wiki/Region_connection_calculus)-like spatial relations (or similar) describing a constraint network into Venn-diagram-like images. For example, the constraint network as expressed in RCC8: `W {EC} Y`, `X {TPP} Y`, `Z {NTPP} Y`, `Z {PO} X`. ..could be represented by the following diagram with circular or square regions: ![Example 1: Venn diagram representing constraint network using circular regions.](https://i.stack.imgur.com/QYE9H.png) ..alternatively:   ![Venn diagram representing constraint network using square regions.](https://i.stack.imgur.com/pjAMA.png) Is anyone aware of software that can at least generate such diagrams programmatically (via an API) from a specification of RCC-like constraints? I am aware that such a constraint network could be underspecified, precluding a match to any single such diagram (many solutions may exist). Ideally, I would like to deal with this by being able to generate possible alternatives, but can resort to none (and raising an error) for now. Just to be clear, in this question I am specifically asking for software which can calculate a ***diagram layout*** based on RCC-like constraints in a ***declarative manner***. I am not concerned with tools to turn a DSL for RCC into some other syntax, nor am I interested in particular image serialization formats or methods. I am hoping to find an algorithm to do this for dealing with an arbitrary number of constraints for up to six unique sets. ***Notes:*** [Graphviz](http://www.graphviz.org/) (as @vickirk mentioned below) is an example of a **diagram layout software package**, which is akin to what I'm after. Unfortunately, it seems that Graphviz itself cannot help with this problem (but I'd be very happy to be proven wrong!). It seems this is a very hard problem.
2011/03/20
[ "https://Stackoverflow.com/questions/5371869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Who need's a backend? Here's a **working prototype** using HTML/CSS/JS: <http://jsfiddle.net/RuvE6/6/> Just enter the RCC8 code syntax in the field and hit the button! ![HTML/CSS/JS RCC8 Diagram Builder](https://i.stack.imgur.com/owghs.png) Some current limitations: * Doesn't handle ambiguity * There's no error handling if syntax is off * Probably breaks in some valid cases (I haven't tested very much) * Didn't implement any inverse cases (yet?) **Edit: How it works** Basically, there are two *families* of relationships shown with these diagrams: * **A *contains* B** * **A *is adjacent to* B**. There are then sub-types or variations, like: * **A *contains* B** and **B *is tangential to* A** * **A *is adjacent to* B** and **A *overlaps with* to B** Both of the basic concepts are *kind of* baked into the HTML rendering world: * containment --> nested HTML elements: `<div class="region"><div class="region"></div></div>` * adjacency --> sibling HTML elements: `<div class="region"></div><div class="region"></div>` I handle the variations with special classes that (rather crudely) wiggle margins around to accomplish the desired layout: * **containment, with tangent:** `<div class="region"><div class="region touches-parent"></div></div>` (child has negative top margin to touch parent) * **adjacency, with overlap:** `<div class="ven"><div class="region"></div><div class="region touches-parent"></div></div>` (a wrapper is added to trigger CSS on the children - the second element has negative left margin to overlap the first.) There is some static markup commented out in the jsfiddle showing the structure I started with. To complete the functional loop, there is a bit of code that parses the RCC8 statement into A {XX} B parts, and attempts to render the necessary markup for each part. It checks as it goes to not duplicate regions. I also go through afterwards and set the heights of all sibling the same, which ensures they will overlap and/or abut properly. This code is really just a start, and it has it's conceits. It's basically a *linear* diagram, which means it doesn't, for instance, handle cases where there are complicated adjacencies, like this: `A {EC} B, C {EC} B, D {EC} B` These might be handled be smarted JS parsing and more complicated CSS, but probably quickly venture into the realm of more force-directed layouts (a *smarter* [bubble chart](http://vis.stanford.edu/protovis/ex/bubble.html), for instance).
I don't know of any software that can generate such diagrams. However, If I had to tackle your problem I would probably explore the possibility of using [Scalable Vector Graphics (SVG)](http://en.wikipedia.org/wiki/Scalable_Vector_Graphics). I think you can translate your DSL for RCC into SVG XML, and then you can render it (maybe in a Web browser). You can easily find examples on the Web by searching for "svg venn diagram". A nice one is [here](http://jura.wi.mit.edu/bioc/tools/venn.php): here's a diagram that I generate from that website ![enter image description here](https://i.stack.imgur.com/S0Nan.png) and here's the corresponding SVG code (also from the website): ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg height="150" width="200" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title >WIBR Venn diagram</title> <ellipse cx="141.795128105731" cy="75" id="circle2" rx="58.2048718942687" ry="58.2048718942687" style="fill: gray; fill-opacity: 0.5; stroke: black; stroke-width: 1; stroke-opacity: 1" /> <ellipse cx="67.2091969126074" cy="75" id="circle1" rx="67.2091969126074" ry="67.2091969126074" style="fill: darkgray; fill-opacity: 0.5; stroke: black; stroke-width: 1; stroke-opacity: 1"/> </svg> ``` There's also an Apache toolkit for SVG called [Batik](http://xmlgraphics.apache.org/batik/), which should support display, generation or manipulation of SVGs. Another option is to use [TikZ & PGF](http://pgf.sourceforge.net/) with LaTeX: there you have powerful macros that let you programmatically place shapes, and the rendering is done by LaTeX. Here's an example: ``` \documentclass[a4paper,10pt]{article} \usepackage{tikz} \usetikzlibrary{shapes,calc} \begin{document} \pagestyle{empty} \begin{tikzpicture} \node (TPP) {X TPP Y}; \node [ circle, draw, minimum width=2cm, label={[label distance=-0.7cm]145:X}, ] (X) [right of=TPP,xshift=1cm] {}; \node [ circle, draw, minimum width=1cm, anchor=south east, ] (Y) at (X.south east) {Y}; \end{tikzpicture} \end{document} ``` which produces the following (i.e. the RCC8 TPP relation): ![enter image description here](https://i.stack.imgur.com/XfnLY.jpg) You can see from the LaTeX code that you can draw the Y circle at south west of X (`X.south west`) saying that Y's anchor is also at south west (`anchor=south west`). You can find a more complex example [here](http://www.texample.net/tikz/examples/venn-diagram/), and some additional discussion [here](https://tex.stackexchange.com/questions/9681/how-to-draw-venn-diagrams-especially-complements-in-latex). Although this is not yet a layout algorithm that draws RCC8 relation for you, I think you can define LaTeX macro that translate RCC8 relations into PGF/TikZ macros. The drawback is that you must then compile the LaTeX code. I hope this helps and good luck!
74,412,503
I don't know why when `a` is located in `def test()` it can not be found and gives the error > > UnboundLocalError: cannot access local variable 'a' where it is not associated with a value > > > ```py import keyboard import time a = 0 def test(): a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ``` I tried setting `a` as `global a` or using a `nonlocal` modifier on it inside the `def` but it doesn't seem to work. Is there a way I can get it to recognize `a` and run properly?
2022/11/12
[ "https://Stackoverflow.com/questions/74412503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485120/" ]
To access a global variable within a function you must specify it with global. Otherwise, the variable inside the function is a local variable that only has utility inside that function. That's why you get the error: "UnboundLocalError: local variable 'a' referenced before assignment". Inside the function you haven't defined the variable 'a' yet, either local or global. ``` import keyboard import time a = 0 def test(): global a a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ```
You need to pass a to the function test. Python thinks as the `a` in the function as a local variable. This will work: ``` import keyboard import time a = 0 def test(a=a): a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ```
74,412,503
I don't know why when `a` is located in `def test()` it can not be found and gives the error > > UnboundLocalError: cannot access local variable 'a' where it is not associated with a value > > > ```py import keyboard import time a = 0 def test(): a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ``` I tried setting `a` as `global a` or using a `nonlocal` modifier on it inside the `def` but it doesn't seem to work. Is there a way I can get it to recognize `a` and run properly?
2022/11/12
[ "https://Stackoverflow.com/questions/74412503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485120/" ]
To access a global variable within a function you must specify it with global. Otherwise, the variable inside the function is a local variable that only has utility inside that function. That's why you get the error: "UnboundLocalError: local variable 'a' referenced before assignment". Inside the function you haven't defined the variable 'a' yet, either local or global. ``` import keyboard import time a = 0 def test(): global a a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ```
Python variables are scope based. This means one cannot access a value declared inside a function. But you can access a variable declared outside a function. This would fail: ``` def func(): a = 1 func() print(a) ``` this would print `1`: ``` def func(): print(a) a = 1 func() ``` Notice you can access it. You'll fail if you want to update it. This would fail too: ``` def func(): a = a + 1 print(a) a = 1 func() ``` What you need is no tell the interpreter to find variable `a` in the global scope. ``` def func(): global a a = a + 1 print(a) a = 1 func() ``` Warning: It's not a good practice to use `global` variables. So better make sure the function is getting the value. ``` def func(a): a = a + 1 print(a) a = 1 func(1) ```
33,504,770
I have a `UIView` that contains buttons and labels. When these buttons are pressed, this `UIView` will become blur using the code below. ``` @IBOutlet weak var blurView: UIView! var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) var blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = blurView.bounds blurView.addSubview(blurEffectView) ``` However, I want to remove the blur effect later on. What is the code for removing the blurred `UIView`?
2015/11/03
[ "https://Stackoverflow.com/questions/33504770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/794575/" ]
It's hard to know exactly what is going on in your code, as you've clearly posted a cut up version (the last 4 lines are part of a method somewhere, presumably). You could do something like this to remove all `UIVisualEffectView` subviews from your `blurView`: ``` for subview in blurView.subviews { if subview is UIVisualEffectView { subview.removeFromSuperview() } } ```
``` func addBlurEffect(view: UIView, style: UIBlurEffect.Style) { view.backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.tag = 9 view.insertSubview(blurEffectView, at: 0) } func removeBlurEffect(view: UIView){ view.viewWithTag(9)?.removeFromSuperview() } ```
74,195,322
i have a quick question i'm trying to make an application but i've faced a problem, i want to assign data to a button then pass that data to datagridview when the button is clicked ex. [![enter image description here](https://i.stack.imgur.com/5T3di.png)](https://i.stack.imgur.com/5T3di.png) ``` private void TeaButton_Click(object sender, EventArgs e) { sales.OrderDataGridView.Rows.Add(1, "Tea", 5.0); } ``` i expected it to pass the values inside the parentheses to the data grid view, but it returned a null reference error, the reason was "sales." it was returning null value, but i don't know any other way beside this .
2022/10/25
[ "https://Stackoverflow.com/questions/74195322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20330704/" ]
Add the `max-width` property with the value of `{n}ch`. For example: `max-width: 100ch`. Then, apply `white-space: nowrap`, and `overflow: hidden` to remove the overflow characters. In order to add some dots at the end, add the `text-overflow: ellipsis` property. Any character after the value you defined will be removed. ```css p { max-width: 30ch; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } ``` ```html <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore</p> ``` --- If you want to limit the number of lines, you can use the `line-clamp` properties instead of setting the number of characters (`max-width: {n}ch`): ```css display: -webkit-box; -webkit-line-clamp: 3; /* Set the number of lines here */ -webkit-box-orient: vertical; ``` Example: ```css div { max-width: 100px; } p { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; } ``` ```html <div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore</p> </div> ```
Just do it with JS based on the value of the string. In base JS you can do something like this. In react you can do the same but in a useEffect, then store the string (truncated or not) as a state value. The example bellow will truncate a string that is > 20 characters long. To change that, just alter the two 20s to something else, maybe even put the truncate length as a param of the function. ``` const truncateString = (string) => { if (string.length > 20) { const truncatedString = `${string.slice(0, 20)}...`; setStringSomewhere(truncatedString) } else setStringSomewhere(string); } ```
160,224
I have a custom menu using `add_menu_page`: ``` add_menu_page('My menu' , 'Some text', 'read', 'nwcm'); ``` Under it, I show a custom post type menu item; ``` // Create the news custom post type register_post_type('nwcm_news', array( 'labels' => array( 'name' => __('News for clients', NWCM_TEXT_DOMAIN) , 'singular_name' => __('News', NWCM_TEXT_DOMAIN) ) , 'public' => true, 'has_archive' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => 'nwcm', 'taxonomies' => array( 'nwcm_news_category' ) , )); ``` Then I add a custom taxonomy hooked to that "nwcm\_news" post type: ``` // register news taxonomy register_taxonomy('nwcm_news_category', 'nwcm_news', array( 'label' => __('News categories') , 'menu_name' => __('News categories') , 'rewrite' => array( 'slug' => 'nwcm_news_category' ) , 'hierarchical' => true )); ``` The parent menu and the custom post type both show correctly... but, the taxonomy menu isn't showing :( How can I solve this? I had checked [this solution](https://stackoverflow.com/a/20034946/232082) but the answer lacks the full code example..
2014/09/04
[ "https://wordpress.stackexchange.com/questions/160224", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7515/" ]
You have some messed up code. I have reformatted your code to code which actually works. The following solution allows you to give your Custom Post Type menu a menu name of what ever you want. Just change the label "menu\_name". **POST TYPE** ``` // Create the news custom post type register_post_type('nwcm_news', array( 'labels' => array( 'name' => __('News for clients', 'NWCM'), 'singular_name' => __('News', 'NWCM'), 'menu_name' => __('NWCM', 'NWCM'), 'all_items' => __('View Articles', 'NWCM'), ), 'public' => true, 'has_archive' => true, 'show_ui' => true, 'show_in_menu' => true, 'taxonomies' => array( 'nwcm_news_category' ) )); ``` **TAXONOMY** ``` // register news taxonomy register_taxonomy('nwcm_news_category', 'nwcm_news', array( 'label' => 'News Categories', 'labels' => array( 'menu_name' => __('News Categories', 'NWCM') ), 'rewrite' => array( 'slug' => 'nwcm-news-category' ), 'hierarchical' => true )); ``` I'm not 100% sure if you are wanting your own custom admin menu to add your stuff under, or if you just want to change the menu name of the custom post type. I have added in the `menu_name` of "NWCM" to the `labels` of your custom post type. I would highly recommend you read through and fully understand the parameters and arguments for registering custom post types and taxonomies. * [`register_post_type();`](http://codex.wordpress.org/Function_Reference/register_post_type#Parameters) * [`register_taxonomy();`](http://codex.wordpress.org/Function_Reference/register_taxonomy#Parameters) --- **EDIT: 09/05/2014** If you wanted to completely add your own custom admin menu, and mix in your Custom Post Types, Custom Taxonomies, and any other custom admin pages of your own... The following solution works. Please note, it's just a starting point and you don't have to do it this way 100% to a "T". It's just an example... I recommend you modify it, so that it's understandable and maintainable by you or your developer. **Hook into `init` and register Custom Post Types and Custom Taxonomies.** ``` if ( ! function_exists( 'mbe_init' ) ) { function mbe_init() { # Create the news custom post type register_post_type( 'nwcm_news', array( 'labels' => array( 'name' => __( 'News for clients', 'NWCM' ), 'singular_name' => __( 'News', 'NWCM' ), ), 'public' => true, 'has_archive' => true, 'show_ui' => true, 'show_in_menu' => false,// adding to custom menu manually 'taxonomies' => array( 'nwcm_news_category' ) ) ); # Create the news categories custom taxonomy register_taxonomy( 'nwcm_news_category', 'nwcm_news', array( 'label' => 'News Categories', 'labels' => array( 'menu_name' => __( 'News Categories', 'NWCM' ) ), 'rewrite' => array( 'slug' => 'nwcm-news-category' ), 'hierarchical' => true ) ); } add_action( 'init', 'mbe_init' ); } ``` **Hook into `admin_menu` to create a custom parent admin menu, and add Custom Submenu Admin Pages, Custom Post Type pages, and Custom Taxonomy Pages all to the custom parent admin menu.** ``` if ( ! function_exists( 'mbe_add_admin_menu' ) && ! function_exists( 'mbe_display_admin_page' ) ) { function mbe_add_admin_menus() { # Settings for custom admin menu $page_title = 'News for clients'; $menu_title = 'NWCM'; $capability = 'post'; $menu_slug = 'nwcm'; $function = 'mbe_display_admin_page';// Callback function which displays the page content. $icon_url = 'dashicons-admin-page'; $position = 0; # Add custom admin menu add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position ); $submenu_pages = array( # Avoid duplicate pages. Add submenu page with same slug as parent slug. array( 'parent_slug' => 'nwcm', 'page_title' => 'Summary of News', 'menu_title' => 'Summary', 'capability' => 'read', 'menu_slug' => 'nwcm', 'function' => 'mbe_display_admin_page',// Uses the same callback function as parent menu. ), # Post Type :: View All Posts array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'View News', 'capability' => '', 'menu_slug' => 'edit.php?post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), # Post Type :: Add New Post array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'Add News', 'capability' => '', 'menu_slug' => 'post-new.php?post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), # Taxonomy :: Manage News Categories array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'News Categories', 'capability' => '', 'menu_slug' => 'edit-tags.php?taxonomy=nwcm_news_category&post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), ); # Add each submenu item to custom admin menu. foreach ( $submenu_pages as $submenu ) { add_submenu_page( $submenu['parent_slug'], $submenu['page_title'], $submenu['menu_title'], $submenu['capability'], $submenu['menu_slug'], $submenu['function'] ); } } add_action( 'admin_menu', 'mbe_add_admin_menus', 1 ); /* If you add any extra custom sub menu pages which are not a Custom Post Type or a Custom Taxonomy, you will need * to create a callback function for each of your custom submenu items you create above. */ # Default Admin Page for Custom Admin Menu function mbe_display_admin_page() { # Display custom admin page content from newly added custom admin menu. echo '<div class="wrap">' . PHP_EOL; echo '<h2>My Custom Admin Page Title</h2>' . PHP_EOL; echo '<p>This is the custom admin page created from the custom admin menu.</p>' . PHP_EOL; echo '</div><!-- end .wrap -->' . PHP_EOL; echo '<div class="clear"></div>' . PHP_EOL; } } ``` **Hook into `parent_file` to correctly highlight your Custom Post Type and Custom Taxonomy submenu items with your custom parent menu/page.** ``` if ( ! function_exists( 'mbe_set_current_menu' ) ) { function mbe_set_current_menu( $parent_file ) { global $submenu_file, $current_screen, $pagenow; # Set the submenu as active/current while anywhere in your Custom Post Type (nwcm_news) if ( $current_screen->post_type == 'nwcm_news' ) { if ( $pagenow == 'post.php' ) { $submenu_file = 'edit.php?post_type=' . $current_screen->post_type; } if ( $pagenow == 'edit-tags.php' ) { $submenu_file = 'edit-tags.php?taxonomy=nwcm_news_category&post_type=' . $current_screen->post_type; } $parent_file = 'nwcm'; } return $parent_file; } add_filter( 'parent_file', 'mbe_set_current_menu' ); } ``` If you need any clarification about how any of this works, read the following pages from top to bottom. 1. [Adding Custom Parent Admin Menus](http://codex.wordpress.org/Function_Reference/add_menu_page) 2. [Adding Custom Child Admin Menus](http://codex.wordpress.org/Function_Reference/add_submenu_page) 3. [Roles and Capabilities in WordPress](http://codex.wordpress.org/Roles_and_Capabilities) 4. [Registering Custom Post Types](http://codex.wordpress.org/Function_Reference/register_post_type) 5. [Registering Custom Taxonomies](http://codex.wordpress.org/Function_Reference/register_taxonomy) 6. [WordPress Plugin API :: Action Reference](http://codex.wordpress.org/Plugin_API/Action_Reference) 7. [WordPress Plugin API :: Action Reference :: `init`](http://codex.wordpress.org/Plugin_API/Action_Reference/init) 8. [WordPress Plugin API :: Action Reference :: `admin_menu`](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_menu) 9. [WordPress Plugin API :: Filter Reference](http://codex.wordpress.org/Plugin_API/Filter_Reference) 10. [List of All WordPress Hooks (including actions and filters)](http://adambrown.info/p/wp_hooks/hook)
Here is how i accomplished this: Inside of the admin\_menu action, I added a submenu item to the parent menu item ('nwcm') with the menu\_slug parameter set to the URL the taxonomy edit page. ``` add_submenu_page('nwcm', 'News categories', 'News categories', 'edit_posts', 'edit-tags.php?taxonomy=nwcm_news&post_type=nwcm_news',false ); ```
64,127,599
So I've started learning vectors for the first time and wrote a simple program which goes like this: ``` #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; int n; cout<<"enter values"<<endl; do { cin>>n; g1.push_back(n); } while (n); cout<<"Vector values are: "<<endl; for(auto i=g1.begin(); i<g1.size();i++) cout<<*i<<endl; } ``` When I try executing it, an error shows up saying "type mismatch" at the g1.size() part. Why exactly does this happen? I used the auto keyword for the iterator involved and assumed there wouldn't be any problem?
2020/09/29
[ "https://Stackoverflow.com/questions/64127599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987935/" ]
That is the bad side of using `auto`. If you have no idea what the result of `auto` is, you get no idea why it is something totally different you expect! `std::vector::begin` delivers a `std::vector::iterator` and you can't compare it against an `size_type` value which is a result of `std::vector::size`. This type is typically `std::size_t` You have to compare against another iterator which is the representation of the end of the vector like: ``` for(auto i = g1.begin(); i != g1.end(); i++) ```
There are at least three ways to iterate through the contents of a vector. You can use an index: ``` for (int i = 0; i < vec.size(); ++i) std::cout << vec[i] << '\n'; ``` You can use iterators: ``` for (auto it = vec.begin(); it != vec.end(); ++it) std::cout << *it << '\n'; ``` You can use a range-based for loop: ``` for (auto val : vec) std::cout << Val <<'\n'; ``` The latter two can be used with any container.
64,127,599
So I've started learning vectors for the first time and wrote a simple program which goes like this: ``` #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; int n; cout<<"enter values"<<endl; do { cin>>n; g1.push_back(n); } while (n); cout<<"Vector values are: "<<endl; for(auto i=g1.begin(); i<g1.size();i++) cout<<*i<<endl; } ``` When I try executing it, an error shows up saying "type mismatch" at the g1.size() part. Why exactly does this happen? I used the auto keyword for the iterator involved and assumed there wouldn't be any problem?
2020/09/29
[ "https://Stackoverflow.com/questions/64127599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987935/" ]
That is the bad side of using `auto`. If you have no idea what the result of `auto` is, you get no idea why it is something totally different you expect! `std::vector::begin` delivers a `std::vector::iterator` and you can't compare it against an `size_type` value which is a result of `std::vector::size`. This type is typically `std::size_t` You have to compare against another iterator which is the representation of the end of the vector like: ``` for(auto i = g1.begin(); i != g1.end(); i++) ```
`g1.begin()` returns an *iterator* to the 1st element, whereas `g1.size()` returns the *number* of elements. You can't compare an iterator to a size, which is why you are getting the error. It has nothing to do with your use of `auto`, it has to do with you comparing 2 different things that are unrelated to each other. You need to change your loop to compare your `i` iterator to the vector's `end()` iterator, eg: ```cpp for(auto i = g1.begin(); i != g1.end(); ++i) cout << *i << endl; ``` Or, simply use a [range-based `for` loop](https://en.cppreference.com/w/cpp/language/range-for) instead, which uses iterators internally: ```cpp for(auto i : g1) cout << i << endl; ``` Otherwise, if you want to use `size()` then use indexes with the vector's `operator[]`, instead of using iterators, eg: ```cpp for(size_t i = 0; i < g1.size(); ++i) cout << g1[i] << endl; ```
64,127,599
So I've started learning vectors for the first time and wrote a simple program which goes like this: ``` #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; int n; cout<<"enter values"<<endl; do { cin>>n; g1.push_back(n); } while (n); cout<<"Vector values are: "<<endl; for(auto i=g1.begin(); i<g1.size();i++) cout<<*i<<endl; } ``` When I try executing it, an error shows up saying "type mismatch" at the g1.size() part. Why exactly does this happen? I used the auto keyword for the iterator involved and assumed there wouldn't be any problem?
2020/09/29
[ "https://Stackoverflow.com/questions/64127599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987935/" ]
There are at least three ways to iterate through the contents of a vector. You can use an index: ``` for (int i = 0; i < vec.size(); ++i) std::cout << vec[i] << '\n'; ``` You can use iterators: ``` for (auto it = vec.begin(); it != vec.end(); ++it) std::cout << *it << '\n'; ``` You can use a range-based for loop: ``` for (auto val : vec) std::cout << Val <<'\n'; ``` The latter two can be used with any container.
`g1.begin()` returns an *iterator* to the 1st element, whereas `g1.size()` returns the *number* of elements. You can't compare an iterator to a size, which is why you are getting the error. It has nothing to do with your use of `auto`, it has to do with you comparing 2 different things that are unrelated to each other. You need to change your loop to compare your `i` iterator to the vector's `end()` iterator, eg: ```cpp for(auto i = g1.begin(); i != g1.end(); ++i) cout << *i << endl; ``` Or, simply use a [range-based `for` loop](https://en.cppreference.com/w/cpp/language/range-for) instead, which uses iterators internally: ```cpp for(auto i : g1) cout << i << endl; ``` Otherwise, if you want to use `size()` then use indexes with the vector's `operator[]`, instead of using iterators, eg: ```cpp for(size_t i = 0; i < g1.size(); ++i) cout << g1[i] << endl; ```
58,479,855
``` dfs=[] for i in range(387): print(i) dfs.append(pd.DataFrame(0, index=range(121211), columns=range(31))) pd.concat(dfs,axis=1) #can only change this ``` In the code above, `pd.concat` is pretty slow, is there a way to make column join faster? assume I can only change the `pd.concat` part.
2019/10/21
[ "https://Stackoverflow.com/questions/58479855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497720/" ]
You are instantiating a very large dataframe all containing zero values. Rather than concatenate, just use the dataframe constructor with your desired index and columns. ``` dfs = pd.DataFrame( 0, index=range(121211), columns=list(range(31)) * 387 ) ``` For example (using a much smaller size dataframe): ``` >>> pd.DataFrame(0, index=range(3), columns=list(range(2)) * 3) 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 ``` **EDIT** Assuming that each dataframe has the same index, different columns and different values, try concatenating the numpy values directly (avoiding the overhead of index and column checking for `concat`). ``` pd.DataFrame( np.concatenate([df.values for df in dfs], axis=1), index=dfs[0].index, columns=[col for df in dfs for col in df] ) ``` After checking the timings of this approach vs. concat, they are very similar when using random data. For dataframes this large, you may want to consider alternative solutions such as [Dask](https://dask.org/).
It seems that `generator` and `transposing` do the work faster. Beware that this code is RAM-hungry, so it is better to run both version separately. ``` import pandas as pd import timeit dfs=[] for i in range(387): print(i) dfs.append(pd.DataFrame(0, index=range(121211), columns=range(31))) #original start = timeit.timeit() fin1 = pd.concat(dfs, axis=1) print((timeit.timeit() - start) * 1000) print(fin1.shape) #0.7748472388211941 #(121211, 11997) #faster start = timeit.timeit() fin2 = pd.concat((df.T for df in dfs), axis=0).T print((timeit.timeit() - start) * 1000) print(fin2.shape) #0.09283745513703756 #(121211, 11997) ```
42,430,928
I did a lot of research before I post this question, but still cant figure out why I can't print a simple php value. My issue is that I'm trying to assign a value to an id, basically I want to assign the id that comes back from DataBase to button id. I'm able to print the values of id, name, email, but I can't assign the id as a value. Can anyone tell me what is wrong with this line of code please? ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Here's my PHP code which simply pulls data from database and display them on the page using Ajax. ``` <?php require "conexion.php"; $name =$_GET["nombre"]; if($name === "showPeople"){ $client = mysqli_real_escape_string($con, $name); $result = mysqli_query($con,"SELECT * FROM people"); $table .= '<table>'; while($row = mysqli_fetch_assoc($result)) { $table .= '<tr>'; $table .= '<td>' .$row['id'] . '</td>'; $table .= '<td>' .$row['name'] . '</td>'; $table .= '<td>' .$row['email'] . '</td>'; $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; $table .= '</tr>'; } $table .= '</table>'; echo $table; } ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42430928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245070/" ]
You can't put `<?php` and `?>` inside of strings and then print them to execute their contents. Try this instead: ``` $table .= '<td><button id="' .$row['id'] . '" onclick="editUser()">Edit</button></td>'; ```
instead of line ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Try ``` $table .= '<td><button id = "' . $row['id'] . '" onclick = "editUser()">Edit</button></td>'; ```
42,430,928
I did a lot of research before I post this question, but still cant figure out why I can't print a simple php value. My issue is that I'm trying to assign a value to an id, basically I want to assign the id that comes back from DataBase to button id. I'm able to print the values of id, name, email, but I can't assign the id as a value. Can anyone tell me what is wrong with this line of code please? ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Here's my PHP code which simply pulls data from database and display them on the page using Ajax. ``` <?php require "conexion.php"; $name =$_GET["nombre"]; if($name === "showPeople"){ $client = mysqli_real_escape_string($con, $name); $result = mysqli_query($con,"SELECT * FROM people"); $table .= '<table>'; while($row = mysqli_fetch_assoc($result)) { $table .= '<tr>'; $table .= '<td>' .$row['id'] . '</td>'; $table .= '<td>' .$row['name'] . '</td>'; $table .= '<td>' .$row['email'] . '</td>'; $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; $table .= '</tr>'; } $table .= '</table>'; echo $table; } ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42430928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245070/" ]
You can't put `<?php` and `?>` inside of strings and then print them to execute their contents. Try this instead: ``` $table .= '<td><button id="' .$row['id'] . '" onclick="editUser()">Edit</button></td>'; ```
Try this ``` $table .= '<td><button id ='. $row['id'] .' onclick = "editUser()">Edit</button></td>'; ```
42,430,928
I did a lot of research before I post this question, but still cant figure out why I can't print a simple php value. My issue is that I'm trying to assign a value to an id, basically I want to assign the id that comes back from DataBase to button id. I'm able to print the values of id, name, email, but I can't assign the id as a value. Can anyone tell me what is wrong with this line of code please? ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Here's my PHP code which simply pulls data from database and display them on the page using Ajax. ``` <?php require "conexion.php"; $name =$_GET["nombre"]; if($name === "showPeople"){ $client = mysqli_real_escape_string($con, $name); $result = mysqli_query($con,"SELECT * FROM people"); $table .= '<table>'; while($row = mysqli_fetch_assoc($result)) { $table .= '<tr>'; $table .= '<td>' .$row['id'] . '</td>'; $table .= '<td>' .$row['name'] . '</td>'; $table .= '<td>' .$row['email'] . '</td>'; $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; $table .= '</tr>'; } $table .= '</table>'; echo $table; } ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42430928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245070/" ]
instead of line ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Try ``` $table .= '<td><button id = "' . $row['id'] . '" onclick = "editUser()">Edit</button></td>'; ```
Try this ``` $table .= '<td><button id ='. $row['id'] .' onclick = "editUser()">Edit</button></td>'; ```
46,622,473
i use [multer](/questions/tagged/multer "show questions tagged 'multer'") according to it's readme file in github it's readme said call multer in [middleware](/questions/tagged/middleware "show questions tagged 'middleware'") like this: **app.js** ``` var multer = require('multer') app.post('/upload', upload.single('image'), function(req, res){}) ``` but i defined my **function(req, res)** in another file - post.js - and my code in **app.js** looks like this: ``` app.post('/upload', upload.single('image'), post.new) ``` how can i **require** multer only on post.js, almost like this: **post.js** ``` var multer = require('multer') module.exports.new = function(req, res){ //access to req.file } ``` **app.js** ``` app.post('/upload', post.new) ```
2017/10/07
[ "https://Stackoverflow.com/questions/46622473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8455506/" ]
Since rails expects your module naming to follow your file structure, your concern should be named: ``` module Api::Concerns::ErrorSerializer ``` Since you're including it in `Api::TemplatesController`, I would do: ``` class Api::TemplatesController < ApiController include Api::Concerns::ErrorSerializer ... end ``` To help rails out with the constant lookup.
Thanks to the answer from @jvillian and [this blog post](http://jordifierro.com/rails-apicontroller-and-concerns), I was able to figure out the 'Rails' way to do this (since actually I will need the concern in all Api controllers, and also my api controller was outside the api namespace). So I'm posting this solution as (I think) it's the preferred way: I moved the error\_serialzier.rb file into api/concerns and change the code to include the Api namespace: ``` module Api::Concerns::ErrorSerializer extend ActiveSupport::Concern ... end ``` I also moved `api_controller.rb` file and put it inside the /api folder, and thus into the API module namespace, so now it looks like this: ``` class Api::ApiController < ActionController::API before_action :authenticate_api_user! include DeviseTokenAuth::Concerns::SetUserByToken include Concerns::ErrorSerializer respond_to :json end ``` This got rid of the uninitialized constant errors.
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are no strong typedefs in C++11. There is support for units with `<chrono>` but that is a totally different thing. Nobody can agree on what behaviour strong typedefs should have, exactly, so there has never been a proposal for them that got anywhere, so not only are they in neither C++11 nor C++14, there is no realistic prospect at this time that they will get into any future Standard.
C++ compilers generally expect the command line option `-std=c++11` (or `-std=c++0x` for slightly older ones, respectively) to activate C++11-support. > > not supporting C++11 style at all. > > > No, it perfectly does. GCC 4.7.2's support can be [checked here](https://gcc.gnu.org/gcc-4.7/cxx0x_status.html). To activate some experimental features, pass `-std=gnu++11`. And Clang 3.4 actually supports pretty much everything [in C++11 and already much out of C++1y](http://clang.llvm.org/cxx_status.html).
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are several ways to solve this, but since I was looking for a fix to Bjarne's code in the presentation slides, I'm accepting this answer which @robson3.14 left in comments to the question: ``` #include <iostream> template<int M, int K, int S> struct Unit { // a unit in the MKS system enum { m=M, kg=K, s=S }; }; template<typename Unit> // a magnitude with a unit struct Value { double val; // the magnitude // construct a Value from a double constexpr explicit Value(double d) : val(d) {} }; using Meter = Unit<1,0,0>; // unit: meter using Second = Unit<0,0,1>; // unit: sec using Speed = Value<Unit<1,0,-1>>; // meters/second type // a f-p literal suffixed by ‘_s’ constexpr Value<Second> operator "" _s(long double d) { return Value<Second> (d); } // a f-p literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(long double d) { return Value<Meter> (d); } // an integral literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(unsigned long long d) { return Value<Meter> (d); } template<int m1, int k1, int s1, int m2, int k2, int s2> Value<Unit<m1 - m2, k1 - k2, s1 - s2>> operator / (Value<Unit<m1, k1, s1>> a, Value<Unit<m2, k2, s2>> b) { return Value<Unit<m1 - m2, k1 - k2, s1 - s2>>(a.val / b.val); } int main() { Speed sp1 = 100_m / 9.8_s; std::cout << sp1.val; } ```
C++ compilers generally expect the command line option `-std=c++11` (or `-std=c++0x` for slightly older ones, respectively) to activate C++11-support. > > not supporting C++11 style at all. > > > No, it perfectly does. GCC 4.7.2's support can be [checked here](https://gcc.gnu.org/gcc-4.7/cxx0x_status.html). To activate some experimental features, pass `-std=gnu++11`. And Clang 3.4 actually supports pretty much everything [in C++11 and already much out of C++1y](http://clang.llvm.org/cxx_status.html).
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
C++ compilers generally expect the command line option `-std=c++11` (or `-std=c++0x` for slightly older ones, respectively) to activate C++11-support. > > not supporting C++11 style at all. > > > No, it perfectly does. GCC 4.7.2's support can be [checked here](https://gcc.gnu.org/gcc-4.7/cxx0x_status.html). To activate some experimental features, pass `-std=gnu++11`. And Clang 3.4 actually supports pretty much everything [in C++11 and already much out of C++1y](http://clang.llvm.org/cxx_status.html).
One alternative that does not involve typedef and is not strongly enforced by the compiler but makes it very hard for the programmer to make mistakes it to encode the unit in question as a struct member. For my arduino project I have types like ``` template <typename T> struct millisecond { T millisecond; static constexpr const struct millisecond<T> zero = { 0 }; }; template <typename T> struct microsecond { T microsecond; static constexpr const struct microsecond<T> zero = { 0 }; }; ``` and use like ``` auto time_diff = millisecond<unsigned long>::zero; time_diff.millisecond = nowMilliseconds() - s_lastPollTime.millisecond; ``` So with this strategy the compiler does not stop you from mixing units, but if you do then the error will always [scream at you](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/): ``` total_expenses.euros = expence1.euros + expence2.dollars; ```
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are no strong typedefs in C++11. There is support for units with `<chrono>` but that is a totally different thing. Nobody can agree on what behaviour strong typedefs should have, exactly, so there has never been a proposal for them that got anywhere, so not only are they in neither C++11 nor C++14, there is no realistic prospect at this time that they will get into any future Standard.
Not sure this is what you want, it is ugly, but it works :) You can wrap the type into a template class, ``` template <typename T, int N> // N is used for tagging struct strong_typedef { using strong_type = strong_typedef<T,N>; // typedef for the strong type using type = T; // the wrapped type T value; // the wrapped value strong_typedef(T val): value(val){}; // constructor strong_typedef(){value={};}; // default, zero-initialization // operator overloading, basic example: strong_type operator+(const strong_type& rhs) const { return value + rhs.value; } // display it friend ostream& operator<<(ostream & lhs, const strong_typedef& rhs) { lhs << rhs.value; return lhs; } }; ``` then use it as ``` // these are all different types strong_typedef<double, 0> x = 1.1; strong_typedef<double, 1> y = 2.2; strong_typedef<double, 2> z = 3.3; std::cout << x + x << std::endl; // outputs 2.2, can add x and x // cout << x + y << endl; // compile-time ERROR, different types ``` `x`, `y` and `z` are 3 different types now, because of the different `N`-s used in the template. You can access the type and value using the fields `type` and `value`, like `x::value` (will be double 1.1). Of course if you directly `typedef` the `struct_typedef::type`, you're back to square one, as you are losing the `strong` type. So basically your type should be `strong_typedef` and not `strong_typedef::type`.
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are no strong typedefs in C++11. There is support for units with `<chrono>` but that is a totally different thing. Nobody can agree on what behaviour strong typedefs should have, exactly, so there has never been a proposal for them that got anywhere, so not only are they in neither C++11 nor C++14, there is no realistic prospect at this time that they will get into any future Standard.
One alternative that does not involve typedef and is not strongly enforced by the compiler but makes it very hard for the programmer to make mistakes it to encode the unit in question as a struct member. For my arduino project I have types like ``` template <typename T> struct millisecond { T millisecond; static constexpr const struct millisecond<T> zero = { 0 }; }; template <typename T> struct microsecond { T microsecond; static constexpr const struct microsecond<T> zero = { 0 }; }; ``` and use like ``` auto time_diff = millisecond<unsigned long>::zero; time_diff.millisecond = nowMilliseconds() - s_lastPollTime.millisecond; ``` So with this strategy the compiler does not stop you from mixing units, but if you do then the error will always [scream at you](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/): ``` total_expenses.euros = expence1.euros + expence2.dollars; ```
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are several ways to solve this, but since I was looking for a fix to Bjarne's code in the presentation slides, I'm accepting this answer which @robson3.14 left in comments to the question: ``` #include <iostream> template<int M, int K, int S> struct Unit { // a unit in the MKS system enum { m=M, kg=K, s=S }; }; template<typename Unit> // a magnitude with a unit struct Value { double val; // the magnitude // construct a Value from a double constexpr explicit Value(double d) : val(d) {} }; using Meter = Unit<1,0,0>; // unit: meter using Second = Unit<0,0,1>; // unit: sec using Speed = Value<Unit<1,0,-1>>; // meters/second type // a f-p literal suffixed by ‘_s’ constexpr Value<Second> operator "" _s(long double d) { return Value<Second> (d); } // a f-p literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(long double d) { return Value<Meter> (d); } // an integral literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(unsigned long long d) { return Value<Meter> (d); } template<int m1, int k1, int s1, int m2, int k2, int s2> Value<Unit<m1 - m2, k1 - k2, s1 - s2>> operator / (Value<Unit<m1, k1, s1>> a, Value<Unit<m2, k2, s2>> b) { return Value<Unit<m1 - m2, k1 - k2, s1 - s2>>(a.val / b.val); } int main() { Speed sp1 = 100_m / 9.8_s; std::cout << sp1.val; } ```
Not sure this is what you want, it is ugly, but it works :) You can wrap the type into a template class, ``` template <typename T, int N> // N is used for tagging struct strong_typedef { using strong_type = strong_typedef<T,N>; // typedef for the strong type using type = T; // the wrapped type T value; // the wrapped value strong_typedef(T val): value(val){}; // constructor strong_typedef(){value={};}; // default, zero-initialization // operator overloading, basic example: strong_type operator+(const strong_type& rhs) const { return value + rhs.value; } // display it friend ostream& operator<<(ostream & lhs, const strong_typedef& rhs) { lhs << rhs.value; return lhs; } }; ``` then use it as ``` // these are all different types strong_typedef<double, 0> x = 1.1; strong_typedef<double, 1> y = 2.2; strong_typedef<double, 2> z = 3.3; std::cout << x + x << std::endl; // outputs 2.2, can add x and x // cout << x + y << endl; // compile-time ERROR, different types ``` `x`, `y` and `z` are 3 different types now, because of the different `N`-s used in the template. You can access the type and value using the fields `type` and `value`, like `x::value` (will be double 1.1). Of course if you directly `typedef` the `struct_typedef::type`, you're back to square one, as you are losing the `strong` type. So basically your type should be `strong_typedef` and not `strong_typedef::type`.
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
Not sure this is what you want, it is ugly, but it works :) You can wrap the type into a template class, ``` template <typename T, int N> // N is used for tagging struct strong_typedef { using strong_type = strong_typedef<T,N>; // typedef for the strong type using type = T; // the wrapped type T value; // the wrapped value strong_typedef(T val): value(val){}; // constructor strong_typedef(){value={};}; // default, zero-initialization // operator overloading, basic example: strong_type operator+(const strong_type& rhs) const { return value + rhs.value; } // display it friend ostream& operator<<(ostream & lhs, const strong_typedef& rhs) { lhs << rhs.value; return lhs; } }; ``` then use it as ``` // these are all different types strong_typedef<double, 0> x = 1.1; strong_typedef<double, 1> y = 2.2; strong_typedef<double, 2> z = 3.3; std::cout << x + x << std::endl; // outputs 2.2, can add x and x // cout << x + y << endl; // compile-time ERROR, different types ``` `x`, `y` and `z` are 3 different types now, because of the different `N`-s used in the template. You can access the type and value using the fields `type` and `value`, like `x::value` (will be double 1.1). Of course if you directly `typedef` the `struct_typedef::type`, you're back to square one, as you are losing the `strong` type. So basically your type should be `strong_typedef` and not `strong_typedef::type`.
One alternative that does not involve typedef and is not strongly enforced by the compiler but makes it very hard for the programmer to make mistakes it to encode the unit in question as a struct member. For my arduino project I have types like ``` template <typename T> struct millisecond { T millisecond; static constexpr const struct millisecond<T> zero = { 0 }; }; template <typename T> struct microsecond { T microsecond; static constexpr const struct microsecond<T> zero = { 0 }; }; ``` and use like ``` auto time_diff = millisecond<unsigned long>::zero; time_diff.millisecond = nowMilliseconds() - s_lastPollTime.millisecond; ``` So with this strategy the compiler does not stop you from mixing units, but if you do then the error will always [scream at you](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/): ``` total_expenses.euros = expence1.euros + expence2.dollars; ```
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are several ways to solve this, but since I was looking for a fix to Bjarne's code in the presentation slides, I'm accepting this answer which @robson3.14 left in comments to the question: ``` #include <iostream> template<int M, int K, int S> struct Unit { // a unit in the MKS system enum { m=M, kg=K, s=S }; }; template<typename Unit> // a magnitude with a unit struct Value { double val; // the magnitude // construct a Value from a double constexpr explicit Value(double d) : val(d) {} }; using Meter = Unit<1,0,0>; // unit: meter using Second = Unit<0,0,1>; // unit: sec using Speed = Value<Unit<1,0,-1>>; // meters/second type // a f-p literal suffixed by ‘_s’ constexpr Value<Second> operator "" _s(long double d) { return Value<Second> (d); } // a f-p literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(long double d) { return Value<Meter> (d); } // an integral literal suffixed by ‘_m’ constexpr Value<Meter> operator "" _m(unsigned long long d) { return Value<Meter> (d); } template<int m1, int k1, int s1, int m2, int k2, int s2> Value<Unit<m1 - m2, k1 - k2, s1 - s2>> operator / (Value<Unit<m1, k1, s1>> a, Value<Unit<m2, k2, s2>> b) { return Value<Unit<m1 - m2, k1 - k2, s1 - s2>>(a.val / b.val); } int main() { Speed sp1 = 100_m / 9.8_s; std::cout << sp1.val; } ```
One alternative that does not involve typedef and is not strongly enforced by the compiler but makes it very hard for the programmer to make mistakes it to encode the unit in question as a struct member. For my arduino project I have types like ``` template <typename T> struct millisecond { T millisecond; static constexpr const struct millisecond<T> zero = { 0 }; }; template <typename T> struct microsecond { T microsecond; static constexpr const struct microsecond<T> zero = { 0 }; }; ``` and use like ``` auto time_diff = millisecond<unsigned long>::zero; time_diff.millisecond = nowMilliseconds() - s_lastPollTime.millisecond; ``` So with this strategy the compiler does not stop you from mixing units, but if you do then the error will always [scream at you](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/): ``` total_expenses.euros = expence1.euros + expence2.dollars; ```
12,243,560
I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position.... but its not detecting current position in android phone. ``` private class mylocationlistener implements LocationListener { public void onLocationChanged(Location location) { Date today = new Date(); Timestamp currentTimeStamp = new Timestamp(today.getTime()); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener ll = new mylocationlistener(); boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (isGPS){ lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); if (location != null) { Log.d("LOCATION CHANGED", location.getLatitude() + ""); Log.d("LOCATION CHANGED", location.getLongitude() + ""); String str = "\n CurrentLocation: "+ "\n Latitude: "+ location.getLatitude() + "\n Longitude: " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy() + "\n CurrentTimeStamp "+ currentTimeStamp; Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show(); tv.append(str); } else { String s1="GPS activation in process"; Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); /*alert.setTitle("gps"); alert.setMessage("GPS activation in progress,\n Please click after few second."); alert.setPositiveButton("OK", null); alert.show();*/ } } else { String s2="Enable Gps"; Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show(); } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } ``` }
2012/09/03
[ "https://Stackoverflow.com/questions/12243560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642978/" ]
I made one service for that. It is easy for get Longitude / Latitude using it. Copy/paste this class in your project. ``` package com.sample; import com.sample.globalconstant; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyServiceGPS extends Service { private static final String TAG = "BOOMBOOMTESTGPS"; private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 10f; private class LocationListener implements android.location.LocationListener{ Location mLastLocation; public LocationListener(String provider) { Log.e(TAG, "LocationListener " + provider); mLastLocation = new Location(provider); } public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude()); globalconstant.lat = location.getLatitude(); globalconstant.lon = location.getLongitude(); Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show(); mLastLocation.set(location); } public void onProviderDisabled(String provider) { Log.e(TAG, "onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { Log.e(TAG, "onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(TAG, "onStatusChanged: " + provider); } } LocationListener[] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, "onCreate"); initializeLocationManager(); try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "gps provider does not exist " + ex.getMessage()); } } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } } private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager"); if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } } } ``` Copy this code in your Activity when you want to start: ``` startService(new Intent(this,MyServiceGPS.class)); ``` Create one class globalconstant: ``` public class globalconstant { public static double lat, lon; } ``` when you want to current latitude and longitude in your project only write this `globalconstant.lat ,globalconstant.lon` Add `uses-permission in Manifest`
If you want to overlay of your current location then it is better to use default method instead of custom overlay.. Here is default overlay method of current location. ``` MyLocationOverlay mMyLocationOverlay = new MyLocationOverlay(getApplicationContext(), Your_MapView); mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.onProviderEnabled(LocationManager.NETWORK_PROVIDER); mapOverlays = map_view.getOverlays(); ``` you can also use GPS ``` mMyLocationOverlay.onProviderEnabled(LocationManager.GPS_PROVIDER); ```
12,243,560
I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position.... but its not detecting current position in android phone. ``` private class mylocationlistener implements LocationListener { public void onLocationChanged(Location location) { Date today = new Date(); Timestamp currentTimeStamp = new Timestamp(today.getTime()); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener ll = new mylocationlistener(); boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (isGPS){ lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); if (location != null) { Log.d("LOCATION CHANGED", location.getLatitude() + ""); Log.d("LOCATION CHANGED", location.getLongitude() + ""); String str = "\n CurrentLocation: "+ "\n Latitude: "+ location.getLatitude() + "\n Longitude: " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy() + "\n CurrentTimeStamp "+ currentTimeStamp; Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show(); tv.append(str); } else { String s1="GPS activation in process"; Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); /*alert.setTitle("gps"); alert.setMessage("GPS activation in progress,\n Please click after few second."); alert.setPositiveButton("OK", null); alert.show();*/ } } else { String s2="Enable Gps"; Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show(); } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } ``` }
2012/09/03
[ "https://Stackoverflow.com/questions/12243560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642978/" ]
I made one service for that. It is easy for get Longitude / Latitude using it. Copy/paste this class in your project. ``` package com.sample; import com.sample.globalconstant; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyServiceGPS extends Service { private static final String TAG = "BOOMBOOMTESTGPS"; private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 10f; private class LocationListener implements android.location.LocationListener{ Location mLastLocation; public LocationListener(String provider) { Log.e(TAG, "LocationListener " + provider); mLastLocation = new Location(provider); } public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude()); globalconstant.lat = location.getLatitude(); globalconstant.lon = location.getLongitude(); Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show(); mLastLocation.set(location); } public void onProviderDisabled(String provider) { Log.e(TAG, "onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { Log.e(TAG, "onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(TAG, "onStatusChanged: " + provider); } } LocationListener[] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, "onCreate"); initializeLocationManager(); try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "gps provider does not exist " + ex.getMessage()); } } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } } private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager"); if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } } } ``` Copy this code in your Activity when you want to start: ``` startService(new Intent(this,MyServiceGPS.class)); ``` Create one class globalconstant: ``` public class globalconstant { public static double lat, lon; } ``` when you want to current latitude and longitude in your project only write this `globalconstant.lat ,globalconstant.lon` Add `uses-permission in Manifest`
you can use this [Example for Finding Location Periodically](https://github.com/commonsguy/cwac-locpoll)
12,243,560
I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position.... but its not detecting current position in android phone. ``` private class mylocationlistener implements LocationListener { public void onLocationChanged(Location location) { Date today = new Date(); Timestamp currentTimeStamp = new Timestamp(today.getTime()); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener ll = new mylocationlistener(); boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (isGPS){ lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); if (location != null) { Log.d("LOCATION CHANGED", location.getLatitude() + ""); Log.d("LOCATION CHANGED", location.getLongitude() + ""); String str = "\n CurrentLocation: "+ "\n Latitude: "+ location.getLatitude() + "\n Longitude: " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy() + "\n CurrentTimeStamp "+ currentTimeStamp; Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show(); tv.append(str); } else { String s1="GPS activation in process"; Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); /*alert.setTitle("gps"); alert.setMessage("GPS activation in progress,\n Please click after few second."); alert.setPositiveButton("OK", null); alert.show();*/ } } else { String s2="Enable Gps"; Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show(); } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } ``` }
2012/09/03
[ "https://Stackoverflow.com/questions/12243560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642978/" ]
I made one service for that. It is easy for get Longitude / Latitude using it. Copy/paste this class in your project. ``` package com.sample; import com.sample.globalconstant; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyServiceGPS extends Service { private static final String TAG = "BOOMBOOMTESTGPS"; private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 10f; private class LocationListener implements android.location.LocationListener{ Location mLastLocation; public LocationListener(String provider) { Log.e(TAG, "LocationListener " + provider); mLastLocation = new Location(provider); } public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude()); globalconstant.lat = location.getLatitude(); globalconstant.lon = location.getLongitude(); Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show(); mLastLocation.set(location); } public void onProviderDisabled(String provider) { Log.e(TAG, "onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { Log.e(TAG, "onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(TAG, "onStatusChanged: " + provider); } } LocationListener[] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, "onCreate"); initializeLocationManager(); try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "gps provider does not exist " + ex.getMessage()); } } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } } private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager"); if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } } } ``` Copy this code in your Activity when you want to start: ``` startService(new Intent(this,MyServiceGPS.class)); ``` Create one class globalconstant: ``` public class globalconstant { public static double lat, lon; } ``` when you want to current latitude and longitude in your project only write this `globalconstant.lat ,globalconstant.lon` Add `uses-permission in Manifest`
Is it possible that your android phone is not getting a GPS signal? locationManager.getLastKnownLocation will return null if the GPS has not had time to get a fix yet. Android does not provide a 'give me the location now' method. When the GPS has got a fix, the onLocationChanged() will run. If it is fine with emulator, then there is some problem with the device. Checkout my question [Not able to get Location by GPS : Android](https://stackoverflow.com/questions/12028117/not-able-to-get-location-by-gps-android) I had similar problem. What happened with me was that I was receiving location in google maps by network provider. Are you sure you are receiving it through GPS?
588,732
I am using OSX 10.7.5 and my OSX is becoming a bit unresponsive, comparing to what it was like before. Sometimes just opening new window of browser or terminal takes few seconds or the Dock hovering effect is not fluent. At these moments I watch system resources and I still have 3G of memory free and the processor is not used at all. Can it be caused by hard drive or other IO? How can I found out which application is causing this?
2013/04/28
[ "https://superuser.com/questions/588732", "https://superuser.com", "https://superuser.com/users/128678/" ]
Use `top` to monitor system resources. As you mention issues with opening the browser possibly there is malware active or some other agent which is causing unwarranted network activity. To monitor this use-: ``` ifconfig -a # for the network interface name to monitor ``` then ``` tcpdump -i <interface> ``` An alternative for network monitoring is `nettop` - a command line tool which I believe is available from Lion version. It's available from Apple store.
Check the logs for clues. Even a high volume of relatively harmless error messages (itself an error!), could swamp your response time. Edit: /var/log/system.log and /var/log/kernel.log would be most likely. Or open the Console app in Utilities and show all messages.
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I don't believe you *can* get that information directly from MATLAB, short of printing something with each iteration and counting these lines by hand. To see why, recall that each `parfor` iteration executes in its own workspace: while incrementing a counter within the loop is legal, accessing its "current" value is not (because this value does not really exist until completion of the loop). Furthermore, the `parfor` construct does not guarantee any particular execution order, so printing the iterator value isn't helpful. ``` cnt = 0; parfor i=1:n cnt = cnt + 1; % legal disp(cnt); % illegal disp(i); % legal ofc. but out of order end ``` Maybe someone does have a clever workaround, but I think that the independent nature of the `parfor` iterations belies taking a reliable count. The restrictions mentioned above, plus those on using `evalin`, etc. support this conclusion. As @Jonas suggested, you could obtain the iteration count via side effects occurring outside of MATLAB, e.g. creating empty files in a certain directory and counting them. This you can do in MATLAB of course: ``` fid = fopen(['countingDir/f' num2str(i)],'w'); fclose(fid); length(dir('countingDir')); ```
Try this FEX file: <http://www.mathworks.com/matlabcentral/fileexchange/32101-progress-monitor--progress-bar--that-works-with-parfor> You can easily modify it to return the iteration number instead of displaying a progress bar.
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
With Matlab 2017a or later you can use a [data queue](https://se.mathworks.com/help/distcomp/parallel.pool.dataqueue.html) or a [pollable data queue](https://se.mathworks.com/help/distcomp/parallel.pool.pollabledataqueue.html) to achieve this. Here's the MathWorks documentation example of how to do a progress bar from the first link : ``` function a = parforWaitbar D = parallel.pool.DataQueue; h = waitbar(0, 'Please wait ...'); afterEach(D, @nUpdateWaitbar); N = 200; p = 1; parfor i = 1:N a(i) = max(abs(eig(rand(400)))); send(D, i); end function nUpdateWaitbar(~) waitbar(p/N, h); p = p + 1; end end ``` End result : [![A picture of the resulting wait bar](https://i.stack.imgur.com/bLeIQ.jpg)](https://i.stack.imgur.com/bLeIQ.jpg)
I created a utility to do this: <http://www.mathworks.com/matlabcentral/fileexchange/48705-drdan14-parforprogress>
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I don't believe you *can* get that information directly from MATLAB, short of printing something with each iteration and counting these lines by hand. To see why, recall that each `parfor` iteration executes in its own workspace: while incrementing a counter within the loop is legal, accessing its "current" value is not (because this value does not really exist until completion of the loop). Furthermore, the `parfor` construct does not guarantee any particular execution order, so printing the iterator value isn't helpful. ``` cnt = 0; parfor i=1:n cnt = cnt + 1; % legal disp(cnt); % illegal disp(i); % legal ofc. but out of order end ``` Maybe someone does have a clever workaround, but I think that the independent nature of the `parfor` iterations belies taking a reliable count. The restrictions mentioned above, plus those on using `evalin`, etc. support this conclusion. As @Jonas suggested, you could obtain the iteration count via side effects occurring outside of MATLAB, e.g. creating empty files in a certain directory and counting them. This you can do in MATLAB of course: ``` fid = fopen(['countingDir/f' num2str(i)],'w'); fclose(fid); length(dir('countingDir')); ```
I created a utility to do this: <http://www.mathworks.com/matlabcentral/fileexchange/48705-drdan14-parforprogress>
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
Something like a progress bar could be done similar to this... Before the `parfor` loop : ``` fprintf('Progress:\n'); fprintf(['\n' repmat('.',1,m) '\n\n']); ``` And during the loop: ``` fprintf('\b|\n'); ``` Here we have `m` is the total number of iterations, the `.` shows the total number of iterations and `|` shows the number of iterations completed. The `\n` makes sure the characters are printed in the `parfor` loop.
If you just want to know how much time is left approximately, you can run the program once record the max time and then do this ``` tStart = tic; parfor i=1:n tElapsed = toc(tStart;) disp(['Time left in min ~ ', num2str( ( tMax - tElapsed ) / 60 ) ]); ... end ```
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I don't believe you *can* get that information directly from MATLAB, short of printing something with each iteration and counting these lines by hand. To see why, recall that each `parfor` iteration executes in its own workspace: while incrementing a counter within the loop is legal, accessing its "current" value is not (because this value does not really exist until completion of the loop). Furthermore, the `parfor` construct does not guarantee any particular execution order, so printing the iterator value isn't helpful. ``` cnt = 0; parfor i=1:n cnt = cnt + 1; % legal disp(cnt); % illegal disp(i); % legal ofc. but out of order end ``` Maybe someone does have a clever workaround, but I think that the independent nature of the `parfor` iterations belies taking a reliable count. The restrictions mentioned above, plus those on using `evalin`, etc. support this conclusion. As @Jonas suggested, you could obtain the iteration count via side effects occurring outside of MATLAB, e.g. creating empty files in a certain directory and counting them. This you can do in MATLAB of course: ``` fid = fopen(['countingDir/f' num2str(i)],'w'); fclose(fid); length(dir('countingDir')); ```
Something like a progress bar could be done similar to this... Before the `parfor` loop : ``` fprintf('Progress:\n'); fprintf(['\n' repmat('.',1,m) '\n\n']); ``` And during the loop: ``` fprintf('\b|\n'); ``` Here we have `m` is the total number of iterations, the `.` shows the total number of iterations and `|` shows the number of iterations completed. The `\n` makes sure the characters are printed in the `parfor` loop.
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
Try this FEX file: <http://www.mathworks.com/matlabcentral/fileexchange/32101-progress-monitor--progress-bar--that-works-with-parfor> You can easily modify it to return the iteration number instead of displaying a progress bar.
If you just want to know how much time is left approximately, you can run the program once record the max time and then do this ``` tStart = tic; parfor i=1:n tElapsed = toc(tStart;) disp(['Time left in min ~ ', num2str( ( tMax - tElapsed ) / 60 ) ]); ... end ```
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
Try this FEX file: <http://www.mathworks.com/matlabcentral/fileexchange/32101-progress-monitor--progress-bar--that-works-with-parfor> You can easily modify it to return the iteration number instead of displaying a progress bar.
I created a utility to do this: <http://www.mathworks.com/matlabcentral/fileexchange/48705-drdan14-parforprogress>
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
With Matlab 2017a or later you can use a [data queue](https://se.mathworks.com/help/distcomp/parallel.pool.dataqueue.html) or a [pollable data queue](https://se.mathworks.com/help/distcomp/parallel.pool.pollabledataqueue.html) to achieve this. Here's the MathWorks documentation example of how to do a progress bar from the first link : ``` function a = parforWaitbar D = parallel.pool.DataQueue; h = waitbar(0, 'Please wait ...'); afterEach(D, @nUpdateWaitbar); N = 200; p = 1; parfor i = 1:N a(i) = max(abs(eig(rand(400)))); send(D, i); end function nUpdateWaitbar(~) waitbar(p/N, h); p = p + 1; end end ``` End result : [![A picture of the resulting wait bar](https://i.stack.imgur.com/bLeIQ.jpg)](https://i.stack.imgur.com/bLeIQ.jpg)
If you just want to know how much time is left approximately, you can run the program once record the max time and then do this ``` tStart = tic; parfor i=1:n tElapsed = toc(tStart;) disp(['Time left in min ~ ', num2str( ( tMax - tElapsed ) / 60 ) ]); ... end ```
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I don't believe you *can* get that information directly from MATLAB, short of printing something with each iteration and counting these lines by hand. To see why, recall that each `parfor` iteration executes in its own workspace: while incrementing a counter within the loop is legal, accessing its "current" value is not (because this value does not really exist until completion of the loop). Furthermore, the `parfor` construct does not guarantee any particular execution order, so printing the iterator value isn't helpful. ``` cnt = 0; parfor i=1:n cnt = cnt + 1; % legal disp(cnt); % illegal disp(i); % legal ofc. but out of order end ``` Maybe someone does have a clever workaround, but I think that the independent nature of the `parfor` iterations belies taking a reliable count. The restrictions mentioned above, plus those on using `evalin`, etc. support this conclusion. As @Jonas suggested, you could obtain the iteration count via side effects occurring outside of MATLAB, e.g. creating empty files in a certain directory and counting them. This you can do in MATLAB of course: ``` fid = fopen(['countingDir/f' num2str(i)],'w'); fclose(fid); length(dir('countingDir')); ```
If you just want to know how much time is left approximately, you can run the program once record the max time and then do this ``` tStart = tic; parfor i=1:n tElapsed = toc(tStart;) disp(['Time left in min ~ ', num2str( ( tMax - tElapsed ) / 60 ) ]); ... end ```
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
Something like a progress bar could be done similar to this... Before the `parfor` loop : ``` fprintf('Progress:\n'); fprintf(['\n' repmat('.',1,m) '\n\n']); ``` And during the loop: ``` fprintf('\b|\n'); ``` Here we have `m` is the total number of iterations, the `.` shows the total number of iterations and `|` shows the number of iterations completed. The `\n` makes sure the characters are printed in the `parfor` loop.
I created a utility to do this: <http://www.mathworks.com/matlabcentral/fileexchange/48705-drdan14-parforprogress>
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
Since I didn't notice the "without jQuery" in the original question, here is a new answer: ``` var request = new XMLHttpRequest(); request.open('GET', './test.json', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; ``` It does two things: 1. Loads the json file 2. Parses the loaded string into a javascript object.
Before you can even do anything with your JSON file, you need to load it. jQuery has a shortcut, which will even automatically parse the JSON-string into a native JS object for you: ``` $.getJSON('./test.json', function(data) { console.dir(data); }); ``` <https://api.jquery.com/jquery.getjson/>
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
I just need to fill my array "groups" like that : ``` [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` with a json file and without jquery
Before you can even do anything with your JSON file, you need to load it. jQuery has a shortcut, which will even automatically parse the JSON-string into a native JS object for you: ``` $.getJSON('./test.json', function(data) { console.dir(data); }); ``` <https://api.jquery.com/jquery.getjson/>
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```
Since I didn't notice the "without jQuery" in the original question, here is a new answer: ``` var request = new XMLHttpRequest(); request.open('GET', './test.json', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; ``` It does two things: 1. Loads the json file 2. Parses the loaded string into a javascript object.
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
I just need to fill my array "groups" like that : ``` [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` with a json file and without jquery
if you can't edit original text, you need replace ' to " and then did `JSON.parse(json.groups)`; otherwise you can change a little your json like this: ``` JSON.parse('[{ "id": 1, "title": "group 1" }, { "id": 2, "title": "group 2" }]') ``` be careful with " and ' parentheses ``` { "key":"string" } ``` string with defined with ' parentheses not valid in JSON keys must be to in "" parentheses
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
Since I didn't notice the "without jQuery" in the original question, here is a new answer: ``` var request = new XMLHttpRequest(); request.open('GET', './test.json', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; ``` It does two things: 1. Loads the json file 2. Parses the loaded string into a javascript object.
You can parse the object to an array this way: `Object.values(YOUR_OBJECT)` docs: <https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/values>
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```
Before you can even do anything with your JSON file, you need to load it. jQuery has a shortcut, which will even automatically parse the JSON-string into a native JS object for you: ``` $.getJSON('./test.json', function(data) { console.dir(data); }); ``` <https://api.jquery.com/jquery.getjson/>
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```
if you can't edit original text, you need replace ' to " and then did `JSON.parse(json.groups)`; otherwise you can change a little your json like this: ``` JSON.parse('[{ "id": 1, "title": "group 1" }, { "id": 2, "title": "group 2" }]') ``` be careful with " and ' parentheses ``` { "key":"string" } ``` string with defined with ' parentheses not valid in JSON keys must be to in "" parentheses
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```
I just need to fill my array "groups" like that : ``` [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` with a json file and without jquery
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
Since I didn't notice the "without jQuery" in the original question, here is a new answer: ``` var request = new XMLHttpRequest(); request.open('GET', './test.json', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; ``` It does two things: 1. Loads the json file 2. Parses the loaded string into a javascript object.
if you can't edit original text, you need replace ' to " and then did `JSON.parse(json.groups)`; otherwise you can change a little your json like this: ``` JSON.parse('[{ "id": 1, "title": "group 1" }, { "id": 2, "title": "group 2" }]') ``` be careful with " and ' parentheses ``` { "key":"string" } ``` string with defined with ' parentheses not valid in JSON keys must be to in "" parentheses
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```
You can parse the object to an array this way: `Object.values(YOUR_OBJECT)` docs: <https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/values>
3,214
For Category theory there is a well known and quite active research mailing list <https://www.mta.ca/~cat-dist/> Do similar mailing lists or usenet groups exist for other branches of mathematics? For example in metric geometry, conformal geometry,... Or do most research related discussions now take place on MO?
2017/04/18
[ "https://meta.mathoverflow.net/questions/3214", "https://meta.mathoverflow.net", "https://meta.mathoverflow.net/users/54495/" ]
Here is a list of some mailing list for specific areas of mathematics. (This is posted as a [community wiki](https://meta.mathoverflow.net/tags/community-wiki/info), if you are aware of some other mailings lists, do not hesitate to add them to the list. And also if you have some additional useful information related to some of the lists.) * FOM -- Foundations of Mathematics - [basic info](http://www.cs.nyu.edu/mailman/listinfo/fom), [archive](http://cs.nyu.edu/pipermail/fom/). This mailing list has been mentioned quite often [in MO posts](https://www.google.com/search?q=pipermail+fom+site:mathoverflow.net) and [elsewhere](https://www.google.com/search?q=pipermail+fom), including citations in some [books](http://books.google.com/books?q=pipermail+fom) and [papers](https://scholar.google.com/scholar?hl=en&q=pipermail+fom). * Banach -- Banach Space Theory News - [basic info](https://www.mathdept.okstate.edu/cgi-bin/mailman/listinfo/banach), [archive](https://www.mathdept.okstate.edu/pipermail/banach/) * ALGTOP-L -- Algebraic Topology Discussion Group - [basic info](https://lists.lehigh.edu/mailman/listinfo/algtop-l), [archive](https://lists.lehigh.edu/pipermail/algtop-l/) * Categories List (category theory) - [basic info](https://www.mta.ca/~cat-dist/), [archive until 2009](https://www.mta.ca/~cat-dist/#archives) * ~~Real Analysis List~~ - [basic info](http://www.math.louisville.edu/~lee/rae/rafaq.html) (now very likely defunct - see [GEdgar's comment](https://meta.mathoverflow.net/questions/3214/mailing-lists-usenet-groups-for-research-math/3219?noredirect=1#comment14271_3219))
Sci.math, sci.math.research, alt.sci.(whatever) are some of the newsgroups that dealt with mathematics and various branches. You can find histories of them and other information on them with web searches. The unmoderated groups became spam wastelands, especially after Google instituted their version called Google Groups. I left sci.math for this reason, and only looked sparingly at sci.math.research, which was moderated. When Kevin Buzzard posted in s.m.r. about MathOverflow back in 2010, I tried it, and have not looked back since. If you frequent some older web pages (using the Wayback Machine, for example), you will find references to mailing lists and other resources. It seems that blogs and forums and YouTube are the current means of idea exchange; (as I believe Gerry Myerson might say) I will be surprised if you find many active mailing lists. Gerhard "The Technologies, They Are A-Changing" Paseman, 2017.04.18.
9,439,136
I have set up the code to call a remote server from Android app to a remote server. Here is the code: ``` private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... theParams) { Log.d( "Inner class: " , "Doing stuff in background" ); String myUrl = theParams[0]; String myEmail = theParams[1]; String myPassword = theParams[2]; Log.d( "Inner myURL: " , myUrl ); Log.d( "myEmail: " , myEmail ); Log.d( "myPass: " , myPassword ); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("username", myEmail )); postParameters.add(new BasicNameValuePair("password", myPassword )); String response = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(myUrl); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } Log.d( "After call, response: " , " " + response); } catch (Exception e) { Log.d( "Exception: " , "Yup"); e.printStackTrace(); } return response; } @Override protected void onPostExecute(String result) { Log.d( "Post execute: " , "In the post-execute method" ); //textView.setText(result); if ( result != null && result == "Ok") { Log.d( "Post execute: " , "OKKKK :)" ); } else { Log.d( "Post execute: " , "NOOOT OKKKK :)" ); } } ``` } This is a request to be authenticated and logged in. Right now as you can see, I am collecting a login and password from the user, but not sure how to best attach that to the request URL. I can just do something like urlString + "?login=login&pass=pass but I was wondering whether there is a "good practice" way of doing this in the Android environment? Also, my url is not htpps - is there a way to make it secure? Thanks!
2012/02/24
[ "https://Stackoverflow.com/questions/9439136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731255/" ]
This is **not** secure. Your URL is passed through the internet most likely through several hops unencrypted. It is trivially simple to sniff these requests. The simplest way is to send this data in the message body using HttpPost and use HTTPS. If you must use HTTP, try [digest authentication](http://en.wikipedia.org/wiki/Digest_access_authentication) explained here: [how to use Digest authentication in android?](https://stackoverflow.com/questions/6704607/how-to-use-digest-authentication-in-android)
Had to answer just to comment on Heesham Saeed's "answer" (which is actually a directive to screw any sense of security your App may ever have): A mobile phone (android included) might be a smokescreen to simple-minded people but it is NOT a black-box that someone with technical ability cannot see into. The URL sent by the phone can be seen by the User if the User inspects, say, proxy logs. The URL can be seen by strangers who inspect the logs of ANY proxy that the HTTP traffic is routed through. It's gross misunderstandings like Hesham's + the putting forward of that misunderstandings to newcomers to development that cause vulnerable Apps to be made. Next... MD5 is NOT encryption! MD5 cannot be decrypted! Holy shit, get a clue before you talk like you have a clue! MD5 is a one-way hashing algorithm. Any MD5 hash can be reversed using Rainbow Tables IFF you have enough time and CPU power (and whose to say someone/something doesn't have both). Same goes for all hashing algoithms and encryption algorithms, actually - but MD5 is one of the least trivial and least time+CPU costly to reverse. MD5 is NOT a suitable means for securing data that is transmitted via unencrypted channels NOR is it suitable at all for extraction of the data on the receiving end.
30,658,916
When I execute the following code, it returns non-standard characters, so how do we remove it or get original string? ``` header('Content-type: text/html; charset=utf-8'); $String = "à¸?่อตั้งเมื่อ"; echo $String; ``` Output : `�?่อตั้งเมื่อ` Need actual result : `ก่อตั้งเมื่อ`
2015/06/05
[ "https://Stackoverflow.com/questions/30658916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979522/" ]
Your string, `�่อตั้งเมื่อ` is not valid utf-8. That is why the `�` shows up - the browser does not know how to interpret it. As others have indicated, the question mark on the third position likely is the problem. The first three bytes of the erroneous string are `e0 b8 3f` (`3f` being the ascii code `?`). I do not know any Thai, but the byte sequence for a [THAI CHARACTER KO KAI](http://www.fileformat.info/info/unicode/char/0e01/index.htm) looks pretty similar and should be`e0 b8 81`.
You mentioned character encdoing as utf-8, where as the string is not encoded as utf-8. That's the reason that "?" mark is appearing in the output instead of the intended one.
30,658,916
When I execute the following code, it returns non-standard characters, so how do we remove it or get original string? ``` header('Content-type: text/html; charset=utf-8'); $String = "à¸?่อตั้งเมื่อ"; echo $String; ``` Output : `�?่อตั้งเมื่อ` Need actual result : `ก่อตั้งเมื่อ`
2015/06/05
[ "https://Stackoverflow.com/questions/30658916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979522/" ]
Your string, `�่อตั้งเมื่อ` is not valid utf-8. That is why the `�` shows up - the browser does not know how to interpret it. As others have indicated, the question mark on the third position likely is the problem. The first three bytes of the erroneous string are `e0 b8 3f` (`3f` being the ascii code `?`). I do not know any Thai, but the byte sequence for a [THAI CHARACTER KO KAI](http://www.fileformat.info/info/unicode/char/0e01/index.htm) looks pretty similar and should be`e0 b8 81`.
First of all, to not be confused by encodings problem, you really want to read the following article: <http://kunststube.net/encoding/> Second, I just have done the following: ``` $ vim ~/sandbox/php/encoding.php ( inserted your code verbatim ) $ cd ~/sandbox/php/ $ php -S localhost:1200 ``` After I opened in Firefox the page <http://localhost:1200>, I got the contents of `$String` as they are. I mean that I got the following line of chars: ``` �่อตั้งเมื่อ ``` This means your browser, whichever it is, does not know how to render the characters you are entering to it. The string itself is being encoded in UTF-8 correctly. You have to set your browser to show the text as UTF-8, or probably install the fonts which support those symbols. Also, if you want to output, say some text with UTF-8 Devanagari symbols, you just need to satisfy the following requirements in PHP: 1. Your source code file must be saved in UTF-8. 2. You must send the utf-8 charset subheader, which you already do. 3. You must put the string you want to output to the browser *verbatim* to the source code, no need to encode it in any way, PHP does not care.