qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
49,102,300
When I trying to install keras with pip3 this message shows. ``` Requirement already satisfied: keras in /usr/local/lib/python3.5/dist-packages Requirement already satisfied: pyyaml in /usr/local/lib/python3.5/dist-packages (from keras) Requirement already satisfied: six>=1.9.0 in ./.local/lib/python3.5/site-packages (from keras) Requirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.5/dist-packages (from keras) Requirement already satisfied: numpy>=1.9.1 in ./.local/lib/python3.5/site-packages (from keras) ``` But I import keras in a project it shows this error. ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'keras' ``` How to solve this problem? I used Ubuntu 16.04 and python 3.
2018/03/05
[ "https://Stackoverflow.com/questions/49102300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5213194/" ]
Are you using a virtual environment? If so make sure to activate it. **EDIT**: To expand on what "virtual environment" means, look [here](https://conda.io/docs/user-guide/install/linux.html) and [here](https://conda.io/docs/_downloads/conda-cheatsheet.pdf) at "Conda." Conda can help you with installations in many ways; it can help you update Keras later on, it will help you manage which packages you need with which Python scripts so you don't have to write a million `import numpy as np` statements everywhere, etc. etc. There is a more in-depth, clear explanation of what Conda is [here](https://stackoverflow.com/questions/20994716/what-is-the-difference-between-pip-and-conda) Also you can see what packages are installed with: ``` pip3 freeze ```
What i would suggest is use keras in a separate environment using conda. Suppose you want to create an env named "myenv" 1.Open Anaconda promt and type the following: ``` conda create --name myenv ``` 2.To activate the environment: ``` conda activate myenv ``` 3.Now you can install keras and other dependencies: ``` pip install keras ```
2,251,752
Web programmer here - using AJAX (HTML, CSS, JavaScript, AJAX, PHP, MySQL), but for some reason Internet Explorer is acting up (surprise surprise). AJAX is updating query results on the HTML page, via a PHP script that queries a MySQL Database. Everything is working fine, except when I use Internet Explorer 8.0 . There are several php scripts, which allow for the data to be ordered according to certain criteria, and for testing purposes I have attached the mktime field (current time, in the format HH:MM:SS) to the beginning of the results for each query. When I use IE, these times appear to remain constant, whereas with ALL other browsers these times are correct and display the current time. I think the issue has something to do with caching or something along those lines anyway. Any thoughts or suggestions welcome...
2010/02/12
[ "https://Stackoverflow.com/questions/2251752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157991/" ]
[Here](http://ajaxian.com/archives/ajax-ie-caching-issue) is an article on the caching issue. If your request is a GET change it to a POST, this will prevent the results being cached.
GET requests are cached in IE; switch it to a POST request and it won't be cached anymore.
2,251,752
Web programmer here - using AJAX (HTML, CSS, JavaScript, AJAX, PHP, MySQL), but for some reason Internet Explorer is acting up (surprise surprise). AJAX is updating query results on the HTML page, via a PHP script that queries a MySQL Database. Everything is working fine, except when I use Internet Explorer 8.0 . There are several php scripts, which allow for the data to be ordered according to certain criteria, and for testing purposes I have attached the mktime field (current time, in the format HH:MM:SS) to the beginning of the results for each query. When I use IE, these times appear to remain constant, whereas with ALL other browsers these times are correct and display the current time. I think the issue has something to do with caching or something along those lines anyway. Any thoughts or suggestions welcome...
2010/02/12
[ "https://Stackoverflow.com/questions/2251752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157991/" ]
[Here](http://ajaxian.com/archives/ajax-ie-caching-issue) is an article on the caching issue. If your request is a GET change it to a POST, this will prevent the results being cached.
Instead of switching to POST, which can be ugly if you're not really using it to update or create content, you should append a random number to the query string, as in `http://domain.com/ajax/some-request?r=123456`. If this number is unique for every request you won't have caching problems.
2,251,752
Web programmer here - using AJAX (HTML, CSS, JavaScript, AJAX, PHP, MySQL), but for some reason Internet Explorer is acting up (surprise surprise). AJAX is updating query results on the HTML page, via a PHP script that queries a MySQL Database. Everything is working fine, except when I use Internet Explorer 8.0 . There are several php scripts, which allow for the data to be ordered according to certain criteria, and for testing purposes I have attached the mktime field (current time, in the format HH:MM:SS) to the beginning of the results for each query. When I use IE, these times appear to remain constant, whereas with ALL other browsers these times are correct and display the current time. I think the issue has something to do with caching or something along those lines anyway. Any thoughts or suggestions welcome...
2010/02/12
[ "https://Stackoverflow.com/questions/2251752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157991/" ]
[Here](http://ajaxian.com/archives/ajax-ie-caching-issue) is an article on the caching issue. If your request is a GET change it to a POST, this will prevent the results being cached.
What I have done is, I have kept the "GET" and added new dummy query parameter to the querystring as follows, ``` ./BaseServlet?sname=3d_motor&calcdir=20110514&dummyParam=datetime ``` I set *dummyParam* a value of date object in the javascript so that every time the url is generated browser will treat it as a new url and fetch new (fresh) results. ``` var d = new Date(); url = url + '&dummyParam='+d.valueOf(); ``` So instead of generating some random numbers this is easy way!
2,251,752
Web programmer here - using AJAX (HTML, CSS, JavaScript, AJAX, PHP, MySQL), but for some reason Internet Explorer is acting up (surprise surprise). AJAX is updating query results on the HTML page, via a PHP script that queries a MySQL Database. Everything is working fine, except when I use Internet Explorer 8.0 . There are several php scripts, which allow for the data to be ordered according to certain criteria, and for testing purposes I have attached the mktime field (current time, in the format HH:MM:SS) to the beginning of the results for each query. When I use IE, these times appear to remain constant, whereas with ALL other browsers these times are correct and display the current time. I think the issue has something to do with caching or something along those lines anyway. Any thoughts or suggestions welcome...
2010/02/12
[ "https://Stackoverflow.com/questions/2251752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157991/" ]
GET requests are cached in IE; switch it to a POST request and it won't be cached anymore.
What I have done is, I have kept the "GET" and added new dummy query parameter to the querystring as follows, ``` ./BaseServlet?sname=3d_motor&calcdir=20110514&dummyParam=datetime ``` I set *dummyParam* a value of date object in the javascript so that every time the url is generated browser will treat it as a new url and fetch new (fresh) results. ``` var d = new Date(); url = url + '&dummyParam='+d.valueOf(); ``` So instead of generating some random numbers this is easy way!
2,251,752
Web programmer here - using AJAX (HTML, CSS, JavaScript, AJAX, PHP, MySQL), but for some reason Internet Explorer is acting up (surprise surprise). AJAX is updating query results on the HTML page, via a PHP script that queries a MySQL Database. Everything is working fine, except when I use Internet Explorer 8.0 . There are several php scripts, which allow for the data to be ordered according to certain criteria, and for testing purposes I have attached the mktime field (current time, in the format HH:MM:SS) to the beginning of the results for each query. When I use IE, these times appear to remain constant, whereas with ALL other browsers these times are correct and display the current time. I think the issue has something to do with caching or something along those lines anyway. Any thoughts or suggestions welcome...
2010/02/12
[ "https://Stackoverflow.com/questions/2251752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157991/" ]
Instead of switching to POST, which can be ugly if you're not really using it to update or create content, you should append a random number to the query string, as in `http://domain.com/ajax/some-request?r=123456`. If this number is unique for every request you won't have caching problems.
What I have done is, I have kept the "GET" and added new dummy query parameter to the querystring as follows, ``` ./BaseServlet?sname=3d_motor&calcdir=20110514&dummyParam=datetime ``` I set *dummyParam* a value of date object in the javascript so that every time the url is generated browser will treat it as a new url and fetch new (fresh) results. ``` var d = new Date(); url = url + '&dummyParam='+d.valueOf(); ``` So instead of generating some random numbers this is easy way!
41,741,798
In Unity, I would like to use the slider in my canvas but only the handle. A default behaviour is that if the user clicks on a certain point in the slider , the handle will jump right to that point. I would like to disable this behaviour, allowing the user only to drag the handle to move it. How can this be done? Thank you.
2017/01/19
[ "https://Stackoverflow.com/questions/41741798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871855/" ]
Simply uncheck the *Raycast Target* property of the **Image** component located on the *Background* **GameObject**. Otherwise you could always override the **Slider** class to fit your need but i guess this would be a bit overkill in your case. Hope this helps,
Disable interactable checkbox in inspector. This option added with new versions.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
These are the rules I follow: 1. If in your header file, you only need to use pointers to classes declared in the header file you are including, then I would just use a `class` sentence on the header file (`.h`) and full import on the definition (`.m`) file. 2. If you need to use full definition of some stuff on the header file you are including, then the full import goes into the header file. For the examples, consider files `MyClass.m`, `MyClass.h` and `MyInclude.h`: Example, scenario #1: ``` // MyClass.h @class MyInclude; @interface MyClass : NSObject { MyInclude *myIncludeObj; } // MyClass.m #import "MyClass.h" #import "MyInclude.h" ``` Exaple, scenario #2: ``` // MyClass.h #import "MyInclude.h" @interface MyClass : NSObject { MyInclude myIncludeObj; // MyInclude could be a plain C structure } // MyClass.m #import "MyClass.h" ```
Best practices is to put #import statements in .m files. If you need access to a class inside the header file, for a property declaration or a function parameter, use a forward declaration, like this: ``` @class Cocos2DController; @interface HoppersAppDelegate : NSObject <UIApplicationDelegate> { Cocos2DController* controller; } ``` A forward declaration lets the system know that the class exists, though it's not yet fully defined. With this pattern, you'll keep your headers lean, and guarantee that you're only importing the headers that you want for a specific class, not chaining #imports all through the application. For a specific problem you might run into: If you include #import statements in a header file, you run the risk of an #import loop if two classes import each other's header files.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
These are the rules I follow: 1. If in your header file, you only need to use pointers to classes declared in the header file you are including, then I would just use a `class` sentence on the header file (`.h`) and full import on the definition (`.m`) file. 2. If you need to use full definition of some stuff on the header file you are including, then the full import goes into the header file. For the examples, consider files `MyClass.m`, `MyClass.h` and `MyInclude.h`: Example, scenario #1: ``` // MyClass.h @class MyInclude; @interface MyClass : NSObject { MyInclude *myIncludeObj; } // MyClass.m #import "MyClass.h" #import "MyInclude.h" ``` Exaple, scenario #2: ``` // MyClass.h #import "MyInclude.h" @interface MyClass : NSObject { MyInclude myIncludeObj; // MyInclude could be a plain C structure } // MyClass.m #import "MyClass.h" ```
The #import directive is an improvement over the #include directive in that instead of blindly copying the file in place, it will not include it if it has already been included. Therefore you shouldn't experience any problems with #import-ing the same file multiple times. As far as best practice goes, IMHO it's best to keep the scope as narrow as possible. Therefore I'd suggest putting your #imports in you implementation files (.m). If you require the class definition in your interface file (.h) then you can use the @class MyClass; construct to inform the compiler that it will be able to find the relevant header in the implementation file. Hope this helps.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
Unless it affects the interface definition you should put it in the .m file. If you just *use* a class, use a forward declaration: ``` @class AClass; @interface Bob : NSObject { AClass* a; } ``` If you *implement* something, then import it: ``` #import "SomeProtocol.h" @interface Bob : NSObject<SomeProtocol> { } ``` These kinds of thing are really "best practice" rather than absolutely essential. Objective C's `#import` directive means that you can't get errors because you include a file multiple times, so it's not *technically* a problem, but it will increase compile times.
These are the rules I follow: 1. If in your header file, you only need to use pointers to classes declared in the header file you are including, then I would just use a `class` sentence on the header file (`.h`) and full import on the definition (`.m`) file. 2. If you need to use full definition of some stuff on the header file you are including, then the full import goes into the header file. For the examples, consider files `MyClass.m`, `MyClass.h` and `MyInclude.h`: Example, scenario #1: ``` // MyClass.h @class MyInclude; @interface MyClass : NSObject { MyInclude *myIncludeObj; } // MyClass.m #import "MyClass.h" #import "MyInclude.h" ``` Exaple, scenario #2: ``` // MyClass.h #import "MyInclude.h" @interface MyClass : NSObject { MyInclude myIncludeObj; // MyInclude could be a plain C structure } // MyClass.m #import "MyClass.h" ```
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
These are the rules I follow: 1. If in your header file, you only need to use pointers to classes declared in the header file you are including, then I would just use a `class` sentence on the header file (`.h`) and full import on the definition (`.m`) file. 2. If you need to use full definition of some stuff on the header file you are including, then the full import goes into the header file. For the examples, consider files `MyClass.m`, `MyClass.h` and `MyInclude.h`: Example, scenario #1: ``` // MyClass.h @class MyInclude; @interface MyClass : NSObject { MyInclude *myIncludeObj; } // MyClass.m #import "MyClass.h" #import "MyInclude.h" ``` Exaple, scenario #2: ``` // MyClass.h #import "MyInclude.h" @interface MyClass : NSObject { MyInclude myIncludeObj; // MyInclude could be a plain C structure } // MyClass.m #import "MyClass.h" ```
I have just one rule: Import at the top of the .h file for the superclass and protocols of any classes you declare in the .h file. This is because any file that imports your .h file also needs the declarations for the superclass and protocols. This is also why the default Xcode template has `#import <UIKit/UIKit.h>` in the .h file rather than the .m file. For everything else (e.g. types used for ivars and method parameters), use forward-declarations and put the #import in the .m file Another way to put this is: *never use forward declarations for superclasses and protocols.*
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
The #import directive is an improvement over the #include directive in that instead of blindly copying the file in place, it will not include it if it has already been included. Therefore you shouldn't experience any problems with #import-ing the same file multiple times. As far as best practice goes, IMHO it's best to keep the scope as narrow as possible. Therefore I'd suggest putting your #imports in you implementation files (.m). If you require the class definition in your interface file (.h) then you can use the @class MyClass; construct to inform the compiler that it will be able to find the relevant header in the implementation file. Hope this helps.
Best practices is to put #import statements in .m files. If you need access to a class inside the header file, for a property declaration or a function parameter, use a forward declaration, like this: ``` @class Cocos2DController; @interface HoppersAppDelegate : NSObject <UIApplicationDelegate> { Cocos2DController* controller; } ``` A forward declaration lets the system know that the class exists, though it's not yet fully defined. With this pattern, you'll keep your headers lean, and guarantee that you're only importing the headers that you want for a specific class, not chaining #imports all through the application. For a specific problem you might run into: If you include #import statements in a header file, you run the risk of an #import loop if two classes import each other's header files.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
Unless it affects the interface definition you should put it in the .m file. If you just *use* a class, use a forward declaration: ``` @class AClass; @interface Bob : NSObject { AClass* a; } ``` If you *implement* something, then import it: ``` #import "SomeProtocol.h" @interface Bob : NSObject<SomeProtocol> { } ``` These kinds of thing are really "best practice" rather than absolutely essential. Objective C's `#import` directive means that you can't get errors because you include a file multiple times, so it's not *technically* a problem, but it will increase compile times.
Best practices is to put #import statements in .m files. If you need access to a class inside the header file, for a property declaration or a function parameter, use a forward declaration, like this: ``` @class Cocos2DController; @interface HoppersAppDelegate : NSObject <UIApplicationDelegate> { Cocos2DController* controller; } ``` A forward declaration lets the system know that the class exists, though it's not yet fully defined. With this pattern, you'll keep your headers lean, and guarantee that you're only importing the headers that you want for a specific class, not chaining #imports all through the application. For a specific problem you might run into: If you include #import statements in a header file, you run the risk of an #import loop if two classes import each other's header files.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
I have just one rule: Import at the top of the .h file for the superclass and protocols of any classes you declare in the .h file. This is because any file that imports your .h file also needs the declarations for the superclass and protocols. This is also why the default Xcode template has `#import <UIKit/UIKit.h>` in the .h file rather than the .m file. For everything else (e.g. types used for ivars and method parameters), use forward-declarations and put the #import in the .m file Another way to put this is: *never use forward declarations for superclasses and protocols.*
Best practices is to put #import statements in .m files. If you need access to a class inside the header file, for a property declaration or a function parameter, use a forward declaration, like this: ``` @class Cocos2DController; @interface HoppersAppDelegate : NSObject <UIApplicationDelegate> { Cocos2DController* controller; } ``` A forward declaration lets the system know that the class exists, though it's not yet fully defined. With this pattern, you'll keep your headers lean, and guarantee that you're only importing the headers that you want for a specific class, not chaining #imports all through the application. For a specific problem you might run into: If you include #import statements in a header file, you run the risk of an #import loop if two classes import each other's header files.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
Unless it affects the interface definition you should put it in the .m file. If you just *use* a class, use a forward declaration: ``` @class AClass; @interface Bob : NSObject { AClass* a; } ``` If you *implement* something, then import it: ``` #import "SomeProtocol.h" @interface Bob : NSObject<SomeProtocol> { } ``` These kinds of thing are really "best practice" rather than absolutely essential. Objective C's `#import` directive means that you can't get errors because you include a file multiple times, so it's not *technically* a problem, but it will increase compile times.
The #import directive is an improvement over the #include directive in that instead of blindly copying the file in place, it will not include it if it has already been included. Therefore you shouldn't experience any problems with #import-ing the same file multiple times. As far as best practice goes, IMHO it's best to keep the scope as narrow as possible. Therefore I'd suggest putting your #imports in you implementation files (.m). If you require the class definition in your interface file (.h) then you can use the @class MyClass; construct to inform the compiler that it will be able to find the relevant header in the implementation file. Hope this helps.
4,325,778
I have several reports that are from SSAS 2008, but one of them has to drill through to a SQL Server report simply because the data is far to granular for a cube. Any tips on passing parameters? Of course they are passed in as MDX, and I can't figure out a way to get just the "Key" with the source MDX. Surprisingly I can't find a lot of pointers on this. Let me know if this is too vague...
2010/12/01
[ "https://Stackoverflow.com/questions/4325778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388058/" ]
Unless it affects the interface definition you should put it in the .m file. If you just *use* a class, use a forward declaration: ``` @class AClass; @interface Bob : NSObject { AClass* a; } ``` If you *implement* something, then import it: ``` #import "SomeProtocol.h" @interface Bob : NSObject<SomeProtocol> { } ``` These kinds of thing are really "best practice" rather than absolutely essential. Objective C's `#import` directive means that you can't get errors because you include a file multiple times, so it's not *technically* a problem, but it will increase compile times.
I have just one rule: Import at the top of the .h file for the superclass and protocols of any classes you declare in the .h file. This is because any file that imports your .h file also needs the declarations for the superclass and protocols. This is also why the default Xcode template has `#import <UIKit/UIKit.h>` in the .h file rather than the .m file. For everything else (e.g. types used for ivars and method parameters), use forward-declarations and put the #import in the .m file Another way to put this is: *never use forward declarations for superclasses and protocols.*
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
The JDBC driver jar (and any jars it depends on) should go in your Oozie sharelib folder on HDFS. I'm running Hortonworks Data Platform 1.2 instead of Cloudera 4.2 so the details may vary, but my JDBC driver is located in `/user/oozie/share/lib/sqoop`. This should allow you to run Sqoop with the JDBC via Oozie. It is not necessary to put to the JDBC driver jar in the sqoop lib on the data nodes. In my setupt I can't run a simple `sqoop eval` from the command line on my data nodes. I understand the logic for why you thought this would work. The reason the JDBC driver jar needs to be on HDFS is so that all the data nodes have access to it. Your solution should accomplish the same goal. I'm not familiar enough with the inner workings of Oozie to say why using the sharelib works but your solution does not.
If you are using CDH-5 the JDBC driver jar (and any jars it depends on) should go in '/user/oozie/share/lib/lib\_timestamp/sqoop' folder on HDFS.
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
The JDBC driver jar (and any jars it depends on) should go in your Oozie sharelib folder on HDFS. I'm running Hortonworks Data Platform 1.2 instead of Cloudera 4.2 so the details may vary, but my JDBC driver is located in `/user/oozie/share/lib/sqoop`. This should allow you to run Sqoop with the JDBC via Oozie. It is not necessary to put to the JDBC driver jar in the sqoop lib on the data nodes. In my setupt I can't run a simple `sqoop eval` from the command line on my data nodes. I understand the logic for why you thought this would work. The reason the JDBC driver jar needs to be on HDFS is so that all the data nodes have access to it. Your solution should accomplish the same goal. I'm not familiar enough with the inner workings of Oozie to say why using the sharelib works but your solution does not.
In CDH5, you should put the jar to '/user/oozie/share/lib/lib\_${timestamp}/sqoop', and after that, you must update the sharelib or restart oozie. update sharelib: `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate`
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
The JDBC driver jar (and any jars it depends on) should go in your Oozie sharelib folder on HDFS. I'm running Hortonworks Data Platform 1.2 instead of Cloudera 4.2 so the details may vary, but my JDBC driver is located in `/user/oozie/share/lib/sqoop`. This should allow you to run Sqoop with the JDBC via Oozie. It is not necessary to put to the JDBC driver jar in the sqoop lib on the data nodes. In my setupt I can't run a simple `sqoop eval` from the command line on my data nodes. I understand the logic for why you thought this would work. The reason the JDBC driver jar needs to be on HDFS is so that all the data nodes have access to it. Your solution should accomplish the same goal. I'm not familiar enough with the inner workings of Oozie to say why using the sharelib works but your solution does not.
I was facing the same issue it was not able to find the `mysql jar`. I am using cloudera 4.4 in this even `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate` command will not work To resolve the issue I had followed the below steps: 1. create a user in `Hue` with `hdfs` and provide the admin privileges 2. using `Hue UI` upload the `jar` into `/user/oozie/share/lib/sqoop` `hdfs` path or you can use below command: `hadoop put /var/lib/sqoop2/mysql-connector-java.jar /user/oozie/share/lib/sqoop` 3. Once the `jar` is placed run the `oozie` command.
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
In CDH5, you should put the jar to '/user/oozie/share/lib/lib\_${timestamp}/sqoop', and after that, you must update the sharelib or restart oozie. update sharelib: `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate`
If you are using CDH-5 the JDBC driver jar (and any jars it depends on) should go in '/user/oozie/share/lib/lib\_timestamp/sqoop' folder on HDFS.
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
If you are using CDH-5 the JDBC driver jar (and any jars it depends on) should go in '/user/oozie/share/lib/lib\_timestamp/sqoop' folder on HDFS.
I was facing the same issue it was not able to find the `mysql jar`. I am using cloudera 4.4 in this even `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate` command will not work To resolve the issue I had followed the below steps: 1. create a user in `Hue` with `hdfs` and provide the admin privileges 2. using `Hue UI` upload the `jar` into `/user/oozie/share/lib/sqoop` `hdfs` path or you can use below command: `hadoop put /var/lib/sqoop2/mysql-connector-java.jar /user/oozie/share/lib/sqoop` 3. Once the `jar` is placed run the `oozie` command.
15,978,164
I am trying to get started with the LLVM binding for Haskell. A great place to start is Hello World. The following is from a blog by the author of the binding. ``` bldGreet :: CodeGenModule (Function (IO ())) bldGreet = do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) greetz <- createStringNul "Hello, World!" func <- createFunction ExternalLinkage $ do tmp <- getElementPtr greetz (0::Word32, (0::Word32, ())) call puts tmp -- Throw away return value. ret () return func ``` It does not compile. Instead I get "Ambiguous type variable `n0' in the constraint: (type-level-0.2.4:Data.TypeLevel.Num.Sets.NatI n0) arising from a use of`getElementPtr0' Probable fix: add a type signature that fixes these type variable(s)" Here is a variation that does work ``` llvmModule :: TFunction (IO Word32) llvmModule = withStringNul "Hello world!" $ \s -> do puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32) main <- newNamedFunction ExternalLinkage "main" :: TFunction (IO Word32) defineFunction main $ do tmp <- getElementPtr0 s (0::Word32, ()) _ <- call puts tmp ret (0::Word32) return main ``` The first seems more natural. The question I have is what is the ambiguity in the first, and how do I fix it. The second question I have is why is the second not ambiguous.
2013/04/12
[ "https://Stackoverflow.com/questions/15978164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819861/" ]
In CDH5, you should put the jar to '/user/oozie/share/lib/lib\_${timestamp}/sqoop', and after that, you must update the sharelib or restart oozie. update sharelib: `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate`
I was facing the same issue it was not able to find the `mysql jar`. I am using cloudera 4.4 in this even `oozie admin -oozie http://localhost:11000/oozie -sharelibupdate` command will not work To resolve the issue I had followed the below steps: 1. create a user in `Hue` with `hdfs` and provide the admin privileges 2. using `Hue UI` upload the `jar` into `/user/oozie/share/lib/sqoop` `hdfs` path or you can use below command: `hadoop put /var/lib/sqoop2/mysql-connector-java.jar /user/oozie/share/lib/sqoop` 3. Once the `jar` is placed run the `oozie` command.
170,627
I would like to see a soft-lock feature for 10k users. This can be considered a scaled-down version of [Content Dispute lock](https://meta.stackexchange.com/q/127557/165773 "discussed in more details here") available to diamond moderators (for the record, "mod lock" lasts for [a week](https://softwareengineering.meta.stackexchange.com/questions/5628/content-dispute-for-why-do-programming-languages-especially-c-use-curly-brace#comment14181_5628 "as clarified here")). Purpose of proposed feature is, like that of other 10K-tools, as explained at [respective privileges page](https://meta.stackoverflow.com/privileges/moderator-tools "Access to moderator tools"): > > **assist our elected community moderators**... in maintaining our community... > > > --- Programmers, and I suspect other sites too, has a number of questions roll through where the first presentation of the question is ... marginal at best. Some of the time, this is due to English as a second language issues, but in other cases there is a gem hidden within an otherwise off-topic or non-constructive question. Due to the review queues, these questions quickly pick up close votes. And in most cases, I would say that's a good thing - the system is working as designed. However, it can be difficult to edit and clarify the questions worth saving before they have picked up a critical mass of close votes which almost guarantees the question's short-term fate. Oftentimes, I'll see a question worthy of clarifying but I won't have the time *right then* to edit and clarify. Yes, I can always edit the question after it's closed and either vote to reopen or flag for moderator review. Reopening is *hard* as it just doesn't seem to attract the same level of attention despite the review queues. And it doesn't make sense to me that a community driven site should be pushing more work to the mods when there are a number of 10k users that can help carry that workload. So I would like to request 10k+ users to be able to apply a soft-lock to buy the question time so it can be edited. Here's what I'm envisioning with a soft-lock versus the regular lock a moderator can apply. * It's time-boxed to a day or so. A day is enough time for me to either make the edits; open the Meta question for discussion; or get a mod to review and apply a full lock. * The question can still be edited by 10k+ users during the soft-lock * An explanation field ("Soft-locked for clarifying edits") is available so other 10k users can see why the soft-lock was applied. * The soft-lock would prevent additional close votes from accumulating and / or would pull the question from the review queue. * The soft-lock could be instantly undone by a mod, the person applying the soft-lock, or some threshold of 10k user votes. * Whether or not new answers are fully blocked by the soft-lock is an open matter. I have seen some cases where they should have been blocked, but in other cases it wouldn't matter. When it's a hidden gem question then it's too easy for the answers to focus on the not-constructive part. At a minimum, the "protected question" functionality for answering should go into effect.
2013/03/07
[ "https://meta.stackexchange.com/questions/170627", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/-1/" ]
> > Why flag your own question? > > > To request moderator action. Anything that you cannot do yourself but moderators can do, is fair game. If you realize you asked your question on the wrong site, for example, you can flag it to request a migration. Another reason to request moderator attention is if another user is causing problems (like vandalizing your post with repeated edits); dealing with conflicts is best left to the moderation team as well. > > Why close your own question? > > > There may be cases where someone points out that your question is a duplicate, or not a real question and you want to delete it, but it already has upvoted answers from other users. In such a case, you may want to close the question.
You might agree with others that your question should be closed, but you can no longer delete it for example. In such a case you can vote to close it. And if there is anything requiring the attention of a moderator, you can flag to notify them.
170,627
I would like to see a soft-lock feature for 10k users. This can be considered a scaled-down version of [Content Dispute lock](https://meta.stackexchange.com/q/127557/165773 "discussed in more details here") available to diamond moderators (for the record, "mod lock" lasts for [a week](https://softwareengineering.meta.stackexchange.com/questions/5628/content-dispute-for-why-do-programming-languages-especially-c-use-curly-brace#comment14181_5628 "as clarified here")). Purpose of proposed feature is, like that of other 10K-tools, as explained at [respective privileges page](https://meta.stackoverflow.com/privileges/moderator-tools "Access to moderator tools"): > > **assist our elected community moderators**... in maintaining our community... > > > --- Programmers, and I suspect other sites too, has a number of questions roll through where the first presentation of the question is ... marginal at best. Some of the time, this is due to English as a second language issues, but in other cases there is a gem hidden within an otherwise off-topic or non-constructive question. Due to the review queues, these questions quickly pick up close votes. And in most cases, I would say that's a good thing - the system is working as designed. However, it can be difficult to edit and clarify the questions worth saving before they have picked up a critical mass of close votes which almost guarantees the question's short-term fate. Oftentimes, I'll see a question worthy of clarifying but I won't have the time *right then* to edit and clarify. Yes, I can always edit the question after it's closed and either vote to reopen or flag for moderator review. Reopening is *hard* as it just doesn't seem to attract the same level of attention despite the review queues. And it doesn't make sense to me that a community driven site should be pushing more work to the mods when there are a number of 10k users that can help carry that workload. So I would like to request 10k+ users to be able to apply a soft-lock to buy the question time so it can be edited. Here's what I'm envisioning with a soft-lock versus the regular lock a moderator can apply. * It's time-boxed to a day or so. A day is enough time for me to either make the edits; open the Meta question for discussion; or get a mod to review and apply a full lock. * The question can still be edited by 10k+ users during the soft-lock * An explanation field ("Soft-locked for clarifying edits") is available so other 10k users can see why the soft-lock was applied. * The soft-lock would prevent additional close votes from accumulating and / or would pull the question from the review queue. * The soft-lock could be instantly undone by a mod, the person applying the soft-lock, or some threshold of 10k user votes. * Whether or not new answers are fully blocked by the soft-lock is an open matter. I have seen some cases where they should have been blocked, but in other cases it wouldn't matter. When it's a hidden gem question then it's too easy for the answers to focus on the not-constructive part. At a minimum, the "protected question" functionality for answering should go into effect.
2013/03/07
[ "https://meta.stackexchange.com/questions/170627", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/-1/" ]
> > Why flag your own question? > > > To request moderator action. Anything that you cannot do yourself but moderators can do, is fair game. If you realize you asked your question on the wrong site, for example, you can flag it to request a migration. Another reason to request moderator attention is if another user is causing problems (like vandalizing your post with repeated edits); dealing with conflicts is best left to the moderation team as well. > > Why close your own question? > > > There may be cases where someone points out that your question is a duplicate, or not a real question and you want to delete it, but it already has upvoted answers from other users. In such a case, you may want to close the question.
For flagging, you may still need to make the mods aware of an issue with the post. For voting to close, I know for sure that it's possible for someone to want to vote to close their own post. I know, because [I have done it myself](https://stackoverflow.com/q/13872316/237838). I posted that question, then realized it was a duplicate, so voted to close.
33,303
Say we have $n$-gons $P$ and $Q$. Is there any necessary condition for $Q = f(P)$, for some linear transformation $f : \mathbb{R}^2 \to \mathbb{R}^2$? Sorry if this is too elementary / general.
2010/07/25
[ "https://mathoverflow.net/questions/33303", "https://mathoverflow.net", "https://mathoverflow.net/users/2503/" ]
Jesse Douglas studied linear transformations of polygons on the complex plane in 1930s. He proved, in particular, that a transformation $z\_i{}'=\sum\_{i=1}^na\_{ij}z\_j$ (all numbers are complex) will transform a polygon $\pi=(z\_1,\cdots,z\_n)$ into a polygon $\pi'=(z\_1{}',\cdots,z\_n{}')$ if, and only if, the matrix $a\_{ij}$ is cyclic, that is, if, and only if, $a\_{ij}=\alpha\_{j-i}$, $\alpha\_{j-i}=\alpha\_k$ if $k\equiv j-1\ (\text{mod}\,n)$. (See his article ["On linear polygon transformations"](http://www.ams.org/journals/bull/1940-46-06/S0002-9904-1940-07259-3/S0002-9904-1940-07259-3.pdf), Bull. Amer. Math. Soc. 46, (1940) pp. 551 - 560.)
By the way, is there any result on linear transformation of polyhedra in $\mathbb{R}^n$?
42,218,278
``` x = Time.now y = 1.hours.from_now z = 1.hours.before_now ``` i'm sorry if this question too stupid. i want to know an effective way to show one hour before and after now in ruby. thanks for watching and for helping.
2017/02/14
[ "https://Stackoverflow.com/questions/42218278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are no such methods in Ruby. You'll have to do: ``` Time.now + 1*60*60 # 1.hours.from_now -> 1 hour, 60 minutes, 60 seconds Time.now - 1*60*60 # 1.hours.before_now -> 1 hour, 60 minutes, 60 seconds ``` or you can include `activesupport` in your project.
Also you can write in this manner : **Current Time:** x = Time.now `=> 2017-02-14 11:55:17 +0530` **one hour ago ( one hour before):** y = x - 1.hour `=> 2017-02-14 10:55:17 +0530` or y = **1.hour.ago** `=> 2017-02-14 10:55:17 +0530` `# available in rails v4.2 **one hour later/since ( one hour after ):** z = x + 1.hour `=> 2017-02-14 12:55:17 +0530` or z = **1.hour.since** `=> 2017-02-14 12:55:17 +0530` `# available in rails v4.2` Note: this calculation perform on x(stored time) not real time(Time.now) but in case of ago and since calculation perform on real time(Time.now)
34,442,666
I have a generic list of `employees` and `supervisors` ``` List<Employee> employees = new List<Employee>(); List<Supervisor> supervisors = new List<Supervisor>(); ``` They are both part of a `employee` class that I have marked as `[Serializable]` Could I put both of these lists into another list so that it can be serialised easier? I have looked at serialisation tutorials but they only specify one generic list or less. I have provided a template, I want to click a 'Save' button and complete the serialise process, preferably with both lists into one bigger list. ``` private void btnSave_Click(object sender, EventArgs e) { FileStream outFile; BinaryFormatter bFormatter = new BinaryFormatter(); } ```
2015/12/23
[ "https://Stackoverflow.com/questions/34442666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4289341/" ]
You can actually serialize two lists to one stream: ``` using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, employees); bf.Serialize(fs, supervisors); } ``` The `BinaryFormatter` prefixes the data block with meta data that also apparently allows it to concatenate data to one file. In order to read back `supervisors` you have to load the other list first. Since the lists aren't fixed length records, the second list could become unusable when you re-write the first and either lose it behind orphaned data or overwrite part of it. Since there are so many things which can prevent that from working, it is easy enough to create a "holder" or container class for multiples: ``` [Serializable()] public class BFHolder { public List<Employee> employees { get; set; } public List<Supervisor> supervisors { get; set; } public BFHolder() { } } ``` After you deserialize, you can pull out the lists as needed. Yet one more -- better -- option is [ProtoBuf-Net](https://github.com/mgravell/protobuf-net) (scroll down to the read me). In addition to being faster and creating smaller output than the BinaryFormatter, it includes the means to serialize multiple objects to one stream. ``` using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) { Serializer.SerializeWithLengthPrefix<List<Employee>>(fs, employees, PrefixStyle.Base128); Serializer.SerializeWithLengthPrefix<List<Supervisor>>(fs, supervisors, PrefixStyle.Base128); } ```
You can put this lists in another class container and serialize/deserialize it. ``` [Serializable] public class Container { public List<Employee> employees = new List<Employee>(); public List<Supervisor> supervisors = new List<Supervisor>(); } ```
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
It really depends on the data you want to store. **SQLite** Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences. **SharedPreferences** SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
This question has an accepted answer, but I think there is more to said on the topic - regarding speed. An application's SharedPreferences and Sqlite DB are both just files, stored in the application's directories on the device's file system. If the amount of data is not too big, the Sqlite option will involve a larger and more complicated file with more processing overhead for simple access. So, if the nature of the data does not dictate your choice (as explained in accepted answer), and speed matters, then you are probably better to use SharedPreferences. And reading some data is often on the critical path to displaying the main activty so I think speed is often very important. One final thought regarding speed and efficiency - if you need to use an Sqlite database for some structured data then it is probably more efficient to also store user preferences in the database so you are not opening a second file. This is a fairly minor consideration - probably worth consideration only if you need to access both the structured data and preferences before you can display the main activity.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
It really depends on the data you want to store. **SQLite** Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences. **SharedPreferences** SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
My take is, it is not about speed or size but the kinds of operation you want to do to your data. If you plan to do **join**, **sort**, **and other DB operations** on your data then go for **Sqlite**. An example is sorting data by date. If you want to map simple values (like int, boolean, String) then use **Preferences**. DB operations won't work here and needless to say you need to have all the keys. An example is user password or app configuration. The big temptation to embrace Preferences is when you want to use it to store a flattened POJO (a serialized JSON object) as String. Having such need is actually the sign to use Sqlite. Why ? Because complex data will eventually need complex oprations. Imagine retrieving a specific entry which could be handled by a simple "SELECT ... WHERE id = 1". In Preferences path, this will be a long process from deserializing to iterating the results.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
It really depends on the data you want to store. **SQLite** Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences. **SharedPreferences** SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
* For storing huge amount of data, go for SQLite database system. This will allow the user to search for data as well. * On the other hand, for storing small amount of data, go for Shared Preferences. In this case, a huge database system is unnecessary. This will allow user to simply save data and load them.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
It really depends on the data you want to store. **SQLite** Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences. **SharedPreferences** SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
Forget SQLLite forget SharedPreferences, use Realm. A single solution for all your local storage. You can use plain old Java Objects as RealmObjects and store your data there. You can convert selcted queries into JSON files. No need to parse the entire data base. Check this link: <https://realm.io/news/introducing-realm/>
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
This question has an accepted answer, but I think there is more to said on the topic - regarding speed. An application's SharedPreferences and Sqlite DB are both just files, stored in the application's directories on the device's file system. If the amount of data is not too big, the Sqlite option will involve a larger and more complicated file with more processing overhead for simple access. So, if the nature of the data does not dictate your choice (as explained in accepted answer), and speed matters, then you are probably better to use SharedPreferences. And reading some data is often on the critical path to displaying the main activty so I think speed is often very important. One final thought regarding speed and efficiency - if you need to use an Sqlite database for some structured data then it is probably more efficient to also store user preferences in the database so you are not opening a second file. This is a fairly minor consideration - probably worth consideration only if you need to access both the structured data and preferences before you can display the main activity.
My take is, it is not about speed or size but the kinds of operation you want to do to your data. If you plan to do **join**, **sort**, **and other DB operations** on your data then go for **Sqlite**. An example is sorting data by date. If you want to map simple values (like int, boolean, String) then use **Preferences**. DB operations won't work here and needless to say you need to have all the keys. An example is user password or app configuration. The big temptation to embrace Preferences is when you want to use it to store a flattened POJO (a serialized JSON object) as String. Having such need is actually the sign to use Sqlite. Why ? Because complex data will eventually need complex oprations. Imagine retrieving a specific entry which could be handled by a simple "SELECT ... WHERE id = 1". In Preferences path, this will be a long process from deserializing to iterating the results.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
This question has an accepted answer, but I think there is more to said on the topic - regarding speed. An application's SharedPreferences and Sqlite DB are both just files, stored in the application's directories on the device's file system. If the amount of data is not too big, the Sqlite option will involve a larger and more complicated file with more processing overhead for simple access. So, if the nature of the data does not dictate your choice (as explained in accepted answer), and speed matters, then you are probably better to use SharedPreferences. And reading some data is often on the critical path to displaying the main activty so I think speed is often very important. One final thought regarding speed and efficiency - if you need to use an Sqlite database for some structured data then it is probably more efficient to also store user preferences in the database so you are not opening a second file. This is a fairly minor consideration - probably worth consideration only if you need to access both the structured data and preferences before you can display the main activity.
* For storing huge amount of data, go for SQLite database system. This will allow the user to search for data as well. * On the other hand, for storing small amount of data, go for Shared Preferences. In this case, a huge database system is unnecessary. This will allow user to simply save data and load them.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
This question has an accepted answer, but I think there is more to said on the topic - regarding speed. An application's SharedPreferences and Sqlite DB are both just files, stored in the application's directories on the device's file system. If the amount of data is not too big, the Sqlite option will involve a larger and more complicated file with more processing overhead for simple access. So, if the nature of the data does not dictate your choice (as explained in accepted answer), and speed matters, then you are probably better to use SharedPreferences. And reading some data is often on the critical path to displaying the main activty so I think speed is often very important. One final thought regarding speed and efficiency - if you need to use an Sqlite database for some structured data then it is probably more efficient to also store user preferences in the database so you are not opening a second file. This is a fairly minor consideration - probably worth consideration only if you need to access both the structured data and preferences before you can display the main activity.
Forget SQLLite forget SharedPreferences, use Realm. A single solution for all your local storage. You can use plain old Java Objects as RealmObjects and store your data there. You can convert selcted queries into JSON files. No need to parse the entire data base. Check this link: <https://realm.io/news/introducing-realm/>
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
My take is, it is not about speed or size but the kinds of operation you want to do to your data. If you plan to do **join**, **sort**, **and other DB operations** on your data then go for **Sqlite**. An example is sorting data by date. If you want to map simple values (like int, boolean, String) then use **Preferences**. DB operations won't work here and needless to say you need to have all the keys. An example is user password or app configuration. The big temptation to embrace Preferences is when you want to use it to store a flattened POJO (a serialized JSON object) as String. Having such need is actually the sign to use Sqlite. Why ? Because complex data will eventually need complex oprations. Imagine retrieving a specific entry which could be handled by a simple "SELECT ... WHERE id = 1". In Preferences path, this will be a long process from deserializing to iterating the results.
* For storing huge amount of data, go for SQLite database system. This will allow the user to search for data as well. * On the other hand, for storing small amount of data, go for Shared Preferences. In this case, a huge database system is unnecessary. This will allow user to simply save data and load them.
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
My take is, it is not about speed or size but the kinds of operation you want to do to your data. If you plan to do **join**, **sort**, **and other DB operations** on your data then go for **Sqlite**. An example is sorting data by date. If you want to map simple values (like int, boolean, String) then use **Preferences**. DB operations won't work here and needless to say you need to have all the keys. An example is user password or app configuration. The big temptation to embrace Preferences is when you want to use it to store a flattened POJO (a serialized JSON object) as String. Having such need is actually the sign to use Sqlite. Why ? Because complex data will eventually need complex oprations. Imagine retrieving a specific entry which could be handled by a simple "SELECT ... WHERE id = 1". In Preferences path, this will be a long process from deserializing to iterating the results.
Forget SQLLite forget SharedPreferences, use Realm. A single solution for all your local storage. You can use plain old Java Objects as RealmObjects and store your data there. You can convert selcted queries into JSON files. No need to parse the entire data base. Check this link: <https://realm.io/news/introducing-realm/>
6,276,358
What is the good mechanism to store information among SQLite database and Shared Preferences? Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.
2011/06/08
[ "https://Stackoverflow.com/questions/6276358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787058/" ]
* For storing huge amount of data, go for SQLite database system. This will allow the user to search for data as well. * On the other hand, for storing small amount of data, go for Shared Preferences. In this case, a huge database system is unnecessary. This will allow user to simply save data and load them.
Forget SQLLite forget SharedPreferences, use Realm. A single solution for all your local storage. You can use plain old Java Objects as RealmObjects and store your data there. You can convert selcted queries into JSON files. No need to parse the entire data base. Check this link: <https://realm.io/news/introducing-realm/>
161,395
Hello I'm studying machine learning processes and I'm beside of a misunderstanding.. **Is this right?** > > "Minimization is a process that minimize the error rate of Y (output > of the feature) to be a valid limiter and this is followed by an > optimization process that acts on the parameters to find the best ones > for the best model to choose" > > > The only parameters I know in my head now are the FEATURES (X inputs). Which are the parameters to optimize? Technical parameters? Thanks for help!
2015/07/14
[ "https://stats.stackexchange.com/questions/161395", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/82276/" ]
This is usually done with maximum likelihood ratio between original model and a model omitting the variance coefficient to be estimate (random intercept/random slope/random co-variance between slope and intercept). A good example is in these tutorials: * When model has more than one random coefficient: <http://www.bodowinter.com/tutorial/bw_LME_tutorial.pdf> (p.12) * When model has one random coefficient: <http://www.stat.wisc.edu/~ane/st572/notes/lec21.pdf> (p.13) Sample R code: ``` > model1 = lmer(resp ˜ fixed1 + (1 | random1)) > model2 = lm(resp ˜ fixed1) > chi2 = -2*logLik(model2, REML=T) +2*logLik(model1, REML=T) > chi2 [1] 5.011 > pchisq(chi2, df=1, lower.tail=F) [1] 0.02518675 ```
Asymptotic test are problematic for variance parameters, because parameter space is bounded by zero. Moreover, the hypothesis you are trying to test, can't be true, as the parameter is continuous. Probability of $\sigma^2 = 0$ is exactly 0. What you can do to make inference on the variance parameters is to switch to a Bayesian implementation, where you would get the full posterior distribution for the variance parameters. For lme4 users, the MCMCglmm package is easy to learn. You could also use JAGS or Stan. For an example, where Stan was used to compare several random effects, see [1]. [1] Schmettow, M., & Havinga, J. (2013). Are users more diverse than designs? Testing and extending a 25 years old claim . In S. Love, K. Hone, & Tom McEwan (Eds.), Proceedings of BCS HCI 2013- The Internet of Things XXVII. Uxbridge, UK: BCS Learning and Development Ltd.
69,731,434
**in edit\_customer:** ``` <form action="{{ url('customer/profile_update', [ 'id'=> $cust->id ]) }}" method="POST" enctype="multipart/form-data"> @csrf @method("PUT") ``` **web.php** //Customer related pages ``` Route::prefix('customer')->middleware(['auth','verified'])->name('customer.')->group(function(){ Route::get('/',[HomeController::class,'index']); Route::get('cdash', Cdash::class)->name('cdash'); Route::get('edit_customer/{id}',[Profile::class,'edit_customer'])->name('edit_customer'); Route::put('update_customer/{id}',[Profile::class,'update_customer'])->name('update_customer'); ``` **Profile.php (controller)** ``` public function edit_customer($id) { $cust= User::findOrFail($id); return view('customer.edit_customer', compact('cust')); } public function update_customer(Request $request, $id) { $customer = User::find($id); //thebarber table details if($request->hasFile('image')) { $avatarpath= '/profileimages/'.$customer->image; if(File::exists($avatarpath)) { File::delete($avatarpath); } $file=$request->file('image'); $ext=$file->getClientOriginalExtension(); $filename=time().'.'.$ext; $file->move('/profileimages/',$filename); $customer->image=$filename; } $customer->firstname=$request->input('firstname'); $customer->lastname=$request->input('lastname'); $customer->email=$request->input('email'); $customer->phone=$request->input('phone'); $customer->city=$request->input('city'); $customer->county=$request->input('county'); $customer->country=$request->input('country'); $customer->update(); return redirect('/home')->with('message',"Customer Updated Sucessfully"); } ```
2021/10/27
[ "https://Stackoverflow.com/questions/69731434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13405269/" ]
you have just missed a closing parenthesis. ``` SELECT UPPER(SUBSTRING(NAME,1,3)) FROM STUDENTS; ``` Also, to get the first 4 letters you should use SUBSTRING(NAME,1,4) Cheers
both of queries that you used have wrong parenthesis match (every opening parenthesis need closing one). If you want to get first 4 letters you should replace 3 with 4 ``` SELECT UCASE(MID(NAME,1,4)) FROM STUDENTS; SELECT UPPER(SUBSTRING(NAME,1,4)) FROM STUDENTS; ```
12,965,588
I'm using jquery-ui-map 3.0 RC to simplify the process of using json to place markers on a google map using javascript api v3. When I prototyped using html files it worked fine. Once I started to use embed code within an MVC4 project and debug using iis express I'd get an error in Google Chrome Developer Tools "Uncaught TypeError: Object [object Object] has no method 'gmap'. ``` <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=MYBROWSERAPIKEYISHERE&sensor=true"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script type="text/javascript" src="../../Scripts/jquery.ui.map.js"></script> <script type="text/javascript" src="../../Scripts/gmap3.js"></script> <script type="text/javascript"> $(document).ready(function () { initialize(); }); function getMarkers() { // This URL won't work on your localhost, so you need to change it // see http://en.wikipedia.org/wiki/Same_origin_policy $.getJSON('../../Data/Australia-WA-Perth.json', function (data) { $.each(data.markers, function (i, marker) { $('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds': true }).click(function () { $('#map_canvas').gmap('openInfoWindow', { 'content': marker.content }, this); }); }); }); } function initialize() { var pointCenter = new google.maps.LatLng(-31.95236980, 115.8571791); var myMapOptions = { zoom: 17, center: pointCenter, mapTypeId: google.maps.MapTypeId.ROADMAP //TERRAIN }; var map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions); google.maps.event.addListenerOnce(map, 'idle', function () { getMarkers(); }); } </script> ```
2012/10/19
[ "https://Stackoverflow.com/questions/12965588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567606/" ]
You are including gmap3 but making calls to `.gmap(...)`. The examples in the gmap3 documentation use `.gmap3(...)`. Also, I can find no evidence that you can initialise a map with the standard `google.maps` API, then add markers etc with gmap3. As far as I can tell, there's no mechanism for mixing the two APIs, at least not in the way you are attempting. If there *is* a mechanism for mixing the two APIs like this, then it would seem necessary somehow to inform gmap3 of the variable `map` returned by `new google.maps.Map(...);`. Otherwise, I'm guessing, gmap3 has no means of addressing the map that is already established. So try re-writing your code to use 100% one API or 100% the other.
The issue may be that Google maps isn't ready yet. You have used jQuery ready functions, but I suggest you instead use a combination of both. Please post up a fiddle or example so we can investigate further
12,965,588
I'm using jquery-ui-map 3.0 RC to simplify the process of using json to place markers on a google map using javascript api v3. When I prototyped using html files it worked fine. Once I started to use embed code within an MVC4 project and debug using iis express I'd get an error in Google Chrome Developer Tools "Uncaught TypeError: Object [object Object] has no method 'gmap'. ``` <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=MYBROWSERAPIKEYISHERE&sensor=true"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script type="text/javascript" src="../../Scripts/jquery.ui.map.js"></script> <script type="text/javascript" src="../../Scripts/gmap3.js"></script> <script type="text/javascript"> $(document).ready(function () { initialize(); }); function getMarkers() { // This URL won't work on your localhost, so you need to change it // see http://en.wikipedia.org/wiki/Same_origin_policy $.getJSON('../../Data/Australia-WA-Perth.json', function (data) { $.each(data.markers, function (i, marker) { $('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds': true }).click(function () { $('#map_canvas').gmap('openInfoWindow', { 'content': marker.content }, this); }); }); }); } function initialize() { var pointCenter = new google.maps.LatLng(-31.95236980, 115.8571791); var myMapOptions = { zoom: 17, center: pointCenter, mapTypeId: google.maps.MapTypeId.ROADMAP //TERRAIN }; var map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions); google.maps.event.addListenerOnce(map, 'idle', function () { getMarkers(); }); } </script> ```
2012/10/19
[ "https://Stackoverflow.com/questions/12965588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567606/" ]
You are including gmap3 but making calls to `.gmap(...)`. The examples in the gmap3 documentation use `.gmap3(...)`. Also, I can find no evidence that you can initialise a map with the standard `google.maps` API, then add markers etc with gmap3. As far as I can tell, there's no mechanism for mixing the two APIs, at least not in the way you are attempting. If there *is* a mechanism for mixing the two APIs like this, then it would seem necessary somehow to inform gmap3 of the variable `map` returned by `new google.maps.Map(...);`. Otherwise, I'm guessing, gmap3 has no means of addressing the map that is already established. So try re-writing your code to use 100% one API or 100% the other.
I had the same problem and found that it was due to multiple jquery references. My \_layout.cshtml was loading jquery via the following line in the body section: @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) It seems that this was effectively overwriting the reference I had in my view. As it is preferable to load the reference in just one place, I removed it from the view however I then got an error that jQuery wasnt defined. I had to move the @Scripts.Render from the body section (placed there by nuget) to the section and everything worked fine. So if you get the same error, view the page and do a 'view source'. See if there are multiple jquery script references. This thread gave me the clue : ["gmap is not a function" when using Google's map api](https://stackoverflow.com/questions/9397907/gmap-is-not-a-function-when-using-googles-map-api)
21,294,191
``` return db.Orders.Where(o => o.Customer == User.Identity.Name); ``` Where does `o` come from? Sometimes I see this form used with other letters like `c`? Is this exchangeable? Where does `User.Identity.Name` come from?
2014/01/22
[ "https://Stackoverflow.com/questions/21294191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893264/" ]
> > Where does o come from? > > > `Where` takes a `Func` delegate that takes an instance of whatever collection type you are using. In this case, it would be `Func<Order, bool>`. Your Lambda statement declares an anonymous function that matches the delegate. `o` is simply the `Order` input. You can name it whatever you like. If you wrote out the function in long-hand, it would look something like: ``` public bool AnonymousFunction(Order o) { return o.Customer == User.Identity.Name; } ``` If you're querying using LINQ to Objects, this delegate will be called for each of the elements to find the ones in the collection that match. If you're querying LINQ to SQL (or some other query provider), your delegate will be converted into an Expression Tree which will be used to generate the actual query syntax. > > Where does User.Identity.Name come from? > > > I'm assuming you're inside of some sort of web application and User.Identity is pulling the logged in user information from the Forms Authentication token.
This is known as [Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) > > By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. > > > In your case, you are using ``` db.Orders.Where(o => o.Customer == User.Identity.Name); ``` In place of `o` you can use whatever character you want and that character will be behave as instance of collection type ie. here you are using collection of `Orders`, so `o` will behave as instance of `Order` class.
21,294,191
``` return db.Orders.Where(o => o.Customer == User.Identity.Name); ``` Where does `o` come from? Sometimes I see this form used with other letters like `c`? Is this exchangeable? Where does `User.Identity.Name` come from?
2014/01/22
[ "https://Stackoverflow.com/questions/21294191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893264/" ]
The `=>` operator is used to define a *lambda statement* - essentially an inline function. It's the inline equivalent of: ``` public bool Myfunc(Order o) { return o.Customer == User.Identity.Name; } ``` The *type* of `o` is inferred from the parameter type of the `Func` passed into `Where`. In this case, the type will be `Order` since `IEnumerable<Order>.Where()` takes a `Func<Order, bool>` with an `Order` as the input and a `bool` as the output. The actual letter does not mater. A good convention is to use an identifier that is relatable to the source type, so `o` or `order` would be good choices. `User` is probably a property of the class the function is in (i.e. `Page`), and `User.Identity.Name` is the name of the identity associated with the user.
This is known as [Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) > > By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. > > > In your case, you are using ``` db.Orders.Where(o => o.Customer == User.Identity.Name); ``` In place of `o` you can use whatever character you want and that character will be behave as instance of collection type ie. here you are using collection of `Orders`, so `o` will behave as instance of `Order` class.
21,294,191
``` return db.Orders.Where(o => o.Customer == User.Identity.Name); ``` Where does `o` come from? Sometimes I see this form used with other letters like `c`? Is this exchangeable? Where does `User.Identity.Name` come from?
2014/01/22
[ "https://Stackoverflow.com/questions/21294191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893264/" ]
This is known as [Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) > > By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. > > > In your case, you are using ``` db.Orders.Where(o => o.Customer == User.Identity.Name); ``` In place of `o` you can use whatever character you want and that character will be behave as instance of collection type ie. here you are using collection of `Orders`, so `o` will behave as instance of `Order` class.
All the answers provided are correct. I'll just try to explain you in simple language about the statement: You are accessing the Order table by writing `db.Orders` Then you are putting up a condition on the table using `Where` Inside `Where` you specify the condition. This is done using lambda expression. Lambda expression is nothing but just a way of saying that I'll call each row as o(or may be anything, it can be x,y, abc, anything, its just a name) and for that(=>) check if o.Customer is equal to currently logged in User. If yes, return me all those rows which match this condition.
21,294,191
``` return db.Orders.Where(o => o.Customer == User.Identity.Name); ``` Where does `o` come from? Sometimes I see this form used with other letters like `c`? Is this exchangeable? Where does `User.Identity.Name` come from?
2014/01/22
[ "https://Stackoverflow.com/questions/21294191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893264/" ]
> > Where does o come from? > > > `Where` takes a `Func` delegate that takes an instance of whatever collection type you are using. In this case, it would be `Func<Order, bool>`. Your Lambda statement declares an anonymous function that matches the delegate. `o` is simply the `Order` input. You can name it whatever you like. If you wrote out the function in long-hand, it would look something like: ``` public bool AnonymousFunction(Order o) { return o.Customer == User.Identity.Name; } ``` If you're querying using LINQ to Objects, this delegate will be called for each of the elements to find the ones in the collection that match. If you're querying LINQ to SQL (or some other query provider), your delegate will be converted into an Expression Tree which will be used to generate the actual query syntax. > > Where does User.Identity.Name come from? > > > I'm assuming you're inside of some sort of web application and User.Identity is pulling the logged in user information from the Forms Authentication token.
All the answers provided are correct. I'll just try to explain you in simple language about the statement: You are accessing the Order table by writing `db.Orders` Then you are putting up a condition on the table using `Where` Inside `Where` you specify the condition. This is done using lambda expression. Lambda expression is nothing but just a way of saying that I'll call each row as o(or may be anything, it can be x,y, abc, anything, its just a name) and for that(=>) check if o.Customer is equal to currently logged in User. If yes, return me all those rows which match this condition.
21,294,191
``` return db.Orders.Where(o => o.Customer == User.Identity.Name); ``` Where does `o` come from? Sometimes I see this form used with other letters like `c`? Is this exchangeable? Where does `User.Identity.Name` come from?
2014/01/22
[ "https://Stackoverflow.com/questions/21294191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893264/" ]
The `=>` operator is used to define a *lambda statement* - essentially an inline function. It's the inline equivalent of: ``` public bool Myfunc(Order o) { return o.Customer == User.Identity.Name; } ``` The *type* of `o` is inferred from the parameter type of the `Func` passed into `Where`. In this case, the type will be `Order` since `IEnumerable<Order>.Where()` takes a `Func<Order, bool>` with an `Order` as the input and a `bool` as the output. The actual letter does not mater. A good convention is to use an identifier that is relatable to the source type, so `o` or `order` would be good choices. `User` is probably a property of the class the function is in (i.e. `Page`), and `User.Identity.Name` is the name of the identity associated with the user.
All the answers provided are correct. I'll just try to explain you in simple language about the statement: You are accessing the Order table by writing `db.Orders` Then you are putting up a condition on the table using `Where` Inside `Where` you specify the condition. This is done using lambda expression. Lambda expression is nothing but just a way of saying that I'll call each row as o(or may be anything, it can be x,y, abc, anything, its just a name) and for that(=>) check if o.Customer is equal to currently logged in User. If yes, return me all those rows which match this condition.
7,278,427
I'm using impromptu <http://www.shiguenori.com/material/jquery.impromptu/> to show dialog boxes and collect user's input. But I can't get the input textbox to focus when it appears. I've tried giving the input an id and add in impromptu.js ``` $('#impromptu_fname').focus(); ``` in several placess. I also tried adding autofocus to the input. None of that worked. Any ideas?
2011/09/02
[ "https://Stackoverflow.com/questions/7278427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/661424/" ]
You'll have to do it in the `loaded` callback: ``` $.prompt('Your message goes here.', { // options loaded: function(){ $('#impromptu_fname').focus(); } }); ```
Thanks for the tip to use the loaded callback. I had the same problem, however to get the focus on the default button of the initial prompt, here's how I did it: ``` var myPrompt = $.prompt(tourStates); myPrompt.on('impromptu:loaded', function(e){$('button.jqidefaultbutton[id^="jqi_0"]').focus();}); ```
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
Since you are rendering your React components which depend on the webpack CSS loader in the backend, on your Express server, you need to run your server-side code through webpack, just as you do your client-side code. In the project I'm currently working on, I have two webpack builds, each with their own config. One produces a bundle named `server.js`, the other `client.js`. In production, I start the server by running `node server.js`. For local dev, I use a script that rebuilds my `server.js` when changes in the backend are detected. It looks like this (file name *backend-dev.js*): ``` const path = require('path'); const webpack = require('webpack'); const spawn = require('child_process').spawn; const compiler = webpack({ // add your webpack configuration here }); const watchConfig = { // compiler watch configuration // see https://webpack.js.org/configuration/watch/ aggregateTimeout: 300, poll: 1000 }; let serverControl; compiler.watch(watchConfig, (err, stats) => { if (err) { console.error(err.stack || err); if (err.details) { console.error(err.details); } return; } const info = stats.toJson(); if (stats.hasErrors()) { info.errors.forEach(message => console.log(message)); return; } if (stats.hasWarnings()) { info.warnings.forEach(message => console.log(message)); } if (serverControl) { serverControl.kill(); } // change server.js to the relative path to the bundle created by webpack, if necessary serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]); serverControl.stdout.on('data', data => console.log(data.toString())); serverControl.stderr.on('data', data => console.error(data.toString())); }); ``` You can start this script on the command line with ``` node backend-dev.js ``` When you make changes in your server code, webpack will recompile and restart your server. Note that I have omitted the actual webpack configuration from the above example, because your mileage will vary. You insert it at the beginning, see code comment.
Try importing your css like that: ``` import "./text.css"; ``` Please share your css as well.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
If you want to use simple css: ``` import './text.css'; ``` But if you want to use CSS Modules, I assume that according to added CSS in your import, check <https://github.com/css-modules/css-modules>. Also, try to change webpack config: ``` { test: /\.css$/, loader: 'style-loader!css-loader!', }, ``` Check example: * using CSS: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/src/components/Logout.jsx> * webpack.config.js: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/webpack.config.js>
Try importing your css like that: ``` import "./text.css"; ``` Please share your css as well.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
I had to remove from: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], include: [ path.resolve(__dirname, "src","client") ], } ``` to: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], } ``` This one works in my case. I don´t know why.
Try importing your css like that: ``` import "./text.css"; ``` Please share your css as well.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
To create npm package, you can build like to: ``` module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /(node_modules|bower_components|build)/, loader: 'babel-loader' }, { test: /\.(css|less)$/, use: ["style-loader", "css-loader"] } ] }, ```
Try importing your css like that: ``` import "./text.css"; ``` Please share your css as well.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
I had to remove from: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], include: [ path.resolve(__dirname, "src","client") ], } ``` to: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], } ``` This one works in my case. I don´t know why.
Since you are rendering your React components which depend on the webpack CSS loader in the backend, on your Express server, you need to run your server-side code through webpack, just as you do your client-side code. In the project I'm currently working on, I have two webpack builds, each with their own config. One produces a bundle named `server.js`, the other `client.js`. In production, I start the server by running `node server.js`. For local dev, I use a script that rebuilds my `server.js` when changes in the backend are detected. It looks like this (file name *backend-dev.js*): ``` const path = require('path'); const webpack = require('webpack'); const spawn = require('child_process').spawn; const compiler = webpack({ // add your webpack configuration here }); const watchConfig = { // compiler watch configuration // see https://webpack.js.org/configuration/watch/ aggregateTimeout: 300, poll: 1000 }; let serverControl; compiler.watch(watchConfig, (err, stats) => { if (err) { console.error(err.stack || err); if (err.details) { console.error(err.details); } return; } const info = stats.toJson(); if (stats.hasErrors()) { info.errors.forEach(message => console.log(message)); return; } if (stats.hasWarnings()) { info.warnings.forEach(message => console.log(message)); } if (serverControl) { serverControl.kill(); } // change server.js to the relative path to the bundle created by webpack, if necessary serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]); serverControl.stdout.on('data', data => console.log(data.toString())); serverControl.stderr.on('data', data => console.error(data.toString())); }); ``` You can start this script on the command line with ``` node backend-dev.js ``` When you make changes in your server code, webpack will recompile and restart your server. Note that I have omitted the actual webpack configuration from the above example, because your mileage will vary. You insert it at the beginning, see code comment.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
To create npm package, you can build like to: ``` module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /(node_modules|bower_components|build)/, loader: 'babel-loader' }, { test: /\.(css|less)$/, use: ["style-loader", "css-loader"] } ] }, ```
Since you are rendering your React components which depend on the webpack CSS loader in the backend, on your Express server, you need to run your server-side code through webpack, just as you do your client-side code. In the project I'm currently working on, I have two webpack builds, each with their own config. One produces a bundle named `server.js`, the other `client.js`. In production, I start the server by running `node server.js`. For local dev, I use a script that rebuilds my `server.js` when changes in the backend are detected. It looks like this (file name *backend-dev.js*): ``` const path = require('path'); const webpack = require('webpack'); const spawn = require('child_process').spawn; const compiler = webpack({ // add your webpack configuration here }); const watchConfig = { // compiler watch configuration // see https://webpack.js.org/configuration/watch/ aggregateTimeout: 300, poll: 1000 }; let serverControl; compiler.watch(watchConfig, (err, stats) => { if (err) { console.error(err.stack || err); if (err.details) { console.error(err.details); } return; } const info = stats.toJson(); if (stats.hasErrors()) { info.errors.forEach(message => console.log(message)); return; } if (stats.hasWarnings()) { info.warnings.forEach(message => console.log(message)); } if (serverControl) { serverControl.kill(); } // change server.js to the relative path to the bundle created by webpack, if necessary serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]); serverControl.stdout.on('data', data => console.log(data.toString())); serverControl.stderr.on('data', data => console.error(data.toString())); }); ``` You can start this script on the command line with ``` node backend-dev.js ``` When you make changes in your server code, webpack will recompile and restart your server. Note that I have omitted the actual webpack configuration from the above example, because your mileage will vary. You insert it at the beginning, see code comment.
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
I had to remove from: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], include: [ path.resolve(__dirname, "src","client") ], } ``` to: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], } ``` This one works in my case. I don´t know why.
If you want to use simple css: ``` import './text.css'; ``` But if you want to use CSS Modules, I assume that according to added CSS in your import, check <https://github.com/css-modules/css-modules>. Also, try to change webpack config: ``` { test: /\.css$/, loader: 'style-loader!css-loader!', }, ``` Check example: * using CSS: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/src/components/Logout.jsx> * webpack.config.js: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/webpack.config.js>
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
To create npm package, you can build like to: ``` module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /(node_modules|bower_components|build)/, loader: 'babel-loader' }, { test: /\.(css|less)$/, use: ["style-loader", "css-loader"] } ] }, ```
If you want to use simple css: ``` import './text.css'; ``` But if you want to use CSS Modules, I assume that according to added CSS in your import, check <https://github.com/css-modules/css-modules>. Also, try to change webpack config: ``` { test: /\.css$/, loader: 'style-loader!css-loader!', }, ``` Check example: * using CSS: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/src/components/Logout.jsx> * webpack.config.js: <https://github.com/Aksana-Tsishchanka/react-routing/blob/master/webpack.config.js>
43,559,543
i have lots of adapters and views, viewsmodels and so on. Since its hard to maintain those i would like to use databinding and mvvm for that case. Now i tried to forward the item clicks into the viewmodel. Since its a recycleview i would lovely not loose the functionality to have less memory usage. Currently i have a view (Activity) which sets the ViewModel. The ViewModel itself has an Adapter. The adapter has a Constructor which receives the viewModel and set this into the item. The Item uses this to send the events back to the ViewModel. How does it affect the memory? Is there a better way doing this? I used RXJava before but this looks like the same concept, doesnt it? Here's my sample code (truncated). **View** ``` public class ScenesFragment extends BaseFragment implements Observer { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.scenesFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.scenes_fragment, container, false); this.scenesListViewModel = new ScenesListViewModel(getContext()); this.scenesFragmentBinding.setViewModel(this.scenesListViewModel); View view = this.scenesFragmentBinding.getRoot(); return view; } } ``` **BaseLayout** ``` <layout ... > <data><variable name="viewModel" type=".viewmodel.ScenesListViewModel"/></data> <android.support.v7.widget.RecyclerView app:adapter="@{viewModel.adapter}" app:layoutManager="@{viewModel.layoutManager}" /> </layout> ``` **ViewModel** ``` public class ScenesListViewModel extends Observable implements IViewModel { public final SceneAdapter adapter; private List<Scene> scenes = new ArrayList<>(); public ScenesListViewModel(@NonNull Context context) { this.adapter = new SceneAdapter(context, scenes, this); } public void onRemoveClick(Scene scene) { Timber.d("Clicked remove in the scene:" + scene); } } ``` **Item Layout** ``` <layout> <data> <variable name="scene"type=".model.Scene"/> <variable name="viewModel" type=".viewmodel.ScenesListViewModel"/> </data> <ImageButton android:id="@+id/sceneDelete" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:layout_weight="1" android:background="@null" android:onClick="@{() -> viewModel.onRemoveClick(scene)}" android:src="@drawable/ic_delete_forever_white_48px"/> </LinearLayout> </layout> ``` and finally the adapter which set the viewModel into the item. **Adapter** ``` public class SceneAdapter extends RecyclerView.Adapter<SceneAdapter.BindingHolder> { private Context context; private List<Scene> scenes; private ScenesListViewModel scenesListViewModel; public SceneAdapter(Context context, List<Scene> list, ScenesListViewModel scenesListViewModel) { this.context = context; this.scenes = list; this.scenesListViewModel = scenesListViewModel; } @Override public void onBindViewHolder(SceneAdapter.BindingHolder holder, int position) { final Scene scene = scenes.get(position); holder.binding.setScene(scene); holder.binding.setViewModel(scenesListViewModel); holder.binding.executePendingBindings(); } ``` Another way doing it is to set a Listener in the ViewModel, but this is more likely mvp then mvvm. I could also use RXJava again and create a Subject within the adapter, but i would like to solve it with the android on-board tools.
2017/04/22
[ "https://Stackoverflow.com/questions/43559543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032539/" ]
I had to remove from: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], include: [ path.resolve(__dirname, "src","client") ], } ``` to: ``` { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ], } ``` This one works in my case. I don´t know why.
To create npm package, you can build like to: ``` module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /(node_modules|bower_components|build)/, loader: 'babel-loader' }, { test: /\.(css|less)$/, use: ["style-loader", "css-loader"] } ] }, ```
43,095,283
I'm having some issues with a Wicket (8.0.0-M4) NumberTextField in Kotlin (1.1.0). My stripped-down form looks like this: ``` class Test : AbstractWebPage() { val housenumberModel: Model<Int> = Model<Int>() val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel) val form: Form<Unit> = object : Form<Unit>("adressForm") {} override fun onInitialize() { super.onInitialize() form.add(housenumber.setRequired(false)) form.add(object : SubmitLink("submit") { override fun onSubmit() { super.onSubmit() println(housenumberModel.`object`) // this is line 28 } }) add(form) } } ``` After submitting the form I get the following stacktrace: > > java.lang.ClassCastException: java.lang.String cannot be cast to > java.lang.Number > at com.mycompany.test.pages.Test$onInitialize$1.onSubmit(Test.kt:28) > at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1312) > at org.apache.wicket.markup.html.form.Form.process(Form.java:979) > at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:802) > at org.apache.wicket.markup.html.form.Form.onRequest(Form.java:715) > at org.apache.wicket.core.request.handler.ListenerRequestHandler.internalInvoke(ListenerRequestHandler.java:301) > at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:250) > at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:210) > at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:203) > at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912) > at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65) > at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283) > at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253) > at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221) > at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262) > at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204) > at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:286) > [...] > > > If I use ``` val housenumberModel: Model<Int> = Model.of(0) ``` instead of ``` val housenumberModel: Model<Int> = Model<Int>() ``` everything works fine. But since my NumberTextField is optional I don't want to have it pre-initialized with 0. Me and my colleagues were trying to change the type signature of the Model in every way we could imagine but came to no solution. A co-worker suggested to write a custom Wicket converter since Kotlins Int is represendeted as a primitive type (From the docs: "On the JVM, non-nullable values of this type are represented as values of the primitive type int.") Even though I don't know yet if this would work it seems like an overkill for me. Another hack I could think of: writing some JavaScript to delete the zero from the input field. Also not really something I would want to do. Question: Is there a simple solution to my problem? (And as a bonus-question: has already anyone written a larger Wicket application in Kotlin and could tell me if this combination is ready for prime time to develop a critical project with this stack or is my problem just the tip of the iceberg?) [edit] Solution as pointed out by svenmeier: Using ``` val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel, Int::class.java) ``` works. Or as an alternative: ``` val housenumbervalue: Int? = null val housenumberModel: IModel<Int> = PropertyModel<Int>(this, "housenumbervalue") val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel) ```
2017/03/29
[ "https://Stackoverflow.com/questions/43095283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875083/" ]
Because of type erasure your NumberTextField cannot detect the generic type parameter of your model. Since your model object is null, it cannot be used to derive the type either. In this case Wicket assumes a String model object type :/. Either provide the type to the NumberTextField explicitly, or use a model that keeps its generic information, e.g. a PropertyModel.
There is a way to tell wicket about the type you want, it is by adding the type in the constructor. More [here](https://ci.apache.org/projects/wicket/apidocs/8.x/org/apache/wicket/markup/html/form/NumberTextField.html#NumberTextField-java.lang.String-org.apache.wicket.model.IModel-java.lang.Class-). In Java it looks like this: ``` new NumberTextField<Integer>("housenumberModel", housenumberModel, Integer.class); ```
5,501,924
I'm trying to do something like this: ``` for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } ``` However, it appears that `std::streampos` does not have `operator++` overloaded. Trying to use `Position = (Position + 1)` results in the following error: ``` ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: ``` Is there any workaround for this, or do I have to rely on `long unsigned int` being big enough for files?
2011/03/31
[ "https://Stackoverflow.com/questions/5501924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497934/" ]
Try a [`std::streamoff`](http://www.cplusplus.com/reference/iostream/streamoff/), which represents an offset in a stream. It supports both pre- and post increment/decrement operators. > > The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (**thus, to streampos too**) > > > Edit to Maxpm's comment: You can apply the `streamoff` to anywhere, be it `ios::beg` or an arbitary `streampos`. Apply it to `ios::beg` and it behaves like a normal `streampos`. Apply it to a `streampos` and you got `streampos+streamoff`.
Use `+=`: ``` for (std::streampos Position = 0; Position < 123; Position += 1) ``` `+` doesn’t work because `operator +` is actually defined for `streampos` and `steamoff`, not `int`. This means that two implicit conversions exist that are equally good: either your `1` could be converted to `streamoff` (which is probably a typedef for `unsigned long`). Or the `streampos` is implicitly converted to `streamoff` which then has `1` added.
5,501,924
I'm trying to do something like this: ``` for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } ``` However, it appears that `std::streampos` does not have `operator++` overloaded. Trying to use `Position = (Position + 1)` results in the following error: ``` ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: ``` Is there any workaround for this, or do I have to rely on `long unsigned int` being big enough for files?
2011/03/31
[ "https://Stackoverflow.com/questions/5501924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497934/" ]
Use `+=`: ``` for (std::streampos Position = 0; Position < 123; Position += 1) ``` `+` doesn’t work because `operator +` is actually defined for `streampos` and `steamoff`, not `int`. This means that two implicit conversions exist that are equally good: either your `1` could be converted to `streamoff` (which is probably a typedef for `unsigned long`). Or the `streampos` is implicitly converted to `streamoff` which then has `1` added.
I came across this link while looking into how I can subtract from a `std::streampos` object: <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=187599> The suggested solution is using the defined operator overload `operator+()` or `operator-()` which work pretty well for me. ``` Position.operator+(increment_val); Position.operator-(decrement_val); // alternative ``` P.S. It may be better to use `operator+()` than `operator-()` to avoid any problems related to sign change
5,501,924
I'm trying to do something like this: ``` for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } ``` However, it appears that `std::streampos` does not have `operator++` overloaded. Trying to use `Position = (Position + 1)` results in the following error: ``` ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: ``` Is there any workaround for this, or do I have to rely on `long unsigned int` being big enough for files?
2011/03/31
[ "https://Stackoverflow.com/questions/5501924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497934/" ]
Try a [`std::streamoff`](http://www.cplusplus.com/reference/iostream/streamoff/), which represents an offset in a stream. It supports both pre- and post increment/decrement operators. > > The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (**thus, to streampos too**) > > > Edit to Maxpm's comment: You can apply the `streamoff` to anywhere, be it `ios::beg` or an arbitary `streampos`. Apply it to `ios::beg` and it behaves like a normal `streampos`. Apply it to a `streampos` and you got `streampos+streamoff`.
`std::streampos` is not a numeric type, although it supports conversion to and from numeric types. If you want to do arithmetic on the position, you need to use `std::streamoff` (and specify the from argument when calling seek). Also, don't forget that you can't seek to an arbitrary position in a file unless it has been opened in binary mode, and imbued with the "C" locale.
5,501,924
I'm trying to do something like this: ``` for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } ``` However, it appears that `std::streampos` does not have `operator++` overloaded. Trying to use `Position = (Position + 1)` results in the following error: ``` ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: ``` Is there any workaround for this, or do I have to rely on `long unsigned int` being big enough for files?
2011/03/31
[ "https://Stackoverflow.com/questions/5501924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497934/" ]
Try a [`std::streamoff`](http://www.cplusplus.com/reference/iostream/streamoff/), which represents an offset in a stream. It supports both pre- and post increment/decrement operators. > > The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (**thus, to streampos too**) > > > Edit to Maxpm's comment: You can apply the `streamoff` to anywhere, be it `ios::beg` or an arbitary `streampos`. Apply it to `ios::beg` and it behaves like a normal `streampos`. Apply it to a `streampos` and you got `streampos+streamoff`.
I came across this link while looking into how I can subtract from a `std::streampos` object: <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=187599> The suggested solution is using the defined operator overload `operator+()` or `operator-()` which work pretty well for me. ``` Position.operator+(increment_val); Position.operator-(decrement_val); // alternative ``` P.S. It may be better to use `operator+()` than `operator-()` to avoid any problems related to sign change
5,501,924
I'm trying to do something like this: ``` for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } ``` However, it appears that `std::streampos` does not have `operator++` overloaded. Trying to use `Position = (Position + 1)` results in the following error: ``` ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: ``` Is there any workaround for this, or do I have to rely on `long unsigned int` being big enough for files?
2011/03/31
[ "https://Stackoverflow.com/questions/5501924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497934/" ]
`std::streampos` is not a numeric type, although it supports conversion to and from numeric types. If you want to do arithmetic on the position, you need to use `std::streamoff` (and specify the from argument when calling seek). Also, don't forget that you can't seek to an arbitrary position in a file unless it has been opened in binary mode, and imbued with the "C" locale.
I came across this link while looking into how I can subtract from a `std::streampos` object: <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=187599> The suggested solution is using the defined operator overload `operator+()` or `operator-()` which work pretty well for me. ``` Position.operator+(increment_val); Position.operator-(decrement_val); // alternative ``` P.S. It may be better to use `operator+()` than `operator-()` to avoid any problems related to sign change
133,750
Please, for the two lists ``` L1 = {{a, b}, {c, d}} L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}} ``` The desired result is ``` {{{ae, bf}, {ag, bh}}, {{ci, dj}, {ck, dq}}} ```
2016/12/18
[ "https://mathematica.stackexchange.com/questions/133750", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/45299/" ]
One way would be ``` l1 = {{a,b},{c,d}}; l2 = {{{e,f},{g,h}},{{i,j},{k,q}}}; Partition[Riffle[l1,l1],2] l2 (* {{{a e, b f},{a g, b h}},{{c i, d j},{c k, d q}}} *) ``` The idea behind this solution is to expand `l1` into the same shape as `l2` ``` Partition[Riffle[l1,l1],2] (* {{{a,b},{a,b}},{{c,d},{c,d}}} *) ``` and then use Mathematicas builtin elementwise multiplication on similar shaped lists to get the result. Another possible solution: ``` MapTimes[x_,{y_,z_}] := {x y,x z} MapTimes @@@ Transpose[{l1,l2}] (* {{{a e, b f},{a g, b h}},{{c i, d j},{c k, d q}}} *) ```
``` Flatten[ Flatten[L2, {{1}, {3}}] L1, {{1}, {3}}] ``` or ``` Function[x, # x] /@ #2 & @@@ Thread[{L1, L2}] ``` > > {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} > > >
133,750
Please, for the two lists ``` L1 = {{a, b}, {c, d}} L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}} ``` The desired result is ``` {{{ae, bf}, {ag, bh}}, {{ci, dj}, {ck, dq}}} ```
2016/12/18
[ "https://mathematica.stackexchange.com/questions/133750", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/45299/" ]
``` L1 = {{a, b}, {c, d}} L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}} Transpose[L1 Transpose[L2, {1, 3, 2}], {1, 3, 2}] ``` > > {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} > > >
``` Flatten[ Flatten[L2, {{1}, {3}}] L1, {{1}, {3}}] ``` or ``` Function[x, # x] /@ #2 & @@@ Thread[{L1, L2}] ``` > > {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} > > >
133,750
Please, for the two lists ``` L1 = {{a, b}, {c, d}} L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}} ``` The desired result is ``` {{{ae, bf}, {ag, bh}}, {{ci, dj}, {ck, dq}}} ```
2016/12/18
[ "https://mathematica.stackexchange.com/questions/133750", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/45299/" ]
``` L1 = {{a, b}, {c, d}}; L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}}; Transpose /@ (L1*(Transpose /@ L2)) (* {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} *) ``` or ``` Thread /@ (L1*(Thread /@ L2)) (* {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} *) % == %% (* True *) ```
``` Flatten[ Flatten[L2, {{1}, {3}}] L1, {{1}, {3}}] ``` or ``` Function[x, # x] /@ #2 & @@@ Thread[{L1, L2}] ``` > > {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} > > >
58,116,924
I have several database objects which need to extract a single record (like TOP 1) from a table, but the priority for which one is chosen depends on a BIT value in a settings table, and that settings table will contain only one row. I have written a view which will perform the required functionality: ``` CREATE VIEW TopOrganisationAddresses AS WITH cte AS ( SELECT OrganisationID, AddressID, CASE WHEN EXISTS (SELECT * FROM GlobalSettings WHERE DeliveryAddressInReports=1) THEN IsDeliveryAddress ELSE IsInvoiceAddress END AS OrderFirst, CASE WHEN EXISTS (SELECT * FROM GlobalSettings WHERE DeliveryAddressInReports=1) THEN IsInvoiceAddress ELSE IsDeliveryAddress END AS OrderSecond FROM OrganisationAddresses ) SELECT OrganisationID, AddressID, ROW_NUMBER() OVER(PARTITION BY OrganisationID ORDER BY OrderFirst DESC, OrderSecond DESC) AS [Row] FROM cte ``` **Will the SELECT \* FROM GlobalSettings queries be evaluated for every fow in the OrganisationAddresses table?** If so this would be incredibly wasteful as it is only a static value that isn't going to change.
2019/09/26
[ "https://Stackoverflow.com/questions/58116924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2882061/" ]
``` pm.response.json().depositInfoList ``` This will save whole depositInfoList JSON data to the environment variable, and hence when you try to access it, it showed up Object Object. ``` pm.response.json().depositInfoList.depositInfoId ``` This doesn't make sense as `depositInfoList` is an array, you have to provide index when you want to fetch values from arrays. ``` pm.response.json().depositInfoList[0].depositInfoId ``` This should work, as you're trying to get the property value of the first record of the array `depositInfoList`.
If you want to store the whole object/array in your Environment/Global/Collection variables, you need to stringify the value first: ``` const jsonBody = pm.response.json(); pm.environment.set('depositInfoList', JSON.stringify(jsonBody.depositInfoList)); //will store the whole array as string pm.environment.set('depositInfoItem', JSON.stringify(jsonBody.depositInfoList[0])); //will store first object from the array as string pm.environment.set('depositInfoItemId', jsonBody.depositInfoList[0].depositInfoId); //will store if of first object from the array ``` Otherwise, you will store [object Object] value: ``` const jsonBody = pm.response.json(); pm.environment.set('depositInfoList', jsonBody.depositInfoList); //will store [object Object] pm.environment.set('depositInfoItem', jsonBody.depositInfoList[0]); //will store [object Object] pm.environment.set('depositInfoItemId', jsonBody.depositInfoList[0].depositInfoId); //will store if of first object from the array ``` Secondly, if you want to get value from the Environment/Global/Collection variable and work with it as array/object you need to parse it as JSON: ``` const depositInfoList = JSON.parse(pm.environment.get('depositInfoList')); //returns array const depositInfoItem = JSON.parse(pm.environment.get('depositInfoItem')); //returns object const depositInfoItemId = pm.environment.get('depositInfoItemId'); //returns number ```
12,453,994
So I'm trying to do my programming assignment, here it is: ``` Write a C/C++ program (call it string invert) that takes a string argument from the command line and outputs the string in reversed order. Here comes the twist: Each process can output at most one character. If you want to output more than a single character, you must fork off one or more processes in order to do that, and each of the forked processes in turn outputs a single character. After the call to program string invert with the command line argument, the output should appear, and no more processes should be running, in addition to the shell. Test your program on any UNIX/LINUX machine, and turn in the source code as part of the written assignment. (The source code should be at most a few lines long.) ``` I can do the read and invert string easy, no problem. The problem is what does it mean when it says "each process can output at most one character". i don't even understand what that means. I don't need any code, i'm confident i can do it myself once i understand. I just need someone to explain what that's supposed to mean.
2012/09/17
[ "https://Stackoverflow.com/questions/12453994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222676/" ]
Let's say you have the input "abcd", then your program should spawn a process for each character. So the first process would return 'd', the second process 'c' and so on. The assignment is probably a test of how well you understand synchronizing processes.
Every process should jsut print *ONE* character. Example: ``` $yourProgamm sample ``` usually you would loop over the sample string and simply print each character with a call to `cout` or so. However you are supposed to only print one character per process. Meaning you output `e`, everything is fine. But if you run the loop again to output `l` the same process printed a second character. So you have to *fork* a process for *each* character, let that process print that *one* character and continue your loop. Be sure to synchronize with `join` else you might get random order output (I guess this is the main point of the assignment, just run it a couple of times without it to see what I mean).
3,537
While writing RoR code I often need to run drop into a [pry](https://github.com/pry/pry) session or a debugger. So I place my `binding.pry` line in the implementation code and run my spec(s). That works fine if I run the specs in a terminal but from inside Emacs, I get a messy output and it's very hard to use the debugger/pry. How are you guys doing that ? ![enter image description here](https://i.stack.imgur.com/yJuLY.png)
2014/11/14
[ "https://emacs.stackexchange.com/questions/3537", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/94/" ]
`rspec-mode` has recently added a [section in the README](https://github.com/pezra/rspec-mode/#debugging) on this subject. It says: Install `inf-ruby` and add this to your init file: ``` (add-hook 'after-init-hook 'inf-ruby-switch-setup) ``` When you've hit the breakpoint, hit `C-x C-q` to enable `inf-ruby`.
I find that [pry-remote](https://github.com/Mon-Ouie/pry-remote) is the best way to run pry within Emacs, since then pry gets its own dedicated buffer and can attach to a ruby process from anywhere (included a non-Emacs terminal or things like [pow](http://pow.cx/)). I use something like this: ``` (defun my-run-remote-pry (&rest args) (interactive) (let ((buffer (apply 'make-comint "pry-remote" "pry-remote" nil args))) (switch-to-buffer buffer) (setq-local comint-process-echoes t))) (define-key ruby-mode-map (kbd "C-c r d") 'my-run-remote-pry) ; (or whatever keybinding) ``` Then, you'll put `binding.remote_pry` in your code; you attach to a waiting `pry` with `C-c r d` (or whatever) and exit pry (continuing the process) with `C-c C-d`. You'll also probably want to disable paging in your `~/.pryrc`, since it doesn't play well with `comint`: ``` Pry.config.pager = false ```
101,558
I've set up a VMWare instance to run CastIron Integration Appliance. I allocated 2gb of memory to the instance, assuming it would take this as physical memory (my server has 8gb total). When I view `top` however on the server, the vmware-vmx process has about 100m Resident memory and 1900m Virtual. Running CastIron it reports that the appliance often hits 50% memory usage. Does this mean I'm using 900mb of harddrive space as memory? I wanted VMWare to use 2gb of physical memory, no swap. Can anyone tell me how to achieve this? **Setup** Debian Lenny 5.0.3 VMWare Server 2.0.2
2010/01/11
[ "https://serverfault.com/questions/101558", "https://serverfault.com", "https://serverfault.com/users/19656/" ]
VMware Server has a setting to define if you want all VM memory to fit in physical RAM, or allow some of them to be swapped; it's in the host settings. If you have more RAM than you're using, you can safely set it to only use RAM; you will then not be able to power on more VMs if there's not enough available physical memory, of course.
Unless you're using ESX and making VM resource reservations your VM will not be given any more physical memory than is being **used**, i.e. if you give your VM 4GB but only ever address 1GB then only 1GB of physical memory is taken up. I'm not sure where the 50% figure comes from but if that VM's vmware-vmx process is only using 100MB then that's all that's being used. Basically don't worry about it :)
101,558
I've set up a VMWare instance to run CastIron Integration Appliance. I allocated 2gb of memory to the instance, assuming it would take this as physical memory (my server has 8gb total). When I view `top` however on the server, the vmware-vmx process has about 100m Resident memory and 1900m Virtual. Running CastIron it reports that the appliance often hits 50% memory usage. Does this mean I'm using 900mb of harddrive space as memory? I wanted VMWare to use 2gb of physical memory, no swap. Can anyone tell me how to achieve this? **Setup** Debian Lenny 5.0.3 VMWare Server 2.0.2
2010/01/11
[ "https://serverfault.com/questions/101558", "https://serverfault.com", "https://serverfault.com/users/19656/" ]
Unless you're using ESX and making VM resource reservations your VM will not be given any more physical memory than is being **used**, i.e. if you give your VM 4GB but only ever address 1GB then only 1GB of physical memory is taken up. I'm not sure where the 50% figure comes from but if that VM's vmware-vmx process is only using 100MB then that's all that's being used. Basically don't worry about it :)
Yes this is true. You need to allocate the RAM usage from properties of VM. Ensure VM is switched off.
101,558
I've set up a VMWare instance to run CastIron Integration Appliance. I allocated 2gb of memory to the instance, assuming it would take this as physical memory (my server has 8gb total). When I view `top` however on the server, the vmware-vmx process has about 100m Resident memory and 1900m Virtual. Running CastIron it reports that the appliance often hits 50% memory usage. Does this mean I'm using 900mb of harddrive space as memory? I wanted VMWare to use 2gb of physical memory, no swap. Can anyone tell me how to achieve this? **Setup** Debian Lenny 5.0.3 VMWare Server 2.0.2
2010/01/11
[ "https://serverfault.com/questions/101558", "https://serverfault.com", "https://serverfault.com/users/19656/" ]
VMware Server has a setting to define if you want all VM memory to fit in physical RAM, or allow some of them to be swapped; it's in the host settings. If you have more RAM than you're using, you can safely set it to only use RAM; you will then not be able to power on more VMs if there's not enough available physical memory, of course.
First, vmware **ALWAYS** creates swap. It's required. If you do not set reservations, ESX host creates a .vswp file equal to the difference between the amount of physical memory assigned to the virtual machine and the reservation it has. By default, memory reservations are set to 0. If you have a virtual machine with 2GB of memory without a reservation, it creates a 2GB .vswp file when it is powered on. Whether it uses it or not depends on other factors (primarily do you have enough free ram on the host to support the guests requests). If you make reservations for your virtual machine's that are equal to the amount of RAM assigned to them, swapping and page sharing does not occur. Second you can give a vm watever you want but vmware will is only going to report what the guest actually uses. When you set a number for how much ram you want to allocate this is the **maximum** amount of ram that server will ever use.
101,558
I've set up a VMWare instance to run CastIron Integration Appliance. I allocated 2gb of memory to the instance, assuming it would take this as physical memory (my server has 8gb total). When I view `top` however on the server, the vmware-vmx process has about 100m Resident memory and 1900m Virtual. Running CastIron it reports that the appliance often hits 50% memory usage. Does this mean I'm using 900mb of harddrive space as memory? I wanted VMWare to use 2gb of physical memory, no swap. Can anyone tell me how to achieve this? **Setup** Debian Lenny 5.0.3 VMWare Server 2.0.2
2010/01/11
[ "https://serverfault.com/questions/101558", "https://serverfault.com", "https://serverfault.com/users/19656/" ]
First, vmware **ALWAYS** creates swap. It's required. If you do not set reservations, ESX host creates a .vswp file equal to the difference between the amount of physical memory assigned to the virtual machine and the reservation it has. By default, memory reservations are set to 0. If you have a virtual machine with 2GB of memory without a reservation, it creates a 2GB .vswp file when it is powered on. Whether it uses it or not depends on other factors (primarily do you have enough free ram on the host to support the guests requests). If you make reservations for your virtual machine's that are equal to the amount of RAM assigned to them, swapping and page sharing does not occur. Second you can give a vm watever you want but vmware will is only going to report what the guest actually uses. When you set a number for how much ram you want to allocate this is the **maximum** amount of ram that server will ever use.
Yes this is true. You need to allocate the RAM usage from properties of VM. Ensure VM is switched off.
101,558
I've set up a VMWare instance to run CastIron Integration Appliance. I allocated 2gb of memory to the instance, assuming it would take this as physical memory (my server has 8gb total). When I view `top` however on the server, the vmware-vmx process has about 100m Resident memory and 1900m Virtual. Running CastIron it reports that the appliance often hits 50% memory usage. Does this mean I'm using 900mb of harddrive space as memory? I wanted VMWare to use 2gb of physical memory, no swap. Can anyone tell me how to achieve this? **Setup** Debian Lenny 5.0.3 VMWare Server 2.0.2
2010/01/11
[ "https://serverfault.com/questions/101558", "https://serverfault.com", "https://serverfault.com/users/19656/" ]
VMware Server has a setting to define if you want all VM memory to fit in physical RAM, or allow some of them to be swapped; it's in the host settings. If you have more RAM than you're using, you can safely set it to only use RAM; you will then not be able to power on more VMs if there's not enough available physical memory, of course.
Yes this is true. You need to allocate the RAM usage from properties of VM. Ensure VM is switched off.
33,708
I am 31 year old with moderate fitness. I cycle 3 times a week about 40 mins average and my heart rate monitor data shows I average more than many other people on strava. I know beats per minute may be considered as a fitness parameter and was wondering why people like Amanda Coker average out 115bpm after a 300+ km ride and mine turns out to be 140bpm for 10k ride. What are the factors which control heart beats? Are there any contributing factors like hormones imbalance, blood count, adrenal fatigue etc?
2017/03/27
[ "https://fitness.stackexchange.com/questions/33708", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/15392/" ]
Its all about conditioning. You have not stated for how long have you been cycling and am assuming not very long. The person you mentioned might also have sub 50 resting heart rate while yours would be in 70-90 range. Once you keep performing the same exercise over a period of time, your body/heart becomes very efficient in doing so. Basically the same 40 mins ride on same tempo would feel a lot easier after few weeks of continuous training. Even your average HRM would gradually lower as the energy expenditure goes down due to the cardio conditioning.
Many things affect your heart rate. Illness, overtraining, the weather, medication, dehydration, stress...and the list goes on. Be sure to do tons of aerobic work if you're just starting out and keep your heart rate below 75% of your maximum. You should see your speed increase and your heart rate drop. You might never have as low a heart rate as Amanda Coker, but it will be strong!
4,852,522
i have been struggling with these problem all today. i added a draggable object inside a jquery accordion menu. the problem is it doesnt allow me to drag it outside. when i try to drag it outside it is resizing the div inside accordion menu and showing scrollbar. here i made a demo of the problem. <http://jsbin.com/efoje4/4> please help :(
2011/01/31
[ "https://Stackoverflow.com/questions/4852522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401006/" ]
in your `draggable` declaration, add the option `appendTo:'body'` working example: <http://jsbin.com/efoje4/6> see [jQuery-Ui: Cannot drag object outside of an accordion](https://stackoverflow.com/questions/1827504/jquery-ui-cannot-drag-object-outside-of-an-accordion)
<http://jsbin.com/efoje4/8/> You can use appendTo: 'body' which binds to object to the body of the page and not the current container element.
53,709,133
I want to find the total number of years(which is simply an integer of four digits) referenced in a document, which is given as a normal string input using python. Can this be done without using Regex?
2018/12/10
[ "https://Stackoverflow.com/questions/53709133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9641740/" ]
In SQL Server you'd use `DATEDIFF` to find the difference between the birthdate and Jan 1, 2015. ``` SELECT * FROM mytable.device WHERE DATEDIFF(YEAR,mytable.birthdate,'1/1/2015') BETWEEN 20 AND 35 ```
Disclaimer: although date arithmetic **is** defined in the SQL standard, only a few DBMS products actually support the ANSI SQL when it comes to date or timestamp arithmetic. The basic idea is that you need to calculate the difference between the 2015-01-01 and the `birthdate` value in your table and compare that with the age range you want to get. Postgres supports an `age()` function that comes in handy here: ``` select * from device where age(date '2015-01-01', birthdate) between interval '20' year and interval '35' year; ``` For ANSI standard SQL this could be written using the `-` operator: ``` select * from device where timestamp '2015-01-01' - birthdate between interval '20' year and interval '35' year; ``` Depending on the actual DBMS you need to check for equivalent functions that can calculate the difference between two dates.
61,544,258
I have a struct defined like this: ``` struct IFSFunc { int a; bool operator<(const IFSFunc& other) { return a < other.a; } }; ``` Since `IFSfunc` is a `struct`, access modifier for the `operator<` should be `public`. I also have this code: ``` #include <algorithm> std::vector<std::pair<double, IFSFunc>> ifsFuncs; // fill the vector with various data std::sort(ifsFuncs.begin(), ifsFuncs.end()); ``` I need to sort ifsFuncs based on the first `double` in the pair. I don't care about `IFSFunc` structure, if the `double` is the same. However, for std::sort to work, which is defined like this: ``` template <class _Ty1, class _Ty2> _NODISCARD constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { return _Left.first < _Right.first || (!(_Right.first < _Left.first) && _Left.second < _Right.second); } ``` I have to override the less than operator for the `second` in this case `IFSfunc`, which I did. However, trying to compile this code gives me the following error: ``` Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const _Ty2' (or there is no acceptable conversion) ``` Why?
2020/05/01
[ "https://Stackoverflow.com/questions/61544258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430705/" ]
You need to define that operator as a const member function. Also, don't just return true for a comparison. That can result in infinite looping.
I just figure it out. The overloaded function signature was wrong, this is what I need: ``` struct IFSFunc { int a; bool operator<(const IFSFunc& other) const { return a < other.a; } }; ``` Notice that the `operator<` is now a const function.
892,805
I came across the identity $$\int^x\_0\frac{\ln(p+qt)}{r+st}{\rm d}t=\frac{1}{2s}\left[\ln^2{\left(\frac{q}{s}(r+sx)\right)}-\ln^2{\left(\frac{qr}{s}\right)}+2\mathrm{Li}\_2\left(\frac{qr-ps}{q(r+sx)}\right)-2\mathrm{Li}\_2\left(\frac{qr-ps}{qr}\right)\right]$$ in a book. Unfortunately, as of now, I am not very adept at manipulating such integrals and thus I have little idea on how to proceed with proving this identity. For example, substituting $u=r+sx$ doesn't seem to help much. Hence, I would like to seek assistance as to how this integral can be evaluated. Help will be greatly appreciated. Thank you.
2014/08/10
[ "https://math.stackexchange.com/questions/892805", "https://math.stackexchange.com", "https://math.stackexchange.com/users/140590/" ]
Among various ways to do it, this one is simple : ![enter image description here](https://i.stack.imgur.com/kYcXA.jpg)
$\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,} \newcommand{\dd}{{\rm d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\fermi}{\,{\rm f}} \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\sech}{\,{\rm sech}} \newcommand{\sgn}{\,{\rm sgn}} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ \begin{align}&\overbrace{\color{#c00000}{\int\_{0}^{x}% {\ln\pars{p+qt} \over r + st}\,\dd t}} ^{\ds{\mbox{Set}\ p + qt\equiv \xi\ \imp\ t = {\xi - p \over q}}}\ =\ \int\_{p}^{p + qx}{\ln\pars{\xi} \over r + s\pars{\xi - p}/q}\,{\dd\xi \over q} =-\int\_{p}^{p + qx}{\ln\pars{\xi} \over sp - rq - s\xi}\,\dd\xi \\[5mm]&={1 \over rq - sp}\ \overbrace{\int\_{p}^{p + qx} {\ln\pars{\xi} \over 1 - s\xi/\pars{sp - rq}}\,\dd\xi} ^{\ds{\mbox{Set}\ {s \over sp - rq}\,\xi\equiv t\ \imp\ \xi = {sp - rq \over s}\,t}} \\[5mm]&= {1 \over rq - sp}\int\_{sp/\pars{sp - rq}}^{s\pars{p + qx}/\pars{sp - rq}} {\ln\pars{\bracks{sp - rq}t/s} \over 1 - t}\,{sp - rq \over s}\,\dd t \\[3mm]&=-\,{1 \over s}\int\_{sp/\pars{sp - rq}}^{s\pars{p + qx}/\pars{sp - rq}} {\ln\pars{\bracks{sp - rq}t/s} \over 1 - t}\,\dd t \\[3mm]&=\left.{1 \over s}\ln\pars{1 - t}\ln\pars{{sp - rq \over s}\,t} \right\vert\_{\,t\ =\ {sp \over sp\ -\ rq}}^{\, t\ =\ s\,{p\ +\ qx \over sp\ -\ rq}} \ -\ {1 \over s}\int\_{sp/\pars{sp - rq}}^{s\pars{p + qx}/\pars{sp - rq}} {\ln\pars{1 - t} \over t}\,\dd t \\[3mm]&={1 \over s}\bracks{\ln\pars{1 - s\,{p + qx \over sp - rq}} \ln\pars{p + qx} - \ln\pars{1 - {sp \over sp - rq}}\ln\pars{p}} \\[3mm]&\phantom{=}+{1 \over s}\bracks{% {\rm Li}\_{2}\pars{{p + qx \over sp - rq}\,s} -{\rm Li}\_{2}\pars{sp \over sp - rq}} \end{align} > > \begin{align}&\color{#66f}{\large\int\_{0}^{x}{\ln\pars{p+qt} \over r + st}\,\dd t} > \\[3mm]&=\color{#66f}{\large{1 \over s}\bracks{% > \ln\pars{{r + sx \over rq - sp}\,q}\ln\pars{p + qx} > - \ln\pars{rq \over rq - sp}\ln\pars{p}}} > \\[3mm]&\color{#66f}{\large + {1 \over s}\bracks{% > {\rm Li}\_{2}\pars{{p + qx \over sp - rq}\,s} > -{\rm Li}\_{2}\pars{sp \over sp - rq}}} > \end{align} > > > Indeed, for particular values of the different parameters we should take care of possible $\color{#c00000}{\large\ds{\ln}}$ or/and $\color{#c00000}{\large\ds{{\rm Li}\_{2}}}$ branch cuts.
2,281,756
I want to prove this: $\bar{E}'\underline{\subset }E'$. Now this is how I look at it: if I have $ x\in \bar{E}'$, then x must be in $\underline{\subset }E'$. Now the conditions for being a limit point is: **def limit point:** A point p is a limit point of set E if every neighborhood of p contains a point q not equal to p, such that q is an element of E. **def neighborhood:** A neighborhood of p is a set Nr(p) consisting of all q such that d(p,q) < r for some r>0. **def $E'$** is the set of limit points. Next we can conclude that there is a y element of $\bar{E}$, hence Y is either an element of E or E' or both. If y is an element of E then we can set d(x,y) Now if y is an element of $E'$, then y is a limit point hence there is a z element of E such that d(y,z) Questions: Is it correct to state: The final goal is to make sure that d(x,z) Given that I have imposed that y=z in first case does this follow in the second case.(do I need to work under this assumption)
2017/05/15
[ "https://math.stackexchange.com/questions/2281756", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110821/" ]
Suppose $p\in (\overline{E})'$ and let $r\_1>0$. By definition, there exists an element $q\neq p$ in $\overline{E}$ such that $d(p,q)<r\_1$. Since $\overline{E}=E\cup E'$, we have either $q\in E$ or $q\in E'$. If $q\in E$ we are done as we have found an element of $E$ which is in $B(p;r\_1)$. Suppose now that $q\in E'$, and take $r\_2=\min \{r\_1-d(p,q),d(p,q)\}$ (or $r\_2=r\_1$ in case $p=q$). We have $r\_2>0$ and $B(q;r\_2)\subseteq B(p;r\_1)$ and, by definition of $E'$, there is an element $x\neq q$ in $E$ such that $x\in B(q;r\_2)$, and hence, $x\in B(p;r\_1)$ as desired.
Assume a in (cl A)' and U open nhood a. Thus some x in U cap cl A with x /= a. Let V = U - {a} which is open for T1 spaces including metric spaces. Since x in V, there is some y in V cap A. y /= a. Hence a in A' and (cl A)' subset A'.
56,788,471
While using `Future` I have seen people use ``` Future{ Thread sleep 500 promise success "You've just completed the promise with me in it!" } ``` Looking at the definition of `Future`, I can see that Future is a trait But when I make my own trait, Example: ``` trait t{} def main(args: Array[String]): Unit = { t{ println("Test") } } ``` It does not compile. Why?
2019/06/27
[ "https://Stackoverflow.com/questions/56788471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7781747/" ]
when you write `Future{ /*your code*/ }` then the `apply` method of the companion object of `Future` is called. the signature of the `Future`'s apply method is the following ``` def apply[T](body:=>T) ``` You can see that the `apply` method is called when you do `ctrl+click` or `cmd+click` on the `Future` in an IDE such as InteliJ. Your trait `t` does not have an apply. Therefore that piece of code does not compile. ``` trait t{} object t{ apply[T](body:=>T){} } ```
The syntax for Future you describe comes from the trait companion object. This object has the following method : ``` def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = unit.map(_ => body) ``` The accepted argument being a function returning a T, it's perfectly idiomatic to pass it via the form you see, which is a bracketed code block. This being said, you can kind of instantiate your traits (by creating anonymous subclasses of them), the following compile : ``` trait t {} object MyApp extends App { new t { println("Test") } } ``` I would not recommend it as a general good practice though, but it has its uses.
4,143
We want to limit the permissions for users i.e. not to provide system admin access to all the users. When a non-admin user tries to port the content, we are getting the error at the time of exporting the content: "Failed to resolve mappings in application data SiteEdit" however there is option to skip the error. Given below is the details of exception. What permission is required to resolve this issue? ``` Error details: System.ServiceModel.FaultException`1[[Tridion.ContentManager.CoreService.Client.CoreServiceFault, Tridion.ContentManager.CoreService.Client, Version=6.1.0.996, Culture=neutral, PublicKeyToken=ddfc895746e5ee6b]]: System.ServiceModel.FaultException`1[Tridion.ContentManager.CoreService.Client.CoreServiceFault]: You do not have permission to perform this action. (Fault Detail is equal to Tridion.ContentManager.CoreService.Client.CoreServiceFault). ```
2014/01/14
[ "https://tridion.stackexchange.com/questions/4143", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/628/" ]
I found the solution to the problem on Tridion forum. [Tridion Article](https://sdltridionworld.com/articles/sdltridion2011/tutorials/using-content-porter-2009-sp1-for-dtap-4.aspx) Essentially, when you perform import in content porting, the publication metadata and other information is also retrieved and tried to be ported. To avoid this from happening, while importing selected children only which will not select any additional items and only will select the required items. After performing above steps, even non-admin can content-port the items on which they have access to.
if you are using a Non-Administrator user to run Content Porter, then you need to look for all the dependencies of the Items that you are accessing. In order to export/import an Item through Content Porter running using a Non-Administrator user, it is necessary that the Specific Item as well as all the dependencies of that Item must have Read/Write Access.
4,143
We want to limit the permissions for users i.e. not to provide system admin access to all the users. When a non-admin user tries to port the content, we are getting the error at the time of exporting the content: "Failed to resolve mappings in application data SiteEdit" however there is option to skip the error. Given below is the details of exception. What permission is required to resolve this issue? ``` Error details: System.ServiceModel.FaultException`1[[Tridion.ContentManager.CoreService.Client.CoreServiceFault, Tridion.ContentManager.CoreService.Client, Version=6.1.0.996, Culture=neutral, PublicKeyToken=ddfc895746e5ee6b]]: System.ServiceModel.FaultException`1[Tridion.ContentManager.CoreService.Client.CoreServiceFault]: You do not have permission to perform this action. (Fault Detail is equal to Tridion.ContentManager.CoreService.Client.CoreServiceFault). ```
2014/01/14
[ "https://tridion.stackexchange.com/questions/4143", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/628/" ]
if you are using a Non-Administrator user to run Content Porter, then you need to look for all the dependencies of the Items that you are accessing. In order to export/import an Item through Content Porter running using a Non-Administrator user, it is necessary that the Specific Item as well as all the dependencies of that Item must have Read/Write Access.
Glad to see you have succeeded in identifying the publication metadata as the cause of the problem (although it does look like a different problem, as you started with an export problem) However the more general case is that content porter is telling you "You do not have permission to perform this action", and you don't know which item is involved. To identify the problematic items you can look in the event log on the Tridion CM server, where authorization failures are logged as warnings. Simply monitor the log as you run your export (or import) and you can get more information about your problem.
4,143
We want to limit the permissions for users i.e. not to provide system admin access to all the users. When a non-admin user tries to port the content, we are getting the error at the time of exporting the content: "Failed to resolve mappings in application data SiteEdit" however there is option to skip the error. Given below is the details of exception. What permission is required to resolve this issue? ``` Error details: System.ServiceModel.FaultException`1[[Tridion.ContentManager.CoreService.Client.CoreServiceFault, Tridion.ContentManager.CoreService.Client, Version=6.1.0.996, Culture=neutral, PublicKeyToken=ddfc895746e5ee6b]]: System.ServiceModel.FaultException`1[Tridion.ContentManager.CoreService.Client.CoreServiceFault]: You do not have permission to perform this action. (Fault Detail is equal to Tridion.ContentManager.CoreService.Client.CoreServiceFault). ```
2014/01/14
[ "https://tridion.stackexchange.com/questions/4143", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/628/" ]
I found the solution to the problem on Tridion forum. [Tridion Article](https://sdltridionworld.com/articles/sdltridion2011/tutorials/using-content-porter-2009-sp1-for-dtap-4.aspx) Essentially, when you perform import in content porting, the publication metadata and other information is also retrieved and tried to be ported. To avoid this from happening, while importing selected children only which will not select any additional items and only will select the required items. After performing above steps, even non-admin can content-port the items on which they have access to.
Glad to see you have succeeded in identifying the publication metadata as the cause of the problem (although it does look like a different problem, as you started with an export problem) However the more general case is that content porter is telling you "You do not have permission to perform this action", and you don't know which item is involved. To identify the problematic items you can look in the event log on the Tridion CM server, where authorization failures are logged as warnings. Simply monitor the log as you run your export (or import) and you can get more information about your problem.
64,263,173
Working on a Ruby on Rails project using ERB. I am trying to link a user to their profile page. For example, clicking on the dropdown link and then profile should bring you to site.com/users/1 if you are logged in as User 1. ``` <a class="dropdown-item" href="users/<%= current_user.id %>">Profile</a ``` This works on all the pages, however when I move to the profile page, it for some reason changes to site.com/users/users/1 if I click on the Profile link while on the profile thus giving me an error. Any tips?
2020/10/08
[ "https://Stackoverflow.com/questions/64263173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13259707/" ]
You could use the cube root of the absolute value of a normal distribution: ``` # generate noisy data set.seed(69) b_x <- 1.3 * (abs(rnorm(2000)))^0.33 + 2 b_y <- 6 * (abs(rnorm(2000)))^0.33 + 20 biased <- data.frame(b_x, b_y) biased$indicator <- 'biased' colnames(biased) <- c("x", "y", "indicator") # put together on plot dummy_data <- rbind(trended, biased) ggplot(dummy_data, aes(x = x, y = y, color = indicator)) + geom_point(show.legend = FALSE) + scale_color_manual(values = c("#FF0000", "#999999")) + theme_bw() + theme(plot.title = element_text(size=9, face='bold'), legend.position = "none") + labs(title = "The Impact of Selection Bias", x = "X", y = "Y") ``` [![enter image description here](https://i.stack.imgur.com/R9LDr.png)](https://i.stack.imgur.com/R9LDr.png)
It seems that you are looking for multivariate normal random numbers as provided by *mvrnorm* in the package *MASS*. You can specify the midpoint of the cloud by the parameter *mu* and the shape of the cloud by the covariance matrix in the parameter *Sigma*. The orientation of the cloud is the direction of the eigenvector to the largest eigenvalue of *Sigma*. As the normal distribution has an unlimited range, you might want to cut off the results at some threshold.
64,263,173
Working on a Ruby on Rails project using ERB. I am trying to link a user to their profile page. For example, clicking on the dropdown link and then profile should bring you to site.com/users/1 if you are logged in as User 1. ``` <a class="dropdown-item" href="users/<%= current_user.id %>">Profile</a ``` This works on all the pages, however when I move to the profile page, it for some reason changes to site.com/users/users/1 if I click on the Profile link while on the profile thus giving me an error. Any tips?
2020/10/08
[ "https://Stackoverflow.com/questions/64263173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13259707/" ]
It seems that you are looking for multivariate normal random numbers as provided by *mvrnorm* in the package *MASS*. You can specify the midpoint of the cloud by the parameter *mu* and the shape of the cloud by the covariance matrix in the parameter *Sigma*. The orientation of the cloud is the direction of the eigenvector to the largest eigenvalue of *Sigma*. As the normal distribution has an unlimited range, you might want to cut off the results at some threshold.
Another way would be to just convolve your uniformly distributed samples with something to smooth out the edges. For example, with a Gaussian like: ```r n <- 1000 biased <- data.frame( x=runif(n, 2, 4) + rnorm(n, sd=0.1), y=runif(n, 20, 30) + rnorm(n, sd=0.5), indicator='biased') ``` Giving the following plot: ![gaussian output](https://i.stack.imgur.com/tKSYe.png) Some of these samples obviously end up outside your box, but you could adjust parameters a bit so that doesn't happen. Otherwise it's just occurred to me that a Beta distribution is probably good for this, e.g.: ```r lambda <- 2 biased <- data.frame( x=2 + 2 * rbeta(n, lambda, lambda), y=20 + 10 * rbeta(n, lambda, lambda), indicator='biased') ``` gives ![beta output](https://i.stack.imgur.com/ig9q3.png) where `lambda` controls how tight you want the red dots to be centered; a value of 1 means uniform, <1 towards the edges, >1 towards the center.
64,263,173
Working on a Ruby on Rails project using ERB. I am trying to link a user to their profile page. For example, clicking on the dropdown link and then profile should bring you to site.com/users/1 if you are logged in as User 1. ``` <a class="dropdown-item" href="users/<%= current_user.id %>">Profile</a ``` This works on all the pages, however when I move to the profile page, it for some reason changes to site.com/users/users/1 if I click on the Profile link while on the profile thus giving me an error. Any tips?
2020/10/08
[ "https://Stackoverflow.com/questions/64263173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13259707/" ]
You could use the cube root of the absolute value of a normal distribution: ``` # generate noisy data set.seed(69) b_x <- 1.3 * (abs(rnorm(2000)))^0.33 + 2 b_y <- 6 * (abs(rnorm(2000)))^0.33 + 20 biased <- data.frame(b_x, b_y) biased$indicator <- 'biased' colnames(biased) <- c("x", "y", "indicator") # put together on plot dummy_data <- rbind(trended, biased) ggplot(dummy_data, aes(x = x, y = y, color = indicator)) + geom_point(show.legend = FALSE) + scale_color_manual(values = c("#FF0000", "#999999")) + theme_bw() + theme(plot.title = element_text(size=9, face='bold'), legend.position = "none") + labs(title = "The Impact of Selection Bias", x = "X", y = "Y") ``` [![enter image description here](https://i.stack.imgur.com/R9LDr.png)](https://i.stack.imgur.com/R9LDr.png)
Another way would be to just convolve your uniformly distributed samples with something to smooth out the edges. For example, with a Gaussian like: ```r n <- 1000 biased <- data.frame( x=runif(n, 2, 4) + rnorm(n, sd=0.1), y=runif(n, 20, 30) + rnorm(n, sd=0.5), indicator='biased') ``` Giving the following plot: ![gaussian output](https://i.stack.imgur.com/tKSYe.png) Some of these samples obviously end up outside your box, but you could adjust parameters a bit so that doesn't happen. Otherwise it's just occurred to me that a Beta distribution is probably good for this, e.g.: ```r lambda <- 2 biased <- data.frame( x=2 + 2 * rbeta(n, lambda, lambda), y=20 + 10 * rbeta(n, lambda, lambda), indicator='biased') ``` gives ![beta output](https://i.stack.imgur.com/ig9q3.png) where `lambda` controls how tight you want the red dots to be centered; a value of 1 means uniform, <1 towards the edges, >1 towards the center.
19,135,121
I'm using a php script that get arguments from a html page and send them to an expect shell. When I call this php from CLI it works fine but when i call it from the web page it displays only the first line `spawn ssh user@host` The code: ``` #!/bin/sh var=$(expect -c " spawn ssh user@host expect \"password:\" send \"XXXX\r\" expect -re \"prompt>\" send \"./xx.sh $1 $2 $3\r\" expect -re \"prompt>\" send \"sleep 35\" expect -re \"prompt>\" send \"logout\" ") echo "$var" ```
2013/10/02
[ "https://Stackoverflow.com/questions/19135121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2131714/" ]
I found a solution for my problem: First create a new header file called `enums.h` which looks like: ``` #ifndef ENUMS_H #define ENUMS_H #include <QtDBus> #include "enumDBus.h" enum Color { RED = 0, BLUE, GREEN }; Q_DECLARE_METATYPE(Color) #endif /* ENUMS_H */ ``` Note following line `#include "enumDBus.h"`, you can find this header file [here](http://techbase.kde.org/Development/Tutorials/D-Bus/CustomTypes#enumDBus.hpp). So after you declared the enum you can declare a method which takes the enum as argument, in this example I declared following method in `calculator.h`: ``` void setColor(Color color); ``` The implementation for this method: ``` void Calculator::setColor(Color c) { switch (c) { case BLUE: std::cout << "Color: blue" << std::endl; break; case GREEN: std::cout << "Color: green" << std::endl; break; case RED: std::cout << "Color: reed" << std::endl; break; default: std::cout << "Color: FAIL!" << std::endl; } } ``` Now let's generate the Interface description (XML), use following command ``` qdbuscpp2xml -M -s calculator.h -o com.meJ.system.CalculatorInterface.xml ``` The generation of method which contains custom types doesn't work properly, so we need to do some adjustments: ``` <!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <interface name="com.meJ.system.CalculatorInterface"> <method name="setColor"> <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="Color"/> <arg type="(i)" direction="in" name="c"/> </method> </interface> </node> ``` With this XML file we can simply create our adaptors and interfaces classes. In our `main.cpp` (on client and server!) we have to register our custom type: ``` int main(int argc, char** argv) { qRegisterMetaType<Color>("Color"); qDBusRegisterMetaType<Color>(); } ``` ### Client Side Include generated `calculatorInterface.h` and `enums.h` in your `main.cpp`. Now you can simply call your method: ``` int main(int argc, char** argv) { qRegisterMetaType<Color>("Color"); qDBusRegisterMetaType<Color>(); QDBusConnection dbus = QDBusConnection::sessionBus(); com::meJ::system::CalculatorInterface *calculator = new com::meJ::system::CalculatorInterface("com.meJ.system", "/Calc", dbus); if (calculator->isValid() == false) { cerr << "ERROR: " << qPrintable(calculator->lastError().message()) << endl; exit(1); } Color c = GREEN; calculator->setColor(c); std::cout << qPrintable(calculator->lastError().message()) << std::endl; exit(0); } ``` If everything worked you should see following output at your server program: ``` ~# Color: green ```
Here is my solution which uses macro and does not have boost dependency. You need to write below statement in your header file to declare << and >> operators. For example: ``` DECLARE_ENUM_DATATYPE(QProcess::ProcessState) ``` and in one .cpp file add below statement to define << and >> operators. ``` CREATE_ENUM_DATATYPE(QProcess::ProcessState) ``` Both above functions require below file, you can save it as enumDBus.hpp ``` #ifndef _ENUM_DBUS_HPP #define _ENUM_DBUS_HPP #include <QtDBus/QDBusArgument> #define DECLARE_ENUM_DATATYPE(ENUM_TYPE_DBUS)\ QDBusArgument &operator<<(QDBusArgument &argument, ENUM_TYPE_DBUS value);\ const QDBusArgument &operator>>(const QDBusArgument &argument, ENUM_TYPE_DBUS &val); #define CREATE_ENUM_DATATYPE(ENUM_TYPE_DBUS)\ QDBusArgument &operator<<(QDBusArgument &argument, ENUM_TYPE_DBUS value)\ {\ argument.beginStructure();\ qlonglong newVal = (qlonglong)value;\ argument << newVal;\ argument.endStructure();\ return argument;\ }\ const QDBusArgument &operator>>(const QDBusArgument &argument, ENUM_TYPE_DBUS &val)\ {\ argument.beginStructure();\ qlonglong result = 0;\ argument >> result;\ val = (ENUM_TYPE_DBUS)result;\ argument.endStructure();\ return argument;\ } #endif //_ENUM_DBUS_HPP ```
34,186,128
I am using bootstrap and I have a container with a login form. However, I want to align this form to the left side of the page. However, using float left makes it look ugly and also makes the form input smaller, as you can see here: <http://codepen.io/anon/pen/xZGOjR> ``` <div class="container"> <div class="form-container"> <form class="form-horizontal" name="form" role="form" > <fieldset> <div class="form-group"> <div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light"> </div> <input type="email" class="form-control input-lg input-round text-center" placeholder="Email" ng-model="user.email" name="email" ng-required autofocus> </div> <div class="form-group"> <div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light"> </div> <input type="password" class="form-control input-lg input-round text-center" placeholder="Password"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-lg btn-round btn-block text-center">Log in</button> </div> </fieldset> </form> </div> </div> ``` How can I make it so the form input is to the left side without looking ugly?
2015/12/09
[ "https://Stackoverflow.com/questions/34186128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354934/" ]
To do it the bootstrap way. You could add a column width to the form `<div class="form-container text-center col-xs-3">` Here is your original example tidied up a bit <http://codepen.io/anon/pen/XXbKvN> Bootstrap uses a 12 column grid system so that everything is nicely laid out on the page. For more info have a look here <http://getbootstrap.com/css/#grid-options>
You can use `width: 350px;` to the `.form-container` class. It can better, if you can upload your design. screenshot.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
A long method is definitely a code smell, but it does not conclusively indicate that something is wrong. In fact, I would argue that you shouldn't break a method apart purely on length, that is arbitrary. For example, I've seen some long methods for distinct ETL (Extract/Transform/Load) tasks where the length is really driven by the amount of data. Don't report it to the boss at this point. Find a tangible reason why the method can be improved, then communicate that to the developer in a constructive way.
Preventing problems is cheaper than waiting for them to happen and then solving them. Your boss likes cheap. Ask your boss if he expects **your** code to be used for a long time and if changes are likely if customers pay for them. In the likely event that you get a yes for both then suggest that you would like to have new code you write reviewed by your peers. It won't take them long and the extra time will be paid tenfold because errors are way cheaper to fix the earlier they are detected. An error found in code which is fresh in the mind is easier to fix than one found by the client with the usual less than helpful error reports from clients. Assure him that you won't be asking for much code review, maybe once each pair of weeks. If he asks if you are unsure about the quality of your code assure him that such is not the case at all. But 6 eyes have a wider view than 2 and code review is a standard industry practice because its benefits far outweigh the minimal costs. If he goes with it, when your pals find errors in your code be sure to mention it to your boss. Mention how much more time would you have had to spend debugging the issue if the code had gone into production. Or the loss of client confidence. Mention how much this team work improves the product even if you work on different projects. If he goes for this step he will easily make himself the next one: having everyone's code reviewed. If he is not willing to accept someone volunteering to have his code reviewed then there is no chance you'd get him to let you review your pal's code.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I sense two major flaws here: * **do you offer a solution to the problem?** Just telling "this code is horrible" won't work. It could be an opinion, it does not bring value to the company; bosses and business want solutions. * **do you have a reviewing process?** Peer reviews of the code should be done regardless of the size of the team: actually providing detailed information on how the code can be refactored is better than any possbile complaint, and solves also the above problem. I get from your edits that the answer to the second is "no", so maybe the right thing to point out to the boss is to talk about **the process** and not pointing out single "code failures" that he is not able to evaluate properly, unless he trusts you big time. If you tell the boss: > > Listen, I have an idea to make our work more productive: we can write better code, adapt better to change in the business, reduce the bugs and have a mantainable code base that is easier to pick up also for newcomers > > > maybe he would listen more carefully. You are offering solutions, not pointing out a problem.
What is the function trying to do? How complex is that task? What optimisation category did they aim for (speed, accuracy, usability)? Without any of that information it will be hard to make a judgement. You can always take a look at the code. If there are inefficiencies, point them out like 'The code is good! Quickie [timesaver/performance booster/whatever], you can always do X to avoid [bottleneck]'
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I'd focus on the maintainability issue. Depending on circumstances, a 1,000 line function that does one thing and is well-documented can be more readable and maintainable than a 20 line function that defers every decision to a ten calls deep stack of utility functions that each had special cases grafted on over time as requirements changed (oddly specific rant, I know). The checklist for having big functions: 1. Remove the need for users of the function to understand it completely: there should be documentation that treats the function as a black box and only describes its behaviour. User code does not get to rely on anything that isn't documented in this specification, which needs to be an explicit point in code reviews for caller functions. 2. Automate verification of the function. All current use cases should exist as unit tests, so if it ever becomes necessary to modify that function, you can do so quickly with the confidence that nothing else breaks as a result. Length of a function often correlates with how easy it is to understand, but that is not a hard and fast rule.
Apart from the "3000 LOC" there were 3 other phrases in the OP caught my eye: > > * Should I communicate this to the boss, who does not know anything about programing? > * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. > * Code Reviews do not exist here. > > > Somebody's leaving is a business risk, perhaps a risk that's easy for a non-programmer to understand, and a risk that's mitigated by code reviews. You might tell your boss that programmers should (at minimum) understand each other's work -- what it does and how it's implemented -- in case one of them [falls under a bus](https://en.wikipedia.org/wiki/Bus_factor). You could add that's normal/professional. Then ask your colleague, during a code review, "how does this work?" You said your concern was ... > > How the hell do I read a 3000 line method? > > > ... so a code review should explain that -- i.e. how they explain, how they read it. You might want to insist "you should use subroutines", but if the colleague is hostile to change (attached to the existing implementation) perhaps it's pointless to insist. Just be sure you understand it, so you could change it if you had to (e.g. if you inherit it). There are other benefits to code reviews ... * Bug detection (but you spot a bug during a code inspections) * Knowledge transfer (you might learn from each other by reading each other's code and discussing it) * Better integration between modules (see also [Conway's law](https://en.wikipedia.org/wiki/Conway%27s_law))
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
If you're concerned about it you should actually read the code and offer suggestions (sounds like a great time to push for code review!). It may be 3000 lines out of need. Deciding that just because there are 3000 lines means it's wrong or bad is arbitrary. [Edited based on updates] You say that the code's speed is not relevant. At this point it sounds like it's just ugly code. The best course of action since you've already given them suggestions (since you're not their supervisor, etc.) would probably be to simply accept it and move on. If you ever need to work on their code it sounds like it's divided up enough that it could be easily broken into multiple functions, but as-is it works and you may never need to touch it. Work on what your bosses want you to work on and make suggestions and improvements where you can fit them. If you try to fix everything wrong you see all at once you'll stress yourself out for no good reason.
I think the getting hit by a bus example might be the best. I would go to your boss, and say "I have concerns about the codes maintainability, if the employee gets hit by a bus or otherwise unavailable it will take me ## weeks to figure it out. Are you ok with me being unavailable to work on other project for ## weeks if this project ever need maintenance if other person is not available.?" Let your boss make the final decision on which is more important for this project "it s done" or "its maintainable"? For all we know the boss could be yay, the customer will have to pay us 2x as much because if they want the modifications done they will have to pay for it. This means that the most important thing to the boss is what will the client pay for.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I'd focus on the maintainability issue. Depending on circumstances, a 1,000 line function that does one thing and is well-documented can be more readable and maintainable than a 20 line function that defers every decision to a ten calls deep stack of utility functions that each had special cases grafted on over time as requirements changed (oddly specific rant, I know). The checklist for having big functions: 1. Remove the need for users of the function to understand it completely: there should be documentation that treats the function as a black box and only describes its behaviour. User code does not get to rely on anything that isn't documented in this specification, which needs to be an explicit point in code reviews for caller functions. 2. Automate verification of the function. All current use cases should exist as unit tests, so if it ever becomes necessary to modify that function, you can do so quickly with the confidence that nothing else breaks as a result. Length of a function often correlates with how easy it is to understand, but that is not a hard and fast rule.
> > How do I react professional to that? > > > "Great, thanks!" Now, if you feel the code is sub-optimal, *regardless of the number of lines*, you can test it on the side to see if it meets any performance requirements. This gives you meaningful, actionable information. If you think the code follows poor practices, you can bring this up in code-review.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I have worked on legacy code before where the entire website is handled in a single file that is approximately 100,000 lines of code. That's right. Everything about the site is done in a single file, single function. It got to a point where adding or modifying something meant you scrolled all the way to the bottom and simply modified the output buffer to change things. Like if someone said they wanted to change a sentence, we do a regex to search the sentence and simply replaced it with the new sentence. We eventually got to the point where it became so bloated only a few people were "experts" at modifying the output buffer. It was ultimately decided to simply toss the file, and redo the entire site with a modern approach. I think that is what will happen here. Maintain the 3k function, and if he goes, simply toss the code. That's what I would do, rather than waste time trying to convince someone something is better. It works, is what the argument is and that might be true. Without a boss who knows code or having a good soft-skill, you probably won't get far with trying to convince your equal co-worker to change.
Don't worry about it. It's not your problem (right now). It's this guys responsibility to maintain the code, not yours. Don't touch it. If your boss asks you to touch it, whether now or later, tell them why you won't. If your colleague leaves, you buy a book about refactoring. That's the point where you tell your boss this function isn't maintainable.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
Preventing problems is cheaper than waiting for them to happen and then solving them. Your boss likes cheap. Ask your boss if he expects **your** code to be used for a long time and if changes are likely if customers pay for them. In the likely event that you get a yes for both then suggest that you would like to have new code you write reviewed by your peers. It won't take them long and the extra time will be paid tenfold because errors are way cheaper to fix the earlier they are detected. An error found in code which is fresh in the mind is easier to fix than one found by the client with the usual less than helpful error reports from clients. Assure him that you won't be asking for much code review, maybe once each pair of weeks. If he asks if you are unsure about the quality of your code assure him that such is not the case at all. But 6 eyes have a wider view than 2 and code review is a standard industry practice because its benefits far outweigh the minimal costs. If he goes with it, when your pals find errors in your code be sure to mention it to your boss. Mention how much more time would you have had to spend debugging the issue if the code had gone into production. Or the loss of client confidence. Mention how much this team work improves the product even if you work on different projects. If he goes for this step he will easily make himself the next one: having everyone's code reviewed. If he is not willing to accept someone volunteering to have his code reviewed then there is no chance you'd get him to let you review your pal's code.
From what you are describing, you have a mountain to climb and a team to drag up it. I don't think I would specifically talk about the 1k line method, I would start by bringing up best practices with your boss in a 1:1. Ask him if the team has any coding guidelines or best practices that they follow. Assuming the answer is no, gather some links to some articles on best practices for whatever programming language you are using. I try to stay with coding guides from big companies... companies everyone will have heard of like google, Microsoft, etc. and start with their coding guides. Bring those to your boss along with some articles about how implementing best practices helps... what are the benefits, etc. Don't bring *your* message, you are the messenger. You bring glad tidings of ways to be more efficient, save money, have fewer defects, and the list goes on... I'm thinking your boss would react better to that approach. Then once you get him hooked (hopefully), you have a team discussion about them and let's start following them. (I would throw in some procedural best practices like code reviews and the like also, not just coding guidelines.) Then if you can get them to buy in this far, then you start applying those guidelines and reviewing new code (and old code as you run into it). "Hey, I found this large method that according to best practice ABC, we should split up into smaller methods that have a single responsibility, etc." and go from there. To be honest, I doubt you will get far with any of this but this is how I would approach it.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I'd focus on the maintainability issue. Depending on circumstances, a 1,000 line function that does one thing and is well-documented can be more readable and maintainable than a 20 line function that defers every decision to a ten calls deep stack of utility functions that each had special cases grafted on over time as requirements changed (oddly specific rant, I know). The checklist for having big functions: 1. Remove the need for users of the function to understand it completely: there should be documentation that treats the function as a black box and only describes its behaviour. User code does not get to rely on anything that isn't documented in this specification, which needs to be an explicit point in code reviews for caller functions. 2. Automate verification of the function. All current use cases should exist as unit tests, so if it ever becomes necessary to modify that function, you can do so quickly with the confidence that nothing else breaks as a result. Length of a function often correlates with how easy it is to understand, but that is not a hard and fast rule.
You've said on one hand that each developer is responsible for their own code, and yet you wish to report one of your colleagues to your manager for not working to your standards. If the code works as expected, there's nothing that needs to be said about it until there's a time when it's a problem or there's a time when coding standards are set for the team as a whole.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
I have worked on legacy code before where the entire website is handled in a single file that is approximately 100,000 lines of code. That's right. Everything about the site is done in a single file, single function. It got to a point where adding or modifying something meant you scrolled all the way to the bottom and simply modified the output buffer to change things. Like if someone said they wanted to change a sentence, we do a regex to search the sentence and simply replaced it with the new sentence. We eventually got to the point where it became so bloated only a few people were "experts" at modifying the output buffer. It was ultimately decided to simply toss the file, and redo the entire site with a modern approach. I think that is what will happen here. Maintain the 3k function, and if he goes, simply toss the code. That's what I would do, rather than waste time trying to convince someone something is better. It works, is what the argument is and that might be true. Without a boss who knows code or having a good soft-skill, you probably won't get far with trying to convince your equal co-worker to change.
> > How do I react professional to that? > > > "Great, thanks!" Now, if you feel the code is sub-optimal, *regardless of the number of lines*, you can test it on the side to see if it meets any performance requirements. This gives you meaningful, actionable information. If you think the code follows poor practices, you can bring this up in code-review.
128,537
I have a co-worker who said his 3000 line method is the most optimized possible. How do I react professionally to that? Should I communicate this to the boss, who does not know anything about programming? Note that we are a small team of only three programmers that are at the same level and each one has his own piece of the project that we manage and code ourselves as we want, while that piece of code do what the boss wants it to do. * My biggest concern here is that my co-worker might end the relationship with the company at some point and I will have to take care of that piece of the project he was working on. How the hell do I read a 3000 line method? My first thought will be to start all over again from zero and as I already did that with my current piece of project, having in mind that "the boss" doesn't understand anything about programming and he only cares that the program works and the time it takes us to make it work. I am pretty sure he will get at least a little mad. * I had seen the method, it does a lot of things (a lot) and it has a conditionals block (big ones) meaning that if he calls the method with parameter A = 1 the first block is executed and the others ignored and so on... I have told him that he could split those blocks on different methods so it will be easy to read and understand hopping that he would see the benefits of that and would do it with the rest of the gigantic method, but I don't think he sees the benefits. He just said that he did "something" like that because every conditional block is inside a C# region. NOTES FROM COMMENTS: * As my co-worker said it is a critical method because it does every single calculations of a particular part of the program * The language used to programming is C#. * The speed of the code is not relevant here. * Code reviews do not exist here. As I said, each one of us works on his own and so long as everything works, no one cares about the **how** it works. * Assume that every single line of those 3000 lines are from actual code, not from spaces or comments.
2019/02/08
[ "https://workplace.stackexchange.com/questions/128537", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/99396/" ]
Don't worry about it. It's not your problem (right now). It's this guys responsibility to maintain the code, not yours. Don't touch it. If your boss asks you to touch it, whether now or later, tell them why you won't. If your colleague leaves, you buy a book about refactoring. That's the point where you tell your boss this function isn't maintainable.
I think the getting hit by a bus example might be the best. I would go to your boss, and say "I have concerns about the codes maintainability, if the employee gets hit by a bus or otherwise unavailable it will take me ## weeks to figure it out. Are you ok with me being unavailable to work on other project for ## weeks if this project ever need maintenance if other person is not available.?" Let your boss make the final decision on which is more important for this project "it s done" or "its maintainable"? For all we know the boss could be yay, the customer will have to pay us 2x as much because if they want the modifications done they will have to pay for it. This means that the most important thing to the boss is what will the client pay for.
6,047,485
In EclipseLink, I run into a problem where an element is inserted twice, resulting into a primary key violation. The scenario is as follows: I have three entities, Element, Restriction and RestrictionElement. The entity RestrictionElement acts as a many-to-many relationship between the two others. When I create a new RestrictionElement and merge the Element, the RestrictionElement is inserted twice. The code: ``` // element is an Element, restriction is a Restriction. Both are already in present in the database. RestrictionElement newRestrictionElement = new RestrictionElement(restriction, element); Transaction transaction = new Transaction(); em.merge(element); //em is the EntityManager transaction.commit(); ``` However, if I remove the line `restriction.getReferencedRestrictionElements().add(this);` the RestrictionElement is inserted once. Can anyone explain why this happens? Or point to a document that explains how to work out what the merge() command does? Relevant JPA code: (I'll only given a small part. There aren't any other big problems with the code.) ``` public class RestrictionElement { @JoinColumns({@JoinColumn(name = "ELEMENT_ID", referencedColumnName = "ID"),@JoinColumn(name = "ELEMENT_DESCRIPTOR", referencedColumnName = "DESCRIPTOR")}) private Element element; @JoinColumns({@JoinColumn(name = "RESTRICTION_ID", referencedColumnName = "ID"),@JoinColumn(name = "RESTRICTION_DESCRIPTOR", referencedColumnName = "DESCRIPTOR")}) private Restriction restriction; public RestrictionElement(Restriction restriction, Element element) { this.restriction = restriction; this.element = element; restriction.getReferencedRestrictionElements().add(this); element.getReferingRestrictionElements().add(this); } } public class Element { @OneToMany(mappedBy = "element") private List<RestrictionElement> referingRestrictionElements = new ArrayList<RestrictionElement>(); } public class Restriction extends Element { @OneToMany(mappedBy = "restriction", cascade = { ALL, PERSIST, MERGE, REMOVE, REFRESH }) private List<RestrictionElement> referencedRestrictionElements = new ArrayList<RestrictionElement>(); } ```
2011/05/18
[ "https://Stackoverflow.com/questions/6047485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/530796/" ]
How do your persist RestrictionElement? My guess is when you persist it you get one copy, then a second when you merge the Element with the reference to it. Try using persist() for new objects, and related the objects after they are managed with the correct managed copy.
Don't forget that once you retrieve an instance of the class using JPA, the instance becomes managed, any changes to it will be automatically merged into the database. By default, this merge will occur at the moment you query the table. Therefore the following situation can happen: * query (find by ID) * update (setName = "xx") * query another class that has a direct relationship to this one (find by ID again) in a situation similar to the above, the second find will effectively issue a merge to the first table. (I'm not sure exactly of the details or scenarios here). My suggestion is that you issue every single query (findById for example) or every instance you have before you start modifying it (ie, set, etc). Hope it helps.
6,047,485
In EclipseLink, I run into a problem where an element is inserted twice, resulting into a primary key violation. The scenario is as follows: I have three entities, Element, Restriction and RestrictionElement. The entity RestrictionElement acts as a many-to-many relationship between the two others. When I create a new RestrictionElement and merge the Element, the RestrictionElement is inserted twice. The code: ``` // element is an Element, restriction is a Restriction. Both are already in present in the database. RestrictionElement newRestrictionElement = new RestrictionElement(restriction, element); Transaction transaction = new Transaction(); em.merge(element); //em is the EntityManager transaction.commit(); ``` However, if I remove the line `restriction.getReferencedRestrictionElements().add(this);` the RestrictionElement is inserted once. Can anyone explain why this happens? Or point to a document that explains how to work out what the merge() command does? Relevant JPA code: (I'll only given a small part. There aren't any other big problems with the code.) ``` public class RestrictionElement { @JoinColumns({@JoinColumn(name = "ELEMENT_ID", referencedColumnName = "ID"),@JoinColumn(name = "ELEMENT_DESCRIPTOR", referencedColumnName = "DESCRIPTOR")}) private Element element; @JoinColumns({@JoinColumn(name = "RESTRICTION_ID", referencedColumnName = "ID"),@JoinColumn(name = "RESTRICTION_DESCRIPTOR", referencedColumnName = "DESCRIPTOR")}) private Restriction restriction; public RestrictionElement(Restriction restriction, Element element) { this.restriction = restriction; this.element = element; restriction.getReferencedRestrictionElements().add(this); element.getReferingRestrictionElements().add(this); } } public class Element { @OneToMany(mappedBy = "element") private List<RestrictionElement> referingRestrictionElements = new ArrayList<RestrictionElement>(); } public class Restriction extends Element { @OneToMany(mappedBy = "restriction", cascade = { ALL, PERSIST, MERGE, REMOVE, REFRESH }) private List<RestrictionElement> referencedRestrictionElements = new ArrayList<RestrictionElement>(); } ```
2011/05/18
[ "https://Stackoverflow.com/questions/6047485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/530796/" ]
I got a similar issue when I run my program, but the issue is not there under step by step debugging. I resolved the issue by changing List to Set in the OneToMany relationship.
Don't forget that once you retrieve an instance of the class using JPA, the instance becomes managed, any changes to it will be automatically merged into the database. By default, this merge will occur at the moment you query the table. Therefore the following situation can happen: * query (find by ID) * update (setName = "xx") * query another class that has a direct relationship to this one (find by ID again) in a situation similar to the above, the second find will effectively issue a merge to the first table. (I'm not sure exactly of the details or scenarios here). My suggestion is that you issue every single query (findById for example) or every instance you have before you start modifying it (ie, set, etc). Hope it helps.