prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Use `padding left` like `editText.setPadding (int left, int top, int right, int bottom);`
Try this in your java code ``` editText.setPadding( 5, 0,0,0); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Use `padding left` like `editText.setPadding (int left, int top, int right, int bottom);`
Try this code..... ``` android:includeFontPadding="true" android:paddingLeft="5dp" ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Use `padding left` like `editText.setPadding (int left, int top, int right, int bottom);`
You can do this through XML as well in coding. If you want to do in XML, You have to do the padding to required Edit text. ``` <EditText android:id="@+id/bt_description" android:layout_height="match_parent" android:layout_width="match_parent" android:paddingLeft="10dp" /> ``` If not you can do this through code as above said. ``` email.setPadding(int left,int top,int right,int bottom); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
try this code ``` android:paddingLeft="5dp" ```
Try this in your java code ``` editText.setPadding( 5, 0,0,0); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
try this code ``` android:paddingLeft="5dp" ```
Try this code..... ``` android:includeFontPadding="true" android:paddingLeft="5dp" ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
try this code ``` android:paddingLeft="5dp" ```
You can do this through XML as well in coding. If you want to do in XML, You have to do the padding to required Edit text. ``` <EditText android:id="@+id/bt_description" android:layout_height="match_parent" android:layout_width="match_parent" android:paddingLeft="10dp" /> ``` If not you can do this through code as above said. ``` email.setPadding(int left,int top,int right,int bottom); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Try this code..... ``` android:includeFontPadding="true" android:paddingLeft="5dp" ```
Try this in your java code ``` editText.setPadding( 5, 0,0,0); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Try this code..... ``` android:includeFontPadding="true" android:paddingLeft="5dp" ```
You can do this through XML as well in coding. If you want to do in XML, You have to do the padding to required Edit text. ``` <EditText android:id="@+id/bt_description" android:layout_height="match_parent" android:layout_width="match_parent" android:paddingLeft="10dp" /> ``` If not you can do this through code as above said. ``` email.setPadding(int left,int top,int right,int bottom); ```
Question: The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong... HTML: ``` <input type="text" id="textEntry" /> <button>Go</button> <ul id="list"> <li>Text from the input field will appear below</li> </ul> ``` jQUERY: ``` $('button').click(function() { $enteredText = $('#textEntry').val(); if($enteredText.length === 0) { alert('PLace an item in the field box'); } else { $newListItem = $('<li/>').html($enteredText).appendTo('#list'); } }); $('li').live('mouseover mouseout', function(event) { if(event.type == mouseover) { $(this).css('background-color', 'yellow'); } else { $(this).css('backgorund-color', 'transparent'); } }); ``` Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue). Any help would be swell. Thanks. Answer:
If the schema contains serial or sequence columns, you should reset these to the max value that occurs in the corresponding column. (normally you should not import the serials from a file, but give them the freedom to autoincrement.) For all imported tables you should identify the sequence fields and run the following code on them. (substitute your schema name for "sch", your table name for "mytable" and your id column name for "id") ``` WITH mx AS ( SELECT MAX(id) AS id FROM sch.mytable) SELECT setval('sch.mytable_id_seq', mx.id) AS curseq FROM mx ; ```
You can automate wildplasser's solution so that all sequences are synchronized with the current maximum value of their associated column: ``` do $block$ declare r record; stmt text; max_id integer; begin for r in ( select * from ( select table_schema, table_name, column_name, pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence from information_schema.columns where table_schema not in ('pg_catalog', 'information_schema') ) t where col_sequence is not null ) loop stmt := 'select coalesce(max('||r.column_name||'), 0) + 1 from '||r.table_schema||'.'||r.table_name; execute stmt into max_id; raise notice 'Next ID for %.%.% is %', r.table_schema, r.table_name, r.column_name, max_id; perform setval(r.col_sequence, max_id); end loop; end; $block$ ``` Note that this will only work if the columns have been defined as `serial`, `bigserial` or have been made the "owner" of a sequence.
Question: The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong... HTML: ``` <input type="text" id="textEntry" /> <button>Go</button> <ul id="list"> <li>Text from the input field will appear below</li> </ul> ``` jQUERY: ``` $('button').click(function() { $enteredText = $('#textEntry').val(); if($enteredText.length === 0) { alert('PLace an item in the field box'); } else { $newListItem = $('<li/>').html($enteredText).appendTo('#list'); } }); $('li').live('mouseover mouseout', function(event) { if(event.type == mouseover) { $(this).css('background-color', 'yellow'); } else { $(this).css('backgorund-color', 'transparent'); } }); ``` Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue). Any help would be swell. Thanks. Answer:
If the schema contains serial or sequence columns, you should reset these to the max value that occurs in the corresponding column. (normally you should not import the serials from a file, but give them the freedom to autoincrement.) For all imported tables you should identify the sequence fields and run the following code on them. (substitute your schema name for "sch", your table name for "mytable" and your id column name for "id") ``` WITH mx AS ( SELECT MAX(id) AS id FROM sch.mytable) SELECT setval('sch.mytable_id_seq', mx.id) AS curseq FROM mx ; ```
Another way is remove the primary key (id) from the columns (or don't dump the id). So your data would look like ``` INSERT INTO book (name, price) VALUES ('Alchemist' , 10); ``` instead of ``` INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10); ``` This way, you won't have to reset the primary key after loading initial data
Question: The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong... HTML: ``` <input type="text" id="textEntry" /> <button>Go</button> <ul id="list"> <li>Text from the input field will appear below</li> </ul> ``` jQUERY: ``` $('button').click(function() { $enteredText = $('#textEntry').val(); if($enteredText.length === 0) { alert('PLace an item in the field box'); } else { $newListItem = $('<li/>').html($enteredText).appendTo('#list'); } }); $('li').live('mouseover mouseout', function(event) { if(event.type == mouseover) { $(this).css('background-color', 'yellow'); } else { $(this).css('backgorund-color', 'transparent'); } }); ``` Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue). Any help would be swell. Thanks. Answer:
You can automate wildplasser's solution so that all sequences are synchronized with the current maximum value of their associated column: ``` do $block$ declare r record; stmt text; max_id integer; begin for r in ( select * from ( select table_schema, table_name, column_name, pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence from information_schema.columns where table_schema not in ('pg_catalog', 'information_schema') ) t where col_sequence is not null ) loop stmt := 'select coalesce(max('||r.column_name||'), 0) + 1 from '||r.table_schema||'.'||r.table_name; execute stmt into max_id; raise notice 'Next ID for %.%.% is %', r.table_schema, r.table_name, r.column_name, max_id; perform setval(r.col_sequence, max_id); end loop; end; $block$ ``` Note that this will only work if the columns have been defined as `serial`, `bigserial` or have been made the "owner" of a sequence.
Another way is remove the primary key (id) from the columns (or don't dump the id). So your data would look like ``` INSERT INTO book (name, price) VALUES ('Alchemist' , 10); ``` instead of ``` INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10); ``` This way, you won't have to reset the primary key after loading initial data
Question: The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong... HTML: ``` <input type="text" id="textEntry" /> <button>Go</button> <ul id="list"> <li>Text from the input field will appear below</li> </ul> ``` jQUERY: ``` $('button').click(function() { $enteredText = $('#textEntry').val(); if($enteredText.length === 0) { alert('PLace an item in the field box'); } else { $newListItem = $('<li/>').html($enteredText).appendTo('#list'); } }); $('li').live('mouseover mouseout', function(event) { if(event.type == mouseover) { $(this).css('background-color', 'yellow'); } else { $(this).css('backgorund-color', 'transparent'); } }); ``` Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue). Any help would be swell. Thanks. Answer:
In Rails you can use the command > > `ActiveRecord::Base.connection.reset_pk_sequence!('users')` > > > to bring the primary key index for the User table in sync again.
You can automate wildplasser's solution so that all sequences are synchronized with the current maximum value of their associated column: ``` do $block$ declare r record; stmt text; max_id integer; begin for r in ( select * from ( select table_schema, table_name, column_name, pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence from information_schema.columns where table_schema not in ('pg_catalog', 'information_schema') ) t where col_sequence is not null ) loop stmt := 'select coalesce(max('||r.column_name||'), 0) + 1 from '||r.table_schema||'.'||r.table_name; execute stmt into max_id; raise notice 'Next ID for %.%.% is %', r.table_schema, r.table_name, r.column_name, max_id; perform setval(r.col_sequence, max_id); end loop; end; $block$ ``` Note that this will only work if the columns have been defined as `serial`, `bigserial` or have been made the "owner" of a sequence.
Question: The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong... HTML: ``` <input type="text" id="textEntry" /> <button>Go</button> <ul id="list"> <li>Text from the input field will appear below</li> </ul> ``` jQUERY: ``` $('button').click(function() { $enteredText = $('#textEntry').val(); if($enteredText.length === 0) { alert('PLace an item in the field box'); } else { $newListItem = $('<li/>').html($enteredText).appendTo('#list'); } }); $('li').live('mouseover mouseout', function(event) { if(event.type == mouseover) { $(this).css('background-color', 'yellow'); } else { $(this).css('backgorund-color', 'transparent'); } }); ``` Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue). Any help would be swell. Thanks. Answer:
In Rails you can use the command > > `ActiveRecord::Base.connection.reset_pk_sequence!('users')` > > > to bring the primary key index for the User table in sync again.
Another way is remove the primary key (id) from the columns (or don't dump the id). So your data would look like ``` INSERT INTO book (name, price) VALUES ('Alchemist' , 10); ``` instead of ``` INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10); ``` This way, you won't have to reset the primary key after loading initial data
Question: For most ML models we say they suffer from high bias or high variance, then we correct for it. However, in DL do neural networks suffer from the same concept in the sense that they initially have high bias or high variance and then you correct through regularization and/or dropout? I would argue they initially suffer from high variance and they overfit the data. Then you correct through regularization, add dropout, image pre-processing in the case of CNNs, etc. Is this train of thought correct? Answer:
In general NNs are prone to overfitting the training set, which is case of a [high variance](https://datascience.stackexchange.com/questions/45578/why-underfitting-is-called-high-bias-and-overfitting-is-called-high-variance). Your train of thought is generally correct in the sense that the proposed solutions (regularization, dropout layers, etc.) are tools that control the bias-variance trade-off.
Neural networks, including DNNs, don't *by themselves* suffer from high variance any more than other machine learning algorithms. It is just that we find it easier to start the training with more complex networks and control for variance by the techniques you mentioned, than to start with simpler (less expressive) networks and gradually increase their complexity. By observing the network behaviour during training you can already get hints regarding simplification. If you'd start with a simpler network, you'd be tapping in the dark how to augment it.
Question: I've create a c# winforms form, It has a bunch of labels positioned and a flowlayoutpanel. on certain occasions i set one of the labels and the flowlayoutpanel to visible =false. As a result i want all labels beneath them to be pushed up - at the moment there is a gap where they were. Also, I'd like the flowlayoutpanel to grow and shrink depending on the number of items it has. at the moment it is just the size i set it to be in the designer. please can you help with these 2 issues. Thanks Answer:
If I got you correctly, I would suggest using a TableLayoutPane with two rows. The top row will contain a docked panel with all the controls that may be hidden. The bottom row will contain a docked panel with all the rest. Set the top row's SizeType to AutoSize and the bottom row's to 100%. When you want to hide the controls, set the top panel's Visible property to false. Now, because the top row is AutoSized it will shrink to nothing, causing the bottom row to "jump" up.
The TableLayoutPanel does the pushing. Maybe you can use that if there is no better answer in next time.
Question: I've create a c# winforms form, It has a bunch of labels positioned and a flowlayoutpanel. on certain occasions i set one of the labels and the flowlayoutpanel to visible =false. As a result i want all labels beneath them to be pushed up - at the moment there is a gap where they were. Also, I'd like the flowlayoutpanel to grow and shrink depending on the number of items it has. at the moment it is just the size i set it to be in the designer. please can you help with these 2 issues. Thanks Answer:
If I got you correctly, I would suggest using a TableLayoutPane with two rows. The top row will contain a docked panel with all the controls that may be hidden. The bottom row will contain a docked panel with all the rest. Set the top row's SizeType to AutoSize and the bottom row's to 100%. When you want to hide the controls, set the top panel's Visible property to false. Now, because the top row is AutoSized it will shrink to nothing, causing the bottom row to "jump" up.
First problem: You may use some simple panels to divide your form, give them the `dock.fill` property. when you'll hide a panel programmatically, the other panels will fill the empty space left. Second problem: You have to set the `Autosize` property to `true`.
Question: I want to say : > > Analysis **conducted at a** insurance company showed that... > > or > > Analysis **into a** insurance company showed that... > > > What is the best way to phrase this? Answer:
I would make it slightly less passive: *"An analysis performed by the insurance company ..."* or other material to indicate *who* performed the analysis and *where* it was performed as well as the issue being analyzed. If you or your associates performed the analysis, you might phrase it: *"An analysis performed by the authors into insurance company policies...'*
Use: > > The analysis that the company made says that \_\_\_. > > >
Question: We are hosting our website in Azure. During the deployment(TFS) we will do the below Steps as the part of the deployment pipeline. 1. Stop the WebApp 2. Deploy Web App Service 3. Start the WebApp After the 1st step, if anyone tries to access our website, then by default Azure will return the below page [![enter image description here](https://i.stack.imgur.com/zXQzr.jpg)](https://i.stack.imgur.com/zXQzr.jpg) We really don't want our users to show this page during the outage. We are planning to show our own outage image/page in such case. Is there is any way to achieve this? Since Azure Web Apps in a Paas model, I'm wondering how to do this? Any inputs Appreciated! Answer:
It should work with ``` from test import foo ``` But you have to add a `__init__.py` to your project directory. For Python 3 it would be: ``` from .test import foo ``` If you use the dot in front of the folder name, python searches for the file in the same directory as the file you are working on is placed in. Sorry for my bad english.
Are you using an IDE? If so add the path to the Python Interpreter inside the project Properties to all the primary packages (foo, test, notebooks). Otherwise try to explicitly add the bar package to the sys path like so ``` import sys import os MYDIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(MYDIR,'test')) sys.path.append(os.path.join(MYDIR,'test/foo')) sys.path.append(os.path.join(MYDIR,'test/foo/bar')) #I am not sure this is entirely needed ```
Question: We are hosting our website in Azure. During the deployment(TFS) we will do the below Steps as the part of the deployment pipeline. 1. Stop the WebApp 2. Deploy Web App Service 3. Start the WebApp After the 1st step, if anyone tries to access our website, then by default Azure will return the below page [![enter image description here](https://i.stack.imgur.com/zXQzr.jpg)](https://i.stack.imgur.com/zXQzr.jpg) We really don't want our users to show this page during the outage. We are planning to show our own outage image/page in such case. Is there is any way to achieve this? Since Azure Web Apps in a Paas model, I'm wondering how to do this? Any inputs Appreciated! Answer:
Messing with `sys.path` is rarely a good idea. Since your plan seems to be to use both `foo` and `test` from `notebooks` (that will probably just contain Jupyter notebooks), the cleanest solution would be to install `foo` and `test` as packages. Remove the `__init__.py` from your top level directory and `notebooks`, since you will not want to import them. Then add a `setup.py` to your top level directory. Since your tests are specific to `foo`, you should either rename them `foo_test` or move them into `foo` itself. A minimal `setup.py` would look like this ``` from setuptools import setup setup(name='foo', version='0.1', description='descroption of fo', author='you', author_email='your@mail', packages=['foo','test_foo]) ``` Then you can simply `pip install -e .` in your top level directory and it will be installed into your current virtualenv. If you are not using virtualenvs, you should `pip install --user -e .`
It should work with ``` from test import foo ``` But you have to add a `__init__.py` to your project directory. For Python 3 it would be: ``` from .test import foo ``` If you use the dot in front of the folder name, python searches for the file in the same directory as the file you are working on is placed in. Sorry for my bad english.
Question: We are hosting our website in Azure. During the deployment(TFS) we will do the below Steps as the part of the deployment pipeline. 1. Stop the WebApp 2. Deploy Web App Service 3. Start the WebApp After the 1st step, if anyone tries to access our website, then by default Azure will return the below page [![enter image description here](https://i.stack.imgur.com/zXQzr.jpg)](https://i.stack.imgur.com/zXQzr.jpg) We really don't want our users to show this page during the outage. We are planning to show our own outage image/page in such case. Is there is any way to achieve this? Since Azure Web Apps in a Paas model, I'm wondering how to do this? Any inputs Appreciated! Answer:
Messing with `sys.path` is rarely a good idea. Since your plan seems to be to use both `foo` and `test` from `notebooks` (that will probably just contain Jupyter notebooks), the cleanest solution would be to install `foo` and `test` as packages. Remove the `__init__.py` from your top level directory and `notebooks`, since you will not want to import them. Then add a `setup.py` to your top level directory. Since your tests are specific to `foo`, you should either rename them `foo_test` or move them into `foo` itself. A minimal `setup.py` would look like this ``` from setuptools import setup setup(name='foo', version='0.1', description='descroption of fo', author='you', author_email='your@mail', packages=['foo','test_foo]) ``` Then you can simply `pip install -e .` in your top level directory and it will be installed into your current virtualenv. If you are not using virtualenvs, you should `pip install --user -e .`
Are you using an IDE? If so add the path to the Python Interpreter inside the project Properties to all the primary packages (foo, test, notebooks). Otherwise try to explicitly add the bar package to the sys path like so ``` import sys import os MYDIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(MYDIR,'test')) sys.path.append(os.path.join(MYDIR,'test/foo')) sys.path.append(os.path.join(MYDIR,'test/foo/bar')) #I am not sure this is entirely needed ```
Question: This code should count the number of prime numbers based on user input. If user input is 10, then I should get 4. However, I only get 0. Why does the second loop not run? ``` #include<stdio.h> #include<math.h> int main() { int N; scanf("%d", &N); int numprime; numprime = 0; int P=1; for (P; P<N; P++) { if (P%2==0) continue; int e = sqrt(P); for (int j=3;j<=e;j+=2) { if (P%j!=0) { numprime = numprime + 1; } else { continue; } } } printf("%d", numprime); } ``` Answer:
`flex-direction: column` ======================== The major problem (besides some bad syntax on background shorthand) is that the `flex-direction` was at default which is `row` (horizontal). The flex items (`.logo` and `.copy`) are stacked vertically thus the `flex-direction` should be `column`. --- Demo ---- **Details commented in demo** ```css html, body { /* Always set the font on html */ font: 700 16px/1.5 Verdana; width: 100%; height: 100%; } .flex { /* shorthand for background goes in this order: position (center) repeat (no-repeat) size (cover) and there's no slash "/" *//* no-repeat is the only one kept */ background: url('https://i.imgur.com/5OLUUfp.png')no-repeat; /* The sidebar is always top to bottom */ min-height: 100%; /* The width was 100vw which is 100% of viewport which I'm assuming is wrong since a sidebar should only cover a portion of the viewport. */ width: 320px; /* By default flex-direction is row (horizontal flow) */ display: flex; /* The flex items (.logo and .copy) are vertical, so the flex- direction should be column. flex-flow is a combination of flex-direction and flex-wrap */ flex-flow: column nowrap; justify-content: center; align-items: center; } .logo { /* This pushes the footer.copy down to the bottom */ margin: auto; } img { display: block; width: 90%; } .copy { font-size: 0.875rem; color: #FFF; /* This property is given to individual tags that will break away from vertical flow of align-items */ align-self: flex-end; margin-right: 10px } ``` ```html <aside class="flex"> <figure class="logo"> <img src="https://i.imgur.com/cx6bov9.png"> </figure> <footer class='copy'>&copy; copyright 2018</footer> </aside> ```
you can use `position`. Add `position:relative;` to `.inner_content` and `position:absolute;` and `bottom:0;` to `.inner_content p` so your css looks like this ``` .flex { align-items: center; display: flex; } aside { background: url('../img/sidebar-image.jpg') no-repeat center/cover; height: 20em; width: 100vw; float: left; } .inner_content { justify-content: center; flex-direction: column; height: inherit; width: inherit; position: relative; } .inner_content p { font-size: 14px; margin-top: 2em; color: #FFF; position: absolute; bottom:0; } ``` but you can do this in multiple ways here is a link to a similar question explaining this in multiple ways: [Center and right align flexbox elements](https://stackoverflow.com/questions/38948102/center-and-right-align-flexbox-elements)
Question: I'm trying to turn a Huffman tree and a stream of bits into a list of characters plus a boolean indicating whether or not the output consumed all the input bits. Here's an example: ``` decode xyz_code [True,False,True,True,True,False,False,True] = ("yzyx",False) ``` Here's what I have so far, but it doesn't work. What's going wrong? Help! ``` data BTree a = Leaf a | Fork (BTree a) (BTree a) deriving (Show, Eq) decode :: BTree a -> [Bool] -> ([a], Bool) decode _ [] = ([],True) decode (Leaf v) [bs] = ([v], bs) decode (Fork left right) (b:bs) | b = decode right bs | otherwise = decode left bs ``` Answer:
I think no, Authorization server is out of their roadmap. Starting from november the 13th every class in spring security which worked with Authorization server features become deprecated. [Spring Security OAuth 2.0 Roadmap Update](https://spring.io/blog/2019/11/14/spring-security-oauth-2-0-roadmap-update#no-authorization-server-support) (here the answer on you question)
@mhrsalehi, please checkout my repo. I added an implementation of old OAuth2 Authorization server for webflux. Currently only support `/oauth/token` if you want support for any other endpoints please submit a ticket or PR. Github: [spring-reactive-authorization-server](https://github.com/VuDo98/spring-reactive-authorization-server)
Question: I have an Ubuntu 6.06 server that needs to be replaced by an Ubuntu 9.04 server clean setup, I already copied the entire samba file server directory to the new 9.04 server using rsync. I need to know how to migrate the existing user accounts (machine accounts) to the new server so as when I physically transfer the connections everything will be ok and I don't have to manually enter `smbpasswd -a <user>` on the new server. ``` passdb backend = tdbsam ``` network workstations accessing the share are either vista or xp. Answer:
``` passdb backend = tdbsam ``` means you have your samba accounts in a `passdb.tdb` file in `SAMBA_DIR/private`. As long as you copy it with rsync you are fine. There are two caveats: * Unix users: a samba user has to be a unix user as well, so you have to copy all files @churnd told you; * timing: machine account are updated every time, so you need a super fresh rsync. In a perfect world, you should stop old server, rsync, start new server.
You'll need to copy /etc/passwd, /etc/shadow, /etc/group, /etc/samba/smbusers, and /etc/samba/smbpasswd. [This site](http://www.cyberciti.biz/faq/howto-move-migrate-user-accounts-old-to-new-server/) shows you how to do the first 3, but I've done the last two and it worked fine.
Question: I am trying to add a new recipe to install new packages in my image. I need the next packages libnfc5 libnfc-bin libnfc-examples, I have found these packages in this page: <http://ftp.de.debian.org/debian/pool/main/libn/libnfc/>, so I am using the next commands to install the packages: * devtool add libnfc5 <http://ftp.de.debian.org/debian/pool/main/libn/libnfc/libnfc5_1.7.1-4+b1_armhf.deb> * devtool build libnfc5 * devtool deploy-target libnfc5 root@my-ip I am not sure if is necessary modify the .bb file generate: libnfc5\_1.7.1-4+b1.bb, and one time that I execute deploy-target which is necessary to do in my device, Do I need to install the library? Answer:
`PIVOT` relational operator is an option: Sample data: ``` SELECT * INTO Company FROM (VALUES (1, 'Frodo B (manager), Gandalf G (director), Batman C (cleaner)'), (2, 'John Doe (secretary), Mark Jacobs (manager), Lilly Hopes (director), Rihanna Williams (cleaner), Maddy James (supervisor), Merry Poppins (HR)'), (3, 'Rick Ross (cleaner)'), (4, 'Orlando Bloom (manager), Keira Knightly (secretary)') ) d (Id, Team) ``` Statement: ``` SELECT * FROM ( SELECT c.Id, LTRIM(s.[value]) AS [Name], p.Position FROM Company c CROSS APPLY STRING_SPLIT(c.Team, ',') s JOIN (VALUES ('cleaner'), ('director'), ('manager'), ('supervisor'), ('secretary'), ('HR'), ('owner') ) p (Position) ON CHARINDEX(p.Position, s.[value]) > 0 ) t PIVOT ( MAX(Name) FOR Position IN ([cleaner], [director], [manager], [supervisor], [secretary], [HR], [owner]) ) p ``` Result: | Id | cleaner | director | manager | supervisor | secretary | HR | owner | | --- | --- | --- | --- | --- | --- | --- | --- | | 1 | Batman C (cleaner) | Gandalf G (director) | Frodo B (manager) | | | | | | 2 | Rihanna Williams (cleaner) | Lilly Hopes (director) | Mark Jacobs (manager) | Maddy James (supervisor) | John Doe (secretary) | Merry Poppins (HR) | | | 3 | Rick Ross (cleaner) | | | | | | | | 4 | | | Orlando Bloom (manager) | | Keira Knightly (secretary) | | | For SQL Server versions before 2016 (but with XML support), you may split the stored text using well-known XML technique: ``` SELECT * FROM ( SELECT c.Id, LTRIM(s.[value].value('.', 'varchar(1000)')) AS [Name], p.Position FROM ( SELECT *, CAST('<x>' + REPLACE(Team, ',', '</x><x>') + '</x>' AS XML) AS XmlTeam FROM Company ) c CROSS APPLY c.XmlTeam.nodes('./x') s ([value]) JOIN (VALUES ('cleaner'), ('director'), ('manager'), ('supervisor'), ('secretary'), ('HR'), ('owner') ) p (Position) ON CHARINDEX(p.Position, s.[value].value('.', 'varchar(1000)')) > 0 ) t PIVOT ( MAX(Name) FOR Position IN ([cleaner], [director], [manager], [supervisor], [secretary], [HR], [owner]) ) p ```
Recursion is another (knowing that it is limited to 7 iterations): ``` with MyTable as ( select * from (values (1, 'Frodo B (manager), Gandalf G (director), Batman C (cleaner)') ,(2, 'John Doe (secretary), Mark Jacobs(manager), Lilly Hopes(director), Rihanna Williams (cleaner), Maddy James (supervisor), Merry Poppins (HR)') ,(3, 'Rick Ross (cleaner)') ,(4,'Orlando Bloom (manager), Keira Knightly (secretary)') ) T (Id, Team) ), RCTE as ( -- Find closing bracket positions select Id, FromPos=1 , BctPos=charindex(')',Team), Team from MyTable union all select R.Id, FromPos=R.BctPos+2, BctPos=charindex(')', M.Team, R.BctPos+1), M.Team from MyTable M inner join RCTE R on R.Id=M.Id where charindex(')',M.Team,R.BctPos+1)>0 ), Parsed as ( select Id, Team, Member=SubString(Team,FromPos,BctPos-FromPos+1) from RCTE) select Id , director=min(case when Member like '%(director)' then left(Member,len(Member)- charindex('(',Member)-1) end) , cleaner=min(case when Member like '%(cleaner)' then left(Member,len(Member)- charindex('(',Member)-1) end) , manager=min(case when Member like '%(manager)' then left(Member,len(Member)- charindex('(',Member)-1) end) , supervisor=min(case when Member like '%(supervisor)' then left(Member,len(Member)- charindex('(',Member)-1) end) , secretary=min(case when Member like '%(secretary)' then left(Member,len(Member)- charindex('(',Member)-1) end) , owner=min(case when Member like '%(owner)' then left(Member,len(Member)- charindex('(',Member)-1) end) from Parsed group by id order by id ``` I assumed that they are all well formed (brackets are correctly opened closed; and blanks are used consistently, etc.
Question: Have some data stored in different directory paths in databricks file system. Need to rename some folders. Is it possible to rename folders in DBFS? If so, what's the command? Answer:
You can use `mv` with `%fs` magic, or `dbutils.fs` to do this. This command is used for renaming and/or moving files and directories `%fs mv -r /path/to/folder /path/to/new_folder_name` the `-r` is to do recursive move with directories. It's documented in the [dbutils](https://docs.databricks.com/_static/notebooks/dbutils.html). There is also more info [here](https://docs.databricks.com/data/databricks-file-system.html#dbfs-and-local-driver-node-paths).
Use this. Just replace the path with your actual path. ``` old_name = r"dbfs:/FileStore/tables/PM/TC/ROBERTA" new_name = r"dbfs:/FileStore/tables/PM/TC/BERT" dbutils.fs.mv(old_name, new_name, True) ```
Question: Hello there I try to align some text in a container to the left but it won't work even when there is free space. As you can see there is some free space directly next to the image which isn't used for no reason. Right here I show you a picture and also the style. Thanks in advance if anyone can help. ![enter image description here](https://i.stack.imgur.com/DTEG9.png) ```css .text-wrapper-overview { position: inherit; left: 100px; width: 65%; } .user-name { position: inherit; margin: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: large; font-weight: bold; } .last-message { position: inherit; height: 20px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin: 5px; font-size: small; } .timestamp-overview { position: inherit; margin: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: small; font-weight: normal; } ``` ```html <div id={this.name} className="chat-overview" onClick={()=>this.renderChat()}> <img className="round-image" src="https://i.pravatar.cc/200"></img> <div className="text-wrapper-overview"> <p className="user-name">{this.name}</p> <p className="last-message">{this.lastMessage.text}</p> <p className="timestamp-overview">{this.lastDate}</p> </div> <div className="notification">10+</div> </div> ``` Answer:
You could use interfaces with default implementations which were introduced in C# 8. Then you could derive from these interfaces. Here's an example of how you could you provide default implementations for the `MoveForward()` and `StartBroadcast()` methods: ```cs public interface IVehicle { void MoveForward() { // your code } void PerformUniqueAbility(); } ``` ```cs public interface IRadioSignalBroadcaster { void StartBroadcast() { // your code } void PerformUniqueBroadcastingAbility(); } ```
You can't inherit more than 1 class but you can inherit more than one interface. Is this what you are looking for? ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { internal class Program { static void Main(string[] args) { IVehicle vehicle = new Vehicle(); IRadioBroadcaster broadcaster = new RadioBroadcaster(); vehicle.MoveForward(); vehicle.PerformUniqueAbility(); broadcaster.StartBroadcast(); broadcaster.PerformUniqueAbility(); } } public interface IUniqueAbillity { void PerformUniqueAbility(); } public interface IVehicle: IUniqueAbillity { void MoveForward(); } public interface IRadioBroadcaster : IUniqueAbillity { void StartBroadcast(); } public abstract class RealWorldObject : IVehicle, IRadioBroadcaster { public void MoveForward() { // Move forward } public abstract void PerformUniqueAbility(); public void StartBroadcast() { // Start broadcast } } public class Vehicle : RealWorldObject, IVehicle { public override void PerformUniqueAbility() { // Do something } } public class RadioBroadcaster : RealWorldObject, IRadioBroadcaster { public override void PerformUniqueAbility() { // Do something } } } ```
Question: It hadn’t properly registered yet with Arthur that the council wanted to knock it down" - what's the meaning of register with someone here? Answer:
This would be dependent on whether the speaker was referring to the group/entity of the Club or to the location of Sunnyside Country Club. For instance if you removed the words 'Sunnyside' and 'Country' and just left the word Club, a speaker would be more likely to choose the term "to". I was accepted for membership to the club. One might then wonder as to which 'club' you are referring, so it is necessary for the speaker to use the Proper Name. Once the proper name is used however, it also has the interchangeable reference to the location of Sunnyside Country Club. If the speaker was referring to the location they would more commonly use 'at' in this sentence. I was accepted for membership at Sunnyside Country Club. (as in over at their location, where they meet.)
See my comment to JA's answer. Membership prepositions per the [Ngram viewer](https://books.google.com/ngrams/graph?content=for%20membership%20*%2Cfor%20membership%20at%2Cfor%20membership%20into&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t2%3B%2Cfor%20membership%20%2A%3B%2Cc0%3B%2Cs0%3B%3Bfor%20membership%20in%3B%2Cc0%3B%3Bfor%20membership%20of%3B%2Cc0%3B%3Bfor%20membership%20and%3B%2Cc0%3B%3Bfor%20membership%20on%3B%2Cc0%3B%3Bfor%20membership%20is%3B%2Cc0%3B%3Bfor%20membership%20to%3B%2Cc0%3B%3Bfor%20membership%20was%3B%2Cc0%3B%3Bfor%20membership%20are%3B%2Cc0%3B%3Bfor%20membership%20were%3B%2Cc0%3B%3Bfor%20membership%20must%3B%2Cc0%3B.t1%3B%2Cfor%20membership%20at%3B%2Cc0%3B.t1%3B%2Cfor%20membership%20into%3B%2Cc0).
Question: It hadn’t properly registered yet with Arthur that the council wanted to knock it down" - what's the meaning of register with someone here? Answer:
This would be dependent on whether the speaker was referring to the group/entity of the Club or to the location of Sunnyside Country Club. For instance if you removed the words 'Sunnyside' and 'Country' and just left the word Club, a speaker would be more likely to choose the term "to". I was accepted for membership to the club. One might then wonder as to which 'club' you are referring, so it is necessary for the speaker to use the Proper Name. Once the proper name is used however, it also has the interchangeable reference to the location of Sunnyside Country Club. If the speaker was referring to the location they would more commonly use 'at' in this sentence. I was accepted for membership at Sunnyside Country Club. (as in over at their location, where they meet.)
I would suggest this is more of a US v UK English issue. I live in the UK and until about five years ago I had never heard the phrase 'membership to' - it was always 'membership of'. Suddenly, 'membership to' has become ubiquitous. As a Brit, 'membership to' makes no sense to me, but had I grown up in the USA it would doubtless seem normal.
Question: It hadn’t properly registered yet with Arthur that the council wanted to knock it down" - what's the meaning of register with someone here? Answer:
This would be dependent on whether the speaker was referring to the group/entity of the Club or to the location of Sunnyside Country Club. For instance if you removed the words 'Sunnyside' and 'Country' and just left the word Club, a speaker would be more likely to choose the term "to". I was accepted for membership to the club. One might then wonder as to which 'club' you are referring, so it is necessary for the speaker to use the Proper Name. Once the proper name is used however, it also has the interchangeable reference to the location of Sunnyside Country Club. If the speaker was referring to the location they would more commonly use 'at' in this sentence. I was accepted for membership at Sunnyside Country Club. (as in over at their location, where they meet.)
I would suggest this is more of a US v UK English issue. UK dictionaries use 'of' when defining membership. Moreover, I've lived in the UK for over 50 years and until about five years ago I had never heard the phrase 'membership to' - it was always 'membership of'. Suddenly, 'membership to' has become ubiquitous. As a Brit, 'membership to' makes no sense to me, but had I grown up in the USA it would doubtless seem normal. I'd add that I'm an editor by profession, so I have a reasonable grasp of UK English and am very alert to changes in usage.
Question: We can extract distinct value set from a list by using following code ``` List<Person> distinctPeople = allPeople .GroupBy(p => new {p.PersonId, p.FavoriteColor} ) .Select(g => g.First()) .ToList(); ``` Assume person has PersonId, FavoriteColor, age, address, etc..... My requirement is I would like to get a separate list which should contain distinct filter data only such as PersonId, FavoriteColor not others. What is the command for that, Assume I can create a small class which contain PersonId, FavoriteColor only Answer:
I am writing this for other people who might run into the same problem like me in the future. Apparently as Mr. Leonardo as pointed out, HTML e-mails doesn't read the external or even internal css at all because the head part of the template are opted out and only body part are used. Thus the solution is to use table and html attributes with inline css to style the html email template. Thanks
The one way is to use inline css in the code, ``` <div class="pre"><strong>Title,</strong>&nbsp;</div> <div class="pre">&nbsp;</div> <blockquote> <div class="pre">Message part</div> </blockquote> <div class="pre">&nbsp;</div> <div class="pre"><span style="background-color: #800080;">Thanks</span>,<br /> <br /> </div> </div> ``` It works for me..
Question: I am newbie to java db coding... This is my java code ``` Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database..."); conn = DriverManager.getConnection("jdbc:mysql://localhost/EMP",USER,PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; ``` This is the exception I am getting : ``` ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/tiles].[default]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet default threw exception: java.net.ConnectException: Connection refused: connect ``` I am mySQL server also running and contains simple table named EMP. I am not interpreting the get connection URL comppletely. Can anyone explain it briefly? Thanks. Answer:
You are using the wrong driver for the database. Every database (MySQL, PostgreSQL, SQL Server, Oracle etc.) has a different driver which is what connects between JDBC and the particular database's communication protocol. You need the Microsoft SQL Server driver. You can download and install it from here if you don't already have it: [Microsoft down page for JDBC 4.0 driver](http://www.microsoft.com/en-us/download/details.aspx?id=11774). And here are the [instructions](http://technet.microsoft.com/en-us/library/ms378526%28v=sql.110%29.aspx) on how to add the jar to your classpath, and what URL to use. Note that in JDBC 4.0 and above, the `forName` is not necessary anymore.
from what i can see and understand is that you're missing the port. you'd have done it in this way: conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/EMP",USER,PASS); The url can be describe in this way jdbc: which is your connector mysql:which is your current installed database //hostname: which the machine hosting the server portNumber: the port which allows the connection for the server /databaseName: which is your created database. hope it was helpful
Question: I am newbie to java db coding... This is my java code ``` Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database..."); conn = DriverManager.getConnection("jdbc:mysql://localhost/EMP",USER,PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; ``` This is the exception I am getting : ``` ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/tiles].[default]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet default threw exception: java.net.ConnectException: Connection refused: connect ``` I am mySQL server also running and contains simple table named EMP. I am not interpreting the get connection URL comppletely. Can anyone explain it briefly? Thanks. Answer:
You are using the wrong driver for the database. Every database (MySQL, PostgreSQL, SQL Server, Oracle etc.) has a different driver which is what connects between JDBC and the particular database's communication protocol. You need the Microsoft SQL Server driver. You can download and install it from here if you don't already have it: [Microsoft down page for JDBC 4.0 driver](http://www.microsoft.com/en-us/download/details.aspx?id=11774). And here are the [instructions](http://technet.microsoft.com/en-us/library/ms378526%28v=sql.110%29.aspx) on how to add the jar to your classpath, and what URL to use. Note that in JDBC 4.0 and above, the `forName` is not necessary anymore.
Download the Microsoft JDBC driver and use `Class.forName(com.microsoft.sqlserver.jdbc.SQLServerDriver);` If the problem still persists enable TCP/IP network protocol, which is disabled by default, and set the TCP/IP port to 1433 which is the default port number.
Question: I am newbie to java db coding... This is my java code ``` Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database..."); conn = DriverManager.getConnection("jdbc:mysql://localhost/EMP",USER,PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; ``` This is the exception I am getting : ``` ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/tiles].[default]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet default threw exception: java.net.ConnectException: Connection refused: connect ``` I am mySQL server also running and contains simple table named EMP. I am not interpreting the get connection URL comppletely. Can anyone explain it briefly? Thanks. Answer:
from what i can see and understand is that you're missing the port. you'd have done it in this way: conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/EMP",USER,PASS); The url can be describe in this way jdbc: which is your connector mysql:which is your current installed database //hostname: which the machine hosting the server portNumber: the port which allows the connection for the server /databaseName: which is your created database. hope it was helpful
Download the Microsoft JDBC driver and use `Class.forName(com.microsoft.sqlserver.jdbc.SQLServerDriver);` If the problem still persists enable TCP/IP network protocol, which is disabled by default, and set the TCP/IP port to 1433 which is the default port number.
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that $$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$ for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have $$a\_0t+a\_2\sin t =0 \tag{2}$$ Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$.
*Hint.* Write one as a linear combination of the others. That is, look for real numbers $a,b,c$ not simultaneously vanishing, so that we may write $$at+be^t+c\sin t=0.$$
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that $$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$ for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have $$a\_0t+a\_2\sin t =0 \tag{2}$$ Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$.
HINT.- A good way to try this problem is to consider that the elements of $V$ are $f\_1,f\_2,f\_3$ where $f\_1(t)=t,f\_2(t)=e^t,f\_3(t)=\sin(t)$ so you have to show that if the linear combination $$a\_1f\_1+a\_2f\_2+a\_3f\_3=0$$ where les $f\_i$ are three vectors and les $a\_i$ are scalars in your vectorial space, then $a\_1=a\_2=a\_3=0$ (Obviously for each $t$ you have $$(a\_1f\_1+a\_2f\_2+a\_3f\_3)(t)=a\_1f\_1(t)+a\_2f\_2(t)+a\_3f\_3(t)=0)$$
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Here is a another way to skin the cat: Suppose $\alpha\_1 t + \alpha\_2 e^t + \alpha\_3 \sin t = 0$ for all $t$. If we differentiate twice and set $t = 0$, we get $\alpha\_2 e^{\pi \over 2} = 0$ and so $\alpha\_2 = 0$. If we differentiate twice and set $t = -{\pi \over 2}$, we get $\alpha\_3 = 0$. Finally, set $t=1$ to get $\alpha\_1 = 0$. Hence $S$ is linearly independent.
Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that $$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$ for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have $$a\_0t+a\_2\sin t =0 \tag{2}$$ Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$.
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that $$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$ for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have $$a\_0t+a\_2\sin t =0 \tag{2}$$ Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$.
Also you may find if $$\begin{vmatrix} f\_1(t) & f\_2(t) & f\_3(t) \\ f\_1'(t) & f\_2'(t) & f\_3'(t)\\ f\_1''(t) & f\_2''(t) & f\_3''(t)\end{vmatrix}= 0,$$ then the three functions are linearly dependent (LD) otherwise they are linearly independent (LI).
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Here is a another way to skin the cat: Suppose $\alpha\_1 t + \alpha\_2 e^t + \alpha\_3 \sin t = 0$ for all $t$. If we differentiate twice and set $t = 0$, we get $\alpha\_2 e^{\pi \over 2} = 0$ and so $\alpha\_2 = 0$. If we differentiate twice and set $t = -{\pi \over 2}$, we get $\alpha\_3 = 0$. Finally, set $t=1$ to get $\alpha\_1 = 0$. Hence $S$ is linearly independent.
*Hint.* Write one as a linear combination of the others. That is, look for real numbers $a,b,c$ not simultaneously vanishing, so that we may write $$at+be^t+c\sin t=0.$$
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Here is a another way to skin the cat: Suppose $\alpha\_1 t + \alpha\_2 e^t + \alpha\_3 \sin t = 0$ for all $t$. If we differentiate twice and set $t = 0$, we get $\alpha\_2 e^{\pi \over 2} = 0$ and so $\alpha\_2 = 0$. If we differentiate twice and set $t = -{\pi \over 2}$, we get $\alpha\_3 = 0$. Finally, set $t=1$ to get $\alpha\_1 = 0$. Hence $S$ is linearly independent.
HINT.- A good way to try this problem is to consider that the elements of $V$ are $f\_1,f\_2,f\_3$ where $f\_1(t)=t,f\_2(t)=e^t,f\_3(t)=\sin(t)$ so you have to show that if the linear combination $$a\_1f\_1+a\_2f\_2+a\_3f\_3=0$$ where les $f\_i$ are three vectors and les $a\_i$ are scalars in your vectorial space, then $a\_1=a\_2=a\_3=0$ (Obviously for each $t$ you have $$(a\_1f\_1+a\_2f\_2+a\_3f\_3)(t)=a\_1f\_1(t)+a\_2f\_2(t)+a\_3f\_3(t)=0)$$
Question: Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent? Answer:
Here is a another way to skin the cat: Suppose $\alpha\_1 t + \alpha\_2 e^t + \alpha\_3 \sin t = 0$ for all $t$. If we differentiate twice and set $t = 0$, we get $\alpha\_2 e^{\pi \over 2} = 0$ and so $\alpha\_2 = 0$. If we differentiate twice and set $t = -{\pi \over 2}$, we get $\alpha\_3 = 0$. Finally, set $t=1$ to get $\alpha\_1 = 0$. Hence $S$ is linearly independent.
Also you may find if $$\begin{vmatrix} f\_1(t) & f\_2(t) & f\_3(t) \\ f\_1'(t) & f\_2'(t) & f\_3'(t)\\ f\_1''(t) & f\_2''(t) & f\_3''(t)\end{vmatrix}= 0,$$ then the three functions are linearly dependent (LD) otherwise they are linearly independent (LI).
Question: I am using Bluez bluetooth Manager, after I send the files from my Android device to the Laptop which contains Linux Mate with the standard File System. I cannot seem to find the files which a received in this manner. The Bluez documentation does not specify where do these files go. Answer:
Grub allows you to password protect its config and console, as well as individual operating system entries. Please note that this *will not* stop dedicated individuals, especially the ones that know what they are doing. But I assume you know that. Lets get started. generate a password hash.. -------------------------- You could store your grub password in plain text but that is entirely insecure and anyone that had access to your account could quickly figure it out. To prevent this we hash the password using the `grub-mkpasswd-pbkdf2` command, like so: ``` user@host~ % grub-mkpasswd-pbkdf2 Enter password: Reenter password: PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.63553D205CF6E... ``` While you type your password no characters will show in the terminal, this is to prevent people looking over your shoulders, etc. Now, copy the entirety of your hash with `Ctrl`+`Shift`+`C`. protecting the config, console.. -------------------------------- Run: ``` sudo nano /etc/grub.d/40_custom ``` This will create a new configuration file called `40_custom` in grub's configuration directory. Now add the lines: ``` set superusers="username" password_pbkdf2 username hash ``` Where `username` is a username of your choice and `hash` is the hash we generated in the last command. Press `Ctrl`+`O` and then `Ctrl`+`X` to save and quit. Run: ``` sudo update-grub ``` To finalize the changes. Now, when anyone attempts to edit the grub configuration or access a grub console it will prompt them for a username and password. password protecting operating system entries.. ---------------------------------------------- Currently the only method to achieve this I can find is to edit the `/boot/grub/grub.cfg` manually. This is only temporary however as any new kernel update will rewrite this file and your passwords will be gone (note that this doesn't effect the console/editing password we set above). All other methods I have found so far are extremely out of date and I can no longer get them to work. I've asked the grub mailing list if there is a newer method and will edit this answer as soon as I find out.
The GRUB manual has a section about [security](http://www.gnu.org/software/grub/manual/grub.html#Security). This tells you how to password protect your GRUB boot menu to restrict access to specific operations or boot variants. It contains a small example.
Question: When we use the cylindrical coordinate system $(r, \theta, z)$ where $r$ is the distance from the point in the $xy$-plane, $\theta$ is the angle with the $x$ axis and $z$ is the heigth. As can been seen in the picture [![enter image description here](https://i.stack.imgur.com/lKIQb.png)](https://i.stack.imgur.com/lKIQb.png) I hav a vector field described by $(0,U\_{\theta}(r),U\_z)$ but how can the angle differ when $r$ is always zero? When $r$ is zero, then there is no difference between different angles. Or am i wrong? Some help would be great. Answer:
**Hint:** You discover the rules by working backwards. First consider polynomials, say of the third degree, like $ax^3+bx^2+cx+d$. The first derivative is a second degree polynomial, so that the LHS of a first order equation would yield $$\alpha y+\beta y'=\alpha ax^3+(\alpha b+3\beta a)x^2+(\alpha c+2\beta b)x+(\alpha d+\beta c),$$ another cubic polynomial. Similarly, $$\alpha y+\beta y'+\gamma y''=\alpha ax^3+(\alpha b+3\beta a)x^2+(\alpha c+2\beta b+6\gamma c)x+(\alpha d+\beta c+2\gamma b)$$ also third degree. Now it is clear that for a linear equation of any degree, if the RHS is a polynomial of degree $d$, there will be another polynomial of degree $d$ which is a solution. --- For an exponential function, $e^{ax}$, $$\alpha y+\beta y'+\gamma y''=(\alpha +\beta a+\gamma a^2)e^{ax}$$ so that an exponential RHS is obtained from an exponential solution. --- You can play the same game with RHS of the form $e^{ax}\sin bx$ and $e^{ax}\cos bx$. If you are familiar with complex numbers, you can even take a shortcut by considering $e^{(a+ib)x}$, which combines the two functions in one.
$$y'''(x)-2y''(x)+y'(x)=x+2$$ It's easy to determine the exponent of the function try to substitute $y=z+ax^n$ $$y'''+.............+y'=x+2$$ $$(z'''+....)+..............+(z'+nax^{n-1})=x+2$$ for y' we get the highest monomial degree in x so it must be equal to the degre of x on right side $$x^{n-1}=x \implies n=2$$ So you have to try a polynomial of degree two $$ax^2+bx+c$$ You observe that you have only derivatives on the left side so $c=0$ And $ax^2+bx$ is the right choice...
Question: How can I create a table like this in Latex? [![enter image description here](https://i.stack.imgur.com/4MYki.png)](https://i.stack.imgur.com/4MYki.png) I have tried but it didn't work. I need also that it is enumerated so that it appears in the List of Tables. It doesn't matter if it is not coloured, as long as the first two rows are bold. ``` \begin{center} \begin{tabular}{ |c|c|c|c|c| } \hline \multicolumn{5}{|c|}{Number of cells per type} \\ \hline a& b& c& d& e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabular} \end{center} ``` Answer:
I suggest you to use `booktabs` for professional tables. ``` \documentclass[11pt,openright]{book} \usepackage{array} \newcolumntype{C}{>{\centering\arraybackslash}X} \renewcommand{\arraystretch}{1.2} \usepackage{booktabs} \usepackage{tabularx} \usepackage{caption} \begin{document} \listoftables \chapter{My chapter} \begin{table}[htb]\centering \caption{Your table\label{tab:yourtab}} \begin{tabularx}{.5\linewidth}{ |C|C|C|C|C| } \hline \multicolumn{5}{|c|}{\bfseries Number of cells per type} \\ \hline \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabularx} \end{table} \begin{table}[htb]\centering \caption{My suggestion\label{tab:mytab}} \begin{tabularx}{.5\linewidth}{*5C} \toprule \multicolumn{5}{c}{\bfseries Number of cells per type} \\ \midrule \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \midrule 44 & 39 & 7 & 32 &22 \\ \bottomrule \end{tabularx} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/7IC07.png)](https://i.stack.imgur.com/7IC07.png) [![enter image description here](https://i.stack.imgur.com/eg5I0.png)](https://i.stack.imgur.com/eg5I0.png)
A mix-and-match with colors and using something as a starting point ``` \documentclass[10pt,a4paper]{article} \usepackage[table,xcdraw]{xcolor} \begin{document} \listoftables\newpage \begin{table}[] \begin{tabular}{!{\color{cyan}\vrule}l!{\color{cyan}\vrule}l!{\color{cyan}\vrule}l!{\color{cyan}\vrule}l!{\color{cyan}\vrule}l!{\color{cyan}\vrule}} \arrayrulecolor{cyan}\hline \rowcolor[HTML]{38FFF8} \multicolumn{5}{!{\color{cyan}\vrule}l!{\color{cyan}\vrule}}{\cellcolor[HTML]{38FFF8}Number of cells per type} \\ \arrayrulecolor{cyan}\hline \rowcolor[HTML]{38FFF8} a & b & c & d & e \\ \arrayrulecolor{cyan}\hline 1 & 2 & 3 & 4 & 5 \\ \hline \end{tabular} \caption{a} \end{table} \end{document} ``` to get: [![enter image description here](https://i.stack.imgur.com/jIr7C.png)](https://i.stack.imgur.com/jIr7C.png) [![enter image description here](https://i.stack.imgur.com/Io68R.png)](https://i.stack.imgur.com/Io68R.png) PS: Feel free to play with colors (I right now, do not have the necessary things to find out the colors) and I was lazy enough not to input your numbers (sorry `;-)`)
Question: How can I create a table like this in Latex? [![enter image description here](https://i.stack.imgur.com/4MYki.png)](https://i.stack.imgur.com/4MYki.png) I have tried but it didn't work. I need also that it is enumerated so that it appears in the List of Tables. It doesn't matter if it is not coloured, as long as the first two rows are bold. ``` \begin{center} \begin{tabular}{ |c|c|c|c|c| } \hline \multicolumn{5}{|c|}{Number of cells per type} \\ \hline a& b& c& d& e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabular} \end{center} ``` Answer:
I suggest you to use `booktabs` for professional tables. ``` \documentclass[11pt,openright]{book} \usepackage{array} \newcolumntype{C}{>{\centering\arraybackslash}X} \renewcommand{\arraystretch}{1.2} \usepackage{booktabs} \usepackage{tabularx} \usepackage{caption} \begin{document} \listoftables \chapter{My chapter} \begin{table}[htb]\centering \caption{Your table\label{tab:yourtab}} \begin{tabularx}{.5\linewidth}{ |C|C|C|C|C| } \hline \multicolumn{5}{|c|}{\bfseries Number of cells per type} \\ \hline \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabularx} \end{table} \begin{table}[htb]\centering \caption{My suggestion\label{tab:mytab}} \begin{tabularx}{.5\linewidth}{*5C} \toprule \multicolumn{5}{c}{\bfseries Number of cells per type} \\ \midrule \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \midrule 44 & 39 & 7 & 32 &22 \\ \bottomrule \end{tabularx} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/7IC07.png)](https://i.stack.imgur.com/7IC07.png) [![enter image description here](https://i.stack.imgur.com/eg5I0.png)](https://i.stack.imgur.com/eg5I0.png)
Don't mix-and-mismatch visual cues and metaphores: if you employ colored rows, don't employ horizontal rules. And, for sure, you can omit all vertical rules -- they're not needed. [![enter image description here](https://i.stack.imgur.com/uJel3.png)](https://i.stack.imgur.com/uJel3.png) ``` \documentclass{article} \usepackage[table,svgnames]{xcolor} \usepackage{array} % for '\extrarowheight' macro \begin{document} \begin{center} \sffamily \setlength\extrarowheight{2pt} % optional \setlength\tabcolsep{9pt} % default: 6pt \begin{tabular}{ ccccc } %\hline \rowcolor{LightBlue} \multicolumn{5}{c}{Number of cells per type} \\ %\hline \rowcolor{LightBlue} a & b & c & d & e\\ %\hline 44 & 39 & 7 & 32 & 22 \\ \hline \end{tabular} \end{center} \end{document} ```
Question: How can I create a table like this in Latex? [![enter image description here](https://i.stack.imgur.com/4MYki.png)](https://i.stack.imgur.com/4MYki.png) I have tried but it didn't work. I need also that it is enumerated so that it appears in the List of Tables. It doesn't matter if it is not coloured, as long as the first two rows are bold. ``` \begin{center} \begin{tabular}{ |c|c|c|c|c| } \hline \multicolumn{5}{|c|}{Number of cells per type} \\ \hline a& b& c& d& e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabular} \end{center} ``` Answer:
I suggest you to use `booktabs` for professional tables. ``` \documentclass[11pt,openright]{book} \usepackage{array} \newcolumntype{C}{>{\centering\arraybackslash}X} \renewcommand{\arraystretch}{1.2} \usepackage{booktabs} \usepackage{tabularx} \usepackage{caption} \begin{document} \listoftables \chapter{My chapter} \begin{table}[htb]\centering \caption{Your table\label{tab:yourtab}} \begin{tabularx}{.5\linewidth}{ |C|C|C|C|C| } \hline \multicolumn{5}{|c|}{\bfseries Number of cells per type} \\ \hline \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \hline 44 & 39 & 7 & 32 &22 \\ \hline \end{tabularx} \end{table} \begin{table}[htb]\centering \caption{My suggestion\label{tab:mytab}} \begin{tabularx}{.5\linewidth}{*5C} \toprule \multicolumn{5}{c}{\bfseries Number of cells per type} \\ \midrule \bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\ \midrule 44 & 39 & 7 & 32 &22 \\ \bottomrule \end{tabularx} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/7IC07.png)](https://i.stack.imgur.com/7IC07.png) [![enter image description here](https://i.stack.imgur.com/eg5I0.png)](https://i.stack.imgur.com/eg5I0.png)
There is also a really handy online tool called [Tables Generator](https://www.tablesgenerator.com/). It lets you input your data (you can even upload it from file), and adapt it WYSIWYG-style. It will then generate the correct LaTeX code for you to copy/paste into you document. Edit: As suggested by Sanctus, here is the code that Tables Generator output me (after 2 minutes of data entry). It does give really nice results for relatively simple tables with standard settings (colors, borders, font style, etc), but if you need something fancy, it probably won't provide enough. But I always use it as a starting point, to get the general structure working. Everything else I can then adapt myself. ``` \documentclass{article} \usepackage[table,xcdraw]{xcolor} \usepackage{graphicx} \usepackage{booktabs} \begin{document} % Please add the following required packages to your document preamble: % \usepackage[table,xcdraw]{xcolor} % If you use beamer only pass "xcolor=table" option, i.e. \documentclass[xcolor=table]{beamer} \begin{table}[] \begin{tabular}{|c|c|c|c|c|} \hline \rowcolor[HTML]{DAE8FC} \multicolumn{5}{|c|}{\cellcolor[HTML]{DAE8FC}\textbf{\tiny{Number of cells per type}}} \\ \hline \rowcolor[HTML]{DAE8FC} \textbf{a} & \textbf{b} & \textbf{c} & \textbf{d} & \textbf{e} \\ \hline 44 & 39 & 7 & 32 & 22 \\ \hline \end{tabular} \end{table} \end{document} ``` [![Output Table](https://i.stack.imgur.com/fHS6h.png)](https://i.stack.imgur.com/fHS6h.png)
Question: I have an azure website and database. I'm running an ASP.NET MVC 4 / EF 5 app localy and trying to put some data to the azure database before to deploy the app. But I have a TargetInvocationException : {"The ASP.NET Simple Membership database could not be initialized. For more information, please see <http://go.microsoft.com/fwlink/?LinkId=256588>"} Keyword not supported : server This is the connection string that I get from my azure dashboard : ``` <add name="myconstring" connectionString=Server=tcp:myserver.database.windows.net,1433;Database=mydatabase;User ID=cdptest@myserver;Password=******;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient" /> ``` I tried this I got "Keyword not supported : data source" ``` <add name="myconstring" connectionString="Data Source=myserver.database.windows.net;Initilal Catalog=mydatabase;User ID=cdptest@myserver;Password=*****;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient"/> ``` Answer:
The following works for me: ``` <add name="coupdpoAPEkowswAEntities" connectionString="Server=tcp:myserver.database.windows.net,1433;Database=mydatabase;User ID=cdptest@myserver;Password=*****;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient"/> ``` Use Server instead of Data Source, and specify the protocol and the port, and use Database instead of Initial Catalog
OK the providername was wrong. System.Data.SqlClient was excepted as this is a code first app model. I probably got System.Data.EntityClient from another app with Model First or Database First...
Question: For a project I am working on, one of the things we're implementing is something that we have code for in some of my teams older ASP.NET and MVC projects - an `Application_Error` exception catcher that dispatches an email to the development team with the exception experience and most relevant details. Here's how it looks: **Global.asax:** ``` protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); string path = "N/A"; if (sender is HttpApplication) path = ((HttpApplication) sender).Request.Url.PathAndQuery; string args = string.Format("<b>Path:</b> {0}", path); // Custom code that generates an HTML-formatted exception dump string message = Email.GenerateExceptionMessage(ex, args); // Custom code that sends an email to the dev team. Email.SendUnexpectedErrorMessage("Some App", message); } ``` One "minor" problem, though - when I intentionally have a part of the code throw an exception in order to test this mechanism... ``` public static void GetMuffinsByTopping(string topping) { throw new Exception("Test Exception!", new Exception("Test Inner Exception!!!")); // Actual repository code is unreachable while this test code is there } ``` The front-end JavaScript is immediately intercepting an HTTP 500 request, but the global.asax.cs code noted above is not being reached (I set a breakpoint on the first executing line of the method.) **Question:** In what way can I get the "old" `Application_Error` handler to dispatch error emails, so that our team's developers can more easily debug our application? Answer:
Abstract out your error handling logic from `Application_Error` into its own function. Create a [Web API exception filter](http://www.asp.net/web-api/overview/error-handling/exception-handling). ``` //register your filter with Web API pipeline //this belongs in the Application_Start event in Global Application Handler class (global.asax) //or some other location that runs on startup GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute()); //Create filter public class LogExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { ErrorLogService.LogError(context.Exception); } } //in global.asax or global.asax.cs protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); ErrorLogService.LogError(ex); } //common service to be used for logging errors public static class ErrorLogService { public static void LogError(Exception ex) { //Email developers, call fire department, log to database etc. } } ``` Errors from Web API do not trigger the Application\_Error event. But we can create an exception filter and register it to handle the errors. Also see [Global Error Handling in ASP.NET Web API 2](https://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling).
In my case, i prefer not use Web.config. Then i created code above in Global.asax file: ``` protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); //Not Found (When user digit unexisting url) if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) { HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "NotFound"); IController controller = new ErrorController(); RequestContext requestContext = new RequestContext(contextWrapper, routeData); controller.Execute(requestContext); Response.End(); } else //Unhandled Errors from aplication { ErrorLogService.LogError(ex); HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); IController controller = new ErrorController(); RequestContext requestContext = new RequestContext(contextWrapper, routeData); controller.Execute(requestContext); Response.End(); } } ``` And thtat is my ErrorController.cs ``` public class ErrorController : Controller { // GET: Error public ViewResult Index() { Response.StatusCode = 500; Exception ex = Server.GetLastError(); return View("~/Views/Shared/SAAS/Error.cshtml", ex); } public ViewResult NotFound() { Response.StatusCode = 404; return View("~/Views/Shared/SAAS/NotFound.cshtml"); } } ``` And that is my ErrorLogService.cs copyed from @mason class ``` //common service to be used for logging errors public static class ErrorLogService { public static void LogError(Exception ex) { //Do what you want here, save log in database, send email to police station } } ```
Question: So I have this code that pops up a file chooser and reads the file: ``` JFileChooser chooser = new JFileChooser(); File file = null; int returnValue = chooser.showOpenDialog( null ) ; if( returnValue == JFileChooser.APPROVE_OPTION ) { file = chooser.getSelectedFile() ; } if(file != null) { String filePath = file.getPath(); } // String filePath (that's what i'm trying to input) = "Users/Bill/Desktop/hello.txt"; try { ReadFile files = new ReadFile(***); String[] lines = files.OpenFile(); ``` the three asterisks (*\**) represent the class path of the file to be read. What should I put there if I want to read the file? Before this, I hard-coded the class-path and passed it in and it worked, but now, the class-path can be whatever the user chooses. Thanks for your help! Answer:
I don't know what your `ReadFile` thing is, but it looks like it takes a string representing the file path. In which case, you probably want to give it `file.getPath()`.
Try using this instead of your code in try block: ``` FileReader fr = new FileReader(filePath); FileWriter outputStream = new FileWriter("filename.txt");; int c; while ((c = fr.read()) != -1) { outputStream.write(c); } ```
Question: i have created an application called "xyz.msi" and installed. Now i created another application called "abc.msi" and trying to install. But my question is if "xyz.msi" is installed already then it shouldn't allow to install "abc.msi". Thanks in advance Answer:
Take a look at the [Upgrade table](http://msdn.microsoft.com/en-us/library/windows/desktop/aa372379%28v=vs.85%29.aspx). You can use this to define the search criteria along with the msidbUpgradeAttributesOnlyDetect attribute to cause your action property to be assigned the ProductCode property that is found. Then you can use your action property in the [LaunchCondition table](http://msdn.microsoft.com/en-us/library/windows/desktop/aa369752%28v=vs.85%29.aspx) to prevent installation.
You are asking how MSI detect an installed application. Its since each MSI will have a unique Product Code (Refer to this: <http://msdn.microsoft.com/en-us/library/windows/desktop/aa370854(v=vs.85).aspx>) whenever you try to install a product it looks up at the product code if it matches it lets you do the re installation or upgrade. if it doesn't it will not. Depends how you creating the MSI. There are lots of ways of creating this but not really sure if you application lets you view the properties or not.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
Old Answer (still applies unless you are using Visual Studio Update 1 RTM (2015) or later) ------------------------------------------------------------------------------------------ In short. No, there doesn't seem to be a good plugin for it. If you use Perl rarely, I would recommend sticking with Visual Studio for Microsoft languages and [Padre](http://padre.perlide.org/) for Perl. However, if you use Perl as much or more than Microsoft languages, you might want to check out [Emacs](http://www.gnu.org/software/emacs/), which has support for [C#](https://stackoverflow.com/questions/8607/any-good-way-to-use-emacs-for-c-development), [VB.NET](http://www.emacswiki.org/emacs/vbnet-mode.el), and Perl. Emacs is designed to be a "one-stop-shop" for all you do all day long, including browsing the web. You can come into work, start using Emacs and never have to leave it until it is time to go home. *disclaimer: The answer above is geared toward the Original Poster. I'm a big fan of [vim](http://www.vim.org/about.php). Personally, if I were thrust into a situation where I had to work with C# and Perl on the same project, I would get [ViEMU for Visual Studio](http://www.viemu.com/) and then use two editors: Visual Studio for C# and vim for Perl.* --- If this is something you are willing to spend some time on, check out [defining your own syntax highlighting](https://stackoverflow.com/questions/115388/how-can-i-customize-the-syntax-highlighting-in-visual-studio-2005) for Visual Studio.
A workaround for Visual Studio desktop version is to use C++ syntax highlighting. * Go to Options -> Text Editor -> File Extension * Enter extension "pl" (no dot) * Assign it to "Microsoft Visual C++" * Click "Add" If necessary, repeat the same steps for "cgi" extension.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
[Visual Studio Update 1 RTM](http://blogs.msdn.com/b/visualstudio/archive/2015/11/30/visual-studio-update-1-rtm.aspx) now (2015) has Perl support, along with Go, Java, R, Ruby, and Swift.
A work-in-progress Visual Studio [extension](https://marketplace.visualstudio.com/items?itemName=scriplit.perl6-lsp) for Perl6 (not the Perl5 asked by the OP) is incrementally more full-featured. It is released under the [MIT License](https://marketplace.visualstudio.com/items/scriplit.perl6-lsp/license) and its [repository](https://github.com/scriplit/vscode-languageserver-perl6) is on GitHub. As a prerequisite, Perl6 (e.g., [Rakudo](https://rakudo.perl6.org/downloads/rakudo)) needs to already be installed.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
[Visual Studio Update 1 RTM](http://blogs.msdn.com/b/visualstudio/archive/2015/11/30/visual-studio-update-1-rtm.aspx) now (2015) has Perl support, along with Go, Java, R, Ruby, and Swift.
A workaround for Visual Studio desktop version is to use C++ syntax highlighting. * Go to Options -> Text Editor -> File Extension * Enter extension "pl" (no dot) * Assign it to "Microsoft Visual C++" * Click "Add" If necessary, repeat the same steps for "cgi" extension.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
[Komodo Edit](http://www.activestate.com/komodo-edit) is quite nice, and free. code folding and other good stuff.
A workaround for Visual Studio desktop version is to use C++ syntax highlighting. * Go to Options -> Text Editor -> File Extension * Enter extension "pl" (no dot) * Assign it to "Microsoft Visual C++" * Click "Add" If necessary, repeat the same steps for "cgi" extension.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
Old Answer (still applies unless you are using Visual Studio Update 1 RTM (2015) or later) ------------------------------------------------------------------------------------------ In short. No, there doesn't seem to be a good plugin for it. If you use Perl rarely, I would recommend sticking with Visual Studio for Microsoft languages and [Padre](http://padre.perlide.org/) for Perl. However, if you use Perl as much or more than Microsoft languages, you might want to check out [Emacs](http://www.gnu.org/software/emacs/), which has support for [C#](https://stackoverflow.com/questions/8607/any-good-way-to-use-emacs-for-c-development), [VB.NET](http://www.emacswiki.org/emacs/vbnet-mode.el), and Perl. Emacs is designed to be a "one-stop-shop" for all you do all day long, including browsing the web. You can come into work, start using Emacs and never have to leave it until it is time to go home. *disclaimer: The answer above is geared toward the Original Poster. I'm a big fan of [vim](http://www.vim.org/about.php). Personally, if I were thrust into a situation where I had to work with C# and Perl on the same project, I would get [ViEMU for Visual Studio](http://www.viemu.com/) and then use two editors: Visual Studio for C# and vim for Perl.* --- If this is something you are willing to spend some time on, check out [defining your own syntax highlighting](https://stackoverflow.com/questions/115388/how-can-i-customize-the-syntax-highlighting-in-visual-studio-2005) for Visual Studio.
A work-in-progress Visual Studio [extension](https://marketplace.visualstudio.com/items?itemName=scriplit.perl6-lsp) for Perl6 (not the Perl5 asked by the OP) is incrementally more full-featured. It is released under the [MIT License](https://marketplace.visualstudio.com/items/scriplit.perl6-lsp/license) and its [repository](https://github.com/scriplit/vscode-languageserver-perl6) is on GitHub. As a prerequisite, Perl6 (e.g., [Rakudo](https://rakudo.perl6.org/downloads/rakudo)) needs to already be installed.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
Old Answer (still applies unless you are using Visual Studio Update 1 RTM (2015) or later) ------------------------------------------------------------------------------------------ In short. No, there doesn't seem to be a good plugin for it. If you use Perl rarely, I would recommend sticking with Visual Studio for Microsoft languages and [Padre](http://padre.perlide.org/) for Perl. However, if you use Perl as much or more than Microsoft languages, you might want to check out [Emacs](http://www.gnu.org/software/emacs/), which has support for [C#](https://stackoverflow.com/questions/8607/any-good-way-to-use-emacs-for-c-development), [VB.NET](http://www.emacswiki.org/emacs/vbnet-mode.el), and Perl. Emacs is designed to be a "one-stop-shop" for all you do all day long, including browsing the web. You can come into work, start using Emacs and never have to leave it until it is time to go home. *disclaimer: The answer above is geared toward the Original Poster. I'm a big fan of [vim](http://www.vim.org/about.php). Personally, if I were thrust into a situation where I had to work with C# and Perl on the same project, I would get [ViEMU for Visual Studio](http://www.viemu.com/) and then use two editors: Visual Studio for C# and vim for Perl.* --- If this is something you are willing to spend some time on, check out [defining your own syntax highlighting](https://stackoverflow.com/questions/115388/how-can-i-customize-the-syntax-highlighting-in-visual-studio-2005) for Visual Studio.
[Komodo Edit](http://www.activestate.com/komodo-edit) is quite nice, and free. code folding and other good stuff.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
Old Answer (still applies unless you are using Visual Studio Update 1 RTM (2015) or later) ------------------------------------------------------------------------------------------ In short. No, there doesn't seem to be a good plugin for it. If you use Perl rarely, I would recommend sticking with Visual Studio for Microsoft languages and [Padre](http://padre.perlide.org/) for Perl. However, if you use Perl as much or more than Microsoft languages, you might want to check out [Emacs](http://www.gnu.org/software/emacs/), which has support for [C#](https://stackoverflow.com/questions/8607/any-good-way-to-use-emacs-for-c-development), [VB.NET](http://www.emacswiki.org/emacs/vbnet-mode.el), and Perl. Emacs is designed to be a "one-stop-shop" for all you do all day long, including browsing the web. You can come into work, start using Emacs and never have to leave it until it is time to go home. *disclaimer: The answer above is geared toward the Original Poster. I'm a big fan of [vim](http://www.vim.org/about.php). Personally, if I were thrust into a situation where I had to work with C# and Perl on the same project, I would get [ViEMU for Visual Studio](http://www.viemu.com/) and then use two editors: Visual Studio for C# and vim for Perl.* --- If this is something you are willing to spend some time on, check out [defining your own syntax highlighting](https://stackoverflow.com/questions/115388/how-can-i-customize-the-syntax-highlighting-in-visual-studio-2005) for Visual Studio.
For Perl syntax highlight `ext install perl6` Install this extension [To Run Perl and Other languages](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner)
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
A work-in-progress Visual Studio [extension](https://marketplace.visualstudio.com/items?itemName=scriplit.perl6-lsp) for Perl6 (not the Perl5 asked by the OP) is incrementally more full-featured. It is released under the [MIT License](https://marketplace.visualstudio.com/items/scriplit.perl6-lsp/license) and its [repository](https://github.com/scriplit/vscode-languageserver-perl6) is on GitHub. As a prerequisite, Perl6 (e.g., [Rakudo](https://rakudo.perl6.org/downloads/rakudo)) needs to already be installed.
A workaround for Visual Studio desktop version is to use C++ syntax highlighting. * Go to Options -> Text Editor -> File Extension * Enter extension "pl" (no dot) * Assign it to "Microsoft Visual C++" * Click "Add" If necessary, repeat the same steps for "cgi" extension.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
[Visual Studio Update 1 RTM](http://blogs.msdn.com/b/visualstudio/archive/2015/11/30/visual-studio-update-1-rtm.aspx) now (2015) has Perl support, along with Go, Java, R, Ruby, and Swift.
[Komodo Edit](http://www.activestate.com/komodo-edit) is quite nice, and free. code folding and other good stuff.
Question: Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. Answer:
[Visual Studio Update 1 RTM](http://blogs.msdn.com/b/visualstudio/archive/2015/11/30/visual-studio-update-1-rtm.aspx) now (2015) has Perl support, along with Go, Java, R, Ruby, and Swift.
For Perl syntax highlight `ext install perl6` Install this extension [To Run Perl and Other languages](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner)
Question: On Android when I am mapping an address on a Mapview I have to wait for that action to return and then my user is given control back so I was wondering how can I send that function of to another thread? ``` mapLocationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mapCurrentAddress(); //Send this function to new thread } }); ``` How can this be done? And how will the new thread respond when it's done? Answer:
Android provides the AsyncTask class to do that. Read <http://developer.android.com/reference/android/os/AsyncTask.html>
You can use an AsyncTask to do this work in the background. Check this [example](http://developer.android.com/reference/android/os/AsyncTask.html)
Question: On Android when I am mapping an address on a Mapview I have to wait for that action to return and then my user is given control back so I was wondering how can I send that function of to another thread? ``` mapLocationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mapCurrentAddress(); //Send this function to new thread } }); ``` How can this be done? And how will the new thread respond when it's done? Answer:
Android provides the AsyncTask class to do that. Read <http://developer.android.com/reference/android/os/AsyncTask.html>
``` Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { p_dialog = ProgressDialog.show((activity_name).this, "", "Loading Image..."); new Thread(new Runnable() { public void run() { function(); } }).start(); } ```
Question: On Android when I am mapping an address on a Mapview I have to wait for that action to return and then my user is given control back so I was wondering how can I send that function of to another thread? ``` mapLocationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mapCurrentAddress(); //Send this function to new thread } }); ``` How can this be done? And how will the new thread respond when it's done? Answer:
You can use an AsyncTask to do this work in the background. Check this [example](http://developer.android.com/reference/android/os/AsyncTask.html)
``` Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { p_dialog = ProgressDialog.show((activity_name).this, "", "Loading Image..."); new Thread(new Runnable() { public void run() { function(); } }).start(); } ```
Question: In X-Men Origins, Scott Summers lost his eyes, which were then put into Deadpool. After this event, in X-Men 1 through X-Men 3 Scott was still able to fire lasers, implying that the mutant ability was not related to the eyes? Yet Deadpool was able to fire the lasers with Scott's eyes. In addition Deadpool was able to control if he shot the beam, whereas Cyclops had to keep his eyes closed or adjust his visor. Why is Deadpool able to shoot lasers with eyes and Cyclops without? Why is Deadpool able to control the lasers without the technology Cyclops has? Answer:
> > Why is Deadpool able to shoot lasers with eyes and Cyclops without? Why is Deadpool able to control the lasers without the technology Cyclops has? > > > Because Cyclops origin story involves trauma (either mental psychological trauma, or actual head injury) that prevents him from controlling his powers. His brother Havok, who has similar enough powers as Scott that they can attack each other and it won't hurt, does not have this problem. This is why Scott needs Ruby-Quartz glasses or the visor to absorb the blasts which are always on. > > The early accounts in the X-Men comics use flashbacks to tell the origin story of Scott parachuting from his parents' plane. The flashbacks are often told from various narrative perspectives and place different emphasis on the events of this period. Scott's poor control over his power have been attributed to events in his childhood. In Uncanny X-Men #156, Scott's parachute caught fire and Scott struck his head upon landing. This caused brain damage to Scott which is responsible for his poor control over his optic blasts. Several origin stories do not feature the head injury account with X-Men Origins: Cyclops #1 being the most recent. The head injury account has also been retconned in Astonishing X-Men Vol. 2 as being due to a self-imposed mental block he made as a child to deal with the traumatic events of his life. With the help of Emma Frost, Scott is able to briefly bypass his own mental block and control his powers, though he reveals that his control is waning and temporary. [wikipedia] > > > As for Origins, you misunderstand what it is that happens in the movie, which is also pulled from the comics. Comic Deadpool is not a mutant, but his origins involve receiving a **COPY** of Wolverine's mutant healing factor. In the movie, this still happens. Notice that Wolverine was not deprived a healing factor, or his claws, yet Deadpool has both. He received copies of Wolverine's and Cyclops' powers (along with Wraith's teleportation and Bradley's technopathy). This somehow involved surgery of the optic nerves. Scott at no point had his eyes removed. The bandages suggest a biopsy or surgery of the eyes that need to heal. The reason Deadpool can use the optic blasts without the glasses is because he lacks the trauma that Scott received.
the reason is because Hollyweird butt-pulled a bunch of powers for him because they didn't do any research before making the character in the film. This is why Deadpool could shoot beams from his eyes, and had other powers he never had in the Marvel universe. They weren't doing any research and, at the time, had no plans to make a genuine Deadpool movie, so they deliberately fudged his powers, and they made him mute because the "Merc with a Mouth" wouldn't exactly be PG-13 friendly if he had any spoken lines. They learned from this mistake, ultimately, and now we have a Deadpool who is not only true to form, but foul-mouthed and truly an Anti-hero.
Question: I am trying to pass an object from one page to another page using `<asp:hyperlink>` without any success. I was trying to invoke a C# method and put that object into a session but then I realized you can't invoke a method using `<asp:hyperlink>`. Then I thought about using `<asp:linkbutton>` but then I need to open the new webpage in a new window. How can I go about doing this properly? Are there any other good alternatives? Answer:
> > Then I thought about using `<asp:linkbutton>` but then I need to > open the new webpage in a new window. > > > You do not need to open a new window... add this to your server side `LinkButton` handler: ``` <asp:LinkButton id="btnYourLinkButton" runat="server" OnClick="btnYourLinkButton_Click">Test</asp:LinkButton> protected void btnLogout_Click(object sender, System.EventArgs e) { var someObject = GetYourDataWithSomeFunction(); Session["YourData"] = someObject; // saves to session Response.Redirect("yourNewUrl.aspx"); } ``` This will store the value in the `Session` and redirect to a new page in the same window. EDIT: If you **need** to open in a new window then do the same thing as outlined above but instead of doing a `Response.Redirect` add the `window.open` javascript call to your page that is served up to open the new window: ``` ScriptManager.RegisterStartupScript(this, this.GetType(), "AUTOOPEN", "window.open('yourNewUrl.aspx', '_blank');", true); ``` Optionally you could just add an ajax call to your click method to setup the `Session` server side and then trigger the redirect based on your ajax call complete.
Add the object to the `Session` then redirect to the new page. In the new page, check the `Session` variable for the object.
Question: I am trying to pass an object from one page to another page using `<asp:hyperlink>` without any success. I was trying to invoke a C# method and put that object into a session but then I realized you can't invoke a method using `<asp:hyperlink>`. Then I thought about using `<asp:linkbutton>` but then I need to open the new webpage in a new window. How can I go about doing this properly? Are there any other good alternatives? Answer:
Add the object to the `Session` then redirect to the new page. In the new page, check the `Session` variable for the object.
Any web application tends to be stateless in nature. Your objects only live during the processing of the page request. When developing and appliction with a technology such as ASP.Net the general pattern for object retrieval is to send an identifier as part of the form post data or the querystring and then use this identifier to reload the object that you were working with prior to the previous page post/request. It is possible to add objects to the session and retrieve them as suggested in other answers here, but there are issues with this approach e.g. sessions timing out, scalability etc. If you were to give some more details as to the nature of what you are trying to do it would be easier to give you a more complete answer or suggestions on how to solve your particular problem.
Question: I am trying to pass an object from one page to another page using `<asp:hyperlink>` without any success. I was trying to invoke a C# method and put that object into a session but then I realized you can't invoke a method using `<asp:hyperlink>`. Then I thought about using `<asp:linkbutton>` but then I need to open the new webpage in a new window. How can I go about doing this properly? Are there any other good alternatives? Answer:
> > Then I thought about using `<asp:linkbutton>` but then I need to > open the new webpage in a new window. > > > You do not need to open a new window... add this to your server side `LinkButton` handler: ``` <asp:LinkButton id="btnYourLinkButton" runat="server" OnClick="btnYourLinkButton_Click">Test</asp:LinkButton> protected void btnLogout_Click(object sender, System.EventArgs e) { var someObject = GetYourDataWithSomeFunction(); Session["YourData"] = someObject; // saves to session Response.Redirect("yourNewUrl.aspx"); } ``` This will store the value in the `Session` and redirect to a new page in the same window. EDIT: If you **need** to open in a new window then do the same thing as outlined above but instead of doing a `Response.Redirect` add the `window.open` javascript call to your page that is served up to open the new window: ``` ScriptManager.RegisterStartupScript(this, this.GetType(), "AUTOOPEN", "window.open('yourNewUrl.aspx', '_blank');", true); ``` Optionally you could just add an ajax call to your click method to setup the `Session` server side and then trigger the redirect based on your ajax call complete.
Any web application tends to be stateless in nature. Your objects only live during the processing of the page request. When developing and appliction with a technology such as ASP.Net the general pattern for object retrieval is to send an identifier as part of the form post data or the querystring and then use this identifier to reload the object that you were working with prior to the previous page post/request. It is possible to add objects to the session and retrieve them as suggested in other answers here, but there are issues with this approach e.g. sessions timing out, scalability etc. If you were to give some more details as to the nature of what you are trying to do it would be easier to give you a more complete answer or suggestions on how to solve your particular problem.
Question: I am trying to clear a session. Below is a little sample code I wrote to check with `SessionStatus`. ``` @Controller @SessionAttributes(value={"sessAttr1","sessAttr2","sessAttr3"}) public class SessionController { @RequestMapping(value="index") public ModelAndView populateSession(){ ModelAndView modelView = new ModelAndView("home"); modelView.addObject("sessAttr1","This value is added in a session 1"); modelView.addObject("sessAttr2","This value is added in a session 2"); modelView.addObject("sessAttr3","This value is added in a session 3"); return modelView; } @RequestMapping(value="home1") public String populateHomeSession(SessionStatus status){ status.setComplete(); return "home1"; } } ``` When `home1` screen is displayed, I can still see the session objects not getting cleared. If I try this: `${sessAttr1 }` then I can read the session values in `home1` screen. Please clarify why is it not working. **EDIT** I an using `<a href="home1">Next</a>` to navigate from one screen to another. Does it have something to do with this isse I am facing? Answer:
`setComplete` is used to mark a session attribute as not needed *after* the request has been processed by the controller: It does not immediately modify the session, and it overall sounds like it's a poor fit for your use case. It's intended to be used in a situation like a POST where the data is intended to be used during the present request, but should not be used in the future. <http://forum.spring.io/forum/spring-projects/web/108339-problem-with-sessionattribute-and-sessionstatus>
you can use [invalidate()](http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#invalidate%28%29) ``` @RequestMapping(value="home1") public String populateHomeSession(HttpservletRequest request){ HttpSession session=request.getSession(); session.invalidate(); return "home1"; } ```
Question: I am trying to clear a session. Below is a little sample code I wrote to check with `SessionStatus`. ``` @Controller @SessionAttributes(value={"sessAttr1","sessAttr2","sessAttr3"}) public class SessionController { @RequestMapping(value="index") public ModelAndView populateSession(){ ModelAndView modelView = new ModelAndView("home"); modelView.addObject("sessAttr1","This value is added in a session 1"); modelView.addObject("sessAttr2","This value is added in a session 2"); modelView.addObject("sessAttr3","This value is added in a session 3"); return modelView; } @RequestMapping(value="home1") public String populateHomeSession(SessionStatus status){ status.setComplete(); return "home1"; } } ``` When `home1` screen is displayed, I can still see the session objects not getting cleared. If I try this: `${sessAttr1 }` then I can read the session values in `home1` screen. Please clarify why is it not working. **EDIT** I an using `<a href="home1">Next</a>` to navigate from one screen to another. Does it have something to do with this isse I am facing? Answer:
you can use [invalidate()](http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#invalidate%28%29) ``` @RequestMapping(value="home1") public String populateHomeSession(HttpservletRequest request){ HttpSession session=request.getSession(); session.invalidate(); return "home1"; } ```
status.setComplete(); remove sessionatribute after render.
Question: I am trying to clear a session. Below is a little sample code I wrote to check with `SessionStatus`. ``` @Controller @SessionAttributes(value={"sessAttr1","sessAttr2","sessAttr3"}) public class SessionController { @RequestMapping(value="index") public ModelAndView populateSession(){ ModelAndView modelView = new ModelAndView("home"); modelView.addObject("sessAttr1","This value is added in a session 1"); modelView.addObject("sessAttr2","This value is added in a session 2"); modelView.addObject("sessAttr3","This value is added in a session 3"); return modelView; } @RequestMapping(value="home1") public String populateHomeSession(SessionStatus status){ status.setComplete(); return "home1"; } } ``` When `home1` screen is displayed, I can still see the session objects not getting cleared. If I try this: `${sessAttr1 }` then I can read the session values in `home1` screen. Please clarify why is it not working. **EDIT** I an using `<a href="home1">Next</a>` to navigate from one screen to another. Does it have something to do with this isse I am facing? Answer:
`setComplete` is used to mark a session attribute as not needed *after* the request has been processed by the controller: It does not immediately modify the session, and it overall sounds like it's a poor fit for your use case. It's intended to be used in a situation like a POST where the data is intended to be used during the present request, but should not be used in the future. <http://forum.spring.io/forum/spring-projects/web/108339-problem-with-sessionattribute-and-sessionstatus>
status.setComplete(); remove sessionatribute after render.
Question: I have a file directory `music/artist/{random_name}/{random_music}.ogg` There's a lot of folder in `{random_name}` and different kind of music title `{random_music}`. So, I wanted to rename the `{random_music}.ogg` to `music.ogg`. Each `{random_name}` folder only have one .ogg files. I've tried with the Bash scripts for hours but didn't managed to find out. ``` for f in ../music/artist/*/*.ogg do echo mv "$f" "${f/.*.ogg/music.ogg}" done ``` It only rename the file on my current dir, which will ask for replace/overwrite. My goals is, I wanted to rename all the `{random_music}.ogg` files to `music.ogg` with their respective directories for example, `music/artist/arai/blue.ogg` to `music/artist/arai/music.ogg` `music/artist/sako/sky.ogg` to `music/artist/sako/music.ogg` Answer:
Your pattern replacement is incorrect. Because all your paths start with `..`, `.*.ogg` actually matches *the entire path*, so *every* file gets turned into `music.ogg` in your current directory. You want `${f/\/*.ogg/music.ogg}` instead, or better yet, `${f%/*}/music.ogg`. That's the rough equivalent of `"$(dirname "$f")"/music.ogg`.
I use usually this: ``` for f in ../music/artist/*/*.ogg do dest="${f/.*.ogg/music.ogg}" if [[ $f != "$dest" ]] # nothing to do if name doesn't change then if [[ -a $dest ]] then printf 'WARNING: File already exists: %s\n' "$dest" else mv "$f" "$dest" fi fi done ```
Question: I have a file directory `music/artist/{random_name}/{random_music}.ogg` There's a lot of folder in `{random_name}` and different kind of music title `{random_music}`. So, I wanted to rename the `{random_music}.ogg` to `music.ogg`. Each `{random_name}` folder only have one .ogg files. I've tried with the Bash scripts for hours but didn't managed to find out. ``` for f in ../music/artist/*/*.ogg do echo mv "$f" "${f/.*.ogg/music.ogg}" done ``` It only rename the file on my current dir, which will ask for replace/overwrite. My goals is, I wanted to rename all the `{random_music}.ogg` files to `music.ogg` with their respective directories for example, `music/artist/arai/blue.ogg` to `music/artist/arai/music.ogg` `music/artist/sako/sky.ogg` to `music/artist/sako/music.ogg` Answer:
Your pattern replacement is incorrect. Because all your paths start with `..`, `.*.ogg` actually matches *the entire path*, so *every* file gets turned into `music.ogg` in your current directory. You want `${f/\/*.ogg/music.ogg}` instead, or better yet, `${f%/*}/music.ogg`. That's the rough equivalent of `"$(dirname "$f")"/music.ogg`.
You can change your code like this ``` for f in ../music/artist/*/*.ogg do echo mv $f "$(dirname "$f")"/music.ogg done ``` Here `dirname` will extract the directory name from your variable and you can append it with your `music.ogg` to get the desired result. For the example path that you provided if `$f` equals `music/artist/arai/blue.ogg`, then the result will be `mv music/artist/arai/blue.ogg music/artist/arai/music.ogg`
Question: I have a file directory `music/artist/{random_name}/{random_music}.ogg` There's a lot of folder in `{random_name}` and different kind of music title `{random_music}`. So, I wanted to rename the `{random_music}.ogg` to `music.ogg`. Each `{random_name}` folder only have one .ogg files. I've tried with the Bash scripts for hours but didn't managed to find out. ``` for f in ../music/artist/*/*.ogg do echo mv "$f" "${f/.*.ogg/music.ogg}" done ``` It only rename the file on my current dir, which will ask for replace/overwrite. My goals is, I wanted to rename all the `{random_music}.ogg` files to `music.ogg` with their respective directories for example, `music/artist/arai/blue.ogg` to `music/artist/arai/music.ogg` `music/artist/sako/sky.ogg` to `music/artist/sako/music.ogg` Answer:
Your pattern replacement is incorrect. Because all your paths start with `..`, `.*.ogg` actually matches *the entire path*, so *every* file gets turned into `music.ogg` in your current directory. You want `${f/\/*.ogg/music.ogg}` instead, or better yet, `${f%/*}/music.ogg`. That's the rough equivalent of `"$(dirname "$f")"/music.ogg`.
I hope this would help you: Previously: ``` [root@user]# tree music music └── artist ├── df │   └── mp.ogg ├── gh │   └── pl.ogg ├── jk │   └── gl.ogg ├── po │   └── ui.ogg ├── ty │   └── lk.ogg └── ui └── dh.ogg 7 directories, 6 files ``` Source code: ``` #!/bin/bash for i in `ls -ld music/artist/* | awk '{print $9}'` do mv $i/*ogg $i/music.ogg done ``` After execution: ``` music └── artist ├── df │   └── music.ogg ├── gh │   └── music.ogg ├── jk │   └── music.ogg ├── po │   └── music.ogg ├── ty │   └── music.ogg └── ui └── music.ogg 7 directories, 6 files ``` As you can see all of the files got renamed correctly.
Question: I have a file directory `music/artist/{random_name}/{random_music}.ogg` There's a lot of folder in `{random_name}` and different kind of music title `{random_music}`. So, I wanted to rename the `{random_music}.ogg` to `music.ogg`. Each `{random_name}` folder only have one .ogg files. I've tried with the Bash scripts for hours but didn't managed to find out. ``` for f in ../music/artist/*/*.ogg do echo mv "$f" "${f/.*.ogg/music.ogg}" done ``` It only rename the file on my current dir, which will ask for replace/overwrite. My goals is, I wanted to rename all the `{random_music}.ogg` files to `music.ogg` with their respective directories for example, `music/artist/arai/blue.ogg` to `music/artist/arai/music.ogg` `music/artist/sako/sky.ogg` to `music/artist/sako/music.ogg` Answer:
Your pattern replacement is incorrect. Because all your paths start with `..`, `.*.ogg` actually matches *the entire path*, so *every* file gets turned into `music.ogg` in your current directory. You want `${f/\/*.ogg/music.ogg}` instead, or better yet, `${f%/*}/music.ogg`. That's the rough equivalent of `"$(dirname "$f")"/music.ogg`.
``` find ../music/artist/ -type f -name "*.ogg" -exec bash -c 'mydir=`dirname {}`;mv {} $mydir/music.ogg' \; ``` This is a one-liner that should work. It implements the exec option of the find command which then gets the directory name and renames the original file to music.ogg.
Question: I have a 20 amp circuit going directly from the panel to the kitchen with 20 amp receptacles and subsequent 12 gauge wire. There are only 4 outlets on that circuit (one being a GFI). I am installing under-cabinet lights and lights above the sink, well within the total amperage and volts allowed for the 20 amp circuit. I will use the 12 gauge wire to power the 15amp single pole switches and go to the lights with 14 gauge wire. Can I connect the 14 gauge neutral to the 12 gauge already in the box or should I just run 12 gauge to the lights for the neutral and connect??.... thank you in advance for your input Answer:
Switches are not circuit breakers (overcurrent protection). They cannot protect wire and do not make it ok to use smaller wire past them. If any 14AWG wire is used, you must downgrade the breaker to 15A, and downgrade the countertop receptacles to 15A. The other wire can remain 12AWG. This will mean it is not one of the two mandatory 20A circuits for countertop receptacles and you may need to add a circuit. There is another reason not to put kitchen lights on receptacle circuits. An appliance trip will plunge the cook into darkness.
If you have any #14 wire in the circuit, you have to put a 15 A breaker on it. So, to keep your 20 A breaker, you should use #12 wire everywhere, and run #12 to the switch and lights.
Question: I have following code ``` $.ajax({ type: 'POST', url: 'index.jsp', data: 'id=111', dataType: 'jsonp', success: function(data) { alert(data.result); }, error: function( err1, err2, err3 ) { alert('Error:' + err3 ) } }); ``` I am returning response as callback parameter generated with argument of json . like this ``` jQuery16105097715278461496_1314674056493({"result" : "success"}) ``` This works absolutely fine in FF . In IE 9 it goes to error function and shows ``` "Error: jQuery16105097715278461496_1314674056493 was not called" . ``` when I see F12 . I see a warning which says . ``` SEC7112: Script from http://otherdomain.com index.jsp?callback=jQuery16105097715278461496_1314674056493 &eid=111&_=1314674056493 was blocked due to mime type mismatch ``` ![enter image description here](https://i.stack.imgur.com/Az4rZ.png) ![enter image description here](https://i.stack.imgur.com/AUw6T.png) ![enter image description here](https://i.stack.imgur.com/3FiX1.png) Answer:
try adding a contentType ``` $.ajax({ type: 'POST', url: 'index.jsp', data: {id:'111'}, contentType: "application/json; charset=utf-8", dataType: 'jsonp', success: function(data) { alert(data.result); }, error: function( err1, err2, err3 ) { alert('Error:' + err3.status ); alert(err1.responseText); } }); ``` here is a good article <http://msdn.microsoft.com/en-us/library/gg622941%28v=vs.85%29.aspx>
**This library is heavenly helpful I found it after wasting a lot hours.** Use this library <https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest> then you won't need to use jsonp. And your Cross Site request will begin to work normally.
Question: My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name? Thanks Answer:
I filed a support request at JetBrains. Here is the answer: > > add "idea.case.sensitive.fs=true" to bin/idea.properties file (<https://intellij-support.jetbrains.com/entries/23395793> ), perform File | Invalidate Caches and restart the IDE. > > > It solved the issue for me. update: 2015-02-14 / Idea 14.0.3 It is no longer sufficient to add the property to the idea.properties file. Add `-Didea.case.sensitive.fs=true` to "Settings | ... | Java Compiler | Additional command line parameters".
To update your case sensitive settings you can simply run the folowing in your shell (Path would have to be changed for InteliJ as I use php storm but should work for the jet brains products) ``` echo idea.case.sensitive.fs=true >> /Applications/PhpStorm.app/Contents/bin/idea.properties ```
Question: My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name? Thanks Answer:
I filed a support request at JetBrains. Here is the answer: > > add "idea.case.sensitive.fs=true" to bin/idea.properties file (<https://intellij-support.jetbrains.com/entries/23395793> ), perform File | Invalidate Caches and restart the IDE. > > > It solved the issue for me. update: 2015-02-14 / Idea 14.0.3 It is no longer sufficient to add the property to the idea.properties file. Add `-Didea.case.sensitive.fs=true` to "Settings | ... | Java Compiler | Additional command line parameters".
It looks like the best option may be to add the idea.properties option to user profile configuration rather than global. See the first comment here: <https://confluence.jetbrains.com/display/IDEADEV/Filesystem+Case-Sensitivity+Mismatch> Also this page mentions where the idea.properties file should go, if you don't have one already. <https://www.jetbrains.com/help/idea/file-idea-properties.html>
Question: My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name? Thanks Answer:
To update your case sensitive settings you can simply run the folowing in your shell (Path would have to be changed for InteliJ as I use php storm but should work for the jet brains products) ``` echo idea.case.sensitive.fs=true >> /Applications/PhpStorm.app/Contents/bin/idea.properties ```
It looks like the best option may be to add the idea.properties option to user profile configuration rather than global. See the first comment here: <https://confluence.jetbrains.com/display/IDEADEV/Filesystem+Case-Sensitivity+Mismatch> Also this page mentions where the idea.properties file should go, if you don't have one already. <https://www.jetbrains.com/help/idea/file-idea-properties.html>
Question: I'm trying to install the SSRS data connector for my CRM4 implementation. I'm using the [Method 2: Modify the Install-config.xml file from this page](http://support.microsoft.com/kb/947060). But keep getting the same error message: > > Unable to validate SQL Server Reporting Services Report Server > installation. Please check that it is correctly installed on the local > machine. > > > I've added the following to my XML file. ``` <reportserverurl>http://SSRS-Server/Reportserver$MYORG_MSCRM</reportserverurl> <instancename>MYORG_MSCRM</instancename> ``` Anyone know what is still wrong? I tried several instance names but they all don't work either. I can access my SSRS server by going to `http://SSRS-Server/Reports` and it will give a list of all services running there. Any help would be much appreciated. Answer:
You may need to post more details regarding this issue: 1) The 2nd method described in this link : [here](http://support.microsoft.com/kb/947060) is used when the Reporting Server database is installed using the SQL Server named instance. Are you installing the Reporting Server database in the default instance or named instance ? 2) If you are using default instance, you might not need to use custom XML, you can just run the installer without requiring the input XML file. 3) What is the architecture of your CRM implementation ? is the CRM Application, SQL server and Reporting Server resided in the same server ? or different server ? Hope this helps.
I realise this is a really old article however I wanted to post the resolution I found to work as I have spent the past 3 days trying to resolve this issue! I created an account just to post this. I was having the same problem as the original article. I had SSRS 2008 installed on a server, CRM (4.0!!!) on a different server and SQL 2008 on a different server again. When all permission issues were resolved and ports were opened from the SSRS server to the SQL server, I was still having problems getting the SetupSrsDataConnector.exe to see the locally installed instance of SSRS2008 (Not R2). I found the resolution to the issue in this article: <https://community.dynamics.com/crm/b/pabloperalta/archive/2011/07/12/unable-to-validate-sql-server-reporting-services-report-server-installation-error-while-installing-srs-data-connector> Effectively the problem I was having is that my copy of the SRS Connector installation files were old and needed updating, however my server did not have internet connectivity. In the link above, it gives you a download location to get a .mps file which contains the updates for the SRS Connector. You need to download this .mps file and then run the installation via command prompt with a customised install-config.xml file, which specifies the SSRS ReportServer URL and the SSRS Instance Name in a custom tag (what you named the SSRS instance when you installed it) and another custom tag for <*Patch update="true">C:\Path to the .msp file< /Patch*> This was my installation command: "D:\Stage\SRSDataConnector\SetupSrsDataConnector.exe" /CONFIG "D:\Stage\SRSDataConnectorUpdates\install-config.xml"
Question: I have a table with two number columns, and a unique constraint over them both. I would like to insert a new pair of values UNLESS the pair already exists. What is the simplest way to do this? If I do ``` insert into TABLE values (100,200) ``` and the pair already exists I get a ORA-00001 error, so I would like to do something like ``` insert or update into TABLE values (100,200) ``` Answer:
You can use [MERGE](http://psoug.org/reference/merge.html)
You can try something like: ``` insert into table select :a, :b from dual where not exists (select 1 from table where column1 = :a and column2=:b) ```
Question: Let it be $\alpha=1+\sqrt[3]{5}\,i$ and $f(x)$ the minimal polynomial of $\alpha$ in $\mathbb{Q}$. Is $\mathbb{Q}(\alpha)$ the splitting field of $\alpha$? I generally know how to deal with splitting field when the roots are simple but I dont know how to deal with this or in general when minimal polynomial aren't that easy to handle with. Are there any properties or theorems that help as criterions to determine whether we have a splitting field or not? (if there is anything more general that covers not only this case I would be more than pleased to note them down) I hope I didn't spell the question wrong and thanks in advance Answer:
For your example, let $\beta=\sqrt[3]5i$, then we have $\beta^6=-25$. Clearly $\beta$ has degree 6 over $\mathbb Q$, and its conjugates are given by $\beta\zeta^k$, $k=0,\dots,5$, where $\zeta=\frac{1+\sqrt3i}2$ is a primitive sixth root of unity. Therefore, the extension $\mathbb Q(\beta)/\mathbb Q$ is not Galois, because $\zeta$ is not contained in $\mathbb Q(\beta)$. If $\mathbb Q(\alpha)$ is the splitting field, then it must be a Galois extension, but $\mathbb Q(\alpha)=\mathbb Q(\beta)$. In general, the extension of the form $\mathbb Q(\sqrt[n]m)$ can be dealt with in the same way.
Knowing that ℚ(1+∛5i)=ℚ(∛5i) and that ∛5i is root of the polynomial x^6+25, then the splitting field must be ℚ(∛5i\*ω), where ω is a primitive root of x^6-1. Thus, ℚ(α) isn't the splitting field.
Question: I'm facing problem with jquery here is my code ``` <script type='text/javascript' src='jquery-1.10.2.min.js'></script> <script type="text/javascript"> $(function() { $(".more2").click(function() { var element = $(this); var msg = element.attr("id"); $.ajax({ type: "POST", url: "insta2.php", data: "lastmsg="+ encodeURIComponent(msg), success:function (data) { $("#morebutton").replaceWith(data); } }); return false; }); }); </script> <span class="more" id="morebutton"> <a id="1" class="more2" title="Follow" href="#" style="color:#000"> Read More </a> </span> ``` and here is insta2.php ``` <?php if(isset($_POST['lastmsg'])) { $a= $_POST['lastmsg']; $a = $a++; ?> <br> <span class="more" id="morebutton"> <a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000"> <?php echo $a;?> Read More </a> </span> <?php }?> ``` my jquery only one 1 set and after that every click not working is there any way to continue counting ? like this Read More 1 Read More 2 Read More 3 Read More 4 Read More and so on... Answer:
Looking at the [source](https://github.com/thquinn/DraggableGridView) you provided, the `DraggableGridView` class is already under `src`. So adding the jar that contains the same is redundant and dex will complain about duplicate definitions. To fix it, just remove the `DraggableGridView.jar` from your project.
Project - build Path - Libraries. Check if android private libraries contains the same jars listed in the libraries in the first place. If so remove private libraries and leave the jars. That worked for me.
Question: I'm facing problem with jquery here is my code ``` <script type='text/javascript' src='jquery-1.10.2.min.js'></script> <script type="text/javascript"> $(function() { $(".more2").click(function() { var element = $(this); var msg = element.attr("id"); $.ajax({ type: "POST", url: "insta2.php", data: "lastmsg="+ encodeURIComponent(msg), success:function (data) { $("#morebutton").replaceWith(data); } }); return false; }); }); </script> <span class="more" id="morebutton"> <a id="1" class="more2" title="Follow" href="#" style="color:#000"> Read More </a> </span> ``` and here is insta2.php ``` <?php if(isset($_POST['lastmsg'])) { $a= $_POST['lastmsg']; $a = $a++; ?> <br> <span class="more" id="morebutton"> <a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000"> <?php echo $a;?> Read More </a> </span> <?php }?> ``` my jquery only one 1 set and after that every click not working is there any way to continue counting ? like this Read More 1 Read More 2 Read More 3 Read More 4 Read More and so on... Answer:
Looking at the [source](https://github.com/thquinn/DraggableGridView) you provided, the `DraggableGridView` class is already under `src`. So adding the jar that contains the same is redundant and dex will complain about duplicate definitions. To fix it, just remove the `DraggableGridView.jar` from your project.
Add all the jars in the libs folder externally and uncheck the android private libraries this should work
Question: I'm facing problem with jquery here is my code ``` <script type='text/javascript' src='jquery-1.10.2.min.js'></script> <script type="text/javascript"> $(function() { $(".more2").click(function() { var element = $(this); var msg = element.attr("id"); $.ajax({ type: "POST", url: "insta2.php", data: "lastmsg="+ encodeURIComponent(msg), success:function (data) { $("#morebutton").replaceWith(data); } }); return false; }); }); </script> <span class="more" id="morebutton"> <a id="1" class="more2" title="Follow" href="#" style="color:#000"> Read More </a> </span> ``` and here is insta2.php ``` <?php if(isset($_POST['lastmsg'])) { $a= $_POST['lastmsg']; $a = $a++; ?> <br> <span class="more" id="morebutton"> <a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000"> <?php echo $a;?> Read More </a> </span> <?php }?> ``` my jquery only one 1 set and after that every click not working is there any way to continue counting ? like this Read More 1 Read More 2 Read More 3 Read More 4 Read More and so on... Answer:
Project - build Path - Libraries. Check if android private libraries contains the same jars listed in the libraries in the first place. If so remove private libraries and leave the jars. That worked for me.
Add all the jars in the libs folder externally and uncheck the android private libraries this should work
Question: I shoul use setText() but how should I use it instead of System.out.println()? I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question. ``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); //TextView tv = (TextView) findViewById( R.id.tv ); //tv.setText(json.toString()); //tv.setText(json.get("display")); } ``` } Answer:
You need to use **Logs** to print and debug stuff in android. Generally there are **five methods**, ``` Log.v() Log.d() Log.i() Log.w() and Log.e() ``` > > v for Verbose > > > d for Debug > > > i for Info > > > w for Warnings > > > e for Error > > > **In your case** ``` Log.d("Key", json.toString() + ""); Log.d("Key", json.get("display") + ""); ``` And you look for the values in the log cat, using the "Key"
You can use a [`CharArrayWriter`](http://developer.android.com/reference/java/io/CharArrayWriter.html) to collect the output: ``` CharArrayWriter writer = new CharArrayWriter(); // write your stuff TextView view = ... view.setText(writer.toString()); ``` You'll have to use the methods available to a `Writer` rather than those of a `PrintStream` such as `System.out` (no `println()` methods). If you want to use basically the same calls to generate the output, you can create a `ByteArrayOutputStream` and wrap it in a `PrintStream`. After writing (and closing the `PrintStream`), retrieve the byte array from the `ByteArrayOutputStream` and convert it to a `String` using one of the `String` constructors. You just have to specify the character encoding you want to use, both when creating the `PrintStream` and when converting the bytes to a `String`. Another alternative would be to replace printing with simply appending your data to a `StringBuilder`. A final alternative is simply to append directly to the `TextView`, but that requires converting every piece of output to some sort of `CharSequence`.
Question: I shoul use setText() but how should I use it instead of System.out.println()? I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question. ``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); //TextView tv = (TextView) findViewById( R.id.tv ); //tv.setText(json.toString()); //tv.setText(json.get("display")); } ``` } Answer:
You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07. To print result in a TextView first add a TextView widget in activity\_main.xml layout file. ``` <TextView android:id="@+id/text_view_id" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());`
You need to use **Logs** to print and debug stuff in android. Generally there are **five methods**, ``` Log.v() Log.d() Log.i() Log.w() and Log.e() ``` > > v for Verbose > > > d for Debug > > > i for Info > > > w for Warnings > > > e for Error > > > **In your case** ``` Log.d("Key", json.toString() + ""); Log.d("Key", json.get("display") + ""); ``` And you look for the values in the log cat, using the "Key"
Question: I shoul use setText() but how should I use it instead of System.out.println()? I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question. ``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); //TextView tv = (TextView) findViewById( R.id.tv ); //tv.setText(json.toString()); //tv.setText(json.get("display")); } ``` } Answer:
You need to use **Logs** to print and debug stuff in android. Generally there are **five methods**, ``` Log.v() Log.d() Log.i() Log.w() and Log.e() ``` > > v for Verbose > > > d for Debug > > > i for Info > > > w for Warnings > > > e for Error > > > **In your case** ``` Log.d("Key", json.toString() + ""); Log.d("Key", json.get("display") + ""); ``` And you look for the values in the log cat, using the "Key"
``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable(){ public void run(){ JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); runOnUiThread(new Runnable(){ public void run(){ TextView tv = (TextView) findViewById( R.id.tv ); tv.setText(json.toString()); tv.setText(json.get("display")); } }); } }).start(); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { //move to onCreate } } ```
Question: I shoul use setText() but how should I use it instead of System.out.println()? I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question. ``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); //TextView tv = (TextView) findViewById( R.id.tv ); //tv.setText(json.toString()); //tv.setText(json.get("display")); } ``` } Answer:
You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07. To print result in a TextView first add a TextView widget in activity\_main.xml layout file. ``` <TextView android:id="@+id/text_view_id" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());`
You can use a [`CharArrayWriter`](http://developer.android.com/reference/java/io/CharArrayWriter.html) to collect the output: ``` CharArrayWriter writer = new CharArrayWriter(); // write your stuff TextView view = ... view.setText(writer.toString()); ``` You'll have to use the methods available to a `Writer` rather than those of a `PrintStream` such as `System.out` (no `println()` methods). If you want to use basically the same calls to generate the output, you can create a `ByteArrayOutputStream` and wrap it in a `PrintStream`. After writing (and closing the `PrintStream`), retrieve the byte array from the `ByteArrayOutputStream` and convert it to a `String` using one of the `String` constructors. You just have to specify the character encoding you want to use, both when creating the `PrintStream` and when converting the bytes to a `String`. Another alternative would be to replace printing with simply appending your data to a `StringBuilder`. A final alternative is simply to append directly to the `TextView`, but that requires converting every piece of output to some sort of `CharSequence`.
Question: I shoul use setText() but how should I use it instead of System.out.println()? I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question. ``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); //TextView tv = (TextView) findViewById( R.id.tv ); //tv.setText(json.toString()); //tv.setText(json.get("display")); } ``` } Answer:
You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07. To print result in a TextView first add a TextView widget in activity\_main.xml layout file. ``` <TextView android:id="@+id/text_view_id" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());`
``` public class JsonReader extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable(){ public void run(){ JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt"); System.out.println(json.toString()); System.out.println(json.get("display")); runOnUiThread(new Runnable(){ public void run(){ TextView tv = (TextView) findViewById( R.id.tv ); tv.setText(json.toString()); tv.setText(json.get("display")); } }); } }).start(); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { //move to onCreate } } ```
Question: How optimize an API call in symfony? I call with Guzzle bundle, but the time in some situations is very long. In client application call a function from the server. In server application extract the objects from the database and send back to the client. In client creat the new object with properties from server respons. Answer:
One of the ways to improve your API calls is to use caching. In Symfony there are many different ways to achieve this. I can show you one of them (`PhpFileCache` example): In **services.yml** create cache service: ``` your_app.cache_provider: class: Doctrine\Common\Cache\PhpFileCache arguments: ["%kernel.cache_dir%/path_to/your_cache_dir", ".your.cached_file_name.php"] ``` (Remember, you need `Doctrine` extension in your app to work) Then pass your caching service `your_app.cache_provider` to any service where you need caching: Again in your **services.yml**: ``` some_service_of_yours: class: AppBundle\Services\YourService arguments: ['@your_app.cache_provider'] ``` Finally, in your service (where you want to perform API caching): ``` use Doctrine\Common\Cache\CacheProvider; class YourService { private $cache; public function __construct(CacheProvider $cache) { $this->cache = $cache; } public function makeApiRequest() { $key = 'some_unique_identifier_of_your_cache_record'; if(!$data = $this->cache->fetch($key)) { $data = $provider->makeActualApiCallHere('http://some_url'); $this->cache->save($key, serialize($data), 10800); //10800 here is amount of seconds to store your data in cache before its invalidated, change it to your needs } return $data; // now you can use the data } } ``` This is quite GENERIC example, you should change it to your exact needs, but idea is simple. You can cache data and avoid unnecessary API calls to speed things up. Be careful though, because cache has drawback of presenting stale(obsolete) data. Some things can (and should) be cached, but some things don't.
**If you control the server** You should put a cache reverse proxy like Varnish on top of your PHP server. The PHP app must send HTTP cache headers to tell to the proxy how many time it must cache the request. Alternatively, you can use a library like [FOSHttpCache](http://foshttpcachebundle.readthedocs.io/en/latest/) to setup a cache invalidation strategy (the PHP server will purge the cache from the proxy when an update of the data occurs - it's a more advanced and complex scenario). The PHP server will not even be called if the requested resource is in the reverse proxy cache. You should also use a profiler like Blackfire.io or xhprof to find why some parts of your PHP code (or your SQL queries) take so many time to be executed, then optimize. **If you control the client** You can use [this HTTP cache middleware for Guzzle](https://github.com/Kevinrob/guzzle-cache-middleware) to cache every API result according to HTTP headers sent by the API.
Question: ``` > CREATE TABLE test(foo FLOAT); > INSERT INTO test VALUES(1.2899999); > SELECT * FROM test; +------+ | foo | +------+ | 1.29 | +------+ ``` While it's obvious that FLOAT is not a precise data type, it is still rounding this data too arbitrarily. Let's check if it's actually able to store it: ``` > ALTER TABLE test MODIFY foo DOUBLE; > SELECT * FROM test; +--------------------+ | foo | +--------------------+ | 1.2899998426437378 | +--------------------+ ``` Whoops, only the 7th digit got corrupted due format limitations. Is there a way to prevent overzealous rounding in this situation, short of converting the column to DOUBLE? Answer:
I hate precision-based issues. I dealt with one before: [Data Truncated for Column](https://dba.stackexchange.com/questions/4091/data-truncated-for-column/4094#4094) You may have do the ALTER TABLE manually ``` CREATE TABLE test_new LIKE test; ALTER TABLE test_new MODIFY foo DOUBLE; INSERT INTO test_new (foo) SELECT CONVERT(foo,DOUBLE) FROM test; RENAME TABLE test TO test_old,test_new TO test; DROP TABLE test_old; ``` or ``` CREATE TABLE test_new LIKE test; ALTER TABLE test_new MODIFY foo DOUBLE; INSERT INTO test_new (foo) SELECT CONVERT(foo,DECIMAL(10,7)) FROM test; RENAME TABLE test TO test_old,test_new TO test; DROP TABLE test_old; ``` or ``` CREATE TABLE test_new LIKE test; ALTER TABLE test_new MODIFY foo DOUBLE; INSERT INTO test_new (foo) SELECT FORMAT(foo,7) FROM test; RENAME TABLE test TO test_old,test_new TO test; DROP TABLE test_old; ``` Not sure what will happen, but give it a try and see what happens.
Maybe this post could be somehow useful for your question - as far as I had experience with till now (even in ERP db we serviced for nearly 5 years) type `FLOAT` or `DOUBLE` was almost never used. Instead of it all the fields storing values like cost prices, purchase prices, stock item characteristics, warehouse, production, accountance data - always had fixed decimal places count by using i.e. `NUMERIC(20,8)` (MSSQL) which of course in MySQL would be `DECIMAL(20,8)`. Thus, if any rounding were to be performed, it must have been done (mostly) in the application layer.
Question: I have a data-set of genetic variants which I'm trying to use as predictors for a simple phenotype, and for starters I use a binary logistic regression in SPSS. I have around 900 individuals, and for each individual around 50 variations and a phenotype. However, I get an unreasonably high amount of removed values when I run the analysis (there is some missing variants data all over the entire table), i.e., only around 50% of my measurements are actually used, and I can't find the exclusion-cut-off SPSS uses for this anywhere. Does anyone know the cut-off that SPSS employs in this? Or does it remove a measurement once it finds a single missing variant? Answer:
SPSS removes cases [list-wise](http://en.wikipedia.org/wiki/Listwise_deletion) by default, and in my experience this is the case for the majority of statistical procedures. So if a case is missing data for any of the variables in the analysis it will be dropped entirely from the model. For generating correlation matrices or linear regression you *can* exclude cases pair-wise if you want (I'm not sure if that is ever really advised), but for logistic and generalized linear model regression procedures this isn't an option. Hence you may want to look at techniques for imputing missing data. Below are some resources I came up quickly for missing data analysis in SPSS; * User [ttnphns](https://stats.stackexchange.com/users/3277/ttnphns) has a macro for hot-deck imputation on his [web site](http://rivita.ru/spssmacros_en.shtml). I also see [Andrew Hayes](http://www.afhayes.com/spss-sas-and-mplus-macros-and-code.html) has a macro for hot-deck imputation. * Raynald Levesque's site has a set of example syntax implementations of various [missing values procedures](http://spsstools.net/SampleSyntax.htm#WorkingWithMissingValues). Including another implementation of hot-deck imputation! * SPSS has various tools in-built for imputing missing values. See the commands `MVA`, `RMV`, and `MULTIPLE IMPUTATION`. See the [Missing Values Analysis](http://publib.boulder.ibm.com/infocenter/spssstat/v20r0m0/index.jsp?topic=%2Fcom.ibm.spss.statistics.help%2Fidh_miss.htm) section in the HELP documentation. I'm not quite sure what is available in base and what are available as add-ons. I believe the `MULTIPLE IMPUTATION` command is an add-on, but the others are part of the base package. and the `MVA` commands are add-ons, but the `RMV` procedure is part of the base package. For more general questions about missing data analysis, peruse the tag [missing-data](/questions/tagged/missing-data "show questions tagged 'missing-data'").
Ran into this problem too, the only option for missing case deletion in logistic regression is listwise. It is very weird that its not an option, there are certainly cases where pairwise deletion is appropriate (e.g. ipsative data) I recommend switching to R Its a steep learning curve but well worth it for the degree of control, particularly if youre working with large datasets
Question: I have a db like this: ``` tibble(Q1 = c("0","A"), Q2 = c("A","A"), Q3 = c("0","A"), C1 = c("A","0") ) -> DB ``` I aim to add a new column which is a count of how many `"0"` are detected in the row when the column starts with `"Q"`. In this case, this column would be like ``` DB %>% mutate(S = c(2,0)) ``` Answer:
```r DB %>% rowwise() %>% mutate(S = sum(c_across(starts_with("Q")) == "0")) %>% ungroup() # # A tibble: 2 x 5 # Q1 Q2 Q3 C1 S # <chr> <chr> <chr> <chr> <int> # 1 0 A 0 A 2 # 2 A A A 0 0 ```
One possible solution: ``` DB %>% mutate(S = rowSums(.[startsWith(names(.), "Q")]=="0")) # A tibble: 2 x 5 Q1 Q2 Q3 C1 S <chr> <chr> <chr> <chr> <dbl> 1 0 A 0 A 2 2 A A A 0 0 ```
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
The second chunk of code is just about the best approach you can get all other things staying the same. However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure. Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them.
The problem you are facing here is related to such language construct as **closure**. Second piece of code fixes the problem.
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i: ``` ItemCollection.ForEach( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); }); ``` Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx): ``` var somethings = ItemCollection.Select( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; return s; }); foreach(Something s in somethings) SomethingCollection.Add(s); ```
The problem you are facing here is related to such language construct as **closure**. Second piece of code fixes the problem.
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
UPDATE: There is extensive analysis and commentary on this issue here: <http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/> --- This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable. This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop. **This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks!
The problem you are facing here is related to such language construct as **closure**. Second piece of code fixes the problem.
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
The second chunk of code is just about the best approach you can get all other things staying the same. However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure. Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them.
``` foreach(Item i on ItemCollection) { Something s = new Something(i); s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);}; SomethingCollection.Add(s); } ``` would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
The second chunk of code is just about the best approach you can get all other things staying the same. However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure. Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them.
If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i: ``` ItemCollection.ForEach( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); }); ``` Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx): ``` var somethings = ItemCollection.Select( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; return s; }); foreach(Something s in somethings) SomethingCollection.Add(s); ```
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
UPDATE: There is extensive analysis and commentary on this issue here: <http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/> --- This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable. This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop. **This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks!
The second chunk of code is just about the best approach you can get all other things staying the same. However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure. Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them.
Question: Suppose the following code: ``` foreach(Item i on ItemCollection) { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); } ``` Of course, this is wrong because all the delegates points to the same Item. The alternative is: ``` foreach(Item i on ItemCollection) { Item tmpItem = i; Something s = new Something(); s.EventX += delegate { ProcessItem(tmpItem); }; SomethingCollection.Add(s); } ``` In this case all the delegates point to their own Item. What about this approach? There is any other better solution? Answer:
If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i: ``` ItemCollection.ForEach( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; SomethingCollection.Add(s); }); ``` Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx): ``` var somethings = ItemCollection.Select( i => { Something s = new Something(); s.EventX += delegate { ProcessItem(i); }; return s; }); foreach(Something s in somethings) SomethingCollection.Add(s); ```
``` foreach(Item i on ItemCollection) { Something s = new Something(i); s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);}; SomethingCollection.Add(s); } ``` would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args