id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
1,452,871
How can I access iframe elements with Javascript?
<p>I have a webpage where there is a textarea within a iframe. I need to read the value of this textarea from its child page JavaScript. Presently by using <code>window.parent.getelementbyID().value</code> in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.</p> <p>The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.</p>
1,452,885
2
3
null
2009-09-21 04:12:03.75 UTC
19
2020-09-05 18:51:00.027 UTC
2020-09-05 18:51:00.027 UTC
null
10,591,078
null
176,223
null
1
70
javascript|dom|iframe
135,543
<p>If you have the HTML</p> <pre><code>&lt;form name="formname" .... id="form-first"&gt; &lt;iframe id="one" src="iframe2.html"&gt; &lt;/iframe&gt; &lt;/form&gt; </code></pre> <p>and JavaScript</p> <pre><code>function iframeRef( frameRef ) { return frameRef.contentWindow ? frameRef.contentWindow.document : frameRef.contentDocument } var inside = iframeRef( document.getElementById('one') ) </code></pre> <p><code>inside</code> is now a reference to the document, so you can do <code>getElementsByTagName('textarea')</code> and whatever you like, depending on what's inside the iframe src.</p>
29,220,535
Changing text color of datepicker
<p>Is it any way to change text color of datepicker in iOS8? I've that it isn't possible in iOS7 and prior, something changed in 8th version?</p> <p>For example I've found modified picker in Yahoo Weather!</p> <p><img src="https://i.stack.imgur.com/hlOg3.jpg" alt="enter image description here"></p>
29,240,759
8
1
null
2015-03-23 21:14:39.507 UTC
7
2020-02-21 15:11:43.19 UTC
2015-03-24 18:35:26.623 UTC
null
4,532,985
null
4,532,985
null
1
38
swift|ios8|datepicker
38,213
<p>Found solution at <a href="https://stackoverflow.com/a/28420738/4532985">comments</a> of stackoverflow. If you need just to change text color to yours and assign this subclass you your picker. For whiteColor works as magic.</p> <p>Only minus i've found that color two lines of selected number is still gray.</p> <pre><code>class ColoredDatePicker: UIDatePicker { var changed = false override func addSubview(view: UIView) { if !changed { changed = true self.setValue(UIColor.whiteColor(), forKey: "textColor") } super.addSubview(view) } } </code></pre>
32,170,597
DataBindingUtil.setContentView - Type parameter T has incompatible upper bounds
<p>"Android Studio" shows error message "Type parameter T has incompatible upper bounds: ViewDataBinding and ActivityChecklistsBinding. </p> <pre><code>ActivityChecklistsBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_checklists); </code></pre> <p>Before update the ADK it works fine. Is there any ideas what wrong?</p>
32,191,257
10
2
null
2015-08-23 19:24:02.783 UTC
7
2022-03-03 07:46:25.183 UTC
2016-09-04 22:22:06.817 UTC
null
1,263,771
null
1,263,771
null
1
44
android
21,389
<p>I had the same problem. I tried a couple of things, Clean and Rebuild project.</p> <p>But, It worked after I choose <code>File -&gt; Invalidate Caches / Restart</code></p>
5,713,295
Specify a Root Path of your HTML directory for script links?
<p>I'm writing a template for dreamweaver, and don't want to change the scripts for subfolder pages.</p> <p>Is there a way to make the path relative to the root directory?</p> <p>for example:</p> <pre><code>&lt;link type="text/css" rel="stylesheet" href="**root**/style.css" /&gt; </code></pre> <p>Instead of <code>**root**</code> above, I want a default path there. Is there any way to do anything like this?</p>
5,713,328
8
0
null
2011-04-19 07:58:22.513 UTC
21
2021-02-20 21:05:13.11 UTC
2016-01-14 14:05:52.273 UTC
null
445,131
null
326,317
null
1
57
html|path
166,995
<p>To be relative to the root directory, just start the URI with a <code>/</code></p> <pre><code>&lt;link type="text/css" rel="stylesheet" href="/style.css" /&gt; &lt;script src="/script.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre>
5,962,366
Android EditText listener for cursor position change
<p>I have a dialog with EditText in it. The EditText is already populated when it is created. When the user places the cursor on or near certain parts of the text a Toast will pop up. </p> <p>My problem is listening for changes in cursor position. Another <a href="http://stackoverflow.com/questions/3652569/android-edittext-listener-for-cursor-position-change">post</a> asks the same question and the accepted solution was</p> <blockquote> <p>You can override onSelectionChanged (int selStart, int selEnd) to get notified about selection changes. If the cursor is moved, this is called as well (in this case selStart == selEnd)</p> </blockquote> <p><a href="http://developer.android.com/reference/android/widget/TextView.html#onSelectionChanged%28int,%20int%29" rel="noreferrer">onSelectionChanged (int selStart, int selEnd)</a> is a protected method of the TextView class. How do override it?</p>
5,962,444
9
1
null
2011-05-11 09:53:29.34 UTC
13
2021-03-02 16:27:02.797 UTC
2019-09-26 13:08:15.997 UTC
null
16,587
null
560,283
null
1
52
android|android-edittext
33,704
<p>Just subclass or extend the class EditText and add the following code to the newly create class:</p> <pre><code> @Override protected void onSelectionChanged(int selStart, int selEnd) { // Do ur task here. } </code></pre> <p>Don't forget to add constructors to the subclass. :)</p>
6,280,789
Generate GUID in MySQL for existing Data?
<p>I've just imported a bunch of data to a MySQL table and I have a column "GUID" that I want to basically fill down all existing rows with new and unique random GUID's.</p> <p>How do I do this in MySQL ?</p> <p>I tried</p> <pre><code>UPDATE db.tablename SET columnID = UUID() where columnID is not null </code></pre> <p>And just get every field the same</p>
6,281,112
12
4
null
2011-06-08 14:53:03.22 UTC
26
2022-08-23 05:01:05.303 UTC
2011-06-08 15:14:34.91 UTC
null
789,403
null
789,403
null
1
130
mysql|random|guid
238,595
<p>I'm not sure if it's the easiest way, but it works. The idea is to create a trigger that does all work for you, then, to execute a query that updates your table, and finally to drop this trigger:</p> <pre><code>delimiter // create trigger beforeYourTableUpdate BEFORE UPDATE on YourTable FOR EACH ROW BEGIN SET new.guid_column := (SELECT UUID()); END // </code></pre> <p>Then execute </p> <pre><code>UPDATE YourTable set guid_column = (SELECT UUID()); </code></pre> <p>And <code>DROP TRIGGER beforeYourTableUpdate</code>;</p> <p><strong>UPDATE</strong> Another solution that doesn't use triggers, but requires primary key or unique index :</p> <pre><code>UPDATE YourTable, INNER JOIN (SELECT unique_col, UUID() as new_id FROM YourTable) new_data ON (new_data.unique_col = YourTable.unique_col) SET guid_column = new_data.new_id </code></pre> <p><strong>UPDATE</strong> once again: It seems that your original query should also work (maybe you don't need <code>WHERE columnID is not null</code>, so all my fancy code is not needed. </p>
17,917,539
read xml file with php
<p>I have an XML file in this format </p> <pre><code> "note.xml" &lt;currencies&gt; &lt;currency name="US dollar" code_alpha="USD" code_numeric="840" /&gt; &lt;currency name="Euro" code_alpha="EUR" code_numeric="978" /&gt; &lt;/currencies&gt; </code></pre> <p>PHP CODE</p> <pre><code>$xml=simplexml_load_file("note.xml"); echo $xml-&gt;name. "&lt;br&gt;"; --no output echo $xml-&gt;code_alpha. "&lt;br&gt;"; --no output echo $xml-&gt;code_numeric . "&lt;br&gt;"; --no output print_r($xml); </code></pre> <p>output of print_r($xml)-->SimpleXMLElement Object ( [currency] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => US dollar [code_alpha] => USD [code_numeric] => 840 ) ) </p> <p>I didnt get any output for the ECHO statements I tried 'simplexml_load_file' and tried reading from it but it doesnt work. Please tell me what php code should I use to read from this format of XML file.</p>
17,917,692
2
3
null
2013-07-29 06:43:46.913 UTC
1
2015-07-04 14:28:43.253 UTC
2013-07-29 08:05:15.627 UTC
null
2,318,491
null
2,318,491
null
1
11
php|xml
42,777
<p>Using DomDocument:</p> <pre><code>&lt;?php $str = &lt;&lt;&lt;XML &lt;currencies&gt; &lt;currency name="US dollar" code_alpha="USD" code_numeric="840" /&gt; &lt;currency name="Euro" code_alpha="EUR" code_numeric="978" /&gt; &lt;/currencies&gt; XML; $dom = new DOMDocument(); $dom-&gt;loadXML($str); foreach($dom-&gt;getElementsByTagName('currency') as $currency) { echo $currency-&gt;getAttribute('name'), "\n"; echo $currency-&gt;getAttribute('code_alpha'), "\n"; echo $currency-&gt;getAttribute('code_numeric'), "\n"; echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n"; } ?&gt; </code></pre> <p><a href="https://eval.in/39440" rel="noreferrer"><strong>Live DEMO.</strong></a></p> <p>Using simplexml:</p> <pre><code>&lt;?php $str = &lt;&lt;&lt;XML &lt;currencies&gt; &lt;currency name="US dollar" code_alpha="USD" code_numeric="840" /&gt; &lt;currency name="Euro" code_alpha="EUR" code_numeric="978" /&gt; &lt;/currencies&gt; XML; $currencies = new SimpleXMLElement($str); foreach($currencies as $currency) { echo $currency['name'], "\n"; echo $currency['code_alpha'], "\n"; echo $currency['code_numeric'], "\n"; echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n"; } ?&gt; </code></pre> <p><strong><a href="https://eval.in/39438" rel="noreferrer">Live DEMO.</a></strong></p>
44,357,336
Setting up a table layout in React Native
<p>I'm transitioning a React project into React Native and need help setting up a grid layout in React Native. I want to set up a 5-col by x-row (number of rows may vary) view. I've played around with the react-native-tableview-simple package, but I can't specify the span of a cell. I've also tried the react-native-flexbox-grid package, which I'm able to set up columns, but I'm still not able to set the span-width of a specific cell. I wonder if there's anything I can use.</p> <p>For reference, I would like my table to look something along the lines like this:</p> <pre><code> |Col 1|Col 2|Col 3|Col 4|Col 5| |------------------------------ Row 1| Text | Yes | No | |------------------------------ Row 2| Text | Yes | No | |------------------------------ Row 3| Text | Dropdown | </code></pre>
44,357,409
4
0
null
2017-06-04 18:12:33.69 UTC
11
2020-07-20 19:22:25.707 UTC
2017-06-04 18:23:45.82 UTC
null
3,059,274
null
3,059,274
null
1
48
react-native
95,695
<p>You can do this without any packages. If each row is exactly the same doing the following should solve your problem;</p> <pre><code>export default class Table extends Component { renderRow() { return ( &lt;View style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}&gt; &lt;View style={{ flex: 1, alignSelf: 'stretch' }} /&gt; { /* Edit these as they are your cells. You may even take parameters to display different data / react elements etc. */} &lt;View style={{ flex: 1, alignSelf: 'stretch' }} /&gt; &lt;View style={{ flex: 1, alignSelf: 'stretch' }} /&gt; &lt;View style={{ flex: 1, alignSelf: 'stretch' }} /&gt; &lt;View style={{ flex: 1, alignSelf: 'stretch' }} /&gt; &lt;/View&gt; ); } render() { const data = [1, 2, 3, 4, 5]; return ( &lt;View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}&gt; { data.map((datum) =&gt; { // This will render a row for each data element. return this.renderRow(); }) } &lt;/View&gt; ); } } </code></pre>
44,320,382
Subclassing collections namedtuple
<p>Python's namedtuple can be really useful as a lightweight, immutable data class. I like using them for bookkeeping parameters rather than dictionaries. When some more functionality is desired, such as a simple docstring or default values, you can easily refactor the namedtuple to a class. However, I've seen classes that inherit from namedtuple. What functionality are they gaining, and what performance are they losing? For example, I would implement this as</p> <pre><code>from collections import namedtuple class Pokemon(namedtuple('Pokemon', 'name type level')): """ Attributes ---------- name : str What do you call your Pokemon? type : str grass, rock, electric, etc. level : int Experience level [0, 100] """ __slots__ = () </code></pre> <p>For the sole purpose of being able to document the attrs cleanly, and <code>__slots__</code> is used to prevent the creation of a <code>__dict__</code> (keeping the lightweight nature of namedtuples).</p> <p>Is there a better recommendation of a lightweight data class for documenting parameters? Note I'm using Python 2.7.</p>
44,320,510
1
1
null
2017-06-02 03:39:44.777 UTC
11
2020-05-19 17:30:32.77 UTC
2020-05-19 17:30:32.77 UTC
null
355,230
null
3,765,905
null
1
27
python|namedtuple
17,433
<p><strong>NEW UPDATE:</strong></p> <p>In python 3.6+, you can use the new typed syntax and create a <code>typing.NamedTuple</code>. The new syntax supports all the usual python class creation features (docstrings, multiple inheritance, default arguments, methods, etc etc are available as of 3.6.1):</p> <pre><code>import typing class Pokemon(MyMixin, typing.NamedTuple): &quot;&quot;&quot; Attributes ---------- name : str What do you call your Pokemon? type : str grass, rock, electric, etc. level : int Experience level [0, 100] &quot;&quot;&quot; name: str type: str level: int = 0 # 3.6.1 required for default args def method(self): # method work </code></pre> <p>The class objects created by this version are mostly equivalent to the original <code>collections.namedtuple</code>, <a href="https://docs.python.org/3/library/typing.html" rel="noreferrer">except for a few details</a>.</p> <p>You can also use the same syntax as the old named tuple:</p> <pre><code>Pokemon = typing.NamedTuple('Pokemon', [('name', str), ('type', str), ('level', int)]) </code></pre> <p><strong>Original Answer</strong></p> <hr /> <p>Short answer: <a href="https://stackoverflow.com/questions/1606436/adding-docstrings-to-namedtuples">no, unless you are using Python &lt; 3.5</a></p> <p>The <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="noreferrer">P3 docs</a> seem to imply pretty clearly that unless you need to add calculated fields (i.e., descriptors), subclassing <code>namedtuple</code> is not considered the canonical approach. This is because you can update the docstrings directly (they are now writable as of 3.5!).</p> <blockquote> <p>Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the <code>_fields</code> attribute...</p> <p>Docstrings can be customized by making direct assignments to the <code>__doc__</code> fields...</p> </blockquote> <p>UPDATE:</p> <p>There are now a couple other compelling possibilities for lightweight data classes in the latest versions of Python.</p> <p>One is <a href="https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions" rel="noreferrer"><code>types.SimpleNamespace</code> (Python 3.3 and later)</a>. It is not structured like <code>namedtuple</code>, but structure isn't always necessary.</p> <p>One thing to note about <code>SimpleNamespace</code>: by default it is required to explicitly designate the field names when instantiating the class. This can be got around fairly easily, though, with a call to <code>super().__init__</code>:</p> <pre><code>from types import SimpleNamespace class Pokemon(SimpleNamespace): &quot;&quot;&quot; Attributes ---------- name : str What do you call your Pokemon? type : str grass, rock, electric, etc. level : int Experience level [0, 100] &quot;&quot;&quot; __slots__ = (&quot;name&quot;, &quot;type&quot;, &quot;level&quot;) # note that use of __init__ is optional def __init__(self, name, type, level): super().__init__(name=name, type=type, level=level) </code></pre> <p>Another intriguing option- <a href="https://www.python.org/downloads/release/python-370a4/" rel="noreferrer">which is available as of Python 3.7</a> - is <a href="https://docs.python.org/3/library/dataclasses.html" rel="noreferrer"><code>dataclasses.dataclass</code></a> (see also <a href="https://www.python.org/dev/peps/pep-0557/" rel="noreferrer">PEP 557</a>):</p> <pre><code>from dataclasses import dataclass @dataclass class Pokemon: __slots__ = (&quot;name&quot;, &quot;type&quot;, &quot;level&quot;) name: str # What do you call your Pokemon? type: str # grass, rock, electric, etc. level: int = 0 # Experience level [0, 100] </code></pre> <p>Note that both of these suggestions are mutable by default, and that <code>__slots__</code> is not required for either one.</p>
21,463,421
A non-empty PSR-4 prefix must end with a namespace separator
<p>I'm trying to setup PSR-4 with Composer but I'm just getting <code>A non-empty PSR-4 prefix must end with a namespace separator.</code></p> <p>My <code>autoload</code> in my <code>composer.json</code> looks like this:</p> <pre><code>"autoload": { "psr-4": { "Acme\\models" : "app/models" } }, </code></pre> <p><code>app/models</code> is empty.</p> <p>What am I doing wrong? How can I fix this?</p>
21,463,602
3
0
null
2014-01-30 17:29:26.327 UTC
16
2022-09-07 05:38:49.183 UTC
2014-03-17 16:43:51.883 UTC
null
397,195
null
397,195
null
1
102
composer-php|psr-4
41,969
<p>Someone made a comment but removed it. He mentioned I was missing <code>\\</code> at the end of <code>Acme\\models</code>. <code>Acme\\models\\</code> will get rid of the message and work as it should.</p>
21,918,380
Rotating axes label text in 3D matplotlib
<p>How do I rotate the z-label so the text reads (bottom => top) rather than (top => bottom)?</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_zlabel('label text flipped', rotation=90) ax.azim = 225 plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/UyQ88.png" alt="enter image description here"></p> <p>I want this to hold no matter what my <code>ax.azim</code> setting is. This seems to be an <a href="https://github.com/matplotlib/matplotlib/issues/1037" rel="noreferrer">old feature request on github</a> but there isn't a work on it. Is there a workaround?</p>
21,921,168
1
1
null
2014-02-20 20:07:10.47 UTC
17
2016-03-15 01:33:26.357 UTC
2016-03-15 01:33:26.357 UTC
null
3,358,223
null
249,341
null
1
29
python|matplotlib|mplot3d
15,657
<p>As a workaround, you could set the direction of the z-label manually by:</p> <pre><code>ax.zaxis.set_rotate_label(False) # disable automatic rotation ax.set_zlabel('label text', rotation=90) </code></pre> <p>Please note that the direction of your z-label also depends on your viewpoint, e.g:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fg = plt.figure(1); fg.clf() axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)] for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]): ax.set_title(u"Azim, elev = {}°, {}°".format(*azel)) ax.set_zlabel('label text') ax.azim, ax.elev = azel fg.canvas.draw() plt.show() </code></pre> <p>gives <img src="https://i.stack.imgur.com/WEB4Z.png" alt="enter image description here"></p> <p><strong>Update:</strong> It is also possible, to adjust the z-label direction of a plot, which is already drawn (but not beforehand). This is the adjusted version to modify the labels:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fg = plt.figure(1); fg.clf() axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)] for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]): ax.set_title(u"Azim, elev = {}°, {}°".format(*azel)) ax.set_zlabel('label text') ax.azim, ax.elev = azel fg.canvas.draw() # the angles of the text are calculated here # Read drawn z-label rotations and switch them if needed for ax in axx: ax.zaxis.set_rotate_label(False) a = ax.zaxis.label.get_rotation() if a&lt;180: a += 180 ax.zaxis.label.set_rotation(a) a = ax.zaxis.label.get_rotation() # put the actual angle in the z-label ax.set_zlabel(u'z-rot = {:.1f}°'.format(a)) fg.canvas.draw() plt.show() </code></pre>
21,596,785
Trigger to update table column after insert?
<p>I need to update a column in table after any record is added in same table</p> <p>Here is my sql code</p> <pre><code>CREATE TRIGGER [dbo].[EmployeeInsert] ON [dbo].[APP_Employees] AFTER INSERT AS BEGIN SET NOCOUNT ON; DECLARE @EmployeeID AS bigint SELECT @EmployeeID = ID FROM inserted UPDATE [dbo].[APP_Employees] SET [EmployeeTotalNumberOfAnnualLeave] = [EmployeeBalanceTheInitialNumberOfDaysOfAnnualLeaveIn] WHERE ID=@EmployeeID END GO </code></pre> <p>and showing error </p> <blockquote> <p>Msg 2714, Level 16, State 2, Procedure EmployeeInsert, Line 17<br> There is already an object named 'EmployeeInsert' in the database.</p> </blockquote>
21,596,837
1
1
null
2014-02-06 07:39:44.053 UTC
1
2020-06-23 13:39:34.07 UTC
2014-02-06 07:44:26.98 UTC
null
352,176
null
2,564,232
null
1
7
sql|sql-server
50,104
<p>The error you're getting is because you have that trigger already, in your database. So if you want to create it again, you need to first drop the existing trigger (or use <code>ALTER TRIGGER</code> instead of <code>CREATE TRIGGER</code> to modify the existing trigger).</p> <p><strong>BUT:</strong> your fundamental flaw is that you seem to expect the trigger to be fired <strong>once per row</strong> - this is <strong>NOT</strong> the case in SQL Server. Instead, the trigger fires <strong>once per statement</strong>, and the pseudo table <code>Inserted</code> might contain <strong>multiple rows</strong>.</p> <p>Given that that table might contain multiple rows - which one do you expect will be selected here??</p> <pre><code>SELECT @EmployeeID = ID FROM inserted </code></pre> <p>It's undefined - you might get the values from arbitrary rows in <code>Inserted</code>.</p> <p>You need to rewrite your entire trigger with the knowledge the <code>Inserted</code> <strong>WILL</strong> contain multiple rows! You need to work with set-based operations - don't expect just a single row in <code>Inserted</code> !</p> <pre><code>-- drop the existing trigger DROP TRIGGER [dbo].[EmployeeInsert] GO -- create a new trigger CREATE TRIGGER [dbo].[EmployeeInsert] ON [dbo].[APP_Employees] AFTER INSERT AS BEGIN SET NOCOUNT ON; -- update your table, using a set-based approach -- from the &quot;Inserted&quot; pseudo table which CAN and WILL -- contain multiple rows! UPDATE [dbo].[APP_Employees] SET [EmployeeTotalNumberOfAnnualLeave] = i.[EmployeeBalanceTheInitialNumberOfDaysOfAnnualLeaveIn] FROM Inserted i WHERE [dbo].[APP_Employees].ID = i.ID END GO </code></pre>
42,324,425
How to uninstall Python and all packages
<p>I wish to uninstall Python 2.7 and all packages connected to it. I initially installed Python from the official website and I installed all packages using the pip install command. Would uninstalling Python from the control panel also uninstall all packages automatically?</p> <p>The reason I want to uninstall Python is because I want to use Anaconda in order to be able to manage packages more easily and also be able to install both Python 2 and 3 to switch between them back and forth.</p>
42,325,553
1
1
null
2017-02-19 06:40:33.87 UTC
4
2020-08-17 17:34:54.407 UTC
2017-02-24 10:35:12.517 UTC
null
1,251,007
null
6,084,667
null
1
7
python|windows|python-2.7|package|anaconda
47,975
<p>If you uninstall from the control panel, it should remove all packages with it. To ensure that your path doesn't contain your old python when you try and use anaconda, you should remove Python from your path. In windows 10:</p> <ol> <li>From desktop go bottom left and find the menu.</li> <li>Click system, then Advanced System Settings</li> <li>In this window, go to the Advanced tab and click on the environment variables button.</li> <li>From there you can edit your Path, with the edit button.</li> <li>Make sure there is no reference to Python here. Also, all variables are separated by a ; so make sure all syntax is good before saving.</li> <li>Install anaconda and at the end of the install it should ask if you want to make it the default Python. Say yes and every time you or another program asks for Python, it will get pointed to anaconda.</li> </ol>
32,723,055
Hooking into fragment's lifecycle like Application.ActivityLifecycleCallbacks
<p>In Android, if you have the Application context you can register an <code>Application.ActivityLifecycleCallbacks</code> instance that will be called everytime an Activity goes through one of its lifecycle callbacks.</p> <p>How can I accomplish the same for fragments? I think there is no such interface for Fragments nor any clear place where I would add that. </p> <p>Maybe customizing a <code>FragmentHostCallback</code> creating a <code>FragmentController</code> but how can I plug that for the whole application?</p> <p>The use case is a library that needs to be notified everytime a Fragment calls its lifecycle callbacks and I don't want to create a BaseFragment. I want to be called only from Application's onCreate and that's it (if possible...).</p> <p>EDIT:</p> <p>I've created <a href="https://code.google.com/p/android/issues/detail?id=232221" rel="noreferrer">an issue in Android Open Source Project</a> about this.</p>
42,426,058
3
1
null
2015-09-22 17:20:27.54 UTC
11
2018-06-26 03:37:14.773 UTC
2017-01-15 19:07:09.55 UTC
null
3,307,993
null
3,307,993
null
1
39
android|android-fragments|fragment
9,652
<p>Since version <a href="https://developer.android.com/topic/libraries/support-library/revisions.html#25-2-0" rel="noreferrer">25.2.0</a> of Android support library, the class <code>FragmentManager.FragmentLifecycleCallbacks</code> is static and accessible to all. </p> <p>We can now use an instance of that class and register it in the <code>supportFragmentManager</code> of the <code>Activity</code>.</p> <pre><code>public class ExampleActivity extends AppCompatActivity { public void onCreate(Bundle savedInstaceState) { // initialization code getSupportFragmentManager() .registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) { super.onFragmentPreAttached(fm, f, context); } @Override public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) { super.onFragmentAttached(fm, f, context); } @Override public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { super.onFragmentCreated(fm, f, savedInstanceState); } @Override public void onFragmentActivityCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { super.onFragmentActivityCreated(fm, f, savedInstanceState); } @Override public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) { super.onFragmentViewCreated(fm, f, v, savedInstanceState); } @Override public void onFragmentStarted(FragmentManager fm, Fragment f) { super.onFragmentStarted(fm, f); } @Override public void onFragmentResumed(FragmentManager fm, Fragment f) { super.onFragmentResumed(fm, f); } @Override public void onFragmentPaused(FragmentManager fm, Fragment f) { super.onFragmentPaused(fm, f); } @Override public void onFragmentStopped(FragmentManager fm, Fragment f) { super.onFragmentStopped(fm, f); } @Override public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) { super.onFragmentSaveInstanceState(fm, f, outState); } @Override public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) { super.onFragmentViewDestroyed(fm, f); } @Override public void onFragmentDestroyed(FragmentManager fm, Fragment f) { super.onFragmentDestroyed(fm, f); } @Override public void onFragmentDetached(FragmentManager fm, Fragment f) { super.onFragmentDetached(fm, f); } }, true); } } </code></pre>
33,428,099
What is the difference between Git for Windows and Github Desktop?
<p>As a programming neophyte, I have recently installed Github Desktop on Windows 10. However, upon using npm, I have discovered that some packages, like <a href="https://www.npmjs.com/package/bower" rel="noreferrer">bower</a>, require the user to install <a href="https://git-for-windows.github.io/" rel="noreferrer">Git for Windows</a>.</p> <p>My questions are: What is the difference between using Github for Desktop's installation of git and using Git for Windows? Would it be necessary to uninstall my current git and Github Desktop installation in order to to adjust my git command-line tools? If so, how should I proceed?</p>
35,129,798
5
1
null
2015-10-30 03:19:27.277 UTC
9
2017-09-12 12:03:50.98 UTC
null
null
null
null
4,616,609
null
1
36
git
37,295
<blockquote> <p>Would it be necessary to uninstall my current git and Github Desktop installation in order to to adjust my git command-line tools? </p> </blockquote> <p>No both are completely independent.</p> <ul> <li><a href="https://github.com/git-for-windows/git/releases" rel="noreferrer">git for Windows</a> delivers MSys2-based Git builds (see "<a href="https://stackoverflow.com/a/35099458/6309">How are msys, msys2, and msysgit related to each other?</a>")</li> <li><a href="https://desktop.github.com/" rel="noreferrer">GitHub Desktop</a> embeds a fixed (older) version of git-for-windows, in quite a complex path (<code>C:\Users\vonc\AppData\Local\GitHub\PortableGit_&lt;sha1&gt;</code>), and you cannot change it easily: "<a href="https://stackoverflow.com/a/33703716/6309">How to update git version from GitHub Desktop on Windows</a>"</li> </ul> <p>You can safely install git-for-windows in addition of GitHub Desktop: both will ignore each others.</p>
33,202,053
Product Versioning Microservices
<p>I go into microservices architecture based on docker and I have 3 microservices, which together create one product for example "CRM system".</p> <p>Now I want my client to be able to upgrade his product, whenever he wants to. I have 3 different versions of my microservices, which one should client see? I guess product version should be independent of microservices, because copying one of the microservices version would make me go into more trouble than having no version at all. </p> <p>So is there any pattern, idea to handle such situation? </p> <p>The only thing that comes to my mind is to have another repository which will be versioned whenever one of the microservices will produce production ready package. However, I now have a version, which none of my Product Owners (PO) would ever know about.</p>
33,213,217
2
2
null
2015-10-18 19:08:57.437 UTC
9
2017-08-04 07:14:37.23 UTC
2015-10-19 05:13:41.677 UTC
null
1,376,205
null
1,757,145
null
1
26
architecture|docker|domain-driven-design|soa|microservices
11,190
<h3>Micro Service Versioning</h3> <p>First of all ensure <a href="http://semver.org/" rel="noreferrer">Semantic Versioning (SemVer)</a> is strictly followed by the micro services. Not doing this will sooner or later lead to incompatibility problems.</p> <p>Capture only API changes in that version, don't mix it up with micro service internal versioning (e.g. DB schema versioning for a service that has a DB).</p> <h3>Product Versioning</h3> <p>Introduce a version for the product as you already suggested. Following SemVer makes sense here, too, but may need to be loosened to meet marketing needs (e.g. allow to make a major version increment even though SemVer would require only a minor version increment). In extreme cases, use dedicated "technical versions" and "marketing versions". This is however more complicated for the customers, too.</p> <p>Also note that you will need to define what the SemVer version means in terms of your application, since the application as a whole has no "API".</p> <h3>Dependency Management</h3> <p>Now a specific product version is a list of micro services of specific versions. Note that this is essentially dependency management in the same sense as <code>apt</code>, <code>npm</code>, <code>bower</code>, etc implement. How sophisticated your solution needs to be is difficult to say, but I recommend to at least support the notion of "minimum required versions". If docker has a built-in mechanism, try to use that one (I don't know docker very well, so I can't tell).</p> <p>With this, you are e.g. able to specify that your product at version <code>4.8.12</code> requires service A at version <code>1.12.0</code> and service B at <code>3.0.4</code>. </p> <p>The update mechanism should then follow a strategy that adheres to SemVer. This means that installing a specific product version automatically installs the newest services <em>with the same major version</em>. In the example above, this could e.g. install <code>1.12.2</code> of service A and <code>3.3.0</code> of service B. Providing a mechanism to keep already installed services that meet the dependency requirement may be a good idea, so that users don't get annoyed by the update mechanism.</p>
9,388,623
Piping output to cut
<p>I am trying to get the name of the shell executing a script.</p> <p>Why does </p> <pre><code>echo $(ps | grep $PPID) | cut -d" " -f4 </code></pre> <p>work while</p> <pre><code>echo ps | grep $PPID | cut -d" " -f4 </code></pre> <p>does not?</p>
9,388,646
3
0
null
2012-02-22 03:17:08.203 UTC
1
2020-11-19 20:27:57.217 UTC
null
null
null
null
217,639
null
1
18
linux|bash|shell
40,671
<p>The reason is that</p> <pre><code>echo ps </code></pre> <p>just prints out the string <code>ps</code>; it doesn't run the program <code>ps</code>. The corrected version of your command would be:</p> <pre><code>ps | grep $PPID | cut -d" " -f4 </code></pre> <p><strong>Edited to add:</strong> paxdiablo points out that <code>ps | grep $PPID</code> includes a lot of whitespace that will get collapsed by <code>echo $(ps | grep $PPID)</code> (since the result of <code>$(...)</code>, when it's not in double-quotes, is split by whitespace into separate arguments, and then <code>echo</code> outputs all of its arguments separated by spaces). To address this, you can use <code>tr</code> to "squeeze" repeated spaces:</p> <pre><code>ps | grep $PPID | tr -s ' ' | cut -d' ' -f5 </code></pre> <p>or you can just stick with what you had to begin with. :-)</p>
9,239,067
How to hide a navigation bar from one particular view controller
<p>I've created a two splash screen iPhone app. Afterwards user is taken to first view. I've added a UINavigationController. It works perfectly fine. </p> <p>How do I remove the navigation bar for the opening view alone?</p> <p><strong>MainWindow</strong></p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.splashScreen = [[SplashScreen alloc] initWithNibName:@"SplashScreen" bundle:nil]; if (self.pageController == nil) { openingpage *page=[[openingpage alloc]initWithNibName:@"openingpage" bundle:[NSBundle mainBundle]]; self.pageController = page; [page release]; } [self.navigationController pushViewController:self.pageController animated:YES]; [window addSubview:splashScreen.view]; [splashScreen displayScreen]; [self.window makeKeyAndVisible]; return YES; } </code></pre>
9,239,246
8
0
null
2012-02-11 09:14:53.11 UTC
15
2022-03-09 08:54:59.017 UTC
2012-02-11 09:40:15.62 UTC
null
652,878
null
652,878
null
1
76
ios|cocoa-touch
68,891
<p>Try this method inside a view controller:</p> <pre><code>// swift self.navigationController?.setNavigationBarHidden(true, animated: true) // objective-c [self.navigationController setNavigationBarHidden:YES animated:YES]; </code></pre> <hr> <p>More clarifications:</p> <p><code>UINavigationController</code> has a property navigationBarHidden, that allows you to hide/show the navigation bar for the whole nav controller.</p> <p>Let's look at the next hierarchy:</p> <pre><code>--UINavigationController ------UIViewController1 ------UIViewController2 ------UIViewController3 </code></pre> <p>Each of three UIViewController has the same nav bar since they are in the UINavigationController. For example, you want to hide the bar for the UIViewController2 (actually it doesn't matter in which one), then write in your UIViewController2:</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES animated:YES]; //it hides the bar } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.navigationController setNavigationBarHidden:NO animated:YES]; // it shows the bar back } </code></pre>
9,296,694
What does inverse_of do? What SQL does it generate?
<p>I'm trying to get my head around <code>inverse_of</code> and I do not get it. </p> <p>What does the generated sql look like, if any?</p> <p>Does the <code>inverse_of</code> option exhibit the same behavior if used with <code>:has_many</code>, <code>:belongs_to</code>, and <code>:has_many_and_belongs_to</code>?</p> <p>Sorry if this is such a basic question.</p> <p>I saw this example:</p> <pre><code>class Player &lt; ActiveRecord::Base has_many :cards, :inverse_of =&gt; :player end class Card &lt; ActiveRecord::Base belongs_to :player, :inverse_of =&gt; :cards end </code></pre>
9,297,745
8
0
null
2012-02-15 15:58:20.75 UTC
45
2019-11-18 19:22:47.6 UTC
2012-10-28 19:15:05.797 UTC
null
64,669
null
352,191
null
1
180
ruby-on-rails|activerecord
60,206
<p>From <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html">the documentation</a>, it seems like the <code>:inverse_of</code> option is a method for avoiding SQL queries, not generating them. It's a hint to ActiveRecord to use already loaded data instead of fetching it again through a relationship.</p> <p>Their example:</p> <pre><code>class Dungeon &lt; ActiveRecord::Base has_many :traps, :inverse_of =&gt; :dungeon has_one :evil_wizard, :inverse_of =&gt; :dungeon end class Trap &lt; ActiveRecord::Base belongs_to :dungeon, :inverse_of =&gt; :traps end class EvilWizard &lt; ActiveRecord::Base belongs_to :dungeon, :inverse_of =&gt; :evil_wizard end </code></pre> <p>In this case, calling <code>dungeon.traps.first.dungeon</code> should return the original <code>dungeon</code> object instead of loading a new one as would be the case by default.</p>
52,074,153
Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars
<p>I'm currently working with the PyTorch framework and trying to understand foreign code. I got an indices issue and wanted to print the shape of a list.<br /> The only way of doing so (as far as Google tells me) is to convert the list into a numpy array and then getting the shape with numpy.ndarray.shape().</p> <p>But trying to convert my list into an array, I got a <code>ValueError: only one element tensors can be converted to Python scalars</code>.</p> <p>My List is a converted PyTorch Tensor (<code>list(pytorchTensor)</code>) and looks somewhat like this:</p> <pre><code>[ tensor([[-0.2781, -0.2567, -0.2353, ..., -0.9640, -0.9855, -1.0069], [-0.2781, -0.2567, -0.2353, ..., -1.0069, -1.0283, -1.0927], [-0.2567, -0.2567, -0.2138, ..., -1.0712, -1.1141, -1.1784], ..., [-0.6640, -0.6425, -0.6211, ..., -1.0712, -1.1141, -1.0927], [-0.6640, -0.6425, -0.5997, ..., -0.9426, -0.9640, -0.9640], [-0.6640, -0.6425, -0.5997, ..., -0.9640, -0.9426, -0.9426]]), tensor([[-0.0769, -0.0980, -0.0769, ..., -0.9388, -0.9598, -0.9808], [-0.0559, -0.0769, -0.0980, ..., -0.9598, -1.0018, -1.0228], [-0.0559, -0.0769, -0.0769, ..., -1.0228, -1.0439, -1.0859], ..., [-0.4973, -0.4973, -0.4973, ..., -1.0018, -1.0439, -1.0228], [-0.4973, -0.4973, -0.4973, ..., -0.8757, -0.9177, -0.9177], [-0.4973, -0.4973, -0.4973, ..., -0.9177, -0.8967, -0.8967]]), tensor([[-0.1313, -0.1313, -0.1100, ..., -0.8115, -0.8328, -0.8753], [-0.1313, -0.1525, -0.1313, ..., -0.8541, -0.8966, -0.9391], [-0.1100, -0.1313, -0.1100, ..., -0.9391, -0.9816, -1.0666], ..., [-0.4502, -0.4714, -0.4502, ..., -0.8966, -0.8966, -0.8966], [-0.4502, -0.4714, -0.4502, ..., -0.8115, -0.8115, -0.7903], [-0.4502, -0.4714, -0.4502, ..., -0.8115, -0.7690, -0.7690]]), ] </code></pre> <p>Is there a way of getting the shape of that list without converting it into a numpy array?</p>
52,074,876
3
2
null
2018-08-29 09:33:50.04 UTC
6
2022-03-29 06:14:28.28 UTC
2022-03-28 13:08:10.967 UTC
null
365,102
null
10,284,295
null
1
27
python|numpy|pytorch|numpy-ndarray
110,453
<p>It seems like you have a list of tensors. For each tensor you can see its <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.size.html#torch.Tensor.size" rel="noreferrer"><code>size()</code></a> (no need to convert to list/numpy). If you insist, you can convert a tensor to numpy array using <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.numpy.html#torch.Tensor.numpy" rel="noreferrer"><code>numpy()</code></a>:</p> <p>Return a list of tensor shapes:</p> <pre><code>&gt;&gt; [t.size() for t in my_list_of_tensors] </code></pre> <p>Returns a list of numpy arrays:</p> <pre><code>&gt;&gt; [t.numpy() for t in my_list_of_tensors] </code></pre> <p>In terms of performance, it is always best to avoid casting of tensors into numpy arrays, as it may incur sync of device/host memory. If you only need to check the <code>shape</code> of a tensor, use <code>size()</code> function.</p>
34,376,854
Delegation: EventEmitter or Observable in Angular
<p>I am trying to implement something like a delegation pattern in Angular. When the user clicks on a <code>nav-item</code>, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.</p> <p>Here is the scenario: I have a <code>Navigation</code> component:</p> <pre class="lang-ts prettyprint-override"><code>import {Component, Output, EventEmitter} from 'angular2/core'; @Component({ // other properties left out for brevity events : ['navchange'], template:` &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;&lt;/div&gt; ` }) export class Navigation { @Output() navchange: EventEmitter&lt;number&gt; = new EventEmitter(); selectedNavItem(item: number) { console.log('selected nav item ' + item); this.navchange.emit(item) } } </code></pre> <p>Here is the observing component: </p> <pre class="lang-ts prettyprint-override"><code>export class ObservingComponent { // How do I observe the event ? // &lt;----------Observe/Register Event ?--------&gt; public selectedNavItem(item: number) { console.log('item index changed!'); } } </code></pre> <p>The key question is, how do I make the observing component observe the event in question ? </p>
35,568,924
7
1
null
2015-12-20 00:32:34.193 UTC
173
2019-04-29 11:56:17.357 UTC
2017-12-17 08:35:46.43 UTC
null
5,485,167
null
1,066,899
null
1
274
angular|observer-pattern|observable|eventemitter|event-delegation
176,268
<p><strong>Update 2016-06-27:</strong> instead of using Observables, use either</p> <ul> <li>a BehaviorSubject, as recommended by @Abdulrahman in a comment, or</li> <li>a ReplaySubject, as recommended by @Jason Goemaat in a comment</li> </ul> <p>A <a href="http://reactivex.io/rxjs/manual/overview.html#subject" rel="noreferrer">Subject</a> is both an Observable (so we can <code>subscribe()</code> to it) and an Observer (so we can call <code>next()</code> on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer). </p> <p><a href="http://reactivex.io/rxjs/manual/overview.html#behaviorsubject" rel="noreferrer">BehaviorSubject</a> is a variant of Subject. It has the notion of "the current value". We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.</p> <p>The code below and the <a href="http://plnkr.co/edit/XqwwUM44NQEpxQVFFxNW?p=preview" rel="noreferrer">plunker</a> use BehaviorSubject.</p> <p><a href="http://reactivex.io/rxjs/manual/overview.html#replaysubject" rel="noreferrer">ReplaySubject</a> is another variant of Subject. If you want to wait until a value is actually produced, use <code>ReplaySubject(1)</code>. Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use <code>first()</code> on the subscription. You do not have to unsubscribe if you use <code>first()</code>. </p> <pre class="lang-ts prettyprint-override"><code>import {Injectable} from '@angular/core' import {BehaviorSubject} from 'rxjs/BehaviorSubject'; @Injectable() export class NavService { // Observable navItem source private _navItemSource = new BehaviorSubject&lt;number&gt;(0); // Observable navItem stream navItem$ = this._navItemSource.asObservable(); // service command changeNav(number) { this._navItemSource.next(number); } } </code></pre> <pre class="lang-ts prettyprint-override"><code>import {Component} from '@angular/core'; import {NavService} from './nav.service'; import {Subscription} from 'rxjs/Subscription'; @Component({ selector: 'obs-comp', template: `obs component, item: {{item}}` }) export class ObservingComponent { item: number; subscription:Subscription; constructor(private _navService:NavService) {} ngOnInit() { this.subscription = this._navService.navItem$ .subscribe(item =&gt; this.item = item) } ngOnDestroy() { // prevent memory leak when component is destroyed this.subscription.unsubscribe(); } } </code></pre> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'my-nav', template:` &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;nav 1 (click me)&lt;/div&gt; &lt;div class="nav-item" (click)="selectedNavItem(2)"&gt;nav 2 (click me)&lt;/div&gt;` }) export class Navigation { item = 1; constructor(private _navService:NavService) {} selectedNavItem(item: number) { console.log('selected nav item ' + item); this._navService.changeNav(item); } } </code></pre> <p><kbd><a href="http://plnkr.co/edit/XqwwUM44NQEpxQVFFxNW?p=preview" rel="noreferrer">Plunker</a></kbd></p> <hr> <p><strong>Original answer that uses an Observable:</strong> (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)</p> <p>So, here's an implementation that uses an Observable <a href="https://stackoverflow.com/a/34402436/215945">instead of an EventEmitter</a>. Unlike my EventEmitter implementation, this implementation also stores the currently selected <code>navItem</code> in the service, so that when an observing component is created, it can retrieve the current value via API call <code>navItem()</code>, and then be notified of changes via the <code>navChange$</code> Observable.</p> <pre class="lang-ts prettyprint-override"><code>import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/share'; import {Observer} from 'rxjs/Observer'; export class NavService { private _navItem = 0; navChange$: Observable&lt;number&gt;; private _observer: Observer; constructor() { this.navChange$ = new Observable(observer =&gt; this._observer = observer).share(); // share() allows multiple subscribers } changeNav(number) { this._navItem = number; this._observer.next(number); } navItem() { return this._navItem; } } @Component({ selector: 'obs-comp', template: `obs component, item: {{item}}` }) export class ObservingComponent { item: number; subscription: any; constructor(private _navService:NavService) {} ngOnInit() { this.item = this._navService.navItem(); this.subscription = this._navService.navChange$.subscribe( item =&gt; this.selectedNavItem(item)); } selectedNavItem(item: number) { this.item = item; } ngOnDestroy() { this.subscription.unsubscribe(); } } @Component({ selector: 'my-nav', template:` &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;nav 1 (click me)&lt;/div&gt; &lt;div class="nav-item" (click)="selectedNavItem(2)"&gt;nav 2 (click me)&lt;/div&gt; `, }) export class Navigation { item:number; constructor(private _navService:NavService) {} selectedNavItem(item: number) { console.log('selected nav item ' + item); this._navService.changeNav(item); } } </code></pre> <p><kbd><a href="http://plnkr.co/edit/vL76b0UjrAav3Ao7kF4W?p=preview" rel="noreferrer">Plunker</a></kbd></p> <hr> <p>See also the <a href="https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service" rel="noreferrer">Component Interaction Cookbook example</a>, which uses a <code>Subject</code> in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.</p>
47,206,924
Angular 5 Service to read local .json file
<p>I am using Angular 5 and I've created a service using the angular-cli</p> <p>What I want to do is to create a service that reads a local json file for Angular 5.</p> <p>This is what I have ... I'm a bit stuck...</p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; @Injectable() export class AppSettingsService { constructor(private http: HttpClientModule) { var obj; this.getJSON().subscribe(data =&gt; obj=data, error =&gt; console.log(error)); } public getJSON(): Observable&lt;any&gt; { return this.http.get("./assets/mydata.json") .map((res:any) =&gt; res.json()) .catch((error:any) =&gt; console.log(error)); } } </code></pre> <p>How can I get this finished?</p>
47,207,063
9
1
null
2017-11-09 16:28:00.6 UTC
28
2021-01-30 11:22:29.087 UTC
2017-12-28 23:38:56.197 UTC
null
3,211,932
user8770372
null
null
1
123
javascript|json|angular
226,723
<p>First You have to inject <code>HttpClient</code> and Not <code>HttpClientModule</code>, second thing you have to remove <code>.map((res:any) =&gt; res.json())</code> you won't need it any more because the new <code>HttpClient</code> will give you the body of the response by default , finally make sure that you import <code>HttpClientModule</code> in your <code>AppModule</code> :</p> <pre><code>import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AppSettingsService { constructor(private http: HttpClient) { this.getJSON().subscribe(data =&gt; { console.log(data); }); } public getJSON(): Observable&lt;any&gt; { return this.http.get("./assets/mydata.json"); } } </code></pre> <p>to add this to your Component: </p> <pre><code>@Component({ selector: 'mycmp', templateUrl: 'my.component.html', styleUrls: ['my.component.css'] }) export class MyComponent implements OnInit { constructor( private appSettingsService : AppSettingsService ) { } ngOnInit(){ this.appSettingsService.getJSON().subscribe(data =&gt; { console.log(data); }); } } </code></pre>
10,477,135
Simple cross-browser, jQuery/PHP file upload with progress bar
<p>I know there are several topics out there about this, but none of them offered a definite solution for a file uploader script that:</p> <ol> <li>Works on IE7+</li> <li>Has a progress bar (On every browser)</li> <li>No Flash (Or fallback)</li> </ol> <p>Any solutions?</p>
10,477,249
5
1
null
2012-05-07 05:34:48.137 UTC
16
2018-04-13 22:11:49.607 UTC
2013-06-15 07:59:40.233 UTC
null
484,082
null
1,088,924
null
1
38
php|jquery|internet-explorer|file-upload|progress-bar
59,253
<p>You may use <strong><a href="http://www.albanx.com/ajaxuploader" rel="nofollow noreferrer">Axuploader</a></strong> by AlbanX. It has got;</p> <ul> <li>Multi file upload on all browsers</li> <li>Multi file select on html5 browsers (not IE)</li> <li>Upload progress information on html5 browsers</li> <li>File size information on html5 browsers</li> <li>No flash, no Silverlight, on other plugins, only JavaScript</li> <li>Support IE 6+, Firefox 2+, Safari 2+, Chrome 1+</li> <li>Upload files by chunk, for more performance</li> <li>Not dependent by server max post size and max upload file size limits</li> </ul> <p>You may also try <strong><a href="http://github.com/FineUploader/fine-uploader" rel="nofollow noreferrer">Fine-Uploader</a></strong> by Widen. It has got;</p> <ul> <li>Multiple file select, progress-bar in FF, Chrome, and Safari</li> <li>Drag-and-drop file select in FF, Chrome, and Safari (OS X)</li> <li>Uploads are cancelable</li> <li>No external dependencies at all if using FineUploader or FineUploaderBasic. If using the optional jQuery wrapper, jQuery is of course required.</li> <li>FineUploaderBasic only requires the associated Fine Uploader javascript file. All Fine Uploader css and image files can be omitted.</li> <li>Doesn't use Flash</li> <li>Fully working with HTTPS</li> <li>Tested in IE7+, Firefox, Safari (OS X), Chrome, IOS6, and various versions of Android. IE10 is now also supported!</li> <li>Ability to upload files as soon as they are selected, or "queue" them for uploading at user's request later</li> <li>Display specific error messages from server on upload failure (hover over failed upload item)</li> <li>Ability to auto-retry failed uploads</li> <li>Option to allow users to manually retry a failed upload</li> <li>Create your own file validator and/or use some default validators include with Fine Uploader</li> <li>Receive callback at various stages of the upload process</li> <li>Send any parameters server-side along with each file.</li> <li>Upload directories via drag and drop (Chrome 21+).</li> <li>Include parameters in the query string OR the request body.</li> <li>Submit files to be uploaded via the API.</li> <li>Split up a file into multiple requests (file chunking/partitioning).</li> <li>Resume failed/stopped uploads from previous sessions</li> <li>Delete uploaded files</li> <li>CORS support</li> <li>Upload any Blob objects via the API.</li> <li>Easily set and enforce a maximum item limit.</li> <li>Upload images via paste (Chrome).</li> <li>Standalone file &amp; folder drag &amp; drop module. Integrated by default into FineUploader mode.</li> <li>Perform async (non-blocking) tasks in callbacks that influence the associated file or files</li> <li>Upload images directly from a mobile device's camera</li> <li>Retrieve statistics for uploaded files and receive callbacks on status changes</li> <li>And many more!</li> </ul> <p>Or <strong><a href="https://github.com/blueimp/jQuery-File-Upload" rel="nofollow noreferrer">jQuery-File-Upload plugin</a></strong> (compatible with IE), which has got;</p> <ul> <li>Multiple file upload: Allows to select multiple files at once and upload them simultaneously.</li> <li>Drag &amp; Drop support: Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window.</li> <li>Upload progress bar: Shows a progress bar indicating the upload progress for individual files and for all uploads combined.</li> <li>Cancelable uploads: Individual file uploads can be canceled to stop the upload progress.</li> <li>Resumable uploads: Aborted uploads can be resumed with browsers supporting the Blob API.</li> <li>Chunked uploads: Large files can be uploaded in smaller chunks with browsers supporting the Blob API.</li> <li>Client-side image resizing: Images can be automatically resized on client-side with browsers supporting the required JS APIs.</li> <li>Preview images: A preview of image files can be displayed before uploading with browsers supporting the required JS APIs.</li> <li>No browser plugins (e.g. Adobe Flash) required: The implementation is based on open standards like HTML5 and JavaScript and requires no additional browser plugins.</li> <li>Graceful fallback for legacy browsers: Uploads files via XMLHttpRequests if supported and uses iframes as fallback for legacy browsers.</li> <li>HTML file upload form fallback: Shows a standard HTML file upload form if JavaScript is disabled.</li> <li>Cross-site file uploads: Supports uploading files to a different domain with Cross-site XMLHttpRequests.</li> <li>Multiple plugin instances: Allows to use multiple plugin instances on the same webpage.</li> <li>Customizable and extensible: Provides an API to set individual options and define callBack methods for various upload events.</li> <li>Multipart and file contents stream uploads: Files can be uploaded as standard "multipart/form-data" or file contents stream (HTTP PUT file upload).</li> <li>Compatible with any server-side application platform: Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.</li> </ul> <h2>References</h2> <p>Check out <strong><a href="http://www.freshdesignweb.com/jquery-html5-file-upload.html" rel="nofollow noreferrer">10 HTML5 File Upload with jQuery Example</a></strong> to see some great file uploaders which works with HTML5</p> <p>Also, here at <strong><a href="http://www.freshdesignweb.com/php-ajax-upload-file.html" rel="nofollow noreferrer">10+ PHP Ajax Upload File Tutorials - Free Download</a></strong> you can choose from a lot of uploaders.</p>
22,564,817
Bootstrap collapsed menu not pushing content down when expanded
<p>I am using Twitter Bootstrap to play around with the responsive side of a website. I am having a problem however with the smaller widths where the collapsed menu is going over the content of the page, rather than pushing it down. </p> <p>I used this example to build my navigation:</p> <p><a href="http://getbootstrap.com/examples/navbar-fixed-top/">http://getbootstrap.com/examples/navbar-fixed-top/</a></p> <p>Looking at the example, it doesn't push the content down either. </p> <p>I've seen some answers to this to use padding on the body, but this has not worked for me. I've also tried putting overflow on some elements but its made no difference. </p> <p>My code for the navigation is:</p> <pre><code>&lt;div class="navbar navbar-default navbar-fixed-top" role="navigation"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;h1 class="logo-title"&gt; &lt;a href="index.html"&gt;&lt;span&gt;Logo&lt;/span&gt;&lt;/a&gt; &lt;/h1&gt; &lt;/div&gt; &lt;div class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="index.html"&gt;item1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;item2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;item3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;item4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'm new to Responsive Design and have seen many websites with the collapsed menu pushing down the content. Is it good practice to have collapsed menus like this or is it a pure preference thing?</p> <p>My main question is how can I get the content to be pushed when the collapsed menu is active?</p> <p>Thank you in advance for the help. </p>
22,565,465
10
0
null
2014-03-21 16:55:01.88 UTC
4
2021-07-01 22:55:00.907 UTC
null
null
null
null
1,825,201
null
1
27
css|twitter-bootstrap|navigation|responsive-design
85,751
<p>I don't know. This seems to work... (kind of a hack though).</p> <pre><code>.navbar-fixed-top { top: -70px; /* you'll have to figure out the exact number here */ } .navbar-fixed-top, .navbar-fixed-bottom { position: relative; /* this can also be static */ } </code></pre>
57,756,557
Initializing a std::array with a constant value
<p>I need to initialize all elements of a <code>std::array</code> with a constant value, like it can be done with <code>std::vector</code>.</p> <pre><code>#include &lt;vector&gt; #include &lt;array&gt; int main() { std::vector&lt;int&gt; v(10, 7); // OK std::array&lt;int, 10&gt; a(7); // does not compile, pretty frustrating } </code></pre> <p>Is there a way to do this elegantly? </p> <p>Right now I'm using this:</p> <pre><code>std::array&lt;int, 10&gt; a; for (auto &amp; v : a) v = 7; </code></pre> <p>but I'd like to avoid using explicit code for the initialisation.</p>
57,757,301
6
1
null
2019-09-02 11:56:41.377 UTC
5
2022-06-26 08:53:16.047 UTC
2019-09-02 23:55:13.653 UTC
null
2,684,539
null
898,348
null
1
44
c++|initialization|stdarray
14,127
<p>With <code>std::index_sequence</code>, you might do:</p> <pre class="lang-cpp prettyprint-override"><code>namespace detail { template &lt;typename T, std::size_t ... Is&gt; constexpr std::array&lt;T, sizeof...(Is)&gt; create_array(T value, std::index_sequence&lt;Is...&gt;) { // cast Is to void to remove the warning: unused value return {{(static_cast&lt;void&gt;(Is), value)...}}; } } template &lt;std::size_t N, typename T&gt; constexpr std::array&lt;T, N&gt; create_array(const T&amp; value) { return detail::create_array(value, std::make_index_sequence&lt;N&gt;()); } </code></pre> <p>With usage</p> <pre><code>auto a = create_array&lt;10 /*, int*/&gt;(7); // auto is std::array&lt;int, 10&gt; </code></pre> <p>Which, contrary to <code>std::fill</code> solution, handle non default constructible types.</p>
7,117,388
Finding out the duplicate element in an array
<p>There is an array of size n and the elements contained in the array are between 1 and n-1 such that each element occurs once and just one element occurs more than once. We need to find this element. </p> <p>Though this is a very FAQ, I still haven't found a proper answer. Most suggestions are that I should add up all the elements in the array and then subtract from it the sum of all the indices, but this won't work if the number of elements is very large. It will overflow. There have also been suggestions regarding the use of XOR gate <code>dup = dup ^ arr[i] ^ i</code>, which are not clear to me.</p> <p>I have come up with this algorithm which is an enhancement of the addition algorithm and will reduce the chances of overflow to a great extent!</p> <pre><code>for i=0 to n-1 begin : diff = A[i] - i; sum = sum + diff; end </code></pre> <p><code>diff</code> contains the duplicate element, but using this method I am unable to find out the index of the duplicate element. For that I need to traverse the array once more which is not desirable. Can anyone come up with a better solution that does not involve the addition method or the XOR method works in O(n)?</p>
7,118,161
2
5
null
2011-08-19 05:39:56.223 UTC
28
2016-07-29 18:37:27.723 UTC
2013-09-25 23:30:43.567 UTC
null
501,557
null
880,005
null
1
21
c|arrays|algorithm|complexity-theory|big-o
9,857
<p>There are many ways that you can think about this problem, depending on the constraints of your problem description.</p> <p><strong>If you know for a fact that exactly one element is duplicated</strong>, then there are many ways to solve this problem. One particularly clever solution is to use the bitwise XOR operator. XOR has the following interesting properties:</p> <ol> <li>XOR is associative, so (x ^ y) ^ z = x ^ (y ^ z)</li> <li>XOR is commutative: x ^ y = y ^ x</li> <li>XOR is its own inverse: x ^ y = 0 iff x = y</li> <li>XOR has zero as an identity: x ^ 0 = x</li> </ol> <p>Properties (1) and (2) here mean that when taking the XOR of a group of values, it doesn't matter what order you apply the XORs to the elements. You can reorder the elements or group them as you see fit. Property (3) means that if you XOR the same value together multiple times, you get back zero, and property (4) means that if you XOR anything with 0 you get back your original number. Taking all these properties together, you get an interesting result: if you take the XOR of a group of numbers, the result is the XOR of all numbers in the group that appear an odd number of times. The reason for this is that when you XOR together numbers that appear an even number of times, you can break the XOR of those numbers up into a set of pairs. Each pair XORs to 0 by (3), and th combined XOR of all these zeros gives back zero by (4). Consequently, all the numbers of even multiplicity cancel out.</p> <p>To use this to solve the original problem, do the following. First, XOR together all the numbers in the list. This gives the XOR of all numbers that appear an odd number of times, which ends up being all the numbers from 1 to (n-1) except the duplicate. Now, XOR this value with the XOR of all the numbers from 1 to (n-1). This then makes all numbers in the range 1 to (n-1) that were not previously canceled out cancel out, leaving behind just the duplicated value. Moreover, this runs in O(n) time and only uses O(1) space, since the XOR of all the values fits into a single integer.</p> <p>In your original post you considered an alternative approach that works by using the fact that the sum of the integers from 1 to n-1 is n(n-1)/2. You were concerned, however, that this would lead to integer overflow and cause a problem. On most machines you are right that this would cause an overflow, but (on most machines) this is not a problem because arithmetic is done using fixed-precision integers, commonly 32-bit integers. When an integer overflow occurs, the resulting number is not meaningless. Rather, it's just the value that you would get if you computed the actual result, then dropped off everything but the lowest 32 bits. Mathematically speaking, this is known as modular arithmetic, and the operations in the computer are done modulo 2<sup>32</sup>. More generally, though, let's say that integers are stored modulo k for some fixed k.</p> <p>Fortunately, many of the arithmetical laws you know and love from normal arithmetic still hold in modular arithmetic. We just need to be more precise with our terminology. We say that x is congruent to y modulo k (denoted x &equiv;<sub>k</sub> y) if x and y leave the same remainder when divided by k. This is important when working on a physical machine, because when an integer overflow occurs on most hardware, the resulting value is congruent to the true value modulo k, where k depends on the word size. Fortunately, the following laws hold true in modular arithmetic:</p> <p>For example:</p> <ol> <li>If x &equiv;<sub>k</sub> y and w &equiv;<sub>k</sub> z, then x + w &equiv;<sub>k</sub> y + z</li> <li>If x &equiv;<sub>k</sub> y and w &equiv;<sub>k</sub> z, then xw &equiv;<sub>k</sub> yz.</li> </ol> <p>This means that if you want to compute the duplicate value by finding the total sum of the elements of the array and subtracting out the expected total, everything will work out fine even if there is an integer overflow because standard arithmetic will still produce the same values (modulo k) in the hardware. That said, you could also use the XOR-based approach, which doesn't need to consider overflow at all. :-)</p> <p><strong>If you are not guaranteed that exactly one element is duplicated, but you can modify the array of elements,</strong> then there is a beautiful algorithm for finding the duplicated value. <a href="https://stackoverflow.com/questions/5739024/finding-duplicates-in-on-time-and-o1-space/5739336#5739336">This earlier SO question</a> describes how to accomplish this. Intuitively, the idea is that you can try to sort the sequence using a <a href="http://en.wikipedia.org/wiki/Bucket_sort" rel="nofollow noreferrer">bucket sort</a>, where the array of elements itself is recycled to hold the space for the buckets as well.</p> <p><strong>If you are not guaranteed that exactly one element is duplicated, and you cannot modify the array of elements,</strong> then the problem is much harder. This is a classic (and hard!) interview problem that reportedly took Don Knuth 24 hours to solve. The trick is to reduce the problem to an instance of <a href="http://en.wikipedia.org/wiki/Cycle_detection" rel="nofollow noreferrer">cycle-finding</a> by treating the array as a function from the numbers 1-n onto 1-(n-1) and then looking for two inputs to that function. However, the resulting algorithm, called <a href="http://en.wikipedia.org/wiki/Floyd%27s_cycle-finding_algorithm#Tortoise_and_hare" rel="nofollow noreferrer">Floyd's cycle-finding algorithm</a>, is extremely beautiful and simple. Interestingly, it's the same algorithm you would use to detect a cycle in a linked list in linear time and constant space. I'd recommend looking it up, since it periodically comes up in software interviews.</p> <p>For a complete description of the algorithm along with an analysis, correctness proof, and Python implementation, check out <strong><a href="http://keithschwarz.com/interesting/code/?dir=find-duplicate" rel="nofollow noreferrer">this implementation</a></strong> that solves the problem.</p> <p>Hope this helps!</p>
7,104,191
Recommend Build Artifact Repository Manager
<p>Currently we use FTP to maintain build artifact distribution and 3rd party products (for internal use only).</p> <p>Artifacts are docs (HTML/pdf/chm/...), libs (.dll/.so/.a/.jar/...), programs (.exe/.jar/...) and anything else. They are not restricted to Java/.NET and can come from different cultures (firmware, driver, mobile/workstation, GUI, Win/Linux/Mac/Solaris/AIX,... etc).</p> <p>To orginize hierarhy we use such paths:</p> <pre> ftp://3pp/VENDOR/PRODUCT/VERSION/... ftp://3pp/opensource/PACKAGE-x.x.x.tar.bz2 ftp://dist/PRODUCT/VERSION/... </pre> <p>To maintain description of artifacts we use <strong>README</strong> and <strong>CHANGES</strong> plain test files (reStructuredText).</p> <p>What is missing in this schema?</p> <ul> <li>Missing permissions (anyone can damage storage).</li> <li>Missing dependency tracking (so <em>every</em> build file must be updated if version dependency changed).</li> <li>Missing fetching activity (some files seem no longer needed, but we don't know which).</li> </ul> <p>I am not deeply looking for existing solutions. Some package manager like rpm/dpkg, heard about Maven repo etc...</p> <p>Please recommend Build Artifact Repository Managers. Also it is good to hear drawbacks and restrictions.</p> <p><strong>UPDATE</strong></p> <ul> <li><a href="https://en.wikipedia.org/wiki/Binary_repository_manager" rel="noreferrer">https://en.wikipedia.org/wiki/Binary_repository_manager</a></li> <li><a href="https://binary-repositories-comparison.github.io/" rel="noreferrer">https://binary-repositories-comparison.github.io/</a></li> </ul>
11,437,695
2
0
null
2011-08-18 08:01:43.03 UTC
14
2017-02-17 14:09:38.863 UTC
2017-02-17 14:09:38.863 UTC
null
173,149
null
173,149
null
1
25
repository|artifacts
34,014
<p>You're creating a custom software artifact repository. There are three open-source projects which already do this:</p> <ul> <li><a href="http://www.jfrog.com/" rel="noreferrer">Artifactory</a></li> <li><a href="http://www.sonatype.org/nexus/" rel="noreferrer">Nexus</a></li> <li><a href="http://archiva.apache.org/" rel="noreferrer">Archiva</a></li> </ul> <p>Artifactory and Nexus also have paid versions.</p> <p>You can store any kind of file in these repositories, and you don't need to use Maven. You can manually deploy artifacts to them. You can set up fine-grained access control. They integrate well with automated build tools.</p> <p>I think using one of these tools would save you a lot of effort!</p> <p><a href="https://binary-repositories-comparison.github.io/" rel="noreferrer">Here</a>'s fairly unbiased (community-driven) comparison matrix between the three.</p>
23,090,706
How to know when OWIN cookie will expire?
<p>I would like to create some kind of countdown timer based on the time the OWIN cookie will expire. I am using OWIN with MVC 5 and from what I understand SlidingExpiration is on by default. I do not use 'session' as I need this app to live within a web farm (I dont plan on deploying a session database).</p>
24,399,919
2
1
null
2014-04-15 17:37:32.307 UTC
24
2019-10-25 11:39:46.44 UTC
2014-04-20 02:21:36.317 UTC
null
41,956
null
1,164,306
null
1
23
.net|asp.net-mvc-5|session-cookies|owin
26,552
<p>All you need is to get hold of the <code>CookieValidateIdentityContext</code> during the cookie validation stage. Once you get it, extract whatever you need and keep them as <code>Claim</code> or some other way that you prefer.</p> <p>For MVC 5 with Asp.NET Identity 2.0, you need to perform two steps:</p> <ol> <li><p>Define custom <code>OnValidateIdentity</code>, extract cookie information, and keep it as <code>Claim</code>.</p> <pre><code>public class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new CookieAuthenticationProvider { OnValidateIdentity = MyCustomValidateIdentity //refer to the implementation below } } } // this method will be called on every request // it is also one of the few places where you can access unencrypted cookie content as CookieValidateIdentityContext // once you get cookie information you need, keep it as one of the Claims // please ignore the MyUserManager and MyUser classes, they are only for sample, you should have yours private static Task MyCustomValidateIdentity(CookieValidateIdentityContext context) { // validate security stamp for 'sign out everywhere' // here I want to verify the security stamp in every 100 seconds. // but I choose not to regenerate the identity cookie, so I passed in NULL var stampValidator = SecurityStampValidator.OnValidateIdentity&lt;MyUserManager&lt;Myuser&gt;. MyUser&gt;(TimeSpan.FromSeconds(100), null); stampValidator.Invoke(context); // here we get the cookie expiry time var expireUtc = context.Properties.ExpiresUtc; // add the expiry time back to cookie as one of the claims, called 'myExpireUtc' // to ensure that the claim has latest value, we must keep only one claim // otherwise we will be having multiple claims with same type but different values var claimType = "myExpireUtc"; var identity = context.Identity; if(identity.HasClaim(c=&gt; c.Type == claimType)) { var existingClaim = identity.FindFirst(claimType); identity.RemoveClaim(existingClaim); } var newClaim = new Claim(claimType, expireUtc.Value.UtcTicks.ToString()); context.Identity.AddClaim(newClaim); return Task.FromResult(0); } } </code></pre></li> <li><p>Access your <code>Claim</code> in your controller methods</p> <pre><code>// since expiry time has now become part of your claims, you now can get it back easily // this example just returns the remaining time in total seconds, as a string value // assuming this method is part of your controller methods public string RemainingTime() { var identity = User.Identity as ClaimsIdentity; var claimType = "myExpireUtc"; //NOTE: must be the same key value "myExpireUtc" defined in code shown above if(identity != null &amp;&amp; identity.HasClaim(c=&gt; c.Type == claimType)) { var expireOn = identity.FindFirstValue(claimType); DateTimeOffset currentUtc = DateTimeOffset.UtcNow; DateTimeOffset? expireUtc = new DateTimeOffset(long.Parse(expireOn), TimeSpan.Zero); var remaining = (expireUtc.Value - currentUtc).TotalSeconds; return remaining.ToString(); } return string.Empty; } </code></pre></li> </ol> <p>I use this approach to remind my application users to extend their session before session time out.</p> <p>Credit to this post <a href="https://stackoverflow.com/questions/19456008/how-do-i-access-microsoft-owin-security-xyz-onauthenticated-context-addclaims-va">How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?</a></p>
19,247,504
Retrieve distinct values from datatable using linq vb.net
<p>I am trying to retrieve all of the distinct values from a particular column in a datatable. The column name in the datatable is "Count". I have 2240 rows and I have 6 distinct values in the "Count" column. The problem is, when I execute the following code, it is giving me the number of rows rather than the 6 distinct values.</p> <pre><code>Dim counts = (From row In loadedData Select row.Item("Count")).Distinct() For Each i In counts MsgBox(i) Next </code></pre> <p>How can I modify this to retrieve the 6 distinct values, rather than it giving me the total number of rows?</p>
19,248,024
3
1
null
2013-10-08 12:18:51.25 UTC
null
2015-09-30 04:06:29.067 UTC
2013-10-08 12:27:16.653 UTC
null
1,977,006
null
2,712,113
null
1
1
vb.net|linq|datatable
46,343
<p>You just have to select the column and use <code>Enumerable.Distinct</code>:</p> <pre><code>Dim distinctCounts As IEnumerable(Of Int32) = loadedData.AsEnumerable(). Select(Function(row) row.Field(Of Int32)("Count")). Distinct() </code></pre> <p>In query syntax(i didn't know that even <code>Distinct</code> is supported directly in VB.NET):</p> <pre><code>distinctCounts = From row In loadedData Select row.Field(Of Int32)("Count") Distinct </code></pre>
17,828,774
Get Resources with string
<p>I have a lot of txt files in Resources folder. One of them is corner.txt. I can access this file via this code snippet:</p> <pre><code>Properties.Resources.corner </code></pre> <p>I keep file names in string variables. For example:</p> <pre><code>string fileName = "corner.txt"; </code></pre> <p><strong>I want to access this file via:</strong></p> <pre><code>Properties.Resources.fileName </code></pre> <p>Is this possible? How can I access?</p>
17,837,224
2
5
null
2013-07-24 08:27:59.8 UTC
1
2013-07-24 14:38:45.767 UTC
2013-07-24 08:34:15.62 UTC
null
1,954,447
null
1,954,447
null
1
27
c#
60,321
<p>I solved the problem this code snippet:</p> <pre><code>string st = Properties.Resources.ResourceManager.GetString(tableName); </code></pre> <p>So, I don't use the filename, I use the txt file's string. This is useful for me.</p> <p>Thanks a lot.</p>
35,704,412
Postgresql query current year
<p>I need to see only the current year rows from a table.</p> <p>Would it be possible filter a timestamp column only by current year parameter, is there some function that can return this value?</p> <pre><code>SELECT * FROM mytable WHERE "MYDATE" LIKE CURRENT_YEAR </code></pre>
35,704,671
2
1
null
2016-02-29 16:21:20.717 UTC
7
2020-08-28 04:39:01.24 UTC
null
null
null
null
2,239,318
null
1
37
sql|postgresql
63,837
<p>In PostgreSQL you can use this:</p> <pre><code>SELECT * FROM mytable WHERE date_part('year', mydate) = date_part('year', CURRENT_DATE); </code></pre> <p>The date_part function is available in all PostgreSQL releases from current down to 7.1 (at least).</p>
21,040,460
SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction by Magento position
<p>We have a problem in our Magento shop when we try to set the position of the products in a category from manage categories. When we try to save a product after changing the position in "category products" we get the following failure:</p> <blockquote> <p>SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction</p> </blockquote> <p>Does anyone know how to solve this?</p>
21,040,549
1
3
null
2014-01-10 09:27:41.863 UTC
6
2014-01-10 09:31:43.063 UTC
2014-01-10 09:30:05.697 UTC
null
2,047,249
null
1,859,654
null
1
10
magento|magento-1.7
45,988
<p>The error occurs most probably because you have the product position index set to auto and Magento tries to rebuild the index along with the product save.<br> Go to <code>System-&gt;Index Management</code> and set the indexes related to catalog to 'manual'.<br> Then set the product positions and when you are done rebuild the indexes manually.</p>
1,890,559
Handle "potentially dangerous Request.Form value..."
<p>What's the best way to handle errors such as</p> <blockquote> <p>A potentially dangerous Request.Form value was detected from the client" </p> </blockquote> <p>in ASP.NET? </p> <p>I'd like to keep the validation on, as my forms have no valid reasons to be allowing HTML characters. However, I'm not quite sure how to handle this error in a more friendly manner. I tried handling it in a <code>Page_Error</code> but, as far as I can tell, this occurs in a lower level section so the <code>Page_Error</code> function never fires. </p> <p>Therefore, I may have to resort to using <code>Application_Error</code> in my <code>Global.asax</code> file. If this is the only way of handling that error, is there a way of specifically handling that one error? I don't want to handle all application errors in the same manner. </p> <p>Thanks</p>
1,890,606
3
2
null
2009-12-11 20:11:18.293 UTC
9
2014-06-05 09:57:10.07 UTC
2014-06-05 09:57:10.07 UTC
null
1,866,810
null
187,697
null
1
14
asp.net|error-handling|application-error
9,456
<p>You have two options:</p> <pre><code>// Editing your global.asax.cs public class Global : System.Web.HttpApplication { protected void Application_Error(object sender, EventArgs e) { Exception lastError = Server.GetLastError(); if (lastError is HttpRequestValidationException) { Response.Redirect("~/RequestValidationError.aspx"); } } } </code></pre> <p>Or</p> <pre><code>// Editing your CUser.aspx.cs public partial class CUser : System.Web.UI.Page { protected override void OnError(EventArgs e) { Response.Redirect("~/RequestValidationError.aspx"); Context.ClearError(); } } </code></pre>
196,150
Is there a way I can retrieve sa password in sql server 2005
<p>I just forgot the password. Can anyone help me how to get back the password.</p>
196,158
4
1
null
2008-10-12 21:39:02.463 UTC
4
2014-08-17 22:08:39.417 UTC
2014-08-17 22:08:39.417 UTC
davr
3,366,929
jazzrai
14,752
null
1
6
sql-server|sql-server-2005|passwords
111,943
<p>There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).</p> <p>Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.</p> <p><img src="https://i.stack.imgur.com/6LttD.png" alt="enter image description here"></p> <p>Now write down the new SA password.</p>
660,798
Multiple iPhone Developer Accounts on One Mac?
<p>I have searched but cant find this question anywhere. My wife and I are about to take on iPhone development and we've only got the funds to purchase one iMac 24" to do this. Anyone out there with iPhone development experience know if two different Apple developer accounts can be profiled on one development Mac? Not only via the developer program but also does the XCODE (I believe it is) IDE support it?</p> <p>What we're hoping to be able to do is that I can log in with my profile and developer/debug, etc my iPhone application and her do the same under her own profile (not seeing mine and vice-versa). Time sharing wont be an issue as I work from home while she works away from home and we'll be able to figure out that part no problem.</p> <p>Please understand that we're both completely new to the Mac, OS X as well as the iPhone development arena and so we have no idea if this is possible. If not our second option would be to purchase two Mac Mini's (keyboards and mice too) and figure out some KVM to each of our existing PC's monitors that we already have, and develop that way. We would rather not and just share one iMac between two developer accounts and IDE profiles.</p> <p><strong>UPDATE:</strong> My wife and I invested in a 24" iMac from Best Buy utilizing a 12 month no-interest offer, which made it the choice over the 20" iMac. Its got plenty of RAM (4G out of 8G max) and HD space (640G) and we're getting used to the MAC OS X and will begin developing soon. We've created two OS X accounts, to keep settings and such separate. Either Windows moved closer to OS X or vice-versa as things on OS X seem quite intuitive and we were highly impressed at the whole un-box and setup time of about 8 minutes! So far, so good.</p>
660,802
4
0
null
2009-03-19 01:51:43.643 UTC
15
2010-12-10 17:47:25.703 UTC
2010-11-10 14:53:21.63 UTC
Optimal Solutions
14,728
Optimal Solutions
14,728
null
1
20
iphone|macos|xcode
18,553
<p>Sure. Just make two user accounts on the iMac. Easy!</p>
1,084,114
Cross domain cookies
<p>I have a small problem.</p> <p>How do I set a cookie for multiple domains?</p> <p>I do understand the security problems, and I am sure it has been done before. The reason for this is SSO.</p> <p>ie.</p> <p><code>account.domain.com</code> will need to set domain logged in for:</p> <p>domain.com, domain1.com, domain2.com.</p> <p>Is there any easy way, using PHP and cookies, or any alternatives?</p>
1,095,901
4
2
null
2009-07-05 14:04:13.267 UTC
17
2016-09-27 16:21:57.39 UTC
2016-02-10 05:21:18.517 UTC
null
6,616,534
null
114,865
null
1
27
php|authentication|cookies|single-sign-on
57,261
<p>There is absolutely no way for domain.com to set a cookie for domain1.com. What you are attempting to do can only be solved by getting the user's browser to submit requests to each domain which will then set its own cookie. </p> <p>Then you need a way for each domain to verify the user's identity. There are two approaches to this:</p> <ol> <li>Back channel - the sites contact each other directly to determine if a user is logged in.</li> <li>Passing a token in the GET or POST - when the user's broweser is redirected to the other site a digitally signed parameter is passed containing the identity and session status.</li> </ol> <p>It's really quite complicated. I suggest you don't roll your own. Take a look at <a href="http://rnd.feide.no/simplesamlphp" rel="noreferrer">SimpleSAMLPHP</a> for a PHP implementation of what I'm describing.</p>
992,532
What .net files should be excluded from source control?
<p>What file extensions from a .net application should be excluded from source control and why please? </p>
992,540
4
1
null
2009-06-14 09:41:55.827 UTC
12
2019-05-09 07:16:32.92 UTC
null
null
null
null
83,860
null
1
30
.net|version-control
8,182
<p>Depends on the project, but I've got the following for a Silverlight + WPF project in my .gitignore:</p> <pre><code># Visual Studio left-overs *.suo # 'user' settings like 'which file is open in Visual Studio' *.ncb # Used for debugging *.user *.ccscc # Used for versioning *.cache # Editor left-overs *~ # (x)emacs *.bak # Windows related \#*\# # (x)emacs *.orig # Own usage # Compiled files */bin/ */obj/ */Obj/ # git is case sensitive */Generated_Code/ PrecompiledWeb */ClientBin # Windows left-overs Thumbs.db # Having images in the source tree generates those files in Explorer </code></pre> <p>However, the '.suo' is somewhat problematic: it also contains 'user' settings which should have been project settings, like the startup page for a Silverlight application.</p> <p>The best and only way is to iteratively add the files to exclude. If you're using git, using git-gui to quickly and interactively see the list of files which you've forgotten to exclude. Adapt .gitignore and refresh in git-gui. Iterate until the files left over are the ones you typed in.</p> <p>Some types of files are not quite clear up front. Be sure you understand all the files you check in. For example, for the RIA services in our Silverlight project we had an authentication database generated by Visual Studio which contained 2 accounts and resulted in a hefty 10Mb .MDB database file(!). Once we understood where it came from, changing it to an SQL dump reduced the size to a (still hefty) 500Kb. Constantly (re)checking prior to the checkin itself is always required, so no list is definite.</p>
1,087,177
What do those strange class names in a java heap dump mean?
<p>I'm trying to track down a memory leak in a java process, using <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html" rel="noreferrer">jmap</a> and <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html" rel="noreferrer">jhat</a>. Every time I do this I see those weird notation for specific object types, like <code>[S</code> for string arrays and <code>[C</code> for Character arrays. I never remember what means what, and it's very hard to google this stuff.</p> <p>(<strong>EDIT</strong>: to prove my point, it turns out that <code>[S</code> is array of short and <code>[C</code> is array of char.)</p> <p>Anyone care to make a table listing all the different class names and what they mean? Or point me to such table?</p> <p>Specifically I'd like to know what <code>[Ljava.lang.Object;</code> means.</p>
1,087,215
4
4
null
2009-07-06 14:08:44.713 UTC
13
2021-09-26 18:24:29.843 UTC
2021-09-26 18:24:29.843 UTC
null
5,459,839
null
7,581
null
1
39
java|debugging|memory-leaks|heap-memory|jmap
19,466
<p>You'll find the complete list documented under <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()" rel="noreferrer">Class.getName()</a>:</p> <blockquote> <p>If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the <em>Java™ Language Specification, Second Edition</em>.</p> <p>If this class object represents a primitive type or void, then the name returned is a <code>String</code> equal to the Java language keyword corresponding to the primitive type or void.</p> <p>If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:</p> <pre> Element Type Encoding boolean Z byte B char C class or interface L<i>classname</i>; double D float F int I long J short S </pre> </blockquote>
59,166
How do you declare a Predicate Delegate inline?
<p>So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects.</p> <pre><code>List&lt;MyObject&gt; myObjects = new List&lt;MyObject&gt;(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); </code></pre> <p>So I want to remove objects from my list based on some criteria. For instance, <code>myObject.X &gt;= 10.</code> I would like to use the <code>RemoveAll(Predicate&lt;T&gt; match)</code> method for to do this.</p> <p>I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.</p>
59,172
4
0
null
2008-09-12 14:45:45.697 UTC
13
2020-08-19 23:56:11.587 UTC
2020-08-19 23:50:30.94 UTC
aku
4,298,200
Curtis
454,247
null
1
43
c#|delegates
33,423
<p>There's two options, an explicit delegate or a delegate disguised as a lamba construct:</p> <p>explicit delegate</p> <pre><code>myObjects.RemoveAll(delegate (MyObject m) { return m.X &gt;= 10; }); </code></pre> <p>lambda</p> <pre><code>myObjects.RemoveAll(m =&gt; m.X &gt;= 10); </code></pre> <hr /> <p>Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs</p>
62,264
Dealing with SVN keyword expansion with git-svn
<p>I recently asked about <a href="https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks">keyword expansion in Git</a> and I'm willing to accept the design not to really support this idea in Git. </p> <p>For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:</p> <pre><code>svn propset svn:keywords "Id" expl3.dtx </code></pre> <p>to keep this string up-to-date:</p> <pre><code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $ </code></pre> <p>But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:</p> <blockquote> <p>"We ignore all SVN properties except svn:executable"</p> </blockquote> <p>But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?</p>
72,874
4
0
null
2008-09-15 12:04:31.833 UTC
15
2015-12-09 11:20:10.923 UTC
2017-05-23 11:46:42.47 UTC
Will Robertson
-1
Will Robertson
4,161
null
1
43
svn|git|version-control
18,930
<p>What's going on here: Git is optimized to switch between branches as quickly as possible. In particular, <code>git checkout</code> is designed to not touch any files that are identical in both branches.</p> <p>Unfortunately, RCS keyword substitution breaks this. For example, using <code>$Date$</code> would require <code>git checkout</code> to touch every file in the tree when switching branches. For a repository the size of the Linux kernel, this would bring everything to a screeching halt.</p> <p>In general, your best bet is to tag at least one version:</p> <pre><code>$ git tag v0.5.whatever </code></pre> <p>...and then call the following command from your Makefile:</p> <pre><code>$ git describe --tags v0.5.15.1-6-g61cde1d </code></pre> <p>Here, git is telling me that I'm working on an anonymous version 6 commits past v0.5.15.1, with an SHA1 hash beginning with <code>g61cde1d</code>. If you stick the output of this command into a <code>*.h</code> file somewhere, you're in business, and will have no problem linking the released software back to the source code. This is the preferred way of doing things.</p> <p>If you can't possibly avoid using RCS keywords, you may want to start with this <a href="http://kerneltrap.org/mailarchive/git/2007/10/12/335953" rel="noreferrer">explanation by Lars Hjemli</a>. Basically, <code>$Id$</code> is pretty easy, and you if you're using <code>git archive</code>, you can also use <code>$Format$</code>.</p> <p>But, if you absolutely cannot avoid RCS keywords, the following should get you started:</p> <pre><code>git config filter.rcs-keyword.clean 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/"' git config filter.rcs-keyword.smudge 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date: `date`\\\$/"' echo '$Date$' &gt; test.html echo 'test.html filter=rcs-keyword' &gt;&gt; .gitattributes git add test.html .gitattributes git commit -m "Experimental RCS keyword support for git" rm test.html git checkout test.html cat test.html </code></pre> <p>On my system, I get:</p> <pre><code>$Date: Tue Sep 16 10:15:02 EDT 2008$ </code></pre> <p>If you have trouble getting the shell escapes in the <code>smudge</code> and <code>clean</code> commands to work, just write your own Perl scripts for expanding and removing RCS keywords, respectively, and use those scripts as your filter.</p> <p>Note that you <em>really</em> don't want to do this for more files than absolutely necessary, or git will lose most of its speed.</p>
1,015,166
C#: event with explicity add/remove != typical event?
<p>I have declared a generic event handler</p> <pre><code>public delegate void EventHandler(); </code></pre> <p>to which I have added the extension method 'RaiseEvent':</p> <pre><code>public static void RaiseEvent(this EventHandler self) { if (self != null) self.Invoke(); } </code></pre> <p>When I define the event using the typical syntax</p> <pre><code>public event EventHandler TypicalEvent; </code></pre> <p>then I can call use the extension method without problems:</p> <pre><code>TypicalEvent.RaiseEvent(); </code></pre> <p>But when I define the event with explicit add/remove syntax</p> <pre><code>private EventHandler _explicitEvent; public event EventHandler ExplicitEvent { add { _explicitEvent += value; } remove { _explicitEvent -= value; } } </code></pre> <p>then the extension method does not exist on the event defined with explicit add/remove syntax:</p> <pre><code>ExplicitEvent.RaiseEvent(); //RaiseEvent() does not exist on the event for some reason </code></pre> <p>And when I hover over to event to see the reason it says: </p> <blockquote> <p>The event 'ExplicitEvent' can only appear on the left hand side of += or -=</p> </blockquote> <p><strong>Why should an event defined using the typical syntax be different from an event defined using the explicit add/remove syntax and why extension methods do not work on the latter?</strong></p> <p><strong>EDIT: I found I can work around it by using the private event handler directly:</strong></p> <pre><code>_explicitEvent.RaiseEvent(); </code></pre> <p>But I still don't understand why I cannot use the event directly like the event defined using the typical syntax. Maybe someone can enlighten me.</p>
1,015,189
4
1
null
2009-06-18 21:03:07.463 UTC
14
2014-08-06 14:55:52.213 UTC
2010-02-13 23:33:00.233 UTC
null
76,337
user65199
null
null
1
45
c#|.net|events
40,523
<p>Because you can do this (it's non-real-world sample, but it "works"):</p> <pre><code>private EventHandler _explicitEvent_A; private EventHandler _explicitEvent_B; private bool flag; public event EventHandler ExplicitEvent { add { if ( flag = !flag ) { _explicitEvent_A += value; /* or do anything else */ } else { _explicitEvent_B += value; /* or do anything else */ } } remove { if ( flag = !flag ) { _explicitEvent_A -= value; /* or do anything else */ } else { _explicitEvent_B -= value; /* or do anything else */ } } } </code></pre> <p>How can the compiler know what it should do with "ExplicitEvent.RaiseEvent();"? Answer: It can't.</p> <p>The "ExplicitEvent.RaiseEvent();" is only syntax sugar, which can be predicated only if the event is implicitly implemented.</p>
721,395
linq question: querying nested collections
<p>I have a <strong>Question</strong> class that has public List property that can contain several <strong>Answers</strong>.</p> <p>I have a question repository which is responsible for reading the questions and its answers from an xml file.</p> <p>So I have a collection of Questions (List) with each Question object having a collection of Answers and I'd like to query this collection of Questions for an Answer (ie by its Name) by using Linq. I don't know how to do this properly.</p> <p>I could do it with a foreach but I'd like to know whether there is a pure Linq way since I'm learning it.</p>
721,422
4
1
null
2009-04-06 13:20:11.577 UTC
19
2017-12-12 22:51:16.567 UTC
null
null
null
null
13,466
null
1
52
c#|.net|linq|collections|linq-to-xml
55,773
<p>To find an answer.</p> <pre><code>questions.SelectMany(q =&gt; q.Answers).Where(a =&gt; a.Name == "SomeName") </code></pre> <p>To find the question of an answer.</p> <pre><code>questions.Where(q =&gt; q.Answers.Any(a =&gt; a.Name == "SomeName")) </code></pre> <p>In fact you will get collections of answers or questions and you will have to use <code>First()</code>, <code>FirstOrDefault()</code>, <code>Single()</code>, or <code>SingleOrDefault()</code> depending on your needs to get one specific answer or question.</p>
708,205
C# Object Type Comparison
<p>How can I compare the types of two objects declared as type.</p> <p>I want to know if two objects are of the same type or from the same base class.</p> <p>Any help is appreciated.</p> <p>e.g.</p> <pre><code>private bool AreSame(Type a, Type b) { } </code></pre>
708,240
4
0
null
2009-04-02 03:46:10.25 UTC
22
2014-11-02 20:21:41.21 UTC
2009-04-02 03:55:20.15 UTC
B Z
25,020
B Z
25,020
null
1
64
c#|types
80,040
<p>Say <code>a</code> and <code>b</code> are the two objects. If you want to see if <code>a</code> and <code>b</code> are in the same inheritance hierarchy, then use <strong><a href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx" rel="noreferrer"><code>Type.IsAssignableFrom</code></a></strong>:</p> <pre><code>var t = a.GetType(); var u = b.GetType(); if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) { // x.IsAssignableFrom(y) returns true if: // (1) x and y are the same type // (2) x and y are in the same inheritance hierarchy // (3) y is implemented by x // (4) y is a generic type parameter and one of its constraints is x } </code></pre> <p>If you want to check if one is a base class of the other, then try <strong><a href="http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx" rel="noreferrer"><code>Type.IsSubclassOf</code></a></strong>.</p> <p>If you know the specific base class, then just use the <code>is</code> keyword:</p> <pre><code>if (a is T &amp;&amp; b is T) { // Objects are both of type T. } </code></pre> <p>Otherwise, you'll have to walk the inheritance hierarchy directly.</p>
624,260
How to reuse an ostringstream?
<p>I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?</p>
624,291
4
1
null
2009-03-08 20:53:24.247 UTC
37
2014-10-19 14:05:49.443 UTC
2009-03-08 21:03:38.437 UTC
Diego Sevilla
62,365
twk
23,524
null
1
122
c++|stl|reset|ostringstream
57,780
<p>I've used a sequence of clear and str in the past:</p> <pre><code>// clear, because eof or other bits may be still set. s.clear(); s.str(""); </code></pre> <p>Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin:</p> <pre><code>s.clear(); s.seekp(0); // for outputs: seek put ptr to start s.seekg(0); // for inputs: seek get ptr to start </code></pre> <p>That will prevent some reallocations done by <code>str</code> by overwriting whatever is in the output buffer currently instead. Results are like this:</p> <pre><code>std::ostringstream s; s &lt;&lt; "hello"; s.seekp(0); s &lt;&lt; "b"; assert(s.str() == "bello"); </code></pre> <p>If you want to use the string for c-functions, you can use <code>std::ends</code>, putting a terminating null like this:</p> <pre><code>std::ostringstream s; s &lt;&lt; "hello"; s.seekp(0); s &lt;&lt; "b" &lt;&lt; std::ends; assert(s.str().size() == 5 &amp;&amp; std::strlen(s.str().data()) == 1); </code></pre> <p><code>std::ends</code> is a relict of the deprecated <code>std::strstream</code>, which was able to write directly to a char array you allocated on the stack. You had to insert a terminating null manually. However, <code>std::ends</code> is not deprecated, i think because it's still useful as in the above cases. </p>
695,752
How to design a product table for many kinds of product where each product has many parameters
<p>I do not have much experience in table design. My goal is to create one or more product tables that meet the requirements below:</p> <ul> <li><p>Support many kinds of products (TV, Phone, PC, ...). Each kind of product has a different set of parameters, like:</p> <ul> <li><p>Phone will have Color, Size, Weight, OS...</p></li> <li><p>PC will have CPU, HDD, RAM...</p></li> </ul></li> <li><p>The set of parameters must be dynamic. You can add or edit any parameter you like.</p></li> </ul> <p>How can I meet these requirements without a separate table for each kind of product?</p>
695,860
4
1
null
2009-03-30 01:19:06.273 UTC
205
2020-02-17 00:55:35.74 UTC
2014-11-04 00:16:37.823 UTC
null
2,359,271
StoneHeart
44,533
null
1
169
database-design|relational-database|database-schema
62,103
<p>You have at least these five options for modeling the type hierarchy you describe:</p> <ul> <li><p><a href="http://martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="noreferrer">Single Table Inheritance</a>: one table for all Product types, with enough columns to store all attributes of all types. This means <em>a lot</em> of columns, most of which are NULL on any given row.</p></li> <li><p><a href="http://martinfowler.com/eaaCatalog/classTableInheritance.html" rel="noreferrer">Class Table Inheritance</a>: one table for Products, storing attributes common to all product types. Then one table per product type, storing attributes specific to that product type.</p></li> <li><p><a href="http://martinfowler.com/eaaCatalog/concreteTableInheritance.html" rel="noreferrer">Concrete Table Inheritance</a>: no table for common Products attributes. Instead, one table per product type, storing both common product attributes, and product-specific attributes.</p></li> <li><p><a href="http://martinfowler.com/eaaCatalog/serializedLOB.html" rel="noreferrer">Serialized LOB</a>: One table for Products, storing attributes common to all product types. One extra column stores a BLOB of semi-structured data, in XML, YAML, JSON, or some other format. This BLOB allows you to store the attributes specific to each product type. You can use fancy Design Patterns to describe this, such as Facade and Memento. But regardless you have a blob of attributes that can't be easily queried within SQL; you have to fetch the whole blob back to the application and sort it out there.</p></li> <li><p><a href="http://en.wikipedia.org/wiki/Entity-Attribute-Value_model" rel="noreferrer">Entity-Attribute-Value</a>: One table for Products, and one table that pivots attributes to rows, instead of columns. EAV is not a valid design with respect to the relational paradigm, but many people use it anyway. This is the "Properties Pattern" mentioned by another answer. See other questions with the <a href="https://stackoverflow.com/questions/tagged/eav">eav tag</a> on StackOverflow for some of the pitfalls.</p></li> </ul> <p>I have written more about this in a presentation, <a href="http://www.slideshare.net/billkarwin/extensible-data-modeling" rel="noreferrer">Extensible Data Modeling</a>.</p> <hr> <p>Additional thoughts about EAV: Although many people seem to favor EAV, I don't. It seems like the most flexible solution, and therefore the best. However, keep in mind the adage <a href="http://en.wikipedia.org/wiki/Tanstaafl" rel="noreferrer">TANSTAAFL</a>. Here are some of the disadvantages of EAV:</p> <ul> <li>No way to make a column mandatory (equivalent of <code>NOT NULL</code>).</li> <li>No way to use SQL data types to validate entries.</li> <li>No way to ensure that attribute names are spelled consistently.</li> <li>No way to put a foreign key on the values of any given attribute, e.g. for a lookup table.</li> <li>Fetching results in a conventional tabular layout is complex and expensive, because to get attributes from multiple rows you need to do <code>JOIN</code> for each attribute.</li> </ul> <p>The degree of flexibility EAV gives you requires sacrifices in other areas, probably making your code as complex (or worse) than it would have been to solve the original problem in a more conventional way.</p> <p>And in most cases, it's unnecessary to have that degree of flexibility. In the OP's question about product types, it's much simpler to create a table per product type for product-specific attributes, so you have some consistent structure enforced at least for entries of the same product type.</p> <p>I'd use EAV only if <em>every row</em> must be permitted to potentially have a distinct set of attributes. When you have a finite set of product types, EAV is overkill. Class Table Inheritance would be my first choice.</p> <hr> <p>Update 2019: The more I see people using JSON as a solution for the "many custom attributes" problem, the less I like that solution. It makes queries too complex, even when using special <a href="https://dev.mysql.com/doc/refman/8.0/en/json-functions.html" rel="noreferrer">JSON functions</a> to support them. It takes a lot more storage space to store JSON documents, versus storing in normal rows and columns.</p> <p>Basically, none of these solutions are easy or efficient in a relational database. The whole idea of having "variable attributes" is fundamentally at odds with relational theory.</p> <p>What it comes down to is that you have to choose one of the solutions based on which is the least bad for <em>your</em> app. Therefore you need to know how you're going to query the data before you choose a database design. There's no way to choose one solution that is "best" because any of the solutions might be best for a given application.</p>
400,805
PHP function to build query string from array
<p>I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for <em>the built in PHP</em> function to do this, not a homebrew one (that's all a google search seems to return). There is one, I just can't remember its name or find it on php.net. IIRC its name isn't that intuitive.</p>
400,814
4
0
null
2008-12-30 16:49:05.52 UTC
32
2020-04-30 09:10:44.013 UTC
2013-04-26 16:20:02.83 UTC
null
425,313
null
1,349,865
null
1
180
php
169,780
<p>You're looking for <a href="http://us.php.net/manual/en/function.http-build-query.php" rel="noreferrer"><code>http_build_query()</code></a>. </p>
19,372,658
jQuery 1.10.2 warning issue from Firefox
<p>I tried to use latest jQuery for my website and I get this warning sign and message from Firefox 24.</p> <blockquote> <p>Warning: Use of <code>getPreventDefault()</code> is deprecated. Use <code>defaultPrevented</code> instead.</p> <p>Source File: file:///C:/wamp/www/bootstrap3/dist/js/jquery-1.10.2.min.js</p> <p>Line: 5</p> <p>Warning: SyntaxError: Using <code>//@</code> to indicate source map URL pragmas is deprecated. Use <code>//#</code> instead</p> <p>Source File: file:///C:/wamp/www/bootstrap3/dist/js/jquery-1.10.2.min.js</p> <p>Line: 1</p> </blockquote> <p>Is it fine to leave that problem? How to solve it?</p>
19,372,680
3
0
null
2013-10-15 03:08:12.627 UTC
8
2015-07-02 19:19:52.273 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,995,781
null
1
31
javascript|jquery|firefox
59,484
<p>This is a known issue, reported for version 1.10.2 and has been resolved for the 1.11/2.1 jQuery milestone. See a proposed pull request <a href="https://github.com/jquery/jquery/pull/1294">here</a>, and the report on the bug tracker <a href="http://bugs.jquery.com/ticket/14282">here</a>.</p> <p>To fix this, just use a later version of jQuery, or change this line in <code>event.js</code> from:</p> <pre><code>this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault &amp;&amp; src.getPreventDefault() ) ? returnTrue : returnFalse; </code></pre> <p>To this line:</p> <pre><code>this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse; </code></pre> <p><strong>Edit:</strong> The pull request linked above was never merged, although it did fix the problem. The issue was instead resolved by <a href="https://github.com/jquery/jquery/commit/4671ef15c2d62962048fd4863911146fcc085f26">this</a> commit and looks like this:</p> <pre><code>this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined &amp;&amp; ( src.returnValue === false || src.getPreventDefault &amp;&amp; src.getPreventDefault() ) ? returnTrue : returnFalse; </code></pre>
19,922,435
How to push changes to github after jenkins build completes?
<p>I have a jenkins job that clones the repository from github, then runs the powershell script that increments the version number in the file. I'm now trying to publish that update file back to the original repository on github, so when developer pulls the changes he gets the latest version number.</p> <p>I tried using Git Publisher in the post build events, and I can publish tags with no issues, but it doesn't seem to publish any files.</p>
19,923,066
5
0
null
2013-11-12 06:32:35.497 UTC
12
2021-01-27 11:17:14.58 UTC
null
null
null
null
1,549,704
null
1
63
git|github|jenkins
127,523
<p>Found an answer myself, this blog helped: <a href="http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3" rel="noreferrer">http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3</a></p> <p>Basically need to execute:</p> <pre><code>git checkout master </code></pre> <p>before modifying any files</p> <p>then</p> <pre><code>git commit -am "Updated version number" </code></pre> <p>after modified files</p> <p>and then use <strong>post build action of Git Publisher</strong> with an option of Merge Results which will push changes to github on successful build.</p>
19,899,642
Remove Border of UISearchBar in iOS7
<p>I'm trying to remove border of UISearchBar in iOS 7. In iOS 6 it's working fine. I created the UISearchBar programatically. I tried almost every thing from Stack Overflow and Google. </p> <p>SearchBar looking right now<br> <img src="https://i.stack.imgur.com/yy6MM.png" alt="SearchBar looking right now"></p> <p>What i want to achieve<br> <img src="https://i.stack.imgur.com/7gvH6.png" alt="What i want to achieve"></p> <p>I tried all these stuffs mentioned below</p> <pre><code>searchBar.layer.borderWidth = 1; searchBar.layer.borderColor = [[UIColor whiteColor] CGColor]; </code></pre> <p>and </p> <pre><code>for (id img in searchBar.subviews) { if ([img isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { [img removeFromSuperview]; } } </code></pre> <p>and </p> <pre><code>for (UIView *sub in self.tableView.tableHeaderView.subviews) { if ([sub isKindOfClass:[UIImageView class]]) { sub.hidden = YES; } } </code></pre> <p>but still no success.</p>
19,900,194
10
0
null
2013-11-11 05:44:56.837 UTC
10
2020-03-24 18:34:26.827 UTC
2014-12-12 06:30:21.867 UTC
null
1,603,234
null
1,760,257
null
1
56
ios|uisearchbar
42,304
<p>I found the solution: set the <code>barTintColor</code> of <code>UISearchBar</code> to <code>clearColor</code> </p> <pre><code>topSearchBar.barTintColor = [UIColor clearColor]; </code></pre>
21,496,905
how to change the background image of div using javascript?
<p>this is my code</p> <pre><code>&lt;div style=&quot;text-align:center;&quot;&gt; &lt;div class=&quot;ghor&quot; id=&quot;a&quot; onclick=&quot;chek_mark()&quot;&gt;&lt;/div&gt; function call &lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt; function chek_mark(){ var el= document.getElementById(&quot;a&quot;).style.background-image; if (el.url(&quot;Black-Wallpaper.jpg&quot;)) { el.url = &quot;cross1.png&quot;; } else if(el.url(&quot;cross1.png&quot;)) { alert(&quot;&lt;h1&gt;This is working too.&lt;/h1&gt;&quot;); } } &lt;/script&gt; </code></pre> <p>here I want to change the background image using if else condition</p> <pre><code>this is the style-sheet .ghor //this is the div class { background-image: url('Black-Wallpaper.jpg'); background-size: cover; border-radius: 5px; height: 100px; width: 100px; box-shadow: 2px 5px 7px 7px white; /*background-color: black;*/ display:inline-block; } </code></pre> <p>i want change the background image of the 'div' which class is 'ghor'</p>
21,496,929
9
0
null
2014-02-01 10:31:04.777 UTC
8
2022-08-03 14:11:53.173 UTC
2021-10-07 18:51:16.657 UTC
null
386,455
null
3,244,883
null
1
38
javascript|html|css
135,191
<p>Try this:</p> <pre><code>document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here </code></pre> <p>Hope it helps!</p>
21,883,129
How to get rid of "The solution you are trying to open is bound to source control" message
<p>I have a Visual Studio solution files copied from a source controlled solution. I don't want it to be source controlled and when I open it I get the message: <code>the solution you are trying to open is bound to source control</code></p> <p>I deleted the .vssscc files but still get the message. How can I get rid of it?</p> <p>Thanks.</p>
21,883,548
1
0
null
2014-02-19 14:16:42.49 UTC
10
2019-08-22 06:56:51.267 UTC
null
null
null
null
386,817
null
1
31
visual-studio|visual-studio-2012|tfs
11,074
<p>You need to clean the solution file (.sln) by removing the following GlobalSection:</p> <pre><code>GlobalSection(TeamFoundationVersionControl) = preSolution SccNumberOfProjects = 2 SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} SccTeamFoundationServer = http://example.com/tfs/defaultcollection SccLocalPath0 = . /// --- more solution specific stuff omitted --- /// EndGlobalSection </code></pre> <p>and you need to remove the source control references from every single project file (.csproj for C# projects):</p> <pre><code>... &lt;SccProjectName&gt;SAK&lt;/SccProjectName&gt; &lt;SccLocalPath&gt;SAK&lt;/SccLocalPath&gt; &lt;SccAuxPath&gt;SAK&lt;/SccAuxPath&gt; &lt;SccProvider&gt;SAK&lt;/SccProvider&gt; ... </code></pre>
45,025,334
How to use router.navigateByUrl and router.navigate in Angular
<p><a href="https://angular.io/api/router/RouterLink" rel="noreferrer">https://angular.io/api/router/RouterLink</a> gives a good overview of how to create links that will take the user to a different route in Angular4, however I can't find how to do the same thing programmatically rather needing the user to click a link</p>
45,025,432
6
0
null
2017-07-11 04:21:02.857 UTC
19
2022-02-12 18:27:45.313 UTC
2017-08-11 14:44:00.177 UTC
null
2,545,680
null
6,879,750
null
1
85
angular|routes|routerlink
174,476
<h3>navigateByUrl</h3> <p><code>routerLink</code> directive as used like this:</p> <pre><code>&lt;a [routerLink]="/inbox/33/messages/44"&gt;Open Message 44&lt;/a&gt; </code></pre> <p>is just a wrapper around imperative navigation using <code>router</code> and its <a href="https://angular.io/api/router/Router#navigateByUrl" rel="noreferrer">navigateByUrl</a> method:</p> <pre><code>router.navigateByUrl('/inbox/33/messages/44') </code></pre> <p>as can be seen from the sources:</p> <pre><code>export class RouterLink { ... @HostListener('click') onClick(): boolean { ... this.router.navigateByUrl(this.urlTree, extras); return true; } </code></pre> <p>So wherever you need to navigate a user to another route, just inject the <code>router</code> and use <code>navigateByUrl</code> method:</p> <pre><code>class MyComponent { constructor(router: Router) { this.router.navigateByUrl(...); } } </code></pre> <h3>navigate</h3> <p>There's another method on the router that you can use - <a href="https://angular.io/api/router/Router#navigate" rel="noreferrer">navigate</a>:</p> <pre><code>router.navigate(['/inbox/33/messages/44']) </code></pre> <h3>difference between the two</h3> <blockquote> <p>Using <code>router.navigateByUrl</code> is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas <code>router.navigate</code> creates a new URL by applying an array of passed-in commands, a patch, to the current URL.</p> <p>To see the difference clearly, imagine that the current URL is <code>'/inbox/11/messages/22(popup:compose)'</code>. </p> <p>With this URL, calling <code>router.navigateByUrl('/inbox/33/messages/44')</code> will result in <code>'/inbox/33/messages/44'</code>. But calling it with <code>router.navigate(['/inbox/33/messages/44'])</code> will result in <code>'/inbox/33/messages/44(popup:compose)'</code>.</p> </blockquote> <p>Read more in <a href="https://angular.io/api/router/Router" rel="noreferrer">the official docs</a>.</p>
29,274,501
R Markdown - changing font size and font type in html output
<p>I am using R Markdown in RStudio and the knit HTML option to create HTML output. However, the font used in the ouput for plain text blocks is rather small and I would like to change it to a differnt font and increase the font size. Can someone show an example how to set the output font - workable without a lot of knowledge in html?</p> <p>So far I tried at the top of my markdown document, but this doesn't work. </p> <pre><code>--- fontsize: 24pt --- </code></pre>
29,298,407
6
0
null
2015-03-26 09:04:48.213 UTC
32
2020-09-29 20:29:27.883 UTC
2015-03-27 01:52:45.877 UTC
null
559,676
null
1,823,746
null
1
79
r|knitr|r-markdown
222,109
<p>I think <code>fontsize:</code> command in YAML only works for LaTeX / pdf. <a href="https://groups.google.com/forum/#!topic/knitr/er7uocm4p5Q" rel="noreferrer">Apart</a>, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).</p> <p>Regarding appearance (different font types and colors), you can specify a <code>theme:</code>. See <a href="http://rmarkdown.rstudio.com/html_document_format.html" rel="noreferrer">Appearance and Style</a>.</p> <p>I guess, what you are looking for is your own <code>css.</code> Make a file called <code>style.css</code>, save it in the same folder as your <code>.Rmd</code> and include it in the YAML header:</p> <pre><code>--- output: html_document: css: style.css --- </code></pre> <p>In the css-file you define your font-type and size:</p> <pre><code>/* Whole document: */ body{ font-family: Helvetica; font-size: 16pt; } /* Headers */ h1,h2,h3,h4,h5,h6{ font-size: 24pt; } </code></pre>
40,720,733
Angular controller is not registered error
<p>I am new to Angular JS and I am using the 1.6 version of it.</p> <p>I have this <code>apptest.js</code> script:</p> <pre><code>var myApp = angular.module("myApp", []); (function(){ "use strict"; myApp.controller("productController", function($scope, $http) { $http.get('data/data.json').then(function(prd) { $scope.prd = prd.data; }); }); }); </code></pre> <p>And here my <code>data/data.json</code> data:</p> <pre><code>[ { "id":"1", "title":"20 Foot Equipment Trailer", "description":"2013 rainbow trailer 20 feet x 82 inch deck area, two 5,000 lb axels, electric brakes, two pull out ramps, break away box, spare tire.", "price":6000, "posted":"2015-10-24", "contact": { "name":"John Doe", "phone":"(555) 555-5555", "email":"[email protected]" }, "categories":[ "Vehicles", "Parts and Accessories" ], "image": "http://www.louisianasportsman.com/classifieds/pics/p1358549934434943.jpg", "views":213 } ] </code></pre> <p>Now here is my html page where I specified the ng-app and ng-controller:</p> <pre><code>&lt;body ng-app="myApp" ng-controller="productController"&gt; &lt;div class="row"&gt; &lt;nav class="navbar navbar-default"&gt; &lt;div class="container-fluid"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Brand&lt;/a&gt; &lt;/div&gt; &lt;!-- Collect the nav links, forms, and other content for toggling --&gt; &lt;div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Add &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;form class="navbar-form navbar-left"&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" placeholder="Search"&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- /.navbar-collapse --&gt; &lt;/div&gt;&lt;!-- /.container-fluid --&gt; &lt;/nav&gt; &lt;div class="col-sm-4" ng-repeat="product in prd"&gt; &lt;div class="panel panel-primary"&gt; &lt;div class="panel-heading"&gt;{{product.title}}&lt;/div&gt; &lt;div class="panel-body"&gt; &lt;img ng-src="{{product.image}}"&gt; {{product.price | currency}} {{product.description}} &lt;/div&gt; &lt;div class="panel-footer"&gt;a&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="angular/angular.js"&gt;&lt;/script&gt; &lt;script src="scripts/appTest.js"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p>I am still getting the following error which is new for me:</p> <blockquote> <p>angular.js:14239 Error: [$controller:ctrlreg] The controller with the name 'productController' is not registered. <a href="http://errors.angularjs.org/1.6.0-rc.0/" rel="noreferrer">http://errors.angularjs.org/1.6.0-rc.0/</a>$controller/ctrlreg?p0=productController</p> </blockquote> <p>Any help is appreciated.</p>
40,720,793
8
4
null
2016-11-21 12:55:08.113 UTC
2
2020-05-21 22:36:19.243 UTC
2016-11-21 13:01:53.05 UTC
null
4,927,984
null
3,922,727
null
1
27
angularjs
99,761
<p>Its because of your <code>Immediately Invoked Function Expression</code>. you have to change it like below :</p> <pre><code>var myApp = angular.module("myApp", []); (function(app){ "use strict"; app.controller("productController", function($scope, $http){ $http.get('data/data.json').then(function(prd){ $scope.prd = prd.data; }); }); })(myApp); </code></pre>
28,246,788
Convert yyyy-MM-dd to MM/dd/yyyy in javascript
<p>This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.</p> <p>Incoming date could be of following format</p> <pre><code>2015-01-25 or nil </code></pre> <p>Output date shoud be</p> <pre><code>01/25/2015 or nil </code></pre> <p>I was trying one from the following link <a href="https://stackoverflow.com/questions/25551322/convert-date-yyyy-mm-dd-to-mm-dd-yyyy">Convert Date yyyy/mm/dd to MM dd yyyy</a> but couldn't make it work.</p> <p>Thanks for any help.</p> <p>Forgot to mention, the incoming date which comes as nil is of the following format in an xml file</p> <pre><code>&lt;Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/&gt; </code></pre> <p>So if I get the above format the output should be just be nil</p>
28,246,873
7
0
null
2015-01-31 00:24:17.103 UTC
3
2021-07-28 06:57:37.51 UTC
2017-05-23 12:26:05.15 UTC
null
-1
null
1,718,932
null
1
6
javascript
43,931
<p>The date <code>toString</code> function has some support for formatting. See <a href="https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript">this</a>. And you also want to handle the undefined case which I took from <a href="https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript">here</a>. So, for your case you can just do this:</p> <pre><code>function format(inputDate) { var date = new Date(inputDate); if (!isNaN(date.getTime())) { // Months use 0 index. return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear(); } } </code></pre> <p>EDIT: Addressing the comment</p> <p>If the padding is important you just need to add that in:</p> <pre><code>var d = date.getDate().toString(); (d[1]?d:"0"+d[0]) </code></pre> <p>I've made an update to the <a href="http://jsfiddle.net/z64ezjkc/" rel="noreferrer">fiddle</a></p>
67,615,278
get_video_info YouTube endpoint suddenly returning 404 not found
<p><a href="https://www.youtube.com/get_video_info?video_id=%7BvideoId%7D" rel="noreferrer">https://www.youtube.com/get_video_info?video_id={videoId}</a> is throwing</p> <blockquote> <p>Response status code does not indicate success: 404 (Not Found).</p> </blockquote>
67,629,882
10
2
null
2021-05-20 06:48:54.477 UTC
16
2021-11-25 00:43:19.36 UTC
2021-06-04 10:29:54.143 UTC
null
5,228,202
null
5,087,902
null
1
19
google-api|youtube|youtube-api
18,863
<p>EDIT: I found this can work. I don't why. But it really works.</p> <p><a href="https://www.youtube.com/get_video_info?video_id=onz2k4zoLjQ&amp;eurl=https%3A%2F%2Fyoutube.googleapis.com%2Fv%2Fonz2k4zoLjQ&amp;html5=1&amp;c=TVHTML5&amp;cver=6.20180913" rel="nofollow noreferrer">https://www.youtube.com/get_video_info?video_id=onz2k4zoLjQ&amp;eurl=https%3A%2F%2Fyoutube.googleapis.com%2Fv%2Fonz2k4zoLjQ&amp;html5=1&amp;c=TVHTML5&amp;cver=6.20180913</a></p> <hr /> <p>You can add <code>&amp;html5=1</code> in the url to fix it.</p>
40,005,233
How can I update global packages in Yarn?
<p>I tried some possible CLI commands but none seem to actually update the packages installed with <code>yarn global add</code>.</p> <p><code>yarn global upgrade</code> &amp; <code>yarn upgrade global</code> both don't work correctly. Is there a way of upgrading global packages?</p>
46,627,971
6
1
null
2016-10-12 17:53:26.843 UTC
12
2020-07-18 21:03:27.503 UTC
2016-12-19 18:33:49.93 UTC
null
769,871
null
3,029,016
null
1
78
javascript|node.js|yarnpkg
39,644
<h3>TL;DR:</h3> <p>As <a href="https://stackoverflow.com/a/47022750/5353461">webjay says</a>, you simply:</p> <pre><code>yarn global upgrade </code></pre> <p>in <code>yarn</code> version 1.2.1 onwards.</p> <p>For earlier versions:</p> <pre><code>(cd ~/.config/yarn/global &amp;&amp; yarn upgrade) </code></pre> <h3>Checking and repairing</h3> <p>Sadly, there is currently no <code>yarn global check</code>.</p> <p>You can run <code>yarn global add --force</code> to reinstall all packages.</p> <p>To <code>check</code> global packages, you can treat <code>~/.config/yarn/global/</code> like a local package, since:</p> <ul> <li><code>~/.config/yarn/global/package.json</code> has dependencies for all global packages</li> <li><code>~/.config/yarn/global/node_modules</code> contains all the global packages. </li> </ul> <p><strong>Check all global packages, and reinstall only if an error is found:</strong></p> <pre><code>$ (cd ~/.config/yarn/global &amp;&amp; yarn check || yarn install --force) </code></pre>
21,956,683
Enable access control on simple HTTP server
<p>I have the following shell script for a very simple HTTP server:</p> <pre><code>#!/bin/sh echo "Serving at http://localhost:3000" python -m SimpleHTTPServer 3000 </code></pre> <p>I was wondering how I can enable or add <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="noreferrer">a CORS header</a> like <code>Access-Control-Allow-Origin: *</code> to this server?</p>
21,957,017
6
1
null
2014-02-22 16:00:26.76 UTC
47
2022-03-30 10:18:19.243 UTC
2018-09-12 13:39:58.663 UTC
null
216,074
null
1,574,486
null
1
164
python|cors|simplehttpserver
117,965
<p>Unfortunately, the simple HTTP server is really that simple that it does not allow any customization, especially not for the headers it sends. You can however create a simple HTTP server yourself, using most of <code>SimpleHTTPRequestHandler</code>, and just add that desired header.</p> <p>For that, simply create a file <code>simple-cors-http-server.py</code> (or whatever) and, depending on the Python version you are using, put one of the following codes inside.</p> <p>Then you can do <code>python simple-cors-http-server.py</code> and it will launch your modified server which will set the CORS header for every response.</p> <p>With the <a href="https://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer">shebang</a> at the top, make the file executable and put it into your PATH, and you can just run it using <code>simple-cors-http-server.py</code> too.</p> <h2>Python 3 solution</h2> <p>Python 3 uses <a href="https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler" rel="noreferrer"><code>SimpleHTTPRequestHandler</code></a> and <a href="https://docs.python.org/3/library/http.server.html#http.server.HTTPServer" rel="noreferrer"><code>HTTPServer</code></a> from the <a href="https://docs.python.org/3/library/http.server.html" rel="noreferrer"><code>http.server</code> module</a> to run the server:</p> <pre><code>#!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test import sys class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) &gt; 1 else 8000) </code></pre> <h2>Python 2 solution</h2> <p>Python 2 uses <a href="https://docs.python.org/2/library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler" rel="noreferrer"><code>SimpleHTTPServer.SimpleHTTPRequestHandler</code></a> and the <a href="https://docs.python.org/2/library/basehttpserver.html" rel="noreferrer"><code>BaseHTTPServer</code> module</a> to run the server.</p> <pre><code>#!/usr/bin/env python2 from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer) </code></pre> <h2>Python 2 &amp; 3 solution</h2> <p>If you need compatibility for both Python 3 and Python 2, you could use this polyglot script that works in both versions. It first tries to import from the Python 3 locations, and otherwise falls back to Python 2:</p> <pre><code>#!/usr/bin/env python try: # Python 3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig import sys def test (*args): test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) &gt; 1 else 8000) except ImportError: # Python 2 from BaseHTTPServer import HTTPServer, test from SimpleHTTPServer import SimpleHTTPRequestHandler class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer) </code></pre>
25,785,579
Does Angular routing template url support *.cshtml files in ASP.Net MVC 5 Project?
<p>I am working on a MVC 5 project. When I use a html page at my views, it load that page but when I use .cshtml page it is not loading the view. The Blank page appears.</p> <pre><code>$urlRouterProvider .otherwise('/app/dashboard'); $stateProvider .state('app', { abstract: true, url: '/app', templateUrl: 'tpl/app.html' }) .state('app.dashboard', { url: '/dashboard', templateUrl: 'tpl/app_dashboard.html' }) </code></pre> <p>Please guide me how to use cshtml file or the best way to do it.</p>
35,066,142
4
1
null
2014-09-11 10:52:42.503 UTC
11
2018-06-29 11:28:04.08 UTC
2018-06-21 16:22:38.56 UTC
null
1,249,713
null
2,746,600
null
1
25
javascript|c#|angularjs|asp.net-mvc|razor
26,868
<h2>Yes, you can.</h2> <p>Adding a similar answer to <a href="https://stackoverflow.com/a/27182836/1476885">Yasser's</a>, but using ngRoute:</p> <p>1) Instead of referencing your partial HTML, you need to reference a Controller/Action to your ASP.NET MVC app.</p> <pre><code>.when('/order', { templateUrl: '/Order/Create', controller: 'ngOrderController' // Angular Controller }) </code></pre> <p>2) Your ASP.NET MVC will return a .cshtml view:</p> <pre><code>public class OrderController : Controller { public ActionResult Create() { var model = new MyModel(); model.Test= "xyz"; return View("MyView", model); } } </code></pre> <p>3) Your MyView.cshtml will mix Razor and Angular. Attention: as its a partial for your Angular app, set the layout as null.</p> <pre><code>@model MyProject.MyModel @{ Layout = null; } &lt;h1&gt;{{ Test }}&lt;/h1&gt; &lt;!-- Angular --&gt; &lt;h1&gt;Model.Test&lt;/h1&gt; &lt;!-- Razor --&gt; </code></pre>
20,834,648
How do I rebase a chain of local git branches?
<p>Suppose I have a chain of local git branches, like this:</p> <pre><code> master branch1 branch2 | | | o----o----o----A----B----C----D </code></pre> <p>I pull in an upstream change onto the master branch:</p> <pre><code> branch1 branch2 | | A----B----C----D / o----o----o----o | master </code></pre> <p>Now I rebase branch1, giving me this:</p> <pre><code> branch2 | A----B----C----D / o----o----o----o----A'---B' | | master branch1 </code></pre> <p>Note that because of rebasing branch1, commits A and B have been rewritten as A' and B'.</p> <p>Here's my problem: now I want to rebase branch2. The obvious syntax is <code>git rebase branch1 branch2</code>, but that definitely does not work. What I want it to do is just reapply C and D on top of branch1, but instead it tries to reconcile A and A' and it considers them conflicting.</p> <p>This does work:</p> <pre><code>git rebase --onto branch1 branch2^^ branch2 </code></pre> <p>This assumes I know that branch2 has exactly 2 commits beyond the previous branch1 ref.</p> <p>Since <code>git rebase --onto</code> works, is there a 1-line git command that will rebase branch2 on top of a newly-rebased branch1, in a way that I don't have to know exactly how many commits were part of branch2? (I want to specify some magic ref instead of branch2^^ for the middle argument.)</p> <p>Or is there some other approach I'm overlooking?</p> <p>I would be most interested in a solution that scales well to extreme cases, not just two branches - suppose I've got something more like 5 local branches, all chained on one another, and I want to rebase all of them together.</p>
20,836,211
5
1
null
2013-12-30 06:45:34.11 UTC
9
2021-10-24 18:10:28.95 UTC
null
null
null
null
7,193
null
1
29
git|rebase
4,182
<p>One-line:</p> <pre><code>git rebase --onto branch1 branch1tmp branch2 </code></pre> <p>That supposes to make a <code>branch1tmp</code> on <code>branch1</code> <em>before</em> rebasing <code>branch1</code>.</p> <pre><code>git checkout branch1 git branch branch1tmp git rebase master git rebase --onto branch1 branch1tmp branch2 </code></pre> <hr> <p>That being said, check what <code>ORIG_HEAD</code> references.<br> From <a href="http://git-scm.com/docs/git-rebase">git rebase man page</a>:</p> <blockquote> <p><code>ORIG_HEAD</code> is set to point at the tip of the branch before the reset. </p> </blockquote> <p>So check if this would work (and scale better):</p> <pre><code>git checkout branch1 git rebase master git rebase --onto branch1 ORIG_HEAD branch2 git rebase --onto branch2 ORIG_HEAD branch3 ... </code></pre>
29,360,959
Passing parameter from controller to jsp in spring
<p>I have a controller method as follow.</p> <pre><code>@RequestMapping("/edit/{jobId}") public String editJob(@PathVariable("jobId") Integer jobId,Model model){ model.addAttribute("id",jobId); return "edit"; } </code></pre> <p>in which i am passing the jobId to get the instance of the job by id and returning "edit" string so that it maps to edit.jsp as per the InternalResourceViewResolver. But when i click on the link it goes to /edit/44 in which case 44 would be the id of the job for which the edit link belongs to. Finally i got the error stating no resource found.</p> <p>home.jsp</p> <pre><code>&lt;%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; &lt;%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%&gt; &lt;%@ page session="false"%&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="&lt;c:url value="/resources/css/style.css"/&gt;" /&gt; &lt;link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /&gt; &lt;title&gt;Home&lt;/title&gt; &lt;/head&gt; &lt;body id="main"&gt; &lt;div class="container"&gt; &lt;h2 style="color:white"&gt;All posted jobs&lt;/h2&gt; &lt;c:if test="${empty jobList}"&gt; &lt;h6&gt;No Job Post Yet&lt;/h6&gt; &lt;/c:if&gt; &lt;c:if test="${!empty jobList}"&gt; &lt;c:forEach items="${jobList}" var="job"&gt; &lt;div class="panel panel-info"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;${job.title }&lt;/h3&gt; &lt;/div&gt; &lt;div class="panel-body"&gt;${job.description }&lt;/div&gt; &lt;div class="panel-footer"&gt; &lt;a id="link" href="delete/${job.id }"&gt;Delete&lt;/a&gt; &lt;a id="link" href="edit/${job.id}"&gt;Edit&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/c:forEach&gt; &lt;/c:if&gt; &lt;section&gt; &lt;form:form method="post" action="add" modelAttribute="job" class="form-horizontal"&gt; &lt;div class="form-group" id="addForm"&gt; &lt;form:label class="control-label" path="title"&gt;Title:&lt;/form:label&gt; &lt;form:input class="form-control" path="title"/&gt; &lt;form:label class="control-label" path="description"&gt;Description&lt;/form:label&gt; &lt;form:textarea class="form-control" rows="5" path="description" /&gt; &lt;button class="btn btn-success"&gt; &lt;span class="glyphicon glyphicon-plus-sign"&gt;&lt;/span&gt; Add a Job &lt;/button&gt; &lt;/div&gt; &lt;a id="addJob" href="add"&gt;+&lt;/a&gt; &lt;/form:form&gt; &lt;/section&gt; &lt;/div&gt; </code></pre> <p> </p> <p>JobController.java</p> <pre><code>package com.job.src; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.job.src.model.Job; import com.job.src.services.JobService; @Controller public class JobController { @Autowired private JobService jobService; @RequestMapping(value= "/") public String listJobs(Map&lt;String,Object&gt; map){ map.put("job", new Job()); map.put("jobList", jobService.listJobs()); return "home"; } @RequestMapping(value= "/add", method=RequestMethod.POST) public String addJob(Job job){ jobService.addJob(job); return "redirect:/"; } @RequestMapping("/delete/{jobId}") public String deleteJob(@PathVariable("jobId") Integer jobId){ jobService.removeJob(jobId); return "redirect:/"; } @RequestMapping("/edit/{jobId}") public String editJob(@PathVariable("jobId") Integer jobId,Model model){ model.addAttribute("id",jobId); return "edit"; } } </code></pre> <p>edit.jsp</p> <pre><code>&lt;%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; &lt;%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%&gt; &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="&lt;c:url value="/resources/css/style.css"/&gt;" /&gt; &lt;link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form:form method="post" action="editSuccess" modelAttribute="job" class="form-horizontal"&gt; &lt;div class="form-group" id="addForm"&gt; &lt;form:label class="control-label" path="title"&gt;Title: &lt;/form:label&gt; &lt;form:input class="form-control" path="title" /&gt; &lt;form:label class="control-label" path="description"&gt;Description&lt;/form:label&gt; &lt;form:textarea class="form-control" rows="5" path="description" /&gt; &lt;button class="btn btn-success"&gt; &lt;span class="glyphicon glyphicon-plus-sign"&gt;&lt;/span&gt; Add a Job &lt;/button&gt; &lt;/div&gt; &lt;/form:form&gt; </code></pre> <p> </p>
29,361,098
1
2
null
2015-03-31 05:05:26.387 UTC
null
2015-03-31 05:20:44.937 UTC
2015-03-31 05:11:57.87 UTC
null
3,244,185
null
3,476,492
null
1
7
java|spring|jsp|view|controller
38,976
<p>In <code>editJob</code> method your are returning only id of job with model attribute to <code>edit.jsp</code>. But actually on edit.jsp page you need job object so you need to get job object by id add it as model attribute.</p> <pre><code>@RequestMapping("/edit/{jobId}") public String editJob(@PathVariable("jobId") Integer jobId,Model model){ //model.addAttribute("id",jobId); this is wrong Job job = jobService.getJobById(jobId); //write method in jobservice to get job by id i.e. getJobById(Integer jobId); model.addAttribute("job",job) return "edit"; } </code></pre>
36,519,974
Can not deserialize instance of java.util.HashMap out of START_ARRAY token
<p>I am facing issue while parsing JSON using jackson-core-2.7.3.jar You can get them from here <a href="http://repo1.maven.org/maven2/com/fasterxml/jackson/core/" rel="noreferrer">http://repo1.maven.org/maven2/com/fasterxml/jackson/core/</a></p> <p>My JSON File is</p> <pre><code>[ { "Name": "System Idle Process", "CreationDate": "20160409121836.675345+330" }, { "Name": "System", "CreationDate": "20160409121836.675345+330" }, { "Name": "smss.exe", "CreationDate": "20160409121836.684966+330" } ] </code></pre> <p>and the Java Code is by which I am trying to parse this is</p> <pre><code>byte[] mapData = Files.readAllBytes(Paths.get("process.txt")); Map&lt;String,String&gt; myMap = new HashMap&lt;String, String&gt;(); ObjectMapper objectMapper=new ObjectMapper(); myMap = objectMapper.readValue(mapData, HashMap.class); System.out.println("Map is: "+myMap); </code></pre> <p>But upon execution I am getting the error</p> <pre><code>com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token at [Source: [B@34ce8af7; line: 1, column: 1] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:216) at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:873) at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:869) at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:874) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:337) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2872) </code></pre> <p>I have tried searching over stackoverflow but couldnot find a matchable solution to this type of JSON.</p> <p>Any help would be appreciated.</p> <blockquote> <p>NOTE: This <code>JSON</code> mentioned here is different a <code>JSON</code> without <code>Key</code> , for the first element it has value directly and inside that value it has <code>key:value</code>pair. I am not sure how do I access <code>key:value</code> pair which is inside a value.</p> </blockquote>
36,520,079
6
3
null
2016-04-09 16:58:51.983 UTC
2
2021-08-07 23:57:06.76 UTC
2016-04-09 17:44:27.25 UTC
null
4,501,480
null
1,624,917
null
1
27
java|json|jackson
87,047
<p>Create a simple <code>pojo</code> Class First</p> <pre><code>class MyClass { @JsonProperty private String Name; @JsonProperty private String CreationDate; } </code></pre> <p>and use this code...</p> <pre><code>byte[] mapData = Files.readAllBytes(Paths.get("process.txt")); ObjectMapper objectMapper=new ObjectMapper(); //add this line objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); List&lt;MyClass&gt; myObjects = mapper.readValue(mapData , new TypeReference&lt;List&lt;MyClass&gt;&gt;(){}); </code></pre> <p>or</p> <pre><code>byte[] mapData = Files.readAllBytes(Paths.get("process.txt")); ObjectMapper objectMapper=new ObjectMapper(); //add this line objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); List&lt;MyClass&gt; myObjects = mapper.readValue(mapData , mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class)); </code></pre> <p><code>myObjects</code> will contains the <code>List</code> of <code>MyClass</code>. Now you can access this list as per your requirement.</p>
36,328,422
Getting a loading wrapper properties error in Android
<p>I am getting the following error :</p> <pre><code>'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'. No value with key 'distributionUrl' specified in wrapper properties file 'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'. </code></pre>
36,328,580
11
3
null
2016-03-31 08:46:34.64 UTC
2
2022-01-31 10:24:11.567 UTC
2016-03-31 09:10:52.353 UTC
null
5,653,461
null
6,138,919
null
1
6
android|android-gradle-plugin
42,205
<p>It seems like the <code>distributionUrl</code> is missing in <strong>gradle-wrapper.properties</strong> of your project. It is shown below:</p> <pre><code>distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip </code></pre>
36,492,084
How to convert an Image to base64 string in java?
<p>It may be a duplicate but i am facing some problem to convert the image into <code>Base64</code> for sending it for <code>Http Post</code>. I have tried this code but it gave me wrong encoded string.</p> <pre><code> public static void main(String[] args) { File f = new File("C:/Users/SETU BASAK/Desktop/a.jpg"); String encodstring = encodeFileToBase64Binary(f); System.out.println(encodstring); } private static String encodeFileToBase64Binary(File file){ String encodedfile = null; try { FileInputStream fileInputStreamReader = new FileInputStream(file); byte[] bytes = new byte[(int)file.length()]; fileInputStreamReader.read(bytes); encodedfile = Base64.encodeBase64(bytes).toString(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return encodedfile; } </code></pre> <p><strong>Output:</strong> [B@677327b6 <br> <br> But i converted this same image into <code>Base64</code> in many online encoders and they all gave the correct big Base64 string.</p> <p><strong>Edit:</strong> How is it a duplicate?? The link which is duplicate of mine doesn't give me solution of converting the string what i wanted.</p> <p><strong>What am i missing here??</strong> </p>
36,492,265
3
3
null
2016-04-08 05:19:00.58 UTC
10
2016-11-23 12:06:37.653 UTC
2016-04-08 05:47:09.087 UTC
null
4,299,527
null
4,299,527
null
1
31
java|image|base64
134,367
<p>The problem is that you are returning the <code>toString()</code> of the call to <code>Base64.encodeBase64(bytes)</code> which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.</p> <p>Instead, you should do:</p> <pre><code>encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8"); </code></pre>
4,243,089
RoR - MD5 generation
<p>How can I encrypt a string with MD5 in Rails 3.0 ? <code>pass = MD5.hexdigest(pass)</code> in a model yields <code>uninitialized constant MyModel::MD5</code></p>
4,243,129
1
2
null
2010-11-22 07:10:03.553 UTC
16
2015-09-24 15:01:35.997 UTC
2012-06-22 05:18:54.967 UTC
null
174,261
null
174,261
null
1
82
ruby|hash|md5|digest
64,477
<p>You can use <code>Digest::MD5</code> from the Ruby standard library for this.</p> <pre><code>irb(main):001:0&gt; require 'digest/md5' =&gt; true irb(main):002:0&gt; Digest::MD5.hexdigest('foobar') =&gt; "3858f62230ac3c915f300c664312c63f" </code></pre> <p>And one more thing: MD5 is a hash algorithm. You don't "encrypt" anything with a hash algorithm.</p>
14,095,018
SetFocusable method or Focusing Components Java
<p>I came across this code:</p> <pre><code>public class Board extends JPanel implements ActionListener{ public Board() { setFocusable(true); } } </code></pre> <p>What exactly does <code>setFocusable(true)</code> do to the JPanel object? What is the notion of a component being focused?</p> <p>Based on the Java API, this method is located in the Component class, the super class of JPanel. The method description states &quot;Sets the focusable state of this Component to the specified value. This value overrides the Component's default focusability.&quot; This description sounds way too technical and high-level jargon for me (who just finished a Java class in the summer). Sometimes, I think these method descriptions were not written for all people with different levels of knowledge of Java. May someone explain the method description in layman's terms?</p>
14,095,174
3
0
null
2012-12-30 21:49:41.753 UTC
2
2021-10-23 21:58:39.38 UTC
2021-10-23 07:55:50.337 UTC
null
12,335,762
null
1,432,756
null
1
5
java|swing|methods|jpanel|focusable
45,427
<p>The <code>focusable</code> flag indicates whether a component can gain the focus if it is requested to do so. The JPanel component is focusable by default, so nothing will be changed when you set it to <code>true</code>.</p> <p>A component that is not focusable can not gain the focus.</p> <p><strong>An example</strong></p> <p>Let's say you have implemented a dialog with several text fields and you want the user to enter some text. When the user starts typing, one text field needs to have the focus of the application: it will be the field that receives the keyboard input.</p> <p>When you implement a focus traversal (a convenient way for the user to jump from one text field to the next, for example by using the <code>tab</code> button), the user can "jump" to the next text field. The application will try to gain the focus for the next field to prepare it to receive text. When the next field is not focusable, this request will be denied and the next field will be tested. For example, you wouldn't want a label to get the focus because you cannot enter text into it.</p> <p>The focusable flag is set to <code>true</code> by default in the <code>Component</code> class. When you construct an object derived from the <code>Component</code> class (for example, when you construct your <code>JPanel</code>), the constructor of the <code>Component</code> class is called and sets the default focusable flag to <code>true</code>. </p> <p>Derived classes that wish to override this default can call the method <code>setFocusable</code> to change that default, like you did in your example.</p> <p>Note that setFocusable does not set the focus in itself, it just gives the ability to potentially gain the focus to the component. </p>
34,670,430
Slick.js how to align images in center of carousel?
<p>By default, images align on the left. Using the setting <code>centerMode: true</code> the images are aligned a few pixels from the left, and the edge of the next image is peeking from the right side, as shown:</p> <p><a href="https://i.stack.imgur.com/G5paU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/G5paU.png" alt="enter image description here"></a></p> <p>These are the settings used:</p> <pre><code>for (var i in data.image_set) { sc.append('&lt;div&gt;&lt;img src="' + data.image_set[i].image + '" height="' + data.image_set[i].height + '" width="' + data.image_set[i].width + '"&gt;&lt;/div&gt;'); } sc.slick({ dots: true, speed: 150, centerMode: true }); </code></pre> <p>I would like to have the slider display only one image at the center, and optionally have the previous and next images partially visible to the left and right sides respectively. How can this be accomplished?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.sc').slick({ dots: true, speed: 150, centerMode: true }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.sc img { height: calc(50vh - 100px); width: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick-theme.min.css"&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js"&gt;&lt;/script&gt; &lt;div class="sc"&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/I152rUr6ZBih.png?Signature=YFF9BB8dlAe7okzBHnRLWgYmFI8%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="900" width="674"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/HvAQty35hkNv.png?Signature=8HQKRBefUe%2B4f3sKX1vag78dCbQ%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/A6CZ5y6EUmNg.png?Signature=bsArQ0sX8o9mtgIISwtFPW2hzSM%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/EGO36t7pzBWp.png?Signature=txW6IP9KJ8bB0S%2B9QCYQTEy6Q%2BQ%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
34,670,711
3
4
null
2016-01-08 05:58:14.527 UTC
6
2020-05-21 23:38:28.91 UTC
2016-01-08 06:19:56.237 UTC
null
2,032,598
null
4,698,922
null
1
13
javascript|css|carousel|slick.js
45,389
<p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.sc').slick({ dots: true, speed: 150, centerMode: true }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.sc img { height: calc(50vh - 100px); width: auto; margin: 0 auto; /* it centers any block level element */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick-theme.min.css"&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js"&gt;&lt;/script&gt; &lt;div class="sc"&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/I152rUr6ZBih.png?Signature=YFF9BB8dlAe7okzBHnRLWgYmFI8%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="900" width="674"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/HvAQty35hkNv.png?Signature=8HQKRBefUe%2B4f3sKX1vag78dCbQ%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/A6CZ5y6EUmNg.png?Signature=bsArQ0sX8o9mtgIISwtFPW2hzSM%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="https://lespider-ca.s3.amazonaws.com:443/EGO36t7pzBWp.png?Signature=txW6IP9KJ8bB0S%2B9QCYQTEy6Q%2BQ%3D&amp;amp;Expires=1452236979&amp;amp;AWSAccessKeyId=AKIAIS4C7GGEGJPLLSMA" height="673" width="900"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
25,346,058
Removing list of words from a string
<p>I have a list of stopwords. And I have a search string. I want to remove the words from the string. </p> <p>As an example: </p> <pre><code>stopwords=['what','who','is','a','at','is','he'] query='What is hello' </code></pre> <p>Now the code should strip 'What' and 'is'. However in my case it strips 'a', as well as 'at'. I have given my code below. What could I be doing wrong? </p> <pre><code>for word in stopwords: if word in query: print word query=query.replace(word,"") </code></pre> <p>If the input query is "What is Hello", I get the output as:<br> <code>wht s llo</code></p> <p>Why does this happen?</p>
25,346,119
6
3
null
2014-08-17 03:23:03.567 UTC
13
2021-05-06 12:48:28.493 UTC
2014-08-17 03:43:42.8 UTC
null
3,558,960
null
1,453,258
null
1
43
python|string
128,705
<p>This is one way to do it:</p> <pre><code>query = 'What is hello' stopwords = ['what', 'who', 'is', 'a', 'at', 'is', 'he'] querywords = query.split() resultwords = [word for word in querywords if word.lower() not in stopwords] result = ' '.join(resultwords) print(result) </code></pre> <p>I noticed that you want to also remove a word if its lower-case variant is in the list, so I've added a call to <code>lower()</code> in the condition check.</p>
31,634,962
"Narrowing conversion from 'int' to 'char' inside { }" for legal values when cross compiling
<p>I have a C++ project that I compile both using <code>g++</code> on my machine (compiling to "host") and to an ARM processor using a cross compiler (in my case <code>arm-cortex_a8-linux-gnueabi-g++</code>). I am in the process of converting to C++0x/11 standart and there is an error I get when compiling initialization list, which I was able to reproduce in the following snippet:</p> <pre><code>int main(void) { char c[1] = {-108}; } </code></pre> <p>This program is seemingly correct as <code>-108</code> is a legal value for a <code>char</code>. Compiling this with <code>g++</code> yields no error with the following command line:</p> <pre><code>g++ example.cc -std=c++0x </code></pre> <p>However, when I compile with the cross-compiler, like so:</p> <pre><code>arm-cortex_a8-linux-gnueabi-g++ example.cc -std=c++0x </code></pre> <p>I get the following error:</p> <pre><code>example.cc: In function 'int main()': example.cc:2:22: error: narrowing conversion of '-0x0000000000000006c' from 'int' to 'char' inside { } [-fpermissive] </code></pre> <p>Since the value is legal, this seems like a bug. Can you explain why I get this error and what to do to solve it?</p> <p><strong>Edit</strong>: note that using positive values (e.g., <code>108</code>) is legal and does not result in an error on both compilers.</p>
31,635,045
5
8
null
2015-07-26 08:16:17.41 UTC
null
2022-01-21 19:41:15.763 UTC
2015-07-26 08:21:43.993 UTC
null
2,022,010
null
2,022,010
null
1
19
c++|linux|c++11|cross-compiling
45,165
<p>When you declare a variable as <code>char</code>, it's implementation-dependent whether it's signed or unsigned. If you need to be able to store negative values, you should declare it <code>signed</code> explicitly, rather than relying on the implementation-defined default.</p> <pre><code>signed char c[1] = { -108 }; </code></pre>
39,306,688
Any way to install app to iPhone 4 with Xcode 8 beta?
<p>When trying to run app on my iPhone 4, Xcode 8 beta shows me this message:</p> <p><code>This iPhone 4 is running iOS 7.1.2 (11D257), which may not be supported by this version of Xcode.</code></p> <p>My app must support iOS 7. I read many answers they say that app build with Xcode 8 beta still can run on iOS 7 devices. So is there a way to install app to iPhone 4 with Xcode 8 beta? Like building the app first, then use a command line to install <code>.app</code> file to the iPhone?</p>
39,449,405
2
3
null
2016-09-03 12:05:02.99 UTC
13
2017-08-01 19:27:27.613 UTC
null
null
null
null
4,405,051
null
1
21
ios|xcode|ios7
8,082
<p>Actually, there is a way. You just need to copy DeviceSupport folder for iOS 7.1 from Xcode 7 to the new one. It's located in:</p> <p><code>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1</code></p> <p>I've tried it and it works.</p> <p>EDIT: If you don't have the 7.1 files anymore, you can find them <a href="https://drive.google.com/open?id=0B3AdrmeePh3MRlU2bUphYXlBa1E" rel="noreferrer">here</a>.</p>
19,966,864
What kind of Android application will require android.permission.READ_PHONE_STATE permission?
<p>I have seen some Android apps on my phone require this android.permission.READ_PHONE_STATE permission. I don't know if I could trust them. I know this permission will give the app access to many information. I'm particularly interested in what functionality in an Android app normally require the information like <code>DeviceId</code> , <code>SimSerialNumber</code>, <code>SubscriberId</code>?</p>
19,966,961
3
1
null
2013-11-13 23:52:58.55 UTC
3
2017-06-19 20:14:06.363 UTC
null
null
null
null
1,231,449
null
1
28
android|permissions|malware|android-permissions
27,438
<p>Phone state provides access to a lot of information about the phone. Usual usages will be for reading the IMEI of your phone and your phone number. This can be useful to identify you in their systems.</p> <p>It can also be needed if the application is made compatible for Android 1.5 or lower, because this permission didn't exist back then and is added automatically by the play store to those apps</p> <p>See also: <a href="https://android.stackexchange.com/questions/605/why-do-so-many-applications-require-permission-to-read-the-phone-state-and-ident">https://android.stackexchange.com/questions/605/why-do-so-many-applications-require-permission-to-read-the-phone-state-and-ident</a></p>
6,579,844
How does Zalgo text work?
<p>I've seen weirdly formatted text called Zalgo like below written on various forums. It's kind of annoying to look at, but it really bothers me because it undermines my notion of what a character is supposed to be. My understanding is that a character is supposed to move horizontally across a line and stay within a certain "container". Obviously the Zalgo text is moving vertically and doesn't seem to be restricted to any space. </p> <p>Is this a bug/flaw/exploit/hack in Unicode? Are these individual characters with weird properties? "What" is happening here?</p> <blockquote> <p><br></p> <p>H̡̫̤̤̣͉̤ͭ̓̓̇͗̎̀ơ̯̗̱̘̮͒̄̀̈ͤ̀͡w͓̲͙͖̥͉̹͋ͬ̊ͦ̂̀̚ ͎͉͖̌ͯͅͅd̳̘̿̃̔̏ͣ͂̉̕ŏ̖̙͋ͤ̊͗̓͟͜e͈͕̯̮̙̣͓͌ͭ̍̐̃͒s͙͔̺͇̗̱̿̊̇͞ ̸̤͓̞̱̫ͩͩ͑̋̀ͮͥͦ̊Z̆̊͊҉҉̠̱̦̩͕ą̟̹͈̺̹̋̅ͯĺ̡̘̹̻̩̩͋͘g̪͚͗ͬ͒o̢̖͇̬͍͇͓̔͋͊̓ ̢͈͙͂ͣ̏̿͐͂ͯ͠t̛͓̖̻̲ͤ̈ͣ͝e͋̄ͬ̽͜҉͚̭͇ͅx͎̬̠͇̌ͤ̓̂̓͐͐́͋͡ț̗̹̝̄̌̀ͧͩ̕͢ ̮̗̩̳̱̾w͎̭̤͍͇̰̄͗ͭ̃͗ͮ̐o̢̯̻̰̼͕̾ͣͬ̽̔̍͟ͅr̢̪͙͍̠̀ͅǩ̵̶̗̮̮ͪ́?̙͉̥̬͙̟̮͕ͤ̌͗ͩ̕͡ <br> <br> <br></p> </blockquote>
20,310,289
2
3
null
2011-07-05 08:30:37.943 UTC
296
2018-11-16 05:23:26.763 UTC
2017-03-08 00:02:22.417 UTC
null
7,659,995
null
357,024
null
1
723
html|unicode|zalgo
209,984
<p>The text uses combining characters, also known as combining marks. See section 2.11 of <a href="http://www.unicode.org/versions/Unicode6.2.0/ch02.pdf#page=36" rel="noreferrer"><em>Combining Characters in the Unicode Standard</em></a> (PDF).</p> <p>In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character</p> <p>So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).</p> <p>And you can mix “combining above” and “combining below” marks.</p> <p>The sample text in the question starts with:</p> <ul> <li><a href="http://www.fileformat.info/info/unicode/char/0048/index.htm" rel="noreferrer">LATIN CAPITAL LETTER H</a> - <code>&amp;#x48;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/036d/index.htm" rel="noreferrer">COMBINING LATIN SMALL LETTER T</a> - <code>&amp;#x36d;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0343/index.htm" rel="noreferrer">COMBINING GREEK KORONIS</a> - <code>&amp;#x343;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0313/index.htm" rel="noreferrer">COMBINING COMMA ABOVE</a> - <code>&amp;#x313;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0307/index.htm" rel="noreferrer">COMBINING DOT ABOVE</a> - <code>&amp;#x307;</code></li> </ul>
7,660,963
Downloading multiple files one by one using AsyncTask?
<p>I'm trying to download multiple files one by one (file is downloaded, we start downloading the next file). Using this method I can keep track of the files being downloaded. The problem is that I'm using the following code for executing a Task:</p> <pre><code> File file = null; for(int i=0; i&lt; videos.length; i++) { file = new File(root.getPath() + videos[i]); boolean exists = file.exists(); if(exists){ //tv.append("\n\n"+fileNames[i]+" already exists"); continue; } else { currentFile = videos[i]; new DownloadFileAsync().execute(videoURL+videos[i],videos[i]); } file = null; } </code></pre> <p>As you can see, I call new DownloadFileAsync().execute(videoURL+videos[i],videos[i]); in a loop which obviously start a task for each of the files and downloads them simultaneously. </p> <p><strong>My question is</strong>: How can I run execute the task for a specific file, check if it has been downloaded- if yes, proceed with next file by executing a task for it? </p>
7,661,095
3
1
null
2011-10-05 12:00:48.38 UTC
9
2015-07-24 12:04:43.51 UTC
null
null
null
null
967,232
null
1
5
android
26,114
<p>If I understand correctly, you do not want to download all the files at the same tim e(simultaneously) but one by one (serially). In order to do so build a String array with the URLs to download, and call <code>execute()</code> with that array.</p> <blockquote> <p>Example: Assuming that your <code>DownloadFileAsync</code> expects String as a parameter to it's <code>doInBackground method</code>, you would call to:</p> </blockquote> <pre><code>new DownloadFileAsync().execute(url1, url2, url3, url4, video1, video2, video3, video4); </code></pre>
7,418,548
css3 slideup slide down
<p>How do I style an element with css transitions so that it would slide up / down / left / right when hidden?</p> <pre><code>.hideUp { transition: .5s; display:none; } .hideLeft { transition: .5s; display:none; } </code></pre> <p>I want to add the class to an element and have it slide left and disappear. Thanks!</p>
7,419,121
3
0
null
2011-09-14 15:02:33.69 UTC
1
2011-09-14 15:40:55.087 UTC
null
null
null
null
663,447
null
1
13
css|css-transitions
40,454
<p>You can't use display:none with transitions. It will cause the transition to just jump from one state to the other without animating it.</p> <p>This fiddle uses top to move the element. It animates. <a href="http://jsfiddle.net/R8zca/4/" rel="noreferrer">http://jsfiddle.net/R8zca/4/</a></p> <p>This fiddle uses display:none. It doesn't animate. <a href="http://jsfiddle.net/R8zca/5/" rel="noreferrer">http://jsfiddle.net/R8zca/5/</a></p> <p>If you want to animate an element hiding you can use z-index, opacity, position or visibilty. Here's the list of animatable properties: <a href="http://www.w3.org/TR/css3-transitions/#animatable-properties-" rel="noreferrer">http://www.w3.org/TR/css3-transitions/#animatable-properties-</a></p>
7,023,590
Const field or get property
<p>What's the difference between the first and second definitions?</p> <pre><code>//1 private static string Mask { get { return "some text"; } } //2 private const string Mask = "some text"; </code></pre> <p>Which benefits has the first and the second approach?</p>
7,023,671
4
7
null
2011-08-11 09:26:31.903 UTC
null
2022-05-17 12:58:30.16 UTC
null
null
null
null
468,345
null
1
32
c#
28,954
<p>As long as they are private they will probably be optimized to more or less the same code. The re is another story if they are public and used from other assemblies.</p> <p><code>const</code> variables will be substitued/inlined in other assemblies using the <code>const</code> expression. That means that you need to recompile every assembly using the <code>const</code> expression if you change the expression. On the other hand the property solution will give you a method call overhead each time used.</p>
1,518,576
Unwanted padding-bottom of a div
<p>Here is my html:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt; &lt;div style="border:1px solid red; float:left; padding:0;"&gt; &lt;img src="xxx.jpg"&gt; &lt;/div&gt; </code></pre> <p>I don't know why the div contains some padding-bottom even I set padding:0.</p> <p>If I remove DOCTYPE, this problem will not occur. Are there any other ways to solve this problem without removing DOCTYPE?</p>
1,518,610
4
3
null
2009-10-05 07:00:02.53 UTC
10
2022-09-22 11:23:09.947 UTC
null
null
null
null
126,639
null
1
18
html|css
12,598
<pre><code>img { display:block; } </code></pre> <p>or</p> <pre><code>img { vertical-align:bottom; } </code></pre> <p>would work. Since images are inline and text is inline, user agents leave some space for descender characters ( y, q, g ). To un-do this effect for images, you can specify either of the styles above, though you might want to make the rules more specific so you don't target an image you don't want this to apply on.</p> <p>Demo: <a href="http://jsbin.com/obuxu" rel="noreferrer">http://jsbin.com/obuxu</a></p> <p>Another alternative as another poster has pointed out would be to set line-height to 0 on the parent element.</p> <p>Technical Explanation: <a href="https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps" rel="noreferrer">https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps</a></p>
1,496,793
RSA Encryption, getting bad length
<p>When calling the following function :</p> <pre><code>byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true); </code></pre> <p>I am now getting the error: bad length. </p> <p>With a smaller string it works, any ideas what the problem could be the string I am passing is under 200 characters.</p>
1,496,812
4
0
null
2009-09-30 08:35:30.32 UTC
18
2020-05-02 10:14:48.54 UTC
2009-09-30 08:42:57.08 UTC
null
2,525
null
41,543
null
1
67
c#|encryption|rsa|encryption-asymmetric
53,590
<p>RSA encryption is only mean for small amounts of data, the amount of data you can encrypt is dependent on the size of the key you are using, for example for 1024 bit RSA keys, and PKCS # 1 V1.5 padding, you can encrypt 117 bytes at most, with a 2048 RSA key, you can encrypt 245 bytes.</p> <p>There's a good reason for this, asymmetric encryption is computationally expensive. If you want to encrypt large amounts of data you should be using symmetric encryption. But what if you want non-repudiation? Well what you then do is use both. You create a symmetric key and exchange it using asymmetric encryption, then that safely exchanged symmetric key to encrypt your large amounts of data. This is what SSL and WS-Secure use underneath the covers.</p>
10,718,082
Show JQuery UI datepicker on input field click?
<p>OK maybe this is a trivial issue but I'm very interested to see if anyone has any ideas on this:</p> <p>I am using JQuery UI. I have an <code>&lt;input id="#myfield" type="text"&gt;</code> field and I call <code>$('#myfield').datepicker()</code>. The datepicker shows whenever the field gets focus. But the field is the first one in my form and is already in focus when it loads, so clicking on the field doesn't show it. Also, if I close the datepicker with the Esc key, then I can't open it again by clicking on the field, for the same reason: it's already in focus.</p> <p>I am aware that I could set the parameter <code>.datepicker({showOn: 'button'})</code> but I don't want the button. Is there any way to have the datepicker appear when the field gets focus OR is clicked when already in focus? I already tried <code>$('#myfield').click( function () { $(this).focus() } )</code> and it makes the datepicker open correctly when I click the input field, but then when I select a date it doesn't appear in the field.</p>
10,718,425
4
2
null
2012-05-23 10:28:09.797 UTC
1
2017-10-23 09:25:42.603 UTC
2012-05-23 10:33:19.713 UTC
null
1,223,744
null
1,223,744
null
1
8
jquery|jquery-ui|focus|datepicker|jquery-ui-datepicker
59,214
<p>Try this</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery-ui-1.8.17.custom.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $('#date1').datepicker(); $('#date1').focus(function(){ $('#date1').datepicker('show'); }); $('#date1').click(function(){ $('#date1').datepicker('show'); }); //$('#ui-datepicker-div').show(); $('#date1').datepicker('show'); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="text" name="date1" id='date1'&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
10,722,589
How to bind keyboard events to div elements?
<p>Is there a way to listen to keyboard events on a DIV element?</p> <p>My code:</p> <pre><code>​&lt;div id="div" style="height:50px" class="ui-widget-content"&gt;&lt;/div&gt; &lt;input id="input"&gt;​​​​​​​​​​​​​​ ​$('#div,#input').keyup(function(event){ console.log(event.keyCode); });​​​​​​ </code></pre> <p>Actually, the code triggers only for the input, can I handle it for the div?</p>
10,722,635
4
2
null
2012-05-23 14:57:13.947 UTC
11
2012-05-23 15:05:48.463 UTC
null
null
null
null
1,308,134
null
1
25
javascript|jquery
22,598
<p>You can add a <code>tabindex</code> in that <code>div</code> to catch keyboard events like this</p> <pre><code>&lt;div id="div" style="height:50px" class="ui-widget-content" tabindex="0"&gt;&lt;/div&gt; </code></pre> <p>Like <a href="https://stackoverflow.com/a/148444/344304">answered</a> here.</p> <p><a href="http://jsfiddle.net/joycse06/nt2Lb/" rel="noreferrer">Working Fiddle</a></p> <p><a href="http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html" rel="noreferrer">Reference</a></p>
7,214,781
Converting units in R
<p>I would like to convert from imperial units to metric and vice versa in R. How do I go about doing that?</p> <p>If there is no current way of doing that, how can I create a package that would?</p>
25,570,205
5
5
null
2011-08-27 13:14:26.953 UTC
8
2021-09-06 17:07:59.953 UTC
2011-11-11 01:02:26.53 UTC
null
168,868
null
915,498
null
1
41
r|units-of-measurement
23,407
<p>I know this is very late, but the package <code>measurements</code> has a function <code>conv_unit()</code> that may be what you're looking for. You enter the imperial value you have, what unit you're converting from (e.g. 'ft') and what you want to convert to (e.g. 'km'). It has a variety of different dimensions (not just length).</p>
7,249,396
How to clone a case class instance and change just one field in Scala?
<p>Let's say I have a case class that represents personas, people on different social networks. Instances of that class are fully immutable, and are held in immutable collections, to be eventually modified by an Akka actor.</p> <p>Now, I have a case class with many fields, and I receive a message that says I must update one of the fields, something like this:</p> <pre><code>case class Persona(serviceName : String, serviceId : String, sentMessages : Set[String]) // Somewhere deep in an actor val newPersona = Persona(existingPersona.serviceName, existingPersona.serviceId, existingPersona.sentMessages + newMessage) </code></pre> <p>Notice I have to specify all fields, even though only one changes. Is there a way to clone existingPersona and replace only one field, without specifying all the fields that don't change? Can I write that as a trait and use it for all my case classes?</p> <p>If Persona was a Map-like instance, it would be easy to do.</p>
7,249,439
5
1
null
2011-08-30 20:28:58.723 UTC
43
2019-04-19 16:18:43.453 UTC
null
null
null
null
7,355
null
1
231
scala
77,560
<p><code>case class</code>comes with a <code>copy</code> method that is dedicated exactly to this usage:</p> <pre><code>val newPersona = existingPersona.copy(sentMessages = existingPersona.sentMessages + newMessage) </code></pre>
7,604,966
Maximum and Minimum values for ints
<p>How do I represent minimum and maximum values for integers in Python? In Java, we have <code>Integer.MIN_VALUE</code> and <code>Integer.MAX_VALUE</code>.</p>
7,604,981
9
6
null
2011-09-30 01:01:06.63 UTC
162
2022-08-24 18:46:17.257 UTC
2022-04-10 12:22:53.083 UTC
null
365,102
null
139,909
null
1
1,102
python|integer
1,663,744
<h3>Python 3</h3> <p>In Python 3, this question doesn't apply. The plain <code>int</code> type is unbound.</p> <p>However, you might actually be looking for information about the current interpreter's <em><a href="http://en.wikipedia.org/wiki/Word_(computer_architecture)#Table_of_word_sizes" rel="noreferrer">word size</a></em>, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as <code>sys.maxsize</code>, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory <a href="https://docs.python.org/3.9/library/sys.html#sys.maxsize" rel="noreferrer">sequence</a>.</p> <p>Generally, the maximum value representable by an unsigned word will be <code>sys.maxsize * 2 + 1</code>, and the number of bits in a word will be <code>math.log2(sys.maxsize * 2 + 2)</code>. See <a href="https://stackoverflow.com/a/6918334/577088">this answer</a> for more information.</p> <h3>Python 2</h3> <p>In Python 2, the maximum value for plain <code>int</code> values is available as <code>sys.maxint</code>:</p> <pre><code>&gt;&gt;&gt; sys.maxint 9223372036854775807 </code></pre> <p>You can calculate the minimum value with <code>-sys.maxint - 1</code> as shown <a href="https://docs.python.org/2/library/sys.html#sys.maxint" rel="noreferrer">here</a>.</p> <p>Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.</p>
7,568,899
Does Selenium support headless browser testing?
<p>I'm looking at Selenium Server at the moment, and I don't seem to notice a driver that supports headless browser testing.</p> <p>Unless I'm mistaken, it doesn't support it. If you're on X, you can create a virtual framebuffer to hide the browser window, but that's not really a headless browser.</p> <p>Can anyone enlighten me? Does Selenium support headless browser testing?</p>
28,372,451
12
0
null
2011-09-27 12:12:11.08 UTC
16
2019-08-15 16:02:42.84 UTC
2016-04-21 10:25:09.12 UTC
null
617,450
null
656,334
null
1
73
unit-testing|selenium|selenium-webdriver|automated-tests|headless-browser
54,484
<p>you need not use PhantomJS as an alternative to Selenium. Selenium includes a PhantomJS webdriver class, which rides on the GhostDriver platform. Simply install the PhantomJS binary to your machine. in python, you can then use:</p> <pre><code>from selenium import webdriver dr = webdriver.PhantomJS() </code></pre> <p>and voila.</p>
7,212,559
Android: mkdirs()/mkdir() on external storage returns false
<p>I'm driven crazy with this:</p> <pre><code>Log.d("STATE", Environment.getExternalStorageState()); File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "work_data"); Log.d("PATH", f.getAbsolutePath()); if (!f.exists()) { Log.d("MAKE DIR", f.mkdirs() + ""); } </code></pre> <p>The output log looks like this:</p> <pre><code>STATE mounted PATH /mnt/sdcard/DCIM/work_data MAKE DIR false </code></pre> <p>I made sure to add the correct permission:</p> <pre><code> &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt; </code></pre> <p>But I don't know why it could not create the folder. I also used <code>mkdir()</code> step by step but the result is the same. Please help me. I have googled so much and spent at least 2 days on this stupid thing. Thanks for your help!!</p> <p>EDITING:</p> <p>Sorry everyone! I had added <code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt;</code> in <code>&lt;application&gt;</code> tag. this was my mistake! But thank you all for reply.</p>
8,182,070
16
1
null
2011-08-27 04:33:56.57 UTC
11
2022-06-27 11:42:59.943 UTC
2016-08-26 22:21:40.793 UTC
null
40,352
null
903,610
null
1
43
android|android-file|android-external-storage
48,852
<p>I have had the same problem and I have searched everything for a week trying to find the answer. I think I found it and I think it's ridiculously easy, you have to put the uses-permission statement in the right place...</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.name" android:versionCode="1" android:versionName="0.2"&gt; &lt;uses-sdk android:minSdkVersion="8" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; </code></pre> <p>When I had it inside the &lt;application&gt;&lt;/application&gt; section it did not work.</p>
14,350,729
Why does Maven report "Checksum validation failed, no checksums available from the repository"?
<p>I am trying to create a custom Maven repository using the 3 steps described here - <a href="http://www.javaworld.com/community/node/3968" rel="noreferrer">http://www.javaworld.com/community/node/3968</a>. So, I followed all the steps and here I have the repository:</p> <pre><code>D:\maven2&gt;dir /s/b D:\maven2\com D:\maven2\org D:\maven2\web.config D:\maven2\com\safenet D:\maven2\com\safenet\hasp D:\maven2\com\safenet\hasp\1 D:\maven2\com\safenet\hasp\maven-metadata.xml D:\maven2\com\safenet\hasp\maven-metadata.xml.md5 D:\maven2\com\safenet\hasp\maven-metadata.xml.sha1 D:\maven2\com\safenet\hasp\1\hasp-1.jar D:\maven2\com\safenet\hasp\1\hasp-1.pom D:\maven2\com\safenet\hasp\1\_maven.repositories D:\maven2\org\jnetpcap D:\maven2\org\jnetpcap\jnetcap D:\maven2\org\jnetpcap\jnetcap\1.3 D:\maven2\org\jnetpcap\jnetcap\maven-metadata.xml D:\maven2\org\jnetpcap\jnetcap\maven-metadata.xml.md5 D:\maven2\org\jnetpcap\jnetcap\maven-metadata.xml.sha1 D:\maven2\org\jnetpcap\jnetcap\1.3\jnetcap-1.3.jar D:\maven2\org\jnetpcap\jnetcap\1.3\jnetcap-1.3.pom D:\maven2\org\jnetpcap\jnetcap\1.3\_maven.repositories D:\maven2&gt;type com\safenet\hasp\maven-metadata.xml &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;metadata&gt; &lt;groupId&gt;com.safenet&lt;/groupId&gt; &lt;artifactId&gt;hasp&lt;/artifactId&gt; &lt;versioning&gt; &lt;release&gt;1&lt;/release&gt; &lt;versions&gt; &lt;version&gt;1&lt;/version&gt; &lt;/versions&gt; &lt;lastUpdated&gt;20130108125547&lt;/lastUpdated&gt; &lt;/versioning&gt; &lt;/metadata&gt; D:\maven2&gt;type org\jnetpcap\jnetcap\maven-metadata.xml.md5 297455697088aad6bdbe256d48fb0676 *maven-metadata.xml D:\maven2&gt;type org\jnetpcap\jnetcap\maven-metadata.xml.sha1 f86d93727a76525f42f1b67997020e1a9a41b948 *maven-metadata.xml D:\maven2&gt;type org\jnetpcap\jnetcap\1.3\jnetcap-1.3.pom &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;org.jnetpcap&lt;/groupId&gt; &lt;artifactId&gt;jnetcap&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;description&gt;POM was created from install:install-file&lt;/description&gt; &lt;/project&gt; D:\maven2&gt; </code></pre> <p>Now I am trying to use the hasp artifact in a pom file like this:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.safenet&lt;/groupId&gt; &lt;artifactId&gt;hasp&lt;/artifactId&gt; &lt;version&gt;1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>And the repository is referenced like this:</p> <pre><code>&lt;repository&gt; &lt;releases&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;updatePolicy&gt;always&lt;/updatePolicy&gt; &lt;checksumPolicy&gt;fail&lt;/checksumPolicy&gt; &lt;/releases&gt; &lt;id&gt;dev-builder&lt;/id&gt; &lt;name&gt;Shunra private repository&lt;/name&gt; &lt;url&gt;http://dev-builder/maven2&lt;/url&gt; &lt;layout&gt;default&lt;/layout&gt; &lt;/repository&gt; </code></pre> <p>Unfortunately, it does not work as expected:</p> <pre><code>[INFO] Building license 0.0.1 [INFO] ------------------------------------------------------------------------ Downloading: http://dev-builder/maven2/com/safenet/hasp/1/hasp-1.pom [WARNING] The POM for com.safenet:hasp:jar:1 is missing, no dependency information available Downloading: http://dev-builder/maven2/com/safenet/hasp/1/hasp-1.jar [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] Local Driver Proxy ................................ SUCCESS [2.579s] [INFO] Emulation API ..................................... SUCCESS [1.637s] [INFO] util.logging ...................................... SUCCESS [1.023s] [INFO] Infra ............................................. SUCCESS [0.250s] [INFO] dtos .............................................. SUCCESS [0.691s] [INFO] commons ........................................... SUCCESS [0.426s] [INFO] license ........................................... FAILURE [2.195s] [INFO] core .............................................. SKIPPED [INFO] vcat .............................................. SKIPPED [INFO] VCat-build ........................................ SKIPPED [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.044s [INFO] Finished at: Tue Jan 15 21:27:43 EST 2013 [INFO] Final Memory: 6M/15M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal on project license: Could not resolve dependencies for project com.shunra:license:jar:0.0.1: Could not transfer artifact com.safenet:hasp:jar:1 from/to dev-builder (http ://dev-builder/maven2): Checksum validation failed, no checksums available from the repository -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException [ERROR] [ERROR] After correcting the problems, you can resume the build with the command [ERROR] mvn &lt;goals&gt; -rf :license c:\dev\shunra\Application\Builder\build\vcat&gt; </code></pre> <p>I have no idea what is the problem with it. The md5 and sha1 files were created using the cygwin port of the md5sum and sha1sum utilities. Still, Maven reports bad checksum.</p>
14,945,261
2
0
null
2013-01-16 03:01:26.397 UTC
3
2021-09-02 21:12:28.897 UTC
2018-05-26 11:11:23.937 UTC
null
472,495
null
80,002
null
1
12
maven|repository
58,314
<p>I came here looking for the same answer. After spending hours trying to figure it out I finally found that the reason this is happening is two fold:</p> <ol> <li>The checksums created by md5sum and shasum are not exactly what maven is looking for</li> <li>You need checksums for all the files.</li> </ol> <p>So basically that tutorial on javaworld.com is completely or at least partially wrong. </p> <p>So whats the answer:</p> <ol> <li>Use the <code>-DcreateChecksum=true</code> param on your <code>mvn install:install-file</code> command.</li> <li>Rename the <code>maven-metadata-local</code> files that are generated to remove the <code>local</code> part.</li> </ol> <p>I decided that I would be doing this often enough I would create a bash script to automate the process, maybe you will find it useful as well.</p> <p>I designed the script below to run the whole process in a temp directory, then zip up the results, which you can then just upload to your custom repository.</p> <pre><code>#! /bin/bash USAGE(){ println "Usage: `basename $0` -g GroupId -a ArtifactId -f file [-voh] args\n\n"; println "Options:"; println " h Print usage"; println " v Version (Defaults to 1.0)"; println " o Output zip file name (Defaults to GroupId.ArtifactId.zip)"; } println(){ echo "$1"; } VERSION="1.0"; # Parse command line options. while getopts hv:o:g:a:f: OPT; do case "$OPT" in h) USAGE exit 0 ;; v) VERSION=$OPTARG; ;; g) GROUP_ID=$OPTARG; ;; a) ARTIFACT_ID=$OPTARG; ;; f) INPUT_FILE=$OPTARG ;; o) OUTPUT_FILE=$OPTARG ;; \?) # getopts issues an error message echo "Error: " &gt;&amp;2; USAGE exit 1 ;; esac done if [ -z "${OUTPUT_FILE}" ]; then OUTPUT_FILE="$GROUP_ID.$ARTIFACT_ID.zip"; fi # Remove the switches we parsed above. shift `expr $OPTIND - 1` if [ -z "${ARTIFACT_ID}" ]; then echo "Error: You must specify an artifact id." fi if [ -z "${GROUP_ID}" ]; then echo "Error: You must specify an group id." fi if [ -z "${INPUT_FILE}" ]; then echo "Error: You must specify an group id." fi if [ ! -f "${INPUT_FILE}" ]; then echo "Error: Input file '$INPUT_FILE' does not exist." fi # Create a temp directory which we will use as our 'local repository' TEMPDIR=$(mktemp -dt "build-maven-dep.XXXXXXX") TEMPDIR_SUB="$GROUP_ID.$ARTIFACT_ID"; TEMP_REPO_LOC="$TEMPDIR/$TEMPDIR_SUB"; mkdir -p $TEMP_REPO_LOC; mvn install:install-file -DlocalRepositoryPath=$TEMP_REPO_LOC -DgroupId=$GROUP_ID -DartifactId=$ARTIFACT_ID -Dversion=$VERSION -Dfile=$INPUT_FILE -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true CUR_DIR=$(pwd); # Enter the temp repository we created which is now populated. cd $TEMP_REPO_LOC; PACKAGE_STRUC="$GROUP_ID.$ARTIFACT_ID"; # Dive down into directory structure until we get to the *.xml files. IFS='. ' read -ra ADDR &lt;&lt;&lt; $PACKAGE_STRUC for i in "${ADDR[@]}"; do println "Moving into: $i"; cd $i; println "Now in $(pwd)"; done # Rename the files to what maven expects. mv maven-metadata-local.xml maven-metadata.xml mv maven-metadata-local.xml.md5 maven-metadata.xml.md5 mv maven-metadata-local.xml.sha1 maven-metadata.xml.sha1 # Zip up our results. cd $TEMP_REPO_LOC; cd ..; zip -r $OUTPUT_FILE $TEMPDIR_SUB mv $OUTPUT_FILE $CUR_DIR # Return back to our original directory and remove the temp directory cd $CUR_DIR; rm -Rf $TEMPDIR; # EOF </code></pre> <p>Say you want to package up myjar.jar for your custom repository:</p> <pre><code>./bundle-for-remote.sh -g com.mygroup -a myJar -f myJar.jar </code></pre> <p>Which will create a .zip in your current directory called com.mygroup.myJar.zip with all the components.</p> <p>Cheers,</p> <p>Casey</p>
14,047,802
How to check amount of data available for a socket in C and Linux
<p>I have a server that receives a continuous stream of data. As opposed to reading multiple times from a socket, I would like to read the entire data in socket receive buffer with one system call to <code>read()</code>.</p> <p>Of course I can pass a large buffer and <code>read()</code> will try to fill it with all available data. But this would waste a lot of memory as most of the times the malloc'ed buffer would be bigger than actual data available on socket. Is there a way to query the available data on a socket?</p>
14,061,803
6
6
null
2012-12-27 00:02:53.96 UTC
7
2013-02-19 16:49:00.523 UTC
2012-12-27 00:09:50.55 UTC
null
1,655,939
null
320,570
null
1
36
c|linux|sockets
38,944
<p>Yes:</p> <pre><code>#include &lt;sys/ioctl.h&gt; ... int count; ioctl(fd, FIONREAD, &amp;count); </code></pre>
14,209,214
Reading the PDF properties/metadata in Python
<p>How can I read the properties/metadata like Title, Author, Subject and Keywords stored on a PDF file using Python?</p>
14,209,316
6
0
null
2013-01-08 06:13:15.933 UTC
13
2022-07-02 10:08:56.293 UTC
2018-06-02 20:10:51.473 UTC
null
1,864,029
null
1,381,999
null
1
48
python|pdf|metadata
48,205
<p>Try <a href="https://github.com/euske/pdfminer/" rel="noreferrer">pdfminer</a>:</p> <pre><code>from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument fp = open('diveintopython.pdf', 'rb') parser = PDFParser(fp) doc = PDFDocument(parser) print(doc.info) # The "Info" metadata </code></pre> <p>Here's the output:</p> <pre><code>&gt;&gt;&gt; [{'CreationDate': 'D:20040520151901-0500', 'Creator': 'DocBook XSL Stylesheets V1.52.2', 'Keywords': 'Python, Dive Into Python, tutorial, object-oriented, programming, documentation, book, free', 'Producer': 'htmldoc 1.8.23 Copyright 1997-2002 Easy Software Products, All Rights Reserved.', 'Title': 'Dive Into Python'}] </code></pre> <p>For more info, look at this tutorial: <a href="http://blog.matt-swain.com/post/25650072381/a-lightweight-xmp-parser-for-extracting-pdf-metadata-in" rel="noreferrer">A lightweight XMP parser for extracting PDF metadata in Python</a>.</p>
9,063,964
Folder path of a PowerShell file in PowerShell
<p>My PowerShell script file is located in <code>C:/this-folder/that-folder/another-folder/powershell-file.ps1</code>.</p> <p>How do I get a variable that returns <code>C:/this-folder/that-folder/another-folder/</code>?</p>
9,064,015
4
1
null
2012-01-30 12:37:11.717 UTC
6
2022-08-05 18:01:46.747 UTC
2022-08-05 17:52:42.75 UTC
null
63,550
null
1,137,669
null
1
37
powershell
34,699
<p>Try this command in your script:</p> <pre><code>Split-Path -parent $MyInvocation.MyCommand.Definition </code></pre>
9,177,252
Detecting a redirect in ajax request?
<p>I want to use jQuery to GET a URL and explicitly check if it responded with a 302 redirect, but <em>not</em> follow the redirect.</p> <p>jQuery's <code>$.ajax</code> appears to always follow redirects. How can I prevent this, and see the redirect without following it?</p> <p>There are various questions with titles like "jquery ajax redirect" but they all appear to involve accomplishing some other goal, rather than just directly checking the status that a server gives.</p>
9,177,299
4
1
null
2012-02-07 13:39:43.897 UTC
12
2019-10-30 08:56:13.003 UTC
2019-10-30 08:56:13.003 UTC
null
441,757
null
99,876
null
1
98
jquery|ajax|http
114,788
<p>The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer <a href="https://stackoverflow.com/a/2573589/965648">https://stackoverflow.com/a/2573589/965648</a></p>
45,882,329
Read large files line by line in Rust
<p>My Rust program is intented to read a very large (up to several GB), simple text file line by line. The problem is, that this file is too large to be read at once, or to transfer all lines into a <code>Vec&lt;String&gt;</code>.</p> <p>What would be an idiomatic way to handle this in Rust?</p>
45,882,510
1
4
null
2017-08-25 13:15:41.293 UTC
15
2020-09-04 06:56:11.337 UTC
2017-08-25 13:36:10.56 UTC
null
4,498,831
null
7,855,177
null
1
53
rust
59,354
<p>You want to use the <a href="https://doc.rust-lang.org/std/io/trait.BufRead.html" rel="noreferrer">buffered reader, <code>BufRead</code></a>, and specifically the function <a href="https://doc.rust-lang.org/std/io/trait.BufRead.html#method.lines" rel="noreferrer"><code>BufReader.lines()</code></a>:</p> <pre><code>use std::fs::File; use std::io::{self, prelude::*, BufReader}; fn main() -&gt; io::Result&lt;()&gt; { let file = File::open(&quot;foo.txt&quot;)?; let reader = BufReader::new(file); for line in reader.lines() { println!(&quot;{}&quot;, line?); } Ok(()) } </code></pre> <p>Note that you are <strong>not</strong> returned the linefeed, as said in the documentation.</p> <hr /> <p>If you do not want to allocate a string for each line, here is an example to reuse the same buffer:</p> <pre><code>fn main() -&gt; std::io::Result&lt;()&gt; { let mut reader = my_reader::BufReader::open(&quot;Cargo.toml&quot;)?; let mut buffer = String::new(); while let Some(line) = reader.read_line(&amp;mut buffer) { println!(&quot;{}&quot;, line?.trim()); } Ok(()) } mod my_reader { use std::{ fs::File, io::{self, prelude::*}, }; pub struct BufReader { reader: io::BufReader&lt;File&gt;, } impl BufReader { pub fn open(path: impl AsRef&lt;std::path::Path&gt;) -&gt; io::Result&lt;Self&gt; { let file = File::open(path)?; let reader = io::BufReader::new(file); Ok(Self { reader }) } pub fn read_line&lt;'buf&gt;( &amp;mut self, buffer: &amp;'buf mut String, ) -&gt; Option&lt;io::Result&lt;&amp;'buf mut String&gt;&gt; { buffer.clear(); self.reader .read_line(buffer) .map(|u| if u == 0 { None } else { Some(buffer) }) .transpose() } } } </code></pre> <p><a href="https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=bd8c177e683929be24e4cb672392f7c3" rel="noreferrer">Playground</a></p> <p>Or if you prefer a standard iterator, you can use this <code>Rc</code> trick I shamelessly took <a href="https://www.reddit.com/r/rust/comments/d4rl3d/a_remarkably_simple_solution_to_the_problem_of/" rel="noreferrer">from Reddit</a>:</p> <pre><code>fn main() -&gt; std::io::Result&lt;()&gt; { for line in my_reader::BufReader::open(&quot;Cargo.toml&quot;)? { println!(&quot;{}&quot;, line?.trim()); } Ok(()) } mod my_reader { use std::{ fs::File, io::{self, prelude::*}, rc::Rc, }; pub struct BufReader { reader: io::BufReader&lt;File&gt;, buf: Rc&lt;String&gt;, } fn new_buf() -&gt; Rc&lt;String&gt; { Rc::new(String::with_capacity(1024)) // Tweakable capacity } impl BufReader { pub fn open(path: impl AsRef&lt;std::path::Path&gt;) -&gt; io::Result&lt;Self&gt; { let file = File::open(path)?; let reader = io::BufReader::new(file); let buf = new_buf(); Ok(Self { reader, buf }) } } impl Iterator for BufReader { type Item = io::Result&lt;Rc&lt;String&gt;&gt;; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let buf = match Rc::get_mut(&amp;mut self.buf) { Some(buf) =&gt; { buf.clear(); buf } None =&gt; { self.buf = new_buf(); Rc::make_mut(&amp;mut self.buf) } }; self.reader .read_line(buf) .map(|u| if u == 0 { None } else { Some(Rc::clone(&amp;self.buf)) }) .transpose() } } } </code></pre> <p><a href="https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=58d67f799b7057e4d56f1de198c7e774" rel="noreferrer">Playground</a></p>
24,610,143
How to create grouped daily,weekly and monthly reports including calculated fields in SQL Server
<p>I'm using SQL Server (2012), and using the two (simplified) tables below, how do I create 3 separate reports (daily, weekly and monthly) and include the following calculated fields:</p> <pre><code>1. new users created in this period 2. total number of users at this time **Users** userID int name varchar(80) userCreated datetime **Orders** orderID int userID int orderCreated datetime </code></pre> <p>I've been messing around with this code: </p> <pre><code>SELECT CAST(DATEPART(dd,userCreated) as VARCHAR(2)) + '/' + CAST(DATEPART(mm,userCreated) AS VARCHAR(2)) + '/' + CAST(DATEPART(yyyy,userCreated) AS VARCHAR(4)) [Date], count(*) newSignUps, (select count(*) from users u2 WHERE u2.userCreated &lt; u1.userCreated) FROM users u1 WHERE userCreated BETWEEN '05/01/2014 00:00:00.000' and '05/31/2014 23:59:59.000' GROUP BY DATEPART(dd,userCreated), DATEPART(mm,userCreated), DATEPART(yyyy,userCreated),userCreated </code></pre> <p>But to show anything, it needs the "userCreated" field added to the grouping...</p> <p>For the reports I need to show:</p> <p><strong>Daily:</strong></p> <pre><code>date new sign ups users in system 17/03/2013 10 100 18/03/2013 4 104 19/03/2013 8 112 </code></pre> <p><strong>Weekly:</strong></p> <pre><code>week 13 8 40 14 2 42 15 5 47 </code></pre> <p><strong>Monthly:</strong></p> <pre><code>Jan 3 54 Feb 9 63 Mar 2 65 </code></pre> <p>I hope this makes sense? Thank you...</p>
24,610,562
2
4
null
2014-07-07 12:02:23.12 UTC
2
2015-08-27 10:18:56.623 UTC
2015-08-27 10:18:56.623 UTC
null
1,213,296
null
3,306,622
null
1
6
sql|sql-server|grouping
43,078
<p>I'm not sure if I understood your question correctly, but this gives you all the users created per day:</p> <pre><code>SELECT year(userCreated), month(userCreated), day(userCreated), count(*) FROM Users GROUP BY year(userCreated), month(userCreated), day(userCreated) </code></pre> <p>this one by month:</p> <pre><code>SELECT year(userCreated), month(userCreated), count(*) FROM Users GROUP BY year(userCreated), month(userCreated) </code></pre> <p>and this one by week:</p> <pre><code>SELECT year(userCreated), datepart(week, userCreated), count(*) FROM Users GROUP BY year(userCreated), datepart(week, userCreated) </code></pre> <p>Edit according to you the missing total field I give you here the example for the month query:</p> <pre><code>SELECT year(userCreated), month(userCreated), count(*) AS NewCount, (SELECT COUNT(*) FROM Users u2 WHERE CAST(CAST(year(u1.userCreated) AS VARCHAR(4)) + RIGHT('0' + CAST(month(u1.userCreated) AS VARCHAR(2)), 2) + '01' AS DATETIME) &gt; u2.userCreated) AS TotalCount FROM Users u1 GROUP BY year(userCreated), month(userCreated) </code></pre> <p>Hope this helps for the other two queries.</p>
35,330,964
No module named 'core' when using pyping for Python 3
<p>I am trying to import <code>pyping</code> for Python 3 but I am getting below error:</p> <pre><code>virt01@virt01:~/Python_Admin$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pyping Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.4/dist-packages/pyping/__init__.py", line 3, in &lt;module&gt; from core import * ImportError: No module named 'core' &gt;&gt;&gt; </code></pre> <p><em>Update 1</em></p> <pre><code>virt01@virt01:~/Python_Admin$ ls /usr/local/lib/python3.4/dist-packages/pyping/ core.py __init__.py __pycache__ </code></pre>
35,331,150
2
4
null
2016-02-11 04:46:03.013 UTC
2
2020-07-19 10:41:46.103 UTC
2019-03-14 15:19:32.093 UTC
null
1,971,003
null
1,293,013
null
1
14
python|python-3.x|python-import
45,360
<p>This is because of absolute imports being in effect (more precisely, the lack of implicit relative imports) for Python 3 and the fact that the <code>pyping</code> module was most likely only written for Python 2. Whereas in Python 2 you can do:</p> <pre><code>from core import * </code></pre> <p>In Python 3 (or if you have <code>from __future__ import absolute_import</code> in Python 2), you have to do:</p> <pre><code>from .core import * </code></pre> <p>or</p> <pre><code>from pyping.core import * </code></pre> <p>You have two options:</p> <ol> <li>ask the module author to make it compatible with Python 3</li> <li>fork it yourself and make it compatible with Python 3 (you can look into using <code>2to3</code> for this)</li> </ol>
35,008,713
Bitbucket git credentials if signed up with Google
<p>I have an account on bitbucket.org that I created by signing up with my Google account. Now everytime I log in I just click "Log in with Google" and that's fine.</p> <p>How can I access my repos from git command line? It requests me username and password. I have a username, but no password. How do I log in then?</p>
35,238,806
11
5
null
2016-01-26 07:23:30.527 UTC
61
2022-04-04 13:15:56.53 UTC
null
null
null
null
3,771,035
null
1
400
git|bitbucket|google-account
174,439
<p>Solved:</p> <ul> <li>Went on the log-in screen and clicked <code>forgot my password</code>.</li> <li>I entered my Google account email and I received a reset link.</li> <li>As you enter there a new password you'll have bitbucket id and password to use.</li> </ul> <p>Sample: </p> <pre><code>git clone https://&lt;bitbucket_id&gt;@bitbucket.org/&lt;repo&gt; </code></pre>
1,160,081
Why is an array not assignable to Iterable?
<p>with Java5 we can write:</p> <pre><code>Foo[] foos = ... for (Foo foo : foos) </code></pre> <p>or just using an Iterable in the for loop. This is very handy. </p> <p>However you can't write a generic method for iterable like this:</p> <pre><code>public void bar(Iterable&lt;Foo&gt; foos) { .. } </code></pre> <p>and calling it with an array since it is not an Iterable:</p> <pre><code>Foo[] foos = { .. }; bar(foos); // compile time error </code></pre> <p>I'm wondering about the reasons behind this design decision.</p>
1,162,255
5
14
null
2009-07-21 15:49:20.96 UTC
18
2020-04-19 20:17:50.83 UTC
2010-02-02 14:45:03.143 UTC
null
40,342
null
89,266
null
1
194
java|language-design
53,485
<p>Arrays can implement interfaces (<code>Cloneable</code> and <code>java.io.Serializable</code>). So why not <code>Iterable</code>? I guess <code>Iterable</code> forces adding an <code>iterator</code> method, and arrays don't implement methods. <code>char[]</code> doesn't even override <code>toString</code>. Anyway, arrays of references should be considered less than ideal - use <code>List</code>s. As dfa comments, <code>Arrays.asList</code> will do the conversion for you, explicitly.</p> <p>(Having said that, you can call <code>clone</code> on arrays.)</p>
871,422
Looping through a SimpleXML object, or turning the whole thing into an array
<p>I'm trying to work out how to iterate though a returned SimpleXML object.</p> <p>I'm using a toolkit called <a href="http://tarzan-aws.com/" rel="noreferrer">Tarzan AWS</a>, which connects to Amazon Web Services (SimpleDB, S3, EC2, etc). I'm specifically using SimpleDB.</p> <p>I can put data into the Amazon SimpleDB service, and I can get it back. I just don't know how to handle the SimpleXML object that is returned.</p> <p>The Tarzan AWS documentation says this:</p> <blockquote> <p>Look at the response to navigate through the headers and body of the response. Note that this is an object, not an array, and that the body is a SimpleXML object.</p> </blockquote> <p>Here's a sample of the returned SimpleXML object:</p> <pre> [body] => SimpleXMLElement Object ( [QueryWithAttributesResult] => SimpleXMLElement Object ( [Item] => Array ( [0] => SimpleXMLElement Object ( [Name] => message12413344443260 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => john ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is a message. ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334444 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413344443260 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.1 ) ) ) [1] => SimpleXMLElement Object ( [Name] => message12413346907303 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => fred ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is another message ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334690 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413346907303 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.2 ) ) ) ) </pre> <p>So what code do I need to get through each of the object items? I'd like to loop through each of them and handle it like a returned mySQL query. For example, I can query SimpleDB and then loop though the SimpleXML so I can display the results on the page.</p> <p>Alternatively, how do you turn the whole shebang into an array? </p> <p>I'm new to SimpleXML, so I apologise if my questions aren't specific enough. </p>
871,439
6
0
null
2009-05-16 01:22:12.6 UTC
6
2019-02-26 11:50:57.587 UTC
2009-06-27 07:33:37.2 UTC
null
52,551
null
100,605
null
1
19
php|amazon-web-services|simplexml|amazon-simpledb
53,084
<p>You can use the <code>SimpleXML</code> object (or its properties) in a <code>foreach</code> loop. If you want to loop through all the 'records' something like this can be used to access and display the data:</p> <pre><code>//Loop through all the members of the Item array //(essentially your two database rows). foreach($SimpleXML-&gt;body-&gt;QueryWithAttributesResult-&gt;Item as $Item){ //Now you can access the 'row' data using $Item in this case //two elements, a name and an array of key/value pairs echo $Item-&gt;Name; //Loop through the attribute array to access the 'fields'. foreach($Item-&gt;Attribute as $Attribute){ //Each attribute has two elements, name and value. echo $Attribute-&gt;Name . ": " . $Attribute-&gt;Value; } } </code></pre> <p>Note that $Item will be a SimpleXML object, as is $Attribute, so they need to be referenced as objects, not arrays. </p> <p>While the example code above is looping through the arrays in the SimpleXML object ($SimpleXML->body->QueryWithAttributesResult->Item), you can also loop through a SimpleXML object (say $SimpleXML->body->QueryWithAttributesResult->Item[0]), and that would give you each of the object's properties.</p> <p>Each child element of a SimpleXML object is an XML entity. If the XML entity (tag) is not unique, then the element is simply an array of SimpleXML objects representing each entity.</p> <p>If you want, this should create a more common row/fields array from your SimpleXML object (or get you close):</p> <pre><code>foreach($SimpleXML-&gt;body-&gt;QueryWithAttributesResult-&gt;Item as $Item){ foreach($Item-&gt;Attribute as $Attribute){ $rows[$Item-&gt;Name][$Attribute-&gt;Name] = $Attribute-&gt;Value; } } //Now you have an array that looks like: $rows['message12413344443260']['active'] = 1; $rows['message12413344443260']['user'] = 'john'; //etc. </code></pre>
56,810
How do I start threads in plain C?
<p>I have used fork() in C to start another process. How do I start a new thread?</p>
56,825
6
4
null
2008-09-11 15:04:25.053 UTC
19
2020-03-07 09:52:35.363 UTC
null
null
null
Hanno
2,077
null
1
57
c|multithreading
80,845
<p>Since you mentioned fork() I assume you're on a Unix-like system, in which case <a href="http://en.wikipedia.org/wiki/POSIX_Threads" rel="noreferrer">POSIX threads</a> (usually referred to as pthreads) are what you want to use.</p> <p>Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:</p> <pre><code>int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); </code></pre> <p>The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.</p>
748,631
Lint for C#
<p>Is there a lint-like tool for C#? I've got the compiler to flag warnings-as-errors, and I've got Stylecop, but these only catch the most egregious errors. Are there any other must-have tools (especially for newbie C#ers like me) that point out probably-dumb things I'm doing?</p>
748,638
6
0
null
2009-04-14 17:36:43.367 UTC
16
2017-09-07 16:00:45.413 UTC
2009-04-14 17:46:08.367 UTC
null
33,708
null
74,900
null
1
58
c#|.net|code-analysis|lint
72,726
<p>Tried <a href="http://msdn.microsoft.com/en-us/library/bb429476.aspx" rel="noreferrer">FxCop</a>? It's integrated into VS as "Code Analysis"</p> <p>In the newer versions of Visual Studio, it is called "Microsoft Code Analysis" and can be downloaded from the Visual Studio Marketplace: <a href="https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.MicrosoftCodeAnalysis2017" rel="noreferrer">https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.MicrosoftCodeAnalysis2017</a></p>
104,983
What is "thread local storage" in Python, and why do I need it?
<p>In Python specifically, how do variables get shared between threads?</p> <p>Although I have used <code>threading.Thread</code> before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?</p> <p>I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. </p> <p>Thanks in advance!</p>
105,025
6
2
null
2008-09-19 19:53:19.447 UTC
36
2021-12-22 14:15:00.913 UTC
2009-09-11 01:14:30.9 UTC
null
811
Mike
19,215
null
1
126
python|multithreading|thread-local
71,086
<p>In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them. The <code>Thread</code> object for a particular thread is not a special object in this regard. If you store the <code>Thread</code> object somewhere all threads can access (like a global variable) then all threads can access that one <code>Thread</code> object. If you want to atomically modify <em>anything</em> that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.</p> <p>If you want actual thread-local storage, that's where <code>threading.local</code> comes in. Attributes of <code>threading.local</code> are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in <a href="https://github.com/python/cpython/blob/master/Lib/_threading_local.py" rel="noreferrer">_threading_local.py</a> in the standard library.</p>
188,688
What does the tilde before a function name mean in C#?
<p>I am looking at some code and it has this statement: </p> <pre><code>~ConnectionManager() { Dispose(false); } </code></pre> <p>The class implements the <code>IDisposable</code> interface, but I do not know if that is part of that the tilde(~) is used for.</p>
188,715
6
0
null
2008-10-09 19:00:38.723 UTC
30
2021-02-05 07:29:08.277 UTC
2014-06-26 05:02:13.953 UTC
null
1,350,209
Keith Sirmons
1,048
null
1
182
c#|syntax|tilde
53,379
<p><strong>~ is the destructor</strong></p> <ol> <li>Destructors are invoked automatically, and cannot be invoked explicitly.</li> <li>Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.</li> <li>Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.</li> <li>Destructors cannot be used with structs. They are only used with classes. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.</li> <li>Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.</li> <li>When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.</li> </ol> <p><strong>Finalize</strong> </p> <p>In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class. </p> <p><strong>Dispose</strong></p> <p>It is preferable to dispose of objects in a <code>Close()</code> or <code>Dispose()</code> method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC.</p> <p>The <em>IDisposable</em> interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method <em>should</em> use the <code>GC.SuppressFinalize()</code> method to ensure that finalization of your instance is suppressed. </p> <p><strong>What to use?</strong></p> <p>It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.</p>
767,851
XPath find if node exists
<p>Using a XPath query how do you find if a node (tag) exists at all?</p> <p>For example if I needed to make sure a website page has the correct basic structure like <code>/html/body</code> and <code>/html/head/title</code>.</p>
767,873
6
1
null
2009-04-20 11:14:39.237 UTC
26
2021-04-01 19:42:49.4 UTC
2021-04-01 19:42:49.4 UTC
null
9,193,372
null
87,921
null
1
208
xslt|xpath|expression
353,786
<pre><code>&lt;xsl:if test="xpath-expression"&gt;...&lt;/xsl:if&gt; </code></pre> <p>so for example</p> <pre><code>&lt;xsl:if test="/html/body"&gt;body node exists&lt;/xsl:if&gt; &lt;xsl:if test="not(/html/body)"&gt;body node missing&lt;/xsl:if&gt; </code></pre>