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
23,830,618
python opencv TypeError: Layout of the output array incompatible with cv::Mat
<p>I'm using the selective search here: <a href="http://koen.me/research/selectivesearch/" rel="noreferrer">http://koen.me/research/selectivesearch/</a> This gives possible regions of interest where an object might be. I want to do some processing and retain only some of the regions, and then remove duplicate bounding boxes to have a final neat collection of bounding boxes. To discard unwanted/duplicated bounding boxes regions, I'm using the <code>grouprectangles</code> function of opencv for pruning.</p> <p>Once I get the interesting regions from Matlab from the "selective search algorithm" in the link above, I save the results in a <code>.mat</code> file and then retrieve them in a python program, like this:</p> <pre><code> import scipy.io as sio inboxes = sio.loadmat('C:\\PATH_TO_MATFILE.mat') candidates = np.array(inboxes['boxes']) # candidates is 4 x N array with each row describing a bounding box like this: # [rowBegin colBegin rowEnd colEnd] # Now I will process the candidates and retain only those regions that are interesting found = [] # This is the list in which I will retain what's interesting for win in candidates: # doing some processing here, and if some condition is met, then retain it: found.append(win) # Now I want to store only the interesting regions, stored in 'found', # and prune unnecessary bounding boxes boxes = cv2.groupRectangles(found, 1, 2) # But I get an error here </code></pre> <p>The error is:</p> <pre><code> boxes = cv2.groupRectangles(found, 1, 2) TypeError: Layout of the output array rectList is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels) </code></pre> <p>What's wrong? I did something very similar in another piece of code which gave no errors. This was the error-free code:</p> <pre><code>inboxes = sio.loadmat('C:\\PATH_TO_MY_FILE\\boxes.mat') boxes = np.array(inboxes['boxes']) pruned_boxes = cv2.groupRectangles(boxes.tolist(), 100, 300) </code></pre> <p>The only difference I can see is that <code>boxes</code> was a numpy array which I then converted to a list. But in my problematic code, <code>found</code> is already a list.</p>
23,830,760
6
0
null
2014-05-23 13:31:34.787 UTC
3
2022-08-22 11:12:44.67 UTC
null
null
null
null
961,627
null
1
16
python|arrays|matlab|opencv|numpy
46,683
<p>The solution was to convert <code>found</code> first to a numpy array, and then to recovert it into a list:</p> <pre><code>found = np.array(found) boxes = cv2.groupRectangles(found.tolist(), 1, 2) </code></pre>
51,716,916
Built-in module to calculate the least common multiple
<p>I am currently using a function that accepts two numbers and uses a loop to find the least common multiple of those numbers,</p> <pre><code>def lcm(x, y): &quot;&quot;&quot;This function takes two integers and returns the L.C.M.&quot;&quot;&quot; # Choose the greater number if x &gt; y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm </code></pre> <p>Is there a built-in module in Python that does it instead of writing a custom function?</p>
51,716,959
5
0
null
2018-08-06 23:33:30.603 UTC
7
2022-05-08 15:37:26.647 UTC
2020-11-18 03:47:26.333 UTC
null
63,550
null
9,738,997
null
1
65
python
71,790
<h3>In Python 3.8 and earlier</h3> <p>There is no such thing built into the stdlib.</p> <p>However, there is a <a href="https://docs.python.org/3/library/math.html#math.gcd" rel="noreferrer">Greatest Common Divisor</a> function in the <code>math</code> library. (For Python 3.4 or 2.7, it's buried in <code>fractions</code> instead.) And writing an LCM on top of a GCD is pretty trivial:</p> <pre><code>def lcm(a, b): return abs(a*b) // math.gcd(a, b) </code></pre> <p>Or, if you're using NumPy, it's come with an <a href="https://www.numpy.org/devdocs/reference/generated/numpy.lcm.html" rel="noreferrer"><code>lcm</code></a> function for quite some time now.</p>
51,587,003
How to center only one element in a row of 2 elements in flutter
<p>In my layout I have two Widgets in a row, one text and the an icon. </p> <p>As shown below, assume that * refers to the icon, and using "-" to represent the row:</p> <pre><code>---------------------------- Text * ---------------------------- </code></pre> <p>How do I make my text centered in the entire row, and the icon to the right end ?</p>
51,587,074
8
0
null
2018-07-30 04:31:08.347 UTC
6
2022-05-31 12:35:07.517 UTC
null
null
null
null
883,430
null
1
50
flutter|flutter-layout
31,608
<p>The main thing you need to notice is that if you don't want to use <code>Stack</code> you should provide same width-consuming widgets both on left and right.</p> <p>I would do this with either <code>Expanded</code> and <code>Padding</code></p> <pre><code>Row( children: &lt;Widget&gt;[ Expanded( child: Padding( padding: const EdgeInsets.only(left: 32.0), child: Text( &quot;Text&quot;, textAlign: TextAlign.center, ), ), ), Icon(Icons.add, size: 32.0,) ], ) </code></pre> <p>or with <code>Row</code>'s <code>mainAxisAlignment</code> and a <code>SizedBox</code></p> <pre><code>Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: &lt;Widget&gt;[ const SizedBox(width: 32.0), Text(&quot;Text&quot;), Icon(Icons.add, size: 32.0) ], ) </code></pre> <p>or with <code>Expanded</code> and a <code>SizedBox</code> on the left instead of the padding :). The padding or extra container on the left is so that the textAlign will truly center the text in the row taking into account the space taken up by the Icon.</p>
69,544,583
Please configure the PostgreSQL Binary Path in the Preferences dialog
<p>So I am setting up PostgreSQL on my PC by following Jose Portilla's Course on Udemy and when I had to restore a database by the name of dvdrental. It showed up the message</p> <pre><code>`Please configure the PostgreSQL Binary Path in the Preferences dialog. </code></pre> <p>What am I supposed to do now? Any and All Help is Appreciated</p>
69,544,749
1
0
null
2021-10-12 17:19:50.723 UTC
2
2021-10-12 17:33:54.227 UTC
2021-10-12 17:26:58.8 UTC
null
330,315
null
16,650,588
null
1
18
postgresql|pgadmin-4
44,374
<p>I had the same problem, I leave you the steps</p> <ol> <li>Click Files -&gt; preferences -&gt; Binary path</li> <li>ProgresSQL Binary path: c:\Program Files\PosgresSQL\13\bin</li> <li>Click right DataBase-&gt; Restore...</li> </ol> <p>NOTE: <a href="https://www.youtube.com/watch?v=7cBkXKCY4Ew" rel="noreferrer">https://www.youtube.com/watch?v=7cBkXKCY4Ew</a></p>
1,040,074
Make javac treat warnings as errors
<p>I have an Ant file that compiles my program. I want the javac task to fail if any warning was reported by the compiler. Any clue on how to do that?</p>
1,040,090
1
1
null
2009-06-24 18:25:08.267 UTC
6
2020-10-07 11:51:55.413 UTC
2020-10-07 11:51:55.413 UTC
null
452,775
null
27,198
null
1
61
java|ant|warnings|javac
18,319
<p>Use the <code>-Werror</code> flag. It's not listed in the <code>-help</code> output, but it works.</p> <p>I found it through <a href="http://weblogs.java.net/blog/tball/archive/2006/11/get_medieval_on.html" rel="noreferrer">this blog entry</a> and tested on my own code (in NetBeans with Ant). The output was:</p> <pre> MyClass.java:38: warning: [serial] serializable class MyClass has no definition of serialVersionUID public class MyClass extends JComponent { 1 warning BUILD FAILED (total time: 3 seconds) </pre> <p>Note that this is Java 6 only, though.</p> <p><strong>Edit</strong>: Example of specifying this in Ant buildfile:</p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"&gt; &lt;compilerarg value="-Xlint:all"/&gt; &lt;compilerarg value="-Werror"/&gt; &lt;/javac&gt; </code></pre>
2,480,557
Providing localized error messages for non-attributed model validation in ASP.Net MVC 2?
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" rel="noreferrer">DataAnnotations</a> attributes along with ASP.Net MVC 2 to provide model validation for my ViewModels:</p> <pre><code>public class ExamplePersonViewModel { [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))] [StringLength(128, ErrorMessageResourceName = "StringLength", ErrorMessageResourceType = typeof(Resources.Validation))] [DataType(DataType.Text)] public string Name { get; set; } [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))] [DataType(DataType.Text)] public int Age { get; set; } } </code></pre> <p>This seems to work as expected (although it's very verbose). The problem I have is that there are behind-the-scenes model validations being performed that are not tied to any specific attribute. An example of this in the above model is that the <code>Age</code> property needs to be an <code>int</code>. If you try to enter a non-integer value on the form, it will error with the following (non-localized) message:</p> <blockquote> <p>The field Age must be a number.</p> </blockquote> <p><strong>How can these non-attribute validation messages be localized?</strong></p> <p><strong>Is there a full list of these messages available so I can make sure they are all localized?</strong></p>
2,551,481
3
0
null
2010-03-19 21:01:01.323 UTC
10
2014-07-24 05:54:35.997 UTC
null
null
null
null
25,549
null
1
20
asp.net-mvc|localization|data-annotations
11,386
<p>Go to <a href="http://forums.asp.net/p/1512140/3608427.aspx" rel="noreferrer">http://forums.asp.net/p/1512140/3608427.aspx</a>, watch the bradwils message dated 01-09-2010, 6:20 PM.</p> <p>The solution works well for me.</p> <p>It should be interesting to know the complete list of the messages overridable...</p> <p><strong>UPDATE</strong></p> <p>Here the post contents:</p> <blockquote> <p>Create a global resource class in App_GlobalResources, and set DefaultModelBinder.ResourceClassKey to the name of this class (for example, if you made "Messages.resx", then set ResourceClassKey to "Messages").</p> <p>There are two strings you can override in MVC 2:</p> <ul> <li>The string value for "PropertyValueInvalid" is used when the data the user entered isn't compatible with the data type (for example, typing in "abc" for an integer field). The default message for this is: "The value '{0}' is not valid for {1}."</li> <li>The string value for "PropertyValueRequired" is used when the user did not enter any data for a field which is not nullable (for example, an integer field). The default message for this is: "A value is required."</li> </ul> <p>It's important to note in the second case that, if you have the DataAnnotationsModelValidatorProvider in your validator providers list (which it is by default), then you will never see this second message. This provider sees non-optional fields and adds an implied [Required] attribute to them so that their messages will be consistent with other fields with explicit [Required] attributes and to ensure that you get client-side validation for required fields.</p> </blockquote>
3,005,973
What is the purpose of ROWLOCK on Delete and when should I use it?
<p>Ex)</p> <p>When should I use this statement:</p> <pre><code>DELETE TOP (@count) FROM ProductInfo WITH (ROWLOCK) WHERE ProductId = @productId_for_del; </code></pre> <p>And when should be just doing:</p> <pre><code>DELETE TOP (@count) FROM ProductInfo WHERE ProductId = @productId_for_del; </code></pre>
3,006,104
3
1
null
2010-06-09 13:01:57.367 UTC
5
2022-04-08 16:21:18.04 UTC
2016-11-18 17:14:54.27 UTC
null
2,975,396
null
357,849
null
1
23
sql|sql-server
72,482
<p>The <code>with (rowlock)</code> is a hint that instructs the database that it should keep locks on a row scope. That means that the database will avoid escalating locks to block or table scope.</p> <p>You use the hint when only a single or only a few rows will be affected by the query, to keep the lock from locking rows that will not be deleted by the query. That will let another query read unrelated rows at the same time instead of having to wait for the delete to complete.</p> <p>If you use it on a query that will delete a lot of rows, it may degrade the performance as the database will try to avoid escalating the locks to a larger scope, even if it would have been more efficient.</p> <p>Normally you shouldn't need to add such hints to a query, because the database knows what kind of lock to use. It's only in situations where you get performance problems because the database made the wrong decision, that you should add such hints to a query.</p>
3,099,904
How do I run multiple lines of Ruby in html.erb file
<p>I'm using Ruby on Rails and need to run a block of Ruby code in one of my html.erb files. Do I do it like this:</p> <pre><code>&lt;% def name %&gt; &lt;% name = username %&gt; &lt;%= name %&gt; </code></pre> <p>or like this:</p> <pre><code>&lt;% def name name = username %&gt; &lt;%= name %&gt; </code></pre> <p>Thanks for reading.</p>
3,099,980
3
2
null
2010-06-23 08:04:44.937 UTC
3
2018-02-21 04:28:26.167 UTC
2018-02-21 04:28:26.167 UTC
null
6,407,868
null
173,634
null
1
31
ruby-on-rails|ruby|block|erb
43,428
<p>It is unusual to define a method in an ERB file, so I recommend against it.</p> <p>If you want to call a block like <code>#each</code>, you can do something like the following:</p> <pre><code>&lt;% names.each do |name| %&gt; &lt;%= name %&gt; &lt;% end %&gt; </code></pre> <p>Don't forget the <code>&lt;% end %&gt;</code>.</p>
2,672,734
TCP sequence number question
<p>This is more of a theoretical question than an actual problem I have.</p> <p>If I understand correctly, the sequence number in the TCP header of a packet is the index of the first byte in the packet in the whole stream, correct? If that is the case, since the sequence number is an unsigned 32-bit integer, then what happens after more than FFFFFFFF = 4294967295 bytes are transferred? Will the sequence number wrap around, or will the sender send a SYN packet to restart at 0?</p>
2,672,750
3
0
null
2010-04-20 05:21:37.407 UTC
13
2017-03-20 21:09:41.51 UTC
null
null
null
null
308,136
null
1
32
tcp
30,514
<p>The sequence number loops back to 0. <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" rel="nofollow noreferrer">Source</a>:</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/Tcp.svg/250px-Tcp.svg.png" alt="alt text" /></p> <blockquote> <p>TCP sequence numbers and receive windows behave very much like a clock. The receive window shifts each time the receiver receives and acknowledges a new segment of data. Once it runs out of sequence numbers, the sequence number loops back to 0.</p> </blockquote> <p>Also see chapter 4 of <a href="https://www.rfc-editor.org/rfc/rfc1323" rel="nofollow noreferrer">RFC 1323</a>.</p>
2,928,371
How to filter the jqGrid data NOT using the built in search/filter box
<p>I want users to be able to filter grid data without using the intrinsic search box.</p> <p>I have created two input fields for date (from and to) and now need to tell the grid to adopt this as its filter and then to request new data.</p> <p>Forging a server request for grid data (bypassing the grid) and setting the grid's data to be the response data wont work - because as soon as the user tries to re-order the results or change the page etc. the grid will request new data from the server using a blank filter.</p> <p>I cant seem to find grid API to achieve this - does anyone have any ideas? Thanks.</p>
2,928,819
3
1
null
2010-05-28 10:58:29.97 UTC
28
2017-02-17 07:21:59.377 UTC
null
null
null
null
175,893
null
1
58
jquery|search|filter|jqgrid
49,873
<p>You problem can be very easy solved with respect of <code>postData</code> parameter including functions and <code>trigger('reloadGrid')</code>. I try explain the idea more detailed.</p> <p>Let us use <code>mtype: "GET"</code>. The only thing which standard search/filter box do after displaying the interface is appending of some additional parameters to the url, sending to server and reloading the grid data. If you have your own interface for searching/filtering (some select controls or checkboxes, for example) you should just append your url yourself and reload the grid with respect of <code>trigger('reloadGrid')</code>. For resetting of the information in the grid you can choose any way which you prefer. For example, you can include in the select controls which you have an option like "no filtering".</p> <p>To be more exact your code should looks like the code from the answer <a href="https://stackoverflow.com/questions/2839721/how-to-reload-jqgrid-in-asp-net-mvc-when-i-change-dropdownlist/2842199#2842199">how to reload jqgrid in asp.net mvc when i change dropdownlist</a>:</p> <pre><code>var myGrid = jQuery("#list").jqGrid({ url: gridDataUrl, postData: { StateId: function() { return jQuery("#StateId option:selected").val(); }, CityId: function() { return jQuery("#CityId option:selected").val(); }, hospname: function() { return jQuery("#HospitalName").val(); } } // ... }); // var myReload = function() { myGrid.trigger('reloadGrid'); }; var keyupHandler = function (e,refreshFunction,obj) { var keyCode = e.keyCode || e.which; if (keyCode === 33 /*page up*/|| keyCode === 34 /*page down*/|| keyCode === 35 /*end*/|| keyCode === 36 /*home*/|| keyCode === 38 /*up arrow*/|| keyCode === 40 /*down arrow*/) { if (typeof refreshFunction === "function") { refreshFunction(obj); } } }; // ... $("#StateId").change(myReload).keyup(function (e) { keyupHandler(e,myReload,this); }); $("#CityId").change(myReload).keyup(function (e) { keyupHandler(e,myReload,this); }); </code></pre> <p>If user change selected option in select box with <code>id=StateId</code> or another select box with <code>id=CityId</code> (with mouse or keyboard), the function <code>myReload</code> will be called, which just force reloading of data in jqGrid. During corresponding <code>$.ajax</code> request, which jqGrid do for us, the value from <code>postData</code> parameter will be forwarded to <code>$.ajax</code> as <code>data</code> parameter. If some from properties of <code>data</code> are functions, these function will be called by <code>$.ajax</code>. So the actual data from select boxes will be loaded and all the data will be appended to the data sent to the server. You need only implement reading of this parameters in your server part.</p> <p>So the data from the <code>postData</code> parameter will be appended to the url (symbols '?' and '&amp;' will be added automatically and all special symbols like blanks will be also encoded as usual). The advantages of the usage of <code>postData</code> is:</p> <ol> <li><strong>usage of functions</strong> inside <code>postData</code> parameter allows you to load <strong>actual</strong> values from all used controls to the moment of reloading;</li> <li>Your code stay have very clear structure.</li> <li>All works fine not only with HTTP GET requests, but with HTTP POST also;</li> </ol> <p>If you use some "no filtering" or "all" entries in the select box <code>StateId</code>, you can modify the function which calculate the value of <code>StateId</code> parameter which should appended to the server url from </p> <pre><code>StateId: function() { return jQuery("#StateId option:selected").val(); } </code></pre> <p>to something like following:</p> <pre><code>StateId: function() { var val = jQuery("#StateId option:selected").val(); return val === "all"? "": val; } </code></pre> <p>On the server side you should makes no filtering for <code>StateId</code> if you receive an empty value as a parameter.</p> <p>Optionally you can use <code>myGrid.setCaption('A text');</code> to change a grid title. This allow user to see more clear, that the data in grid are filtered with some criteria.</p>
3,181,149
PHP, print_r($_SESSION) doesn't show its content?
<p>I want to see the content of the the array $_SESSION with the command print_r($_SESSION) but what I get is just the following output:</p> <pre><code>Array () </code></pre> <p>what am I missing ?</p> <p>thanks</p>
3,181,182
4
2
null
2010-07-05 17:11:33.88 UTC
null
2019-08-18 14:43:03.373 UTC
2012-02-17 15:39:53.757 UTC
null
168,868
null
257,022
null
1
4
php|session
50,871
<p>Make sure you call <code>session_start()</code> at the top of all the pages you wish to use the session.</p> <p><a href="http://php.net/manual/en/function.session-start.php" rel="noreferrer">http://php.net/manual/en/function.session-start.php</a></p> <pre><code>&lt;?php session_start(); echo "&lt;pre&gt;"; print_r($_SESSION); echo "&lt;/pre&gt;"; ?&gt; </code></pre>
2,869,874
How store date in MySQL database?
<p>I have date in <code>dd/mm/yyyy</code> format. How can I store it in a database, if I want to do some operations on it afterwards?</p> <p>For example, I must find out the rows, where <code>date &gt; something</code>. What type I must set for the <code>date</code> field?</p>
2,869,881
4
0
null
2010-05-19 22:22:56.467 UTC
6
2021-12-06 11:19:44.327 UTC
2021-12-06 09:24:56.777 UTC
null
10,871,073
null
291,772
null
1
7
mysql
42,452
<p>To store dates or times in MySQL use <a href="http://dev.mysql.com/doc/refman/5.1/en/datetime.html" rel="noreferrer"><code>date</code>, <code>datetime</code> or <code>timestamp</code></a>. I'd recommend the first two for most purposes.</p> <p>To tell MySQL how to parse your date format use the <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date" rel="noreferrer">STR_TO_DATE</a> function. Here's an example:</p> <pre><code>CREATE TABLE table1 (`Date` Date); INSERT INTO table1 (`Date`) VALUES (STR_TO_DATE('01/05/2010', '%m/%d/%Y')); SELECT * FROM table1; Date 2010-01-05 </code></pre> <p>To format the results back into the original form look at the <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format" rel="noreferrer">DATE_FORMAT</a> function. Note that you only need to format it if you want to display it as a string using something other than the default format.</p>
2,631,087
How to synchronize HTML5 local/webStorage and server-side storage?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1744522/best-way-to-synchronize-local-html5-db-websql-storage-sqlite-with-a-server-2">Best way to synchronize local HTML5 DB (WebSQL Storage, SQLite) with a server (2 way sync)</a> </p> </blockquote> <p>I'm currently seeking solutions for transparently and automatically synchronizing and replicating across the client-side HTML5 localStorage or web storage and (maybe multiple) server-side storage(s) (the only requirement here that it should be simple and affordable to install on a regular hosting service).</p> <p>So do you have any experience with such libraries/technologies that offer data storage which automate the client-server storage synchronization and allow data to be available either offline or online or both? I think this is a fairly common scenario of web applications supporting offline mode...</p>
10,693,863
4
1
null
2010-04-13 15:58:40.803 UTC
16
2020-04-16 11:05:57.35 UTC
2017-05-23 10:29:27.657 UTC
null
-1
null
90,874
null
1
35
html|web-applications|storage|offline-mode|firebase
35,630
<p><a href="http://www.firebase.com/how-it-works.html" rel="nofollow noreferrer">Firebase</a> offers this functionality as a service. Another alternative is <a href="https://parse.com" rel="nofollow noreferrer">Parse</a>.</p>
3,189,454
How to know when a web page was last updated?
<p>How can you detect when somebody else's web page was last updated (or was changed)?</p>
3,189,954
4
7
null
2010-07-06 19:16:30.84 UTC
14
2017-08-11 13:02:51.613 UTC
2017-08-11 13:02:51.613 UTC
null
1,000,551
null
224,859
null
1
51
html|updates
121,570
<p>The last changed time comes with the assumption that the web server provides accurate information. Dynamically generated pages will likely return the time the page was viewed. However, static pages are expected to reflect actual file modification time.</p> <p>This is propagated through the HTTP header <a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers" rel="noreferrer"><code>Last-Modified</code></a>. The Javascript trick by AZIRAR is clever and will display this value. Also, in Firefox going to Tools->Page Info will also display in the "Modified" field.</p>
37,833,495
Add Icons+Text to TabLayout
<p>I am working on a screen which contains Three tabs I am trying to add an icon with My text in tabs and i want the image to be upper the text and there should be some space between them it is my code.</p> <pre><code>public class HomeScreen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private Toolbar toolbar; private ViewPager pager; private ViewPagerAdapter adapter; private SlidingTabLayout tabs; private CharSequence Titles[] = {"News", "Most Views", "Chart"}; int Numboftabs = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); //MAhmoud Code Addtion // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setIcon(R.drawable.ic_launcher); // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles // fot the Tabs and Number Of Tabs. adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.tabs); tabs.setDistributeEvenly(true); tabs.setViewPager(pager); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } }} </code></pre> <p>ViewPagerAdapter</p> <pre><code>public class ViewPagerAdapter extends FragmentStatePagerAdapter { CharSequence Titles[]; int NumbOfTabs; public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) { super(fm); this.Titles = mTitles; this.NumbOfTabs = mNumbOfTabsumb; } // This method return the fragment for the every position in the View Pager @Override public Fragment getItem(int position) { switch (position) { case 0: return new Tap1(); case 1: return new Tap2(); case 2: return new Tap3(); } return null; } // This method return the titles for the Tabs in the Tab Strip @Override public CharSequence getPageTitle(int position) { return Titles[position]; } // This method return the Number of tabs for the tabs Strip @Override public int getCount() { return NumbOfTabs; }} </code></pre>
37,833,589
4
0
null
2016-06-15 10:57:57.073 UTC
21
2021-12-07 11:48:39.16 UTC
2017-03-25 09:03:25.077 UTC
null
4,407,266
null
6,056,262
null
1
26
android|android-layout|material-design|android-tabs|android-tablayout
76,514
<p>Try this way this is exactly what you looking for</p> <p><a href="http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/" rel="noreferrer">http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/</a></p> <pre><code>public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private int[] tabIcons = { R.drawable.ic_tab_favourite, R.drawable.ic_tab_call, R.drawable.ic_tab_contacts }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); setupTabIcons(); } private void setupTabIcons() { tabLayout.getTabAt(0).setIcon(tabIcons[0]); tabLayout.getTabAt(1).setIcon(tabIcons[1]); tabLayout.getTabAt(2).setIcon(tabIcons[2]); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFrag(new OneFragment(), "ONE"); adapter.addFrag(new TwoFragment(), "TWO"); adapter.addFrag(new ThreeFragment(), "THREE"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List&lt;Fragment&gt; mFragmentList = new ArrayList&lt;&gt;(); private final List&lt;String&gt; mFragmentTitleList = new ArrayList&lt;&gt;(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } } </code></pre> <p><a href="https://i.stack.imgur.com/sx61z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sx61z.png" alt="enter image description here"></a></p>
40,714,555
Python string formatting: is '%' more efficient than 'format' function?
<p>I wanted to compare different to build a string in Python from different variables:</p> <ul> <li>using <code>+</code> to concatenate (referred to as 'plus')</li> <li>using <code>%</code></li> <li>using <code>&quot;&quot;.join(list)</code></li> <li>using <code>format</code> function</li> <li>using <code>&quot;{0.&lt;attribute&gt;}&quot;.format(object)</code></li> </ul> <p>I compared for 3 types of scenari</p> <ul> <li>string with 2 variables</li> <li>string with 4 variables</li> <li>string with 4 variables, each used twice</li> </ul> <p>I measured 1 million operations of each time and performed an average over 6 measures. I came up with the following timings:</p> <pre class="lang-none prettyprint-override"><code> test_plus: 0.29480 test_percent: 0.47540 test_join: 0.56240 test_format: 0.72760 test_formatC: 0.90000 test_plus_long: 0.50520 test_percent_long: 0.58660 test_join_long: 0.64540 test_format_long: 1.03400 test_formatC_long: 1.28020 test_plus_long2: 0.95220 test_percent_long2: 0.81580 test_join_long2: 0.88400 test_format_long2: 1.51500 test_formatC_long2: 1.97160 </code></pre> <p>In each scenario, I came up with the following conclusion</p> <ul> <li>Concatenation seems to be one of the fastest method</li> <li>Formatting using <code>%</code> is much faster than formatting with <code>format</code> function</li> </ul> <p>I believe <code>format</code> is much better than <code>%</code> (e.g. in <a href="https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format">this question</a>) and <code>%</code> was almost deprecated.</p> <p>I have therefore several questions:</p> <ol> <li>Is <code>%</code> really faster than <code>format</code>?</li> <li>If so, why is that?</li> <li>Why is <code>&quot;{} {}&quot;.format(var1, var2)</code> more efficient than <code>&quot;{0.attribute1} {0.attribute2}&quot;.format(object)</code>?</li> </ol> <hr /> <p>For reference, I used the following code to measure the different timings.</p> <pre><code>import time def timing(f, n, show, *args): if show: print f.__name__ + &quot;:\t&quot;, r = range(n/10) t1 = time.clock() for i in r: f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args) t2 = time.clock() timing = round(t2-t1, 3) if show: print timing return timing class values(object): def __init__(self, a, b, c=&quot;&quot;, d=&quot;&quot;): self.a = a self.b = b self.c = c self.d = d def test_plus(a, b): return a + &quot;-&quot; + b def test_percent(a, b): return &quot;%s-%s&quot; % (a, b) def test_join(a, b): return ''.join([a, '-', b]) def test_format(a, b): return &quot;{}-{}&quot;.format(a, b) def test_formatC(val): return &quot;{0.a}-{0.b}&quot;.format(val) def test_plus_long(a, b, c, d): return a + &quot;-&quot; + b + &quot;-&quot; + c + &quot;-&quot; + d def test_percent_long(a, b, c, d): return &quot;%s-%s-%s-%s&quot; % (a, b, c, d) def test_join_long(a, b, c, d): return ''.join([a, '-', b, '-', c, '-', d]) def test_format_long(a, b, c, d): return &quot;{0}-{1}-{2}-{3}&quot;.format(a, b, c, d) def test_formatC_long(val): return &quot;{0.a}-{0.b}-{0.c}-{0.d}&quot;.format(val) def test_plus_long2(a, b, c, d): return a + &quot;-&quot; + b + &quot;-&quot; + c + &quot;-&quot; + d + &quot;-&quot; + a + &quot;-&quot; + b + &quot;-&quot; + c + &quot;-&quot; + d def test_percent_long2(a, b, c, d): return &quot;%s-%s-%s-%s-%s-%s-%s-%s&quot; % (a, b, c, d, a, b, c, d) def test_join_long2(a, b, c, d): return ''.join([a, '-', b, '-', c, '-', d, '-', a, '-', b, '-', c, '-', d]) def test_format_long2(a, b, c, d): return &quot;{0}-{1}-{2}-{3}-{0}-{1}-{2}-{3}&quot;.format(a, b, c, d) def test_formatC_long2(val): return &quot;{0.a}-{0.b}-{0.c}-{0.d}-{0.a}-{0.b}-{0.c}-{0.d}&quot;.format(val) def test_plus_superlong(lst): string = &quot;&quot; for i in lst: string += str(i) return string def test_join_superlong(lst): return &quot;&quot;.join([str(i) for i in lst]) def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) nb_times = int(1e6) n = xrange(5) lst_numbers = xrange(1000) from collections import defaultdict metrics = defaultdict(list) list_functions = [ test_plus, test_percent, test_join, test_format, test_formatC, test_plus_long, test_percent_long, test_join_long, test_format_long, test_formatC_long, test_plus_long2, test_percent_long2, test_join_long2, test_format_long2, test_formatC_long2, # test_plus_superlong, test_join_superlong, ] val = values(&quot;123&quot;, &quot;456&quot;, &quot;789&quot;, &quot;0ab&quot;) for i in n: for f in list_functions: print &quot;.&quot;, name = f.__name__ if &quot;formatC&quot; in name: t = timing(f, nb_times, False, val) elif '_long' in name: t = timing(f, nb_times, False, &quot;123&quot;, &quot;456&quot;, &quot;789&quot;, &quot;0ab&quot;) elif '_superlong' in name: t = timing(f, nb_times, False, lst_numbers) else: t = timing(f, nb_times, False, &quot;123&quot;, &quot;456&quot;) metrics[name].append(t) # Get Average print &quot;\n===AVERAGE OF TIMINGS===&quot; for f in list_functions: name = f.__name__ timings = metrics[name] print &quot;{:&gt;20}:\t{:0.5f}&quot;.format(name, mean(timings)) </code></pre>
48,465,349
1
7
null
2016-11-21 07:04:36.64 UTC
15
2022-04-29 17:51:48.863 UTC
2022-04-29 17:51:48.863 UTC
null
12,892
null
1,603,480
null
1
52
python|performance
17,603
<ol> <li>Yes, <code>%</code> string formatting is faster than the <code>.format</code> method</li> <li>most likely (this may have a much better explanation) due to <code>%</code> being a syntactical notation (hence fast execution), whereas <code>.format</code> involves <em>at least</em> one extra method call</li> <li>because attribute value access also involves an extra method call, viz. <code>__getattr__</code></li> </ol> <p>I ran a slightly better analysis (on Python 3.8.2) using <code>timeit</code> of various formatting methods, results of which are as follows (pretty-printed with <a href="http://beautifultable.readthedocs.io/en/latest/" rel="nofollow noreferrer">BeautifulTable</a>) -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Type \ num_vars</th> <th style="text-align: right;">1</th> <th style="text-align: right;">2</th> <th style="text-align: right;">5</th> <th style="text-align: right;">10</th> <th style="text-align: right;">50</th> <th style="text-align: right;">250</th> </tr> </thead> <tbody> <tr> <td>f_str_str</td> <td style="text-align: right;">0.056</td> <td style="text-align: right;">0.063</td> <td style="text-align: right;"><strong>0.115</strong></td> <td style="text-align: right;"><strong>0.173</strong></td> <td style="text-align: right;"><strong>0.754</strong></td> <td style="text-align: right;"><strong>3.717</strong></td> </tr> <tr> <td>f_str_int</td> <td style="text-align: right;"><strong>0.055</strong></td> <td style="text-align: right;">0.148</td> <td style="text-align: right;">0.354</td> <td style="text-align: right;">0.656</td> <td style="text-align: right;">3.186</td> <td style="text-align: right;">15.747</td> </tr> <tr> <td>concat_str</td> <td style="text-align: right;">0.012</td> <td style="text-align: right;"><strong>0.044</strong></td> <td style="text-align: right;">0.169</td> <td style="text-align: right;">0.333</td> <td style="text-align: right;">1.888</td> <td style="text-align: right;">10.231</td> </tr> <tr> <td>pct_s_str</td> <td style="text-align: right;">0.091</td> <td style="text-align: right;">0.114</td> <td style="text-align: right;">0.182</td> <td style="text-align: right;">0.313</td> <td style="text-align: right;">1.213</td> <td style="text-align: right;">6.019</td> </tr> <tr> <td>pct_s_int</td> <td style="text-align: right;">0.090</td> <td style="text-align: right;">0.141</td> <td style="text-align: right;">0.248</td> <td style="text-align: right;">0.479</td> <td style="text-align: right;">2.179</td> <td style="text-align: right;">10.768</td> </tr> <tr> <td>dot_format_str</td> <td style="text-align: right;">0.143</td> <td style="text-align: right;">0.157</td> <td style="text-align: right;">0.251</td> <td style="text-align: right;">0.461</td> <td style="text-align: right;">1.745</td> <td style="text-align: right;">8.259</td> </tr> <tr> <td>dot_format_int</td> <td style="text-align: right;">0.141</td> <td style="text-align: right;">0.192</td> <td style="text-align: right;">0.333</td> <td style="text-align: right;">0.620</td> <td style="text-align: right;">2.735</td> <td style="text-align: right;">13.298</td> </tr> <tr> <td>dot_format2_str</td> <td style="text-align: right;">0.159</td> <td style="text-align: right;">0.195</td> <td style="text-align: right;">0.330</td> <td style="text-align: right;">0.634</td> <td style="text-align: right;">3.494</td> <td style="text-align: right;">18.975</td> </tr> <tr> <td>dot_format2_int</td> <td style="text-align: right;">0.158</td> <td style="text-align: right;">0.227</td> <td style="text-align: right;">0.422</td> <td style="text-align: right;">0.762</td> <td style="text-align: right;">4.337</td> <td style="text-align: right;">25.498</td> </tr> </tbody> </table> </div> <p>The trailing <code>_str</code> &amp; <code>_int</code> represent the operation was carried out on respective value types.</p> <p><strong>Kindly note</strong> that the <code>concat_str</code> result for a single variable is essentially just the string itself, so it shouldn't really be considered.</p> <p>My setup for arriving at the results -</p> <pre><code>from timeit import timeit from beautifultable import BeautifulTable # pip install beautifultable times = {} for num_vars in (250, 50, 10, 5, 2, 1): f_str = &quot;f'{&quot; + '}{'.join([f'x{i}' for i in range(num_vars)]) + &quot;}'&quot; # &quot;f'{x0}{x1}'&quot; concat = '+'.join([f'x{i}' for i in range(num_vars)]) # 'x0+x1' pct_s = '&quot;' + '%s'*num_vars + '&quot; % (' + ','.join([f'x{i}' for i in range(num_vars)]) + ')' # '&quot;%s%s&quot; % (x0,x1)' dot_format = '&quot;' + '{}'*num_vars + '&quot;.format(' + ','.join([f'x{i}' for i in range(num_vars)]) + ')' # '&quot;{}{}&quot;.format(x0,x1)' dot_format2 = '&quot;{' + '}{'.join([f'{i}' for i in range(num_vars)]) + '}&quot;.format(' + ','.join([f'x{i}' for i in range(num_vars)]) + ')' # '&quot;{0}{1}&quot;.format(x0,x1)' vars = ','.join([f'x{i}' for i in range(num_vars)]) vals_str = tuple(map(str, range(num_vars))) if num_vars &gt; 1 else '0' setup_str = f'{vars} = {vals_str}' # &quot;x0,x1 = ('0', '1')&quot; vals_int = tuple(range(num_vars)) if num_vars &gt; 1 else 0 setup_int = f'{vars} = {vals_int}' # 'x0,x1 = (0, 1)' times[num_vars] = { 'f_str_str': timeit(f_str, setup_str), 'f_str_int': timeit(f_str, setup_int), 'concat_str': timeit(concat, setup_str), # 'concat_int': timeit(concat, setup_int), # this will be summation, not concat 'pct_s_str': timeit(pct_s, setup_str), 'pct_s_int': timeit(pct_s, setup_int), 'dot_format_str': timeit(dot_format, setup_str), 'dot_format_int': timeit(dot_format, setup_int), 'dot_format2_str': timeit(dot_format2, setup_str), 'dot_format2_int': timeit(dot_format2, setup_int), } table = BeautifulTable() table.column_headers = ['Type \ num_vars'] + list(map(str, times.keys())) # Order is preserved, so I didn't worry much for key in ('f_str_str', 'f_str_int', 'concat_str', 'pct_s_str', 'pct_s_int', 'dot_format_str', 'dot_format_int', 'dot_format2_str', 'dot_format2_int'): table.append_row([key] + [times[num_vars][key] for num_vars in (1, 2, 5, 10, 50, 250)]) print(table) </code></pre> <p>I couldn't go beyond <code>num_vars=250</code> because of the max arguments (255) limit with <code>timeit</code>.</p> <p><strong>tl;dr</strong> - Python string formatting performance : <code>f-strings</code> are fastest and more elegant, but at times (due to some <a href="https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals" rel="nofollow noreferrer">implementation restrictions</a> &amp; being Py3.6+ only), you might have to use other formatting options as necessary.</p>
1,222,392
What is Domain Driven Design (DDD)?
<p>I keep seeing DDD (Domain Driven Design) being used a lot in articles - I have read the Wikipedia entry about DDD but still can't figure out what it actually is and how I would go about implementing it in creating my sites?</p>
1,222,488
2
1
null
2009-08-03 13:33:51.71 UTC
196
2019-08-10 18:14:31.89 UTC
2019-08-10 18:14:31.89 UTC
null
472,495
null
82,197
null
1
305
domain-driven-design
77,767
<p>Firstly, if you don't know that you need it then it's possible that you don't need it. If you don't recognize the problems that DDD solves then maybe you don't have those problems. Even DDD advocates will frequently point out that DDD is only intended for large (>6 month) projects.</p> <p>Assuming that you're still reading at this point, my take on DDD is this:</p> <p>DDD is about trying to make your software a model of a real-world system or process. In using DDD, you are meant to work closely with a <em><a href="http://en.wikipedia.org/wiki/Domain_expert" rel="noreferrer">domain expert</a></em> who can explain how the real-world system works. For example, if you're developing a system that handles the placing of bets on horse races, your domain expert might be an experienced bookmaker.</p> <p>Between yourself and the domain expert, you build a <em>ubiquitous language</em> (UL), which is basically a conceptual description of the system. The idea is that you should be able to write down what the system does in a way that the domain expert can read it and verify that it is correct. In our betting example, the ubiquitous language would include the definition of words such as 'race', 'bet', 'odds' and so on.</p> <p>The concepts described by the UL will form the basis of your object-oriented design. DDD provides some clear guidance on how your objects should interact, and helps you divide your objects into the following categories:</p> <ul> <li>Value objects, which represent a value that might have sub-parts (for example, a date may have a day, month and year)</li> <li>Entities, which are objects with <em>identity</em>. For example, each Customer object has its own identity, so we know that two customers with the same name are not the same customer</li> <li>Aggregate roots are objects that own other objects. This is a complex concept and works on the basis that there are some objects that don't make sense unless they have an owner. For example, an 'Order Line' object doesn't make sense without an 'Order' to belong to, so we say that the Order is the aggregate root, and Order Line objects can only be manipulated via methods in the Order object</li> </ul> <p>DDD also recommends several patterns:</p> <ul> <li><a href="http://martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">Repository</a>, a pattern for persistence (saving and loading your data, typically to/from a database)</li> <li><a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="noreferrer">Factory</a>, a pattern for object creation</li> <li>Service, a pattern for creating objects that manipulate your main domain objects without being a part of the domain themselves</li> </ul> <p>Now, at this point I have to say that if you haven't heard of any of these things before, you shouldn't be trying to use DDD on any project that you have a deadline for. Before attempting DDD, you should be familiar with <a href="http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29" rel="noreferrer">design patterns</a> and <a href="http://martinfowler.com/eaaCatalog/" rel="noreferrer">enterprise design patterns</a>. Knowing these makes DDD a lot easier to grasp. And, as mentioned above, there is a <a href="http://www.infoq.com/minibooks/domain-driven-design-quickly" rel="noreferrer">free introduction to DDD</a> available from InfoQ (where you can also find talks about DDD).</p>
3,087,360
Can't stop animation at end of one cycle
<p>I'm making a CSS animation at the minute, and in it I'm moving stuff and want it to stay at the end position until the user moves their mouse away.</p> <pre><code>body { background: url('osx.jpg'); padding: 0; margin: 0; line-height: 60px; } @-webkit-keyframes item1 { 0% { bottom: -120px; left: 0px; } 10% { bottom: -40px; left: 10px; -webkit-transform: rotate(5deg); } 100% { bottom: -40px; left: 10px; -webkit-transform: rotate(5deg); } } @-webkit-keyframes item2 { 0% { bottom: -120px; left: 0px; } 10% { bottom: 60px; left: 20px; -webkit-transform: rotate(7deg); } 100% { bottom: 60px; left: 20px; -webkit-transform: rotate(7deg); } } @-webkit-keyframes item3 { 0% { bottom: -120px; left: 0px; } 10% { bottom: 160px; left: 30px; -webkit-transform: rotate(9deg); } 100% { bottom: 160px; left: 30px; -webkit-transform: rotate(9deg); } } div { position: relative; } #folder { width: 120px; margin: 0px auto; } #folder &gt; div { position: absolute; } #folder:hover &gt; div:nth-of-type(1) { -webkit-animation-name: item1; -webkit-animation-duration: 10s; } #folder:hover &gt; div:nth-of-type(2) { -webkit-animation-name: item2; -webkit-animation-duration: 10s; } #folder:hover &gt; div:nth-of-type(3) { -webkit-animation-name: item3; -webkit-animation-duration: 10s; } </code></pre> <p>Whenever the animation ends though, it just repeats itself. I only want it to happen once and stay where it is until the user moves away. I tried using the paused thing from the spec but it doesn't work as I'd expect it to. Any help is appreciated. Thanks. :)</p>
5,871,862
5
0
null
2010-06-21 18:28:22.46 UTC
10
2015-02-05 23:13:17.867 UTC
2010-06-22 11:11:56.873 UTC
null
258,127
null
372,457
null
1
50
animation|webkit|css
72,856
<p>The following comment worked for me. Thanks michael</p> <p>"You need to add the fill-mode to freeze the animation state at the end of the animation. </p> <pre><code>-webkit-animation-fill-mode: forwards; </code></pre> <p><code>forwards</code> leaves the animation in the state of the last frame</p> <p><code>backwards</code> leaves the animation at the start</p>
2,522,579
How do I get the real .height() of a overflow: hidden or overflow: scroll div?
<p>I have a question regarding how to get a div height. I'm aware of <code>.height()</code> and <code>innerHeight()</code>, but none of them does the job for me in this case. The thing is that in this case I have a div that is overflown width a overflow: scroll and the div has a fixed height.</p> <p>If I use <code>.height()</code> or <code>innerHeight()</code>, both of them gives me the height of the visible area, but if I want the overflown taken in to account, how do I go about? </p>
2,522,592
6
0
null
2010-03-26 10:44:44.99 UTC
33
2022-05-19 13:44:39.583 UTC
2016-11-30 13:41:15.97 UTC
null
863,110
null
260,877
null
1
174
jquery|height|overflow
136,136
<p>Use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight" rel="noreferrer"><code>.scrollHeight</code></a> property of the DOM node: <code>$('#your_div')[0].scrollHeight</code></p>
3,030,480
How do I select elements of an array given condition?
<p>Suppose I have a numpy array <code>x = [5, 2, 3, 1, 4, 5]</code>, <code>y = ['f', 'o', 'o', 'b', 'a', 'r']</code>. I want to select the elements in <code>y</code> corresponding to elements in <code>x</code> that are greater than 1 and less than 5.</p> <p>I tried</p> <pre><code>x = array([5, 2, 3, 1, 4, 5]) y = array(['f','o','o','b','a','r']) output = y[x &gt; 1 &amp; x &lt; 5] # desired output is ['o','o','a'] </code></pre> <p>but this doesn't work. How would I do this?</p>
3,030,662
6
0
null
2010-06-12 23:28:05.533 UTC
49
2020-04-02 15:58:38.383 UTC
2020-04-02 15:58:38.383 UTC
null
3,924,118
null
365,440
null
1
187
python|numpy
302,946
<p>Your expression works if you add parentheses:</p> <pre><code>&gt;&gt;&gt; y[(1 &lt; x) &amp; (x &lt; 5)] array(['o', 'o', 'a'], dtype='|S1') </code></pre>
2,467,475
text-decoration: underline vs border-bottom
<p>What is the difference to use <code>{text-decoration: underline}</code> and <code>{border-bottom: ...}</code>?</p> <p>which is easy to style and cross browser compatible?</p> <p>when we should use <code>border-bottom</code> over <code>text-decoration: underline</code>?</p> <p>Would it be good to use <code>border-bottom</code> always in place of <code>text-decoration: underline</code>?</p>
2,467,484
7
0
null
2010-03-18 04:08:56.147 UTC
4
2017-11-06 18:17:46.46 UTC
2013-03-25 09:45:02.88 UTC
null
362,951
null
84,201
null
1
17
css
43,221
<p><code>border-bottom</code> puts a line at the bottom of the element box. <code>text-decoration:underline</code> renders the text underlined. The exact difference depends on the HTML and text layout engines in use, but in general if you want text underlined, then underline it.</p>
2,654,839
Rounding a double to turn it into an int (java)
<p>Right now I'm trying this: </p> <pre><code>int a = round(n); </code></pre> <p>where <code>n</code> is a <code>double</code> but it's not working. What am I doing wrong? </p>
2,654,897
8
3
null
2010-04-16 17:05:26.813 UTC
12
2018-02-03 15:13:13.417 UTC
2016-10-24 19:01:33.09 UTC
null
21,926
null
282,315
null
1
134
java|double|int|rounding
296,233
<p>What is the return type of the <code>round()</code> method in the snippet?</p> <p>If this is the <code>Math.round()</code> method, it returns a Long when the input param is Double.</p> <p>So, you will have to cast the return value:</p> <pre><code>int a = (int) Math.round(doubleVar); </code></pre>
2,915,927
More efficient way to remove an element from an array in Actionscript 3
<p>I have an array of objects. Each object has a property called name. I want to efficiently remove an object with a particular name from the array. Is this the BEST way?</p> <pre><code> private function RemoveSpoke(Name:String):void { var Temp:Array=new Array; for each (var S:Object in Spokes) { if (S.Name!=Name) { Temp.push(S); } } Spokes=Temp; } </code></pre>
2,916,776
9
0
null
2010-05-26 19:05:40.057 UTC
11
2011-08-29 19:45:27.307 UTC
2010-05-26 21:04:44.61 UTC
null
233,406
null
247,029
null
1
6
apache-flex|actionscript-3|air
19,318
<p>If you are willing to spend some memory on a lookup table this will be pretty fast:</p> <pre><code>private function remove( data:Array, objectTable:Object, name:String):void { var index:int = data.indexOf( objectTable[name] ); objectTable[name] = null; data.splice( index, 1 ); } </code></pre> <p>The test for this looks like this:</p> <pre><code>private function test():void{ var lookup:Object = {}; var Spokes:Array = []; for ( var i:int = 0; i &lt; 1000; i++ ) { var obj:Object = { name: (Math.random()*0xffffff).toString(16), someOtherProperty:"blah" }; if ( lookup[ obj.name ] == null ) { lookup[ obj.name ] = obj; Spokes.push( obj ); } } var t:int = getTimer(); for ( var i:int = 0; i &lt; 500; i++ ) { var test:Object = Spokes[int(Math.random()*Spokes.length)]; remove(Spokes,lookup,test.name) } trace( getTimer() - t ); </code></pre> <p>}</p>
2,821,040
How do I get the time difference between two DateTime objects using C#?
<p>How do I get the time difference between two <code>DateTime</code> objects using C#?</p>
2,821,078
9
0
null
2010-05-12 17:03:46.85 UTC
33
2018-07-28 10:39:06.227 UTC
2016-08-27 02:13:01.287 UTC
null
1,524,477
null
334,369
null
1
180
c#|datetime
353,331
<p>The following example demonstrates how to do this:</p> <pre><code>DateTime a = new DateTime(2010, 05, 12, 13, 15, 00); DateTime b = new DateTime(2010, 05, 12, 13, 45, 00); Console.WriteLine(b.Subtract(a).TotalMinutes); </code></pre> <p>When executed this prints "30" since there is a 30 minute difference between the date/times.</p> <p>The result of <code>DateTime.Subtract(DateTime x)</code> is a <a href="http://msdn.microsoft.com/en-us/library/system.timespan.aspx" rel="noreferrer">TimeSpan Object</a> which gives other useful properties.</p>
2,857,376
Difference between Java SE/EE/ME?
<p>Which one should I install when I want to start learning Java? I'm going to start with some basics, so I will write simple programs that create files, directories, edit XML files and so on, nothing too complex for now.</p> <p>I guess Java SE (Standard Edition) is the one I should install on my Windows 7 desktop. I already have Komodo IDE which I will use to write the Java code.</p>
2,857,791
14
1
null
2010-05-18 12:53:12.77 UTC
149
2019-03-12 11:17:50.38 UTC
2015-10-17 11:08:33.267 UTC
null
4,170,582
null
95,944
null
1
325
java|jakarta-ee|java-me
413,352
<p><strong>Java SE</strong> = <strong>Standard Edition</strong>. This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...). </p> <p><strong>Java EE</strong> = <strong>Enterprise Edition</strong>. From Wikipedia: </p> <blockquote> <p>The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server.</p> </blockquote> <p>In other words, if your application demands a very large scale, distributed system, then you should consider using Java EE. Built on top of Java SE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (<a href="http://en.wikipedia.org/wiki/Java_Message_Service" rel="noreferrer">JMS</a>), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, Java Server Pages, etc...</p> <p><strong>Java ME</strong> = <strong>Micro Edition</strong>. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. Java ME provides a subset of the functionality of Java SE, but also introduces libraries specific to mobile devices. Because Java ME is based on an earlier version of Java SE, some of the new language features introduced in Java 1.5 (e.g. generics) are not available.</p> <p>If you are new to Java, definitely start with Java SE. </p>
2,706,797
Finding what branch a Git commit came from
<p>Is there a way to find out what branch a commit comes from given its <a href="http://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA-1</a> hash value? </p> <p>Bonus points if you can tell me how to accomplish this using Ruby Grit.</p>
2,707,110
17
2
null
2010-04-25 01:23:33.343 UTC
230
2022-09-14 17:23:55.51 UTC
2019-12-04 12:12:19.97 UTC
null
63,550
null
2,066
null
1
826
git
314,650
<p>While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.</p> <h1>Find branches the commit is on</h1> <pre><code>git branch -a --contains &lt;commit&gt; </code></pre> <p>This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.</p> <h1>Search the reflogs</h1> <p>If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:</p> <pre><code>git reflog show --all | grep a871742 </code></pre> <p>to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:</p> <pre><code>a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite </code></pre> <p>indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.</p> <p><code>git reflog show</code> is actually just an alias for <code>git log -g --abbrev-commit --pretty=oneline</code>, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!</p> <p>If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.</p> <h1>Find a subsequent merge commit</h1> <p>This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:</p> <pre><code>git log --merges &lt;commit&gt;.. </code></pre> <p>to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.</p> <p>If you want to be able to count on doing this, you may want to use the <code>--no-ff</code> option to <code>git merge</code> to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) <a href="https://stackoverflow.com/questions/2850369/why-uses-git-fast-forward-merging-per-default/2850413#2850413">VonC's answer to a related question</a> helpfully elaborates on this topic.</p>
33,913,878
How to get the captured groups from Select-String?
<p>I'm trying to extract text from a set of files on Windows using the Powershell (version 4):</p> <pre><code>PS &gt; Select-String -AllMatches -Pattern &lt;mypattern-with(capture)&gt; -Path file.jsp | Format-Table </code></pre> <p>So far, so good. That gives a nice set of <code>MatchInfo</code> objects:</p> <pre><code>IgnoreCase LineNumber Line Filename Pattern Matches ---------- ---------- ---- -------- ------- ------- True 30 ... file.jsp ... {...} </code></pre> <p>Next, I see that the captures are in the matches member, so I take them out:</p> <pre><code>PS &gt; Select-String -AllMatches -Pattern &lt;mypattern-with(capture)&gt; -Path file.jsp | ForEach-Object -MemberName Matches | Format-Table </code></pre> <p>Which gives:</p> <pre><code>Groups Success Captures Index Length Value ------ ------- -------- ----- ------ ----- {...} True {...} 49 47 ... </code></pre> <p>or as list with <code>| Format-List</code>:</p> <pre><code>Groups : {matched text, captured group} Success : True Captures : {matched text} Index : 39 Length : 33 Value : matched text </code></pre> <p>Here's where I stop, I have no idea how to go further and obtain a list of <em>captured group</em> elements.</p> <p>I've tried adding another <code>| ForEach-Object -MemberName Groups</code>, but it seems to return the same as the above.</p> <p>The closest I get is with <code>| Select-Object -Property Groups</code>, which indeed gives me what I'd expect (a list of sets):</p> <pre><code>Groups ------ {matched text, captured group} {matched text, captured group} ... </code></pre> <p>But then I'm unable to extract the <em>captured group</em> from each of them, I tried with <code>| Select-Object -Index 1</code> I get only one of those sets.</p> <hr> <h2>Update: a possible solution</h2> <p>It seems that by adding <code>| ForEach-Object { $_.Groups.Groups[1].Value }</code> I got what I was looking for, but I don't understand why - so I can't be sure I would be able to get the right result when extending this method to whole sets of files.</p> <p>Why is it working?</p> <p>As a side note, this <code>| ForEach-Object { $_.Groups[1].Value }</code> (i.e. without the second <code>.Groups</code>) gives the same result.</p> <p>I'd like to add that, upon further attempts, it seems the command can be shortened by removing the piped <code>| Select-Object -Property Groups</code>.</p>
33,917,063
5
1
null
2015-11-25 10:20:49.667 UTC
7
2020-05-20 14:25:05 UTC
2015-11-25 10:51:40.713 UTC
null
3,127,111
null
3,127,111
null
1
87
regex|powershell|select-string|select-object
76,499
<p>Have a look at the following</p> <pre><code>$a = "http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$' </code></pre> <p><code>$a</code> is now a <code>MatchInfo</code> (<code>$a.gettype()</code>) it contain a <code>Matches</code> property.</p> <pre><code>PS ps:\&gt; $a.Matches Groups : {http://192.168.3.114:8080/compierews/, 192.168.3.114, compierews} Success : True Captures : {http://192.168.3.114:8080/compierews/} Index : 0 Length : 37 Value : http://192.168.3.114:8080/compierews/ </code></pre> <p>in the groups member you'll find what you are looking for so you can write :</p> <pre><code>"http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$' | % {"IP is $($_.matches.groups[1]) and path is $($_.matches.groups[2])"} IP is 192.168.3.114 and path is compierews </code></pre>
51,014,963
Why doesn't `std::stringstream::stringstream(std::string&&)` exist?
<p>I was hoping <code>stringstream</code> has a constructor that steals its initial content from a <code>string&amp;&amp;</code>. Do such inter-species "move constructors" generally not exist in the STL? If not, why not?</p>
51,015,301
2
1
null
2018-06-25 00:19:40.683 UTC
5
2018-06-25 12:35:53.11 UTC
null
null
null
null
827,280
null
1
48
c++|c++17|move-semantics|stringstream|rvalue-reference
2,313
<p>There's history, which is disappointing. But also a future that looks bright.</p> <p>When move semantics went into C++11, it was huge, controversial, and overwhelming. I wanted to be able to move strings into <em>and</em> out of <code>stringstream</code>. However the politics at the time demanded that the internal store did not <em>have</em> to be a <code>basic_string&lt;charT&gt;</code>. For example the internal store could be a <code>vector</code>. And there was no ability to control things with an allocator. In any event, the need was recognized in the C++11 time frame, but it was just a bridge too far.</p> <p>Fortunately Peter Sommerlad has picked up the slack with <a href="http://wg21.link/p0408" rel="noreferrer">P0408</a>. This proposal adds the functionality you seek, hopefully for C++20, but that is not certain yet. It has successfully passed through the LEWG, and is on the LWG's desk right now. They did not get to it this month in Rapperswil, purely because of an overloaded schedule. I am hopeful that it will pass through the LWG, and the full committee vote. It certainly will have my vote.</p>
42,300,463
Elasticsearch - Bootstrap checks failing
<p>I'm trying to use the Flink 5.x Elasticsearch sink connector to insert data to ES 5.2.1 instance hosted on a tiny VM.</p> <p>As this is a tiny VM in development mode, I cant get it to start up to accept TransportClient remote client connections on 9300 without failing the bootstrap checks.</p> <pre><code>[2017-02-17T09:02:48,581][INFO ][o.e.n.Node ] [Z_fiBnl] starting ... [2017-02-17T09:02:48,866][INFO ][o.e.t.TransportService ] [Z_fiBnl] publish_address {xxxxxx:9300}, bound_addresses {127.0.0.1:9300} [2017-02-17T09:02:48,878][INFO ][o.e.b.BootstrapChecks ] [Z_fiBnl] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks ERROR: bootstrap checks failed max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536] max number of threads [1024] for user [xxx] is too low, increase to at least [2048] max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] system call filters failed to install; check the logs and fix your configuration or disable system call filters at your own risk </code></pre> <p>I've played around with the below settings but just cant get it to startup(http clients on 9200 work fine)</p> <pre><code>transport.publish_host: 0.0.0.0 transport.bind_host: 0.0.0.0 http.host: "xxx" http.host: 169.117.72.167 network.host: 0.0.0.0 network.publish_host: 0.0.0.0 </code></pre> <p>Note that ES is running on a tiny VM just for dev purposes and I don't have access to change for ex. the file descriptor limits on this box.</p>
46,028,614
8
0
null
2017-02-17 14:33:03.377 UTC
9
2022-08-06 05:59:28.077 UTC
2019-02-26 10:30:07.55 UTC
null
4,348,824
null
7,581,243
null
1
27
elasticsearch
81,894
<p>I was able to do this by using the below setting available since ES 5.2 discovery.type: single-node (<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/bootstrap-checks.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/current/bootstrap-checks.html</a>)</p> <p>Once I brought up the ES node with that setting, I was able to connect using the transport client from a non localhost client which was a problem before. </p>
10,525,600
What is the purpose of $.fn.foo.Constructor = Foo in Twitter Bootstrap JS
<p>All of the jQuery plugins for Twitter Bootstrap follow the same basic pattern of defining a class that controls the behavior of the plugin. Near the end, they do this:</p> <pre><code>$.fn.alert.Constructor = Alert </code></pre> <p>What is this doing?</p> <p>I assume that this is defining a prototype constructor, but they use an uppercase C. Does case not matter here? Beyond that, I don't really understand what this is doing and how it's getting used by the plugin.</p> <p>As an example, here is the Alert plugin: <a href="https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alert.js">https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alert.js</a></p>
10,526,115
1
0
null
2012-05-09 23:33:47.52 UTC
9
2012-05-15 16:16:36.537 UTC
2012-05-15 16:16:36.537 UTC
null
630,716
null
630,716
null
1
12
javascript|jquery
2,663
<p>There is no magic here, <code>Constructor</code> (big C) as a property has no special meaning. THis is merely convention.</p> <p>Basically they are using a class like structure to define the functionality</p> <pre><code>var Alert = function() {}; Alert.prototype.foo = function() {}; </code></pre> <p>and exposing it through a non-class like interface.</p> <pre><code>$('#blurf').alert(); </code></pre> <p>So this is simply a useful plugin convention. Each jQuery plugin defines itself primary method on the <code>$.fn</code> object, which has access to the constructors it needs via the closure. But the constructor itself is private to that closure. Assign it to <code>$.fn.myplugin.Constructor</code> simply makes that constructor accessible to other code, allowing you to have advanced control if necesary</p> <pre><code>var myAlert = new $.fn.alert.Constructor('Hello World'); // or something </code></pre> <p>Now you could something like this instead:</p> <pre><code>$.fn.alert.Alert = Alert; </code></pre> <p>This is, subjectively, ugly and redundant. And now you would have to translate or guess the property name that leads to the constructor. If you say each plugin is implemented with a single class, and each class constructor can be found at <code>$.fn.myplugin.Constructor</code> then you have a consistent interface for accessing the classes behind each plugin.</p> <p>So again, this is merely convention, nothing too special about it.</p>
10,287,298
Dynamic UITableView Cell Height Based on Contents
<p>I have a <code>UITableView</code> that is populated with custom cells (inherited from <code>UITableViewCell</code>), each cell contains a <code>UIWebView</code> that is automatically resize based on it's contents. Here's the thing, how can I change the height of the <code>UITableView</code> cells based on their content (variable <code>webView</code>).</p> <p>The solution must be dynamic since the HTML used to populate the <code>UIWebViews</code> is parsed from an ever changing feed.</p> <p>I have a feeling I need to use the <code>UITableView</code> delegate method <code>heightForRowAtIndexPath</code> but from it's definition:</p> <pre><code> - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { ;//This needs to be variable } </code></pre> <p>I can't access the cell or it's contents. Can I change the height of the cell in <code>cellForRowAtIndexPath</code>?</p> <p>Any help would be grand. Thanks.</p> <h1>Note</h1> <p>I asked this question over 2 years ago. With the intro of auto layout the best solution for iOS7 can be found:</p> <p><a href="https://stackoverflow.com/questions/18746929">Using Auto Layout in UITableView for dynamic cell layouts &amp; variable row heights</a></p> <p>and on iOS8 this functionality is built in the SDK</p>
10,287,426
12
0
null
2012-04-23 19:53:49.553 UTC
8
2021-11-09 08:47:59.883 UTC
2021-11-09 08:47:59.883 UTC
null
8,090,893
null
1,050,447
null
1
26
ios|objective-c|iphone|uitableview|cocoa-touch
62,974
<p>The best way that I've found for dynamic height is to calculate the height beforehand and store it in a collection of some sort (probably an array.) Assuming the cell contains mostly text, you can use <code>-[NSString sizeWithFont:constrainedToSize:lineBreakMode:]</code> to calculate the height, and then return the corresponding value in <code>heightForRowAtIndexPath:</code></p> <p>If the content is constantly changing, you could implement a method that updated the array of heights when new data was provided.</p>
10,364,429
How to commit to remote git repository
<p>I am new to git.<br /> I have done a clone of remote repo as follows</p> <pre><code>git clone https://[email protected]/repo.git </code></pre> <p>then I did</p> <pre><code>git checkout master </code></pre> <p>made some changes and committed these changes to my local repository like below..</p> <pre><code>git add . git commit -m &quot;my changes&quot; </code></pre> <p>Now I have to push these changes to the remote repository.<br /> I am not sure what to do.</p> <p>Would I do a merge of my repo to remote ?<br /> what steps do I need to take ?</p> <p>I have git bash and git gui.</p> <p>Please advise.</p>
10,364,506
5
0
null
2012-04-28 14:32:13.147 UTC
13
2022-06-02 10:58:12.377 UTC
2022-06-02 10:58:12.377 UTC
null
446,477
null
1,185,422
null
1
43
git|git-push
158,443
<p>All You have to do is <code>git push origin master</code>, where <code>origin</code> is the default name (alias) of Your remote repository and <code>master</code> is the remote branch You want to push Your changes to.</p> <p>You may also want to check these out:</p> <ol> <li><a href="http://gitimmersion.com/">http://gitimmersion.com/</a></li> <li><a href="http://progit.org/book/">http://progit.org/book/</a></li> </ol>
5,615,579
How to get original destination port of redirected UDP message?
<p>Using <a href="https://stackoverflow.com/questions/3940612/c-dgram-socket-get-the-receiver-address/5309177#5309177">this thing</a> I can obtain original destination IP address of <code>socket(PF_INET, SOCK_DGRAM, 0)</code> socket.</p> <p>How to get original destination port? </p>
5,814,636
2
0
null
2011-04-11 00:02:22.56 UTC
9
2011-05-03 21:35:38.033 UTC
2017-05-23 11:58:53.6 UTC
null
-1
null
266,720
null
1
10
linux|sockets|udp|redirect|iptables
7,857
<p>Depends on the redirection mechanism. If you are using REDIRECT (which is NAT under the hood), then you need to use SO_ORIGINAL_DST, or libnetfilter_conntrack to query the original destination of the connection before NAT was applied. However since you can serve several connections with the same listener socket, this lookup has to be done for every packet.</p> <p>You can experiment with libnetfilter_conntrack and the services it provides using the conntrack command line tool.</p> <p>An alterntive is to use TPROXY for the redirection, which was meant to be used in cases like this. There you can get the original destination of the packet using an ancillirary message using recvmsg(). The key to look for is the IP_RECVORIGDST setsockopt.</p> <p>More information on TPROXY can be found in the kernel Documentation directory, in a file called tproxy.txt. It is a bit difficult to use, but works more reliably as it is implemented by the stack, rather than the packet filtering subsystem.</p> <p><strong>Edited:</strong> to add how to query UDP destination addresses with TProxy.</p> <ol> <li>open an UDP socket, bind it to 0.0.0.0 or to a more specific IP</li> <li>you enable IP_RECVORIGDST via setsockopt(fd, SOL_IP, IP_RECVORIGDSTADDR, ...)</li> <li>you use recvmsg() instead of recvfrom()/recv() to receive frames</li> <li>recvmsg() will return the packet and a series of ancillary messages,</li> <li>iterate the ancillary messages, and locate the CMSG block with level SOL_IP, index IP_ORIGDSTADDR</li> <li>this CMSG block will contain a struct sockaddr_in with both the IP and the port information.</li> </ol> <p><strong>Edited:</strong> SO_ORIGINAL_DST vs. udp</p> <p>SO_ORIGINAL_DST should work with udp sockets, however the kernel doesn't let you specify the connection endpoints, it'll use the socket that you call SO_ORIGINAL_DST on to get this address information. </p> <p>This means that it'll only work, if the UDP socket is properly bound (to the redirected-to address/port) and connected (to the client in question). Your listener socket is probably bound to 0.0.0.0 and is servicing not just a single, but mulitple clients.</p> <p>However, you don't need to use your actual listener socket to query the destination address. Since since UDP doesn't transmit datagrams on connection establishment, you can create a new UDP socket, bind it to the redirect address and connect it to the client (whose address you know since it sent the first packet to your listener anyway). Then you could use this socket to run SO_ORIGINAL_DST on, however there are culprits:</p> <ol> <li>once you open such a socket, the kernel will prefer that if the client would send additional packets after the first one, not your listener socket</li> <li>this is inherently racy, since by the time your application has a chance to call SO_ORIGINAL_DST, the conntrack entry may have timed out.</li> <li>it is slow and a lot of overhead</li> </ol> <p>The TProxy based method is clearly better.</p>
6,164,809
How does Mono for Android work?
<p>I am interested in how Mono for Android (by Novell) works.</p> <p>My biggest question is around the actual runtime's that are used. Is MfA providing a Mono runtime that wraps and calls down to the Dalvik runtime or is the Dalvik completely bypassed in this operation? Is it something else completely?</p> <p>I am curious because I hear that the Mono runtime has better performance on mobile devices (not that I believe anything I read on the internet...), and really I am just trying to understand the whole thing.</p> <p>Any other general knowledge on the topic of comparing and contrasting Mono/Dalvik runtimes would be appreciated.</p> <p>Thanks!</p>
6,164,881
2
0
null
2011-05-28 22:46:08.153 UTC
7
2015-12-28 08:07:24.843 UTC
null
null
null
null
343,568
null
1
29
android|mono|dalvik|xamarin.android
8,266
<p>It's both! Some things are run directly in Mono on the kernel and some things get passed into the Dalvik system.</p> <p><a href="http://mono-android.net/Documentation/Architecture">http://mono-android.net/Documentation/Architecture</a></p>
33,127,130
Console is throwing Unterminated JSX contents error
<p>I am trying to set up a basic react example using jspm/systemjs and babel. I have this code here to show a simple page and am getting an error </p> <pre><code>import React from 'react'; export default React.createClass({ displayName: 'MainComponent', propTypes: { item: React.PropTypes.object }, render: function render() { return ( &lt;div class="builder-conteiner"&gt; &lt;div&gt;; ); } }); React.render(&lt;MainComponent /&gt;, document.getElementById('app')) </code></pre> <p>Nothing is showing up, the console is throwing "Unterminated JSX contents", and babel is pointing to the <code>react.render</code> line: </p> <pre><code> 17 | React.render(&lt;MainComponent /&gt;, document.getElementById('app')) | ^ </code></pre>
33,127,267
2
1
null
2015-10-14 13:46:47.14 UTC
4
2020-03-02 10:13:04.553 UTC
2020-03-02 10:13:04.553 UTC
null
10,607,772
null
3,201,696
null
1
40
javascript|reactjs|babeljs
76,818
<p>You have 2 unclosed <code>&lt;div&gt;</code> tags in your <code>render()</code> and a semicolon that probably doesn't belong. I'd get rid of those (e.g. close them, delete the semicolon in <code>&lt;div&gt;;</code> if it doesn't belong) and try it again.</p>
33,342,984
Not works fs.readFile in node js
<p>I have:</p> <pre><code> fs.readFile('../services/Prescipcion.xml', "utf8", function (err, data) { console.log("err-&gt;", err); console.log("data", data); }); </code></pre> <p>And it logs: </p> <pre><code>err-&gt; { [Error: ENOENT: no such file or directory, open '../services/Prescipcion.xml'] errno: -2, code: 'ENOENT', syscall: 'open', path: '../services/Prescipcion.xml' } </code></pre> <p>I don't understand why this happens.</p>
53,541,959
5
1
null
2015-10-26 10:04:09.84 UTC
3
2019-11-11 09:04:45 UTC
2017-03-01 02:23:23.227 UTC
null
1,768,033
null
4,536,908
null
1
21
node.js|file|fs
39,734
<p>It worked for me</p> <pre><code> var fs = require("fs"); const readFIle = path =&gt; { fs.readFile(__dirname + path, "utf8", (err, data) =&gt; { if (err) { console.log(err.stack); return; } console.log(data.toString()); }); console.log("Program Ended"); }; </code></pre> <p>usage:</p> <blockquote> <p>readFIle("/input.txt");</p> </blockquote>
19,683,179
Remove 'username' field from django-allauth
<p>When django-registration doesn't support django 1.5 and custom user model. I'm trying use django-allauth, from first look it's great product.</p> <p>Problem i have - username field required, but in my app i don't have username's. So, allauth documentation says:</p> <pre><code>**Available settings:** ACCOUNT_AUTHENTICATION_METHOD (="username" | "email" | "username_email") </code></pre> <p>Specifies the login method to use -- whether the user logs in by entering his username, e-mail address, or either one of both.</p> <p><strong>Ok, i done, and got error:</strong></p> <pre><code>AssertionError at /accounts/signup/ No exception supplied </code></pre> <p><strong>models.py:</strong></p> <pre><code>class MyUser(AbstractBaseUser, PermissionsMixin): title = models.CharField ('Name', max_length=100) email = models.EmailField('Email', max_length=255, unique=True) ... </code></pre> <p><strong>settings.py</strong></p> <pre><code>ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = ('email') AUTH_USER_MODEL = 'internboard.MyUser' </code></pre> <p>What i'm doing wrong ?</p>
19,683,532
3
0
null
2013-10-30 13:09:55.483 UTC
5
2020-08-04 02:02:28.09 UTC
null
null
null
null
1,391,525
null
1
31
django|django-allauth
14,530
<p>Thanks, i found, right settings for my task:</p> <pre><code>ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False </code></pre>
21,166,927
Incrementing date object by hours/minutes in Groovy
<p>I want to add hours or minutes to a current date. For example I create a Date object with current time and date, and I want to increment it by 30min, how can I do such thing in Grails/Groovy ?</p> <blockquote> <p><strong>Date Now</strong> : Thu Jan 16 11:05:48 EST 2014<br> <strong>Adding 30min to Now</strong> : Thu Jan 16 11:35:48 EST 2014</p> </blockquote> <p>I was wondering if I could do the same that we can do with add 1 to date and it moves it a day ahead.</p>
21,166,991
2
1
null
2014-01-16 16:08:37.903 UTC
7
2021-10-14 18:30:42.01 UTC
2014-01-16 16:14:28.45 UTC
null
6,509
null
3,005,591
null
1
34
datetime|groovy
43,607
<p>You can use TimeCategory</p> <pre><code>import groovy.time.TimeCategory currentDate = new Date() println currentDate use( TimeCategory ) { after30Mins = currentDate + 30.minutes } println after30Mins </code></pre>
20,975,928
Moving the cursor through long soft-wrapped lines in Vim
<p>I'm sorry if my question isn't very clear. I'm not sure how to phrase it. </p> <p>I'd like to use VIM to write papers for some classes I'm in. The problem I'm having is with the formatting of lines in the editor. If I don't explicitly break the end of a line with the enter key, when I try to move the cursor through the text, it skips multiple lines if I have a sentence that spans more than one line. Is there any way to make it so that the cursor will be able to move through the text akin to the way it does in most word processors?</p>
20,976,014
5
1
null
2014-01-07 15:48:16.127 UTC
10
2022-04-21 13:52:04.057 UTC
2014-01-08 19:14:44.54 UTC
null
329,063
null
2,845,038
null
1
21
vim|text|formatting
5,239
<p>Have you tried the following in vim command line:</p> <pre><code>:set nowrap </code></pre>
21,234,025
Making a bash script switch to interactive mode and give a prompt
<p>I am writing a training tool, it is written in bash to teach bash/unix. </p> <p>I want a script to run to set things up, then to hand control to the user. I want it to be easily runnable by typing <code>./script-name</code></p> <p>How do I do this?</p> <p>I.E.</p> <ul> <li>User types: <code>tutorial/run</code></li> <li>The run-tutorial script sets things up.</li> <li>The user is presented with a task. (this bit works)</li> <li>The command prompt is returned, with the shell still configured.</li> </ul> <p>Currently it will work if I type <code>. tutorial/bashrc</code></p>
21,234,252
2
1
null
2014-01-20 12:23:16.47 UTC
8
2020-02-19 22:19:32.733 UTC
2014-01-20 12:41:32.827 UTC
null
537,980
null
537,980
null
1
16
bash
16,087
<p>There are several options:</p> <ul> <li>You start script in the same shell, using <code>source</code> or <code>.</code>;</li> <li>You start a new shell but with your script as a initialization script:</li> </ul> <p>The first is obvious; I write a little bit more details about the second.</p> <p>For that, you use <code>--init-file</code> option:</p> <pre><code>bash --init-file my-init-script </code></pre> <p>You can even use this option in the shebang line:</p> <pre><code>#!/bin/bash --init-file </code></pre> <p>And then you start you script as always:</p> <pre><code>./script-name </code></pre> <p>Example:</p> <pre><code>$ cat ./script-name #!/bin/bash --init-file echo Setting session up PS1='.\$ ' A=10 $ ./script-name Setting session up .$ echo $A 10 .$ exit $ echo $A $ </code></pre> <p>As you can see, the script has made the environment for the user and then has given him the prompt.</p>
21,598,339
How to connect with mongodb using sailsjs v0.10?
<p>Now Using sailsjs v0.10 . Configure connections.js and models.js and change it to connection: 'localMongodbServer' ,installed npm install sails-mongo.</p> <p>Aftet all this it shows error</p> <pre><code> var des = Object.keys(dbs[collectionName].schema).length === 0 ? ^ TypeError: Cannot read property 'schema' of undefined at Object.module.exports.adapter.describe (app1_test/node_modules/sails-mongo/lib/adapter.js:70:48) </code></pre> <p>If change collections.js to adapter.js shows error </p> <pre><code> [err] In model (model1), invalid connection :: someMongodbServer [err] Must contain an `adapter` key referencing the adapter to use. </code></pre>
21,606,276
2
0
null
2014-02-06 09:10:28.377 UTC
8
2014-02-06 17:56:39.167 UTC
null
null
null
null
2,863,075
null
1
17
node.js|mongodb|sails.js
22,664
<p>Without seeing code, i can only assume a few things.</p> <ol> <li>You're starting a new sailsjs v0.10 project</li> <li>You dont have your configuration setup properly.</li> </ol> <p>If this isnt the case, let me know so i can update the answer appropriately.</p> <hr> <p>I have a boilerplate for v0.10 that has a few things baked into it, so you can see how its done. See that repo <a href="https://github.com/mikedevita/sailsjs-v010-passport-local-mongo-email-activation">here</a></p> <p><code>connections.js</code> is the appropriate filename, it was changed in <code>0.10</code>.</p> <p>First make sure sails-mongo is installed.</p> <pre><code>#From your project root run npm install sails-mongo --save </code></pre> <p>Next you need to define your connection, and tell sails what adapter to use for models by default. Here is an example of what <code>connections.js</code> and <code>models.js</code> should look like.</p> <h2>connections.js</h2> <pre><code>module.exports.connections = { mongodb: { adapter : 'sails-mongo', host : 'localhost', port : 27017, user : '', password : '', database : 'yourdevdb' } } </code></pre> <h1>models.js</h1> <pre><code>module.exports.models = { // Your app's default connection. // i.e. the name of one of your app's connections (see `config/connections.js`) // // (defaults to localDiskDb) connection: 'mongodb' }; </code></pre> <hr> <p>You can also specify your connections in <code>config/local.js</code> to avoid commiting sensitive data to your repository. This is how you do it.</p> <p>You dont need to specify all of the contents, as <code>local.js</code> will override whats defined in <code>connections.js</code> Sails will also combine them.</p> <h2>local.js</h2> <pre><code>module.exports = { connections: { mongodb: { host : 'localhost', port : 27017, user : '', password : '', database : 'yourdevdb' } } } </code></pre> <p>You can even define your adapter in a single model, for instances where you need a single model to talk to a different database type.</p> <p>You do this by specifying the <code>adapter:</code> in your model..</p> <pre><code>module.exports = { adapter: 'myothermongodb', }, config: { user: 'root', password: 'thePassword', database: 'testdb', host: '127.0.0.1' }, </code></pre>
52,980,448
How to disable "just my code" setting in VSCode debugger?
<p>When starting my project in the debugger (C# .NET Core), it states it's debugging "just my code".</p> <p>I want to also debug the libraries, and can't see a setting to disable this anywhere in VSCode.</p> <p>Is it possible to disable?</p>
52,980,481
9
1
null
2018-10-25 02:24:43.08 UTC
11
2022-09-14 08:52:50.117 UTC
null
null
null
null
10,241,703
null
1
69
visual-studio-code|vscode-debugger
60,210
<p>For this you need to change the <code>launch.json</code> file. Inside the <code>launch.json</code> file you have to set <code>"justMyCode"</code> to <code>false</code>.</p> <p>As described <a href="https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#just-my-code" rel="noreferrer">here</a>. (I was pointed to that link through <a href="https://code.visualstudio.com/docs/languages/csharp" rel="noreferrer">this post</a> on the Visual Studio Code site.)</p>
36,883,037
Generate a thumbnail/snapshot of a video file selected by a file input at a specific time
<p>How do I grab a snapshot of a video file selected via <code>&lt;input type="file"&gt;</code> at a specific time in the video silently in-the-background (i.e. no visible elements, flickering, sound, etc.)?</p>
36,883,038
1
0
null
2016-04-27 07:23:44.153 UTC
13
2020-06-13 13:43:40.437 UTC
2016-04-28 00:23:36.437 UTC
user1693593
null
null
6,249,022
null
1
13
javascript|jquery|html5-canvas|html5-video|video-thumbnails
12,473
<p>There are four major steps:</p> <ol> <li>Create <code>&lt;canvas&gt;</code> and <code>&lt;video&gt;</code> elements.</li> <li>Load the <code>src</code> of the video file generated by <code>URL.createObjectURL</code> into the <code>&lt;video&gt;</code> element and wait for it to load <strong>by listening for specific events being fired</strong>.</li> <li>Set the time of the video to the point where you want to take a snapshot <strong>and listen for additional events</strong>.</li> <li>Use the canvas to grab the image.</li> </ol> <hr> <h1>Step 1 - Create the elements</h1> <p>This is very easy: just create one <code>&lt;canvas&gt;</code> and one <code>&lt;video&gt;</code> element and append them to <code>&lt;body&gt;</code> (or anywhere really, it doesn't really matter):</p> <pre><code>var canvasElem = $( '&lt;canvas class="snapshot-generator"&gt;&lt;/canvas&gt;' ).appendTo(document.body)[0]; var $video = $( '&lt;video muted class="snapshot-generator"&gt;&lt;/video&gt;' ).appendTo(document.body); </code></pre> <p>Notice that the video element has the attribute <code>muted</code>. Don't put any other attributes like <code>autoplay</code> or <code>controls</code>. Also notice that they both have the class <code>snapshot-generator</code>. This is so we can set the style for both of them so that they are out of the way:</p> <pre><code>.snapshot-generator { display: block; height: 1px; left: 0; object-fit: contain; position: fixed; top: 0; width: 1px; z-index: -1; } </code></pre> <p>Some browsers work with them set to <code>display: none</code>, but other browsers will have serious problems unless they are rendered on the page, so we just make them minuscule so that they are essentially invisible. (Don't move them outside the viewport though, as otherwise you may see some ugly scrollbars on your page.)</p> <h1>Step 2 - Load the video</h1> <p>Here's where things start to get tricky. You need to listen to events to know when to continue. Different browsers will fire different events, different times and in different orders, so I'll save you the effort. There are three events that must always fire at least once before the video is ready; they are:</p> <ul> <li>loadedmetadata</li> <li>loadeddata</li> <li>suspend</li> </ul> <p>Set up the event handler for these events and keep track how many have fired. Once all three have fired, you are ready to proceed. Keep in mind that, since some of these events may fire more than once, you only want to <strong>handle the first event of each type that is fired, and discard subsequent firings.</strong> I used jQuery's <code>.one</code>, which takes care of this.</p> <pre><code>var step_2_events_fired = 0; $video.one('loadedmetadata loadeddata suspend', function() { if (++step_2_events_fired == 3) { // Ready for next step } }).prop('src', insert_source_here); </code></pre> <p>The source should just be the object URL created via <code>URL.createObjectURL(file)</code>, where <code>file</code> is the file object.</p> <h1>Step 3 - Set the time</h1> <p>This stage is similar to the previous: set the time and then listen for an event. Inside our <code>if</code> block from the previous code:</p> <pre><code>$video.one('seeked', function() { // Ready for next step }).prop('currentTime', insert_time_here_in_seconds); </code></pre> <p>Luckily its only one event this time, so it's pretty clear and concise. Finally...</p> <h1>Step 4 - Grab the snapshot</h1> <p>This part is just using the <code>&lt;canvas&gt;</code> element to grab a screenshot. Inside our <code>seeked</code> event handler:</p> <pre><code>canvas_elem.height = this.videoHeight; canvas_elem.width = this.videoWidth; canvas_elem.getContext('2d').drawImage(this, 0, 0); var snapshot = canvas_elem.toDataURL(); // Remove elements as they are no longer needed $video.remove(); $(canvas_elem).remove(); </code></pre> <p>The canvas needs to match the dimensions of the video (<strong>not</strong> the <code>&lt;video&gt;</code> element) to get a proper image. Also, we are setting the canvas's internal <code>.height</code> and <code>.width</code> properties, <strong>not the canvas height/width CSS style values.</strong></p> <p>The value of snapshot is a data URI, which is basically just a string that starts with <code>data:image/jpeg;base64</code> and then the base64 data.</p> <p>Our final JS code should look like:</p> <pre><code>var step_2_events_fired = 0; $video.one('loadedmetadata loadeddata suspend', function() { if (++step_2_events_fired == 3) { $video.one('seeked', function() { canvas_elem.height = this.videoHeight; canvas_elem.width = this.videoWidth; canvas_elem.getContext('2d').drawImage(this, 0, 0); var snapshot = canvas_elem.toDataURL(); // Delete the elements as they are no longer needed $video.remove(); $(canvas_elem).remove(); }).prop('currentTime', insert_time_here_in_seconds); } }).prop('src', insert_source_here); </code></pre> <h1>Celebrate!</h1> <p>You have your image in base64! Send this to your server, put it as the <code>src</code> of an <code>&lt;img&gt;</code> element, or whatever.</p> <p>For example, you can decode it into binary and directly write it to a file <strong>(trim the prefix first)</strong>, which will become a JPEG image file.</p> <p>You could also use this to offer previews of videos while they are uploaded. If you are putting it as the <code>src</code> of an <code>&lt;img&gt;</code>, use the full data URI <strong>(don't remove the prefix)</strong>.</p>
36,746,055
Generate a Spark StructType / Schema from a case class
<p>If I wanted to create a <code>StructType</code> (i.e. a <code>DataFrame.schema</code>) out of a <code>case class</code>, is there a way to do it without creating a <code>DataFrame</code>? I can easily do:</p> <pre><code>case class TestCase(id: Long) val schema = Seq[TestCase]().toDF.schema </code></pre> <p>But it seems overkill to actually create a <code>DataFrame</code> when all I want is the schema.</p> <p>(If you are curious, the reason behind the question is that I am defining a <code>UserDefinedAggregateFunction</code>, and to do so you override a couple of methods that return <code>StructTypes</code> and I use case classes.)</p>
36,746,279
4
0
null
2016-04-20 13:53:26.39 UTC
22
2019-03-01 00:37:26.27 UTC
null
null
null
null
4,856,939
null
1
59
apache-spark|apache-spark-sql
27,592
<p>You can do it the same way <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/SQLContext.scala#L349"><code>SQLContext.createDataFrame</code></a> does it:</p> <pre><code>import org.apache.spark.sql.catalyst.ScalaReflection val schema = ScalaReflection.schemaFor[TestCase].dataType.asInstanceOf[StructType] </code></pre>
46,849,689
Accessing HTTP Error Response Body from HttpInterceptor in Angular
<p>I have an HttpInterceptor to catch errors and display them in a modal. Besides error code and message, I would also like to show the body of the response which actually holds a more precise description of the error (e.g. on a 500 internal server error). How can I achieve this in angular? (I am using version 4.3.6.)</p> <p>I already looked at related questions but answers like HttpErrorResponse._body or similar don't work for me. Also, when inspecting the error response in the console, HttpErrorResponse.error is set to null.</p> <p>Here is how my interceptor currently looks:</p> <pre><code>@Injectable() export class HttpErrorInterceptor implements HttpInterceptor { public constructor(private httpErrorService: HttpErrorService) { } public intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; { return next.handle(req).do(event =&gt; { }, (error: HttpErrorResponse) =&gt; { console.log('HTTPERROR INTERCEPTOR'); console.log(error); if (error.status &gt;= 400) { this.httpErrorService.onError(error); } }); } } </code></pre>
46,850,982
2
0
null
2017-10-20 13:03:59.943 UTC
5
2018-09-19 14:59:53.57 UTC
2017-10-20 17:36:27.667 UTC
null
3,893,569
null
3,893,569
null
1
16
angular|typescript|http-error|angular-http-interceptors
54,736
<h3>The answer applies to versions of Angular below 6.</h3> <p>The body should be available in the <code>error</code> property, so:</p> <pre><code>return next.handle(req).do(event =&gt; { }, (error: HttpErrorResponse) =&gt; { console.log(error.error); // body ... }); </code></pre> <p>Here is the gist of the implementation <a href="https://github.com/angular/angular/blob/7231f5e26a9d319730373ed6ea871d7d7eb2dc6c/packages/common/http/src/xhr.ts#L218" rel="noreferrer">from the sources</a>:</p> <pre><code>if (ok) { ... } else { // An unsuccessful request is delivered on the error channel. observer.error(new HttpErrorResponse({ // The error in this case is the response body (error from the server). error: body, &lt;-------------------- headers, status, statusText, url: url || undefined, })); } </code></pre> <p>To learn more about mechanics behind interceptors read:</p> <ul> <li><a href="https://blog.angularindepth.com/insiders-guide-into-interceptors-and-httpclient-mechanics-in-angular-103fbdb397bf" rel="noreferrer">Insider’s guide into interceptors and HttpClient mechanics in Angular</a></li> </ul>
25,890,533
How can I get a real IP address from DNS query in Swift?
<p>I want to get the IP address (like 192.168.0.1 or 87.12.56.50) from DNS query in Swift. I tried 100 times with 100 different methods ... Nothing helped me, so I'll have to ask for help. This is my code so far:</p> <pre><code>let host = CFHostCreateWithName(nil,"subdomain.of.stackoverflow.com").takeUnretainedValue(); CFHostStartInfoResolution(host, .Addresses, nil); var success: Boolean = 0; let addresses = CFHostGetAddressing(host, &amp;success).takeUnretainedValue() as NSArray; if(addresses.count &gt; 0){ let theAddress = addresses[0] as NSData; println(theAddress); } </code></pre> <p>OK ... These are the links for the code I tried to implement without success: <a href="https://gist.github.com/mikeash/bca3a341db74221625f5" rel="nofollow noreferrer">https://gist.github.com/mikeash/bca3a341db74221625f5</a><br> <a href="https://stackoverflow.com/questions/5000441/how-to-perform-dns-query-on-ios">How to perform DNS query on iOS</a><br> <a href="https://stackoverflow.com/questions/24516170/create-an-array-in-swift-from-an-nsdata-object">Create an Array in Swift from an NSData Object</a><br> <a href="https://stackoverflow.com/questions/24796142/does-cfhostgetaddressing-support-ipv6-dns-entries">Does CFHostGetAddressing() support ipv6 DNS entries?</a><br> <a href="https://stackoverflow.com/questions/24898001/do-a-simple-dns-lookup-in-swift">Do a simple DNS lookup in Swift</a><br></p>
25,891,306
3
0
null
2014-09-17 12:26:23.22 UTC
8
2020-04-27 17:38:10.323 UTC
2020-04-27 17:38:10.323 UTC
null
23,649
null
3,934,005
null
1
12
swift|dns|ip-address
13,274
<p>Your code retrieves the address as a "socket address" structure. <code>getnameinfo()</code> can be used to convert the address into a numerical IP string (code recycled from <a href="https://stackoverflow.com/a/25627545/1187415">https://stackoverflow.com/a/25627545/1187415</a>, now updated to <strong>Swift 2</strong>):</p> <pre><code>let host = CFHostCreateWithName(nil,"www.google.com").takeRetainedValue() CFHostStartInfoResolution(host, .Addresses, nil) var success: DarwinBoolean = false if let addresses = CFHostGetAddressing(host, &amp;success)?.takeUnretainedValue() as NSArray?, let theAddress = addresses.firstObject as? NSData { var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) if getnameinfo(UnsafePointer(theAddress.bytes), socklen_t(theAddress.length), &amp;hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { if let numAddress = String.fromCString(hostname) { print(numAddress) } } } </code></pre> <p>Output (example): <code>173.194.112.147</code></p> <p>Note also the usage of <code>takeRetainedValue()</code> in the first line, because <code>CFHostCreateWithName()</code> has "Create" in its name the therefore returns a (+1) retained object.</p> <hr> <p><strong>Update for Swift 3/Xcode 8:</strong></p> <pre><code>let host = CFHostCreateWithName(nil,"www.google.com" as CFString).takeRetainedValue() CFHostStartInfoResolution(host, .addresses, nil) var success: DarwinBoolean = false if let addresses = CFHostGetAddressing(host, &amp;success)?.takeUnretainedValue() as NSArray?, let theAddress = addresses.firstObject as? NSData { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(theAddress.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(theAddress.length), &amp;hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { let numAddress = String(cString: hostname) print(numAddress) } } </code></pre> <p>Or, to get <em>all</em> IP addresses for the host:</p> <pre><code>let host = CFHostCreateWithName(nil,"www.google.com" as CFString).takeRetainedValue() CFHostStartInfoResolution(host, .addresses, nil) var success: DarwinBoolean = false if let addresses = CFHostGetAddressing(host, &amp;success)?.takeUnretainedValue() as NSArray? { for case let theAddress as NSData in addresses { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(theAddress.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(theAddress.length), &amp;hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { let numAddress = String(cString: hostname) print(numAddress) } } } </code></pre>
8,791,049
Get video NSData from ALAsset url iOS
<p>I am not able to retrieve NSData from the url that I get from ALAsset</p> <p>Below is the code I tried:- I always get NSData as nil.</p> <pre><code> NSData *webData = [NSData dataWithContentsOfURL:[asset defaultRepresentation].url]; </code></pre> <p>I also tried something like this</p> <pre><code> NSData *webData1 = [NSData dataWithContentsOfURL:[[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]]]; </code></pre> <p>The url that I get from the ALAsset:-</p> <p>assets-library://asset/asset.MOV?id=1000000116&amp;ext=MOV</p> <p>I have tried this below link which works but I need to unnecessary write to a temp location which is very time consuming.</p> <p><a href="https://stackoverflow.com/questions/4545982/getting-video-from-alasset">Getting video from ALAsset</a></p> <p>Any hint in right direction would be highly appreciated.</p> <p>Waiting for your replies</p>
8,801,656
2
0
null
2012-01-09 15:46:44.427 UTC
19
2015-11-25 21:04:35.39 UTC
2017-05-23 12:00:25.28 UTC
null
-1
null
248,014
null
1
14
iphone|ios|cocoa-touch|cocoa|alasset
23,168
<p>try this code:-</p> <pre><code>ALAssetRepresentation *rep = [asset defaultRepresentation]; Byte *buffer = (Byte*)malloc((NSUInteger)rep.size); NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil]; NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; </code></pre>
8,832,916
Remove / Replace the username field with email using FOSUserBundle in Symfony2 / Symfony3
<p>I only want to have email as mode of login, I don't want to have username. Is it possible with symfony2/symfony3 and FOSUserbundle?</p> <p>I read here <a href="http://groups.google.com/group/symfony2/browse_thread/thread/92ac92eb18b423fe" rel="noreferrer">http://groups.google.com/group/symfony2/browse_thread/thread/92ac92eb18b423fe</a></p> <p>But then I am stuck with two constraint violations.</p> <p>Problem is if the user leaves the email address blank, I get two constraint violations:</p> <ul> <li>Please enter a username</li> <li>Please enter an email</li> </ul> <p>Is there a way to disable validation for a given field, or a better way to remove a field from the form altogether? </p>
21,064,627
8
0
null
2012-01-12 09:44:56.043 UTC
39
2019-10-21 18:26:44.39 UTC
2017-05-17 06:29:44.403 UTC
null
1,384,374
null
767,244
null
1
56
php|symfony|fosuserbundle
25,846
<h1>A complete overview of what needs to be done</h1> <p>Here is a complete overview of what needs to be done. I have listed the different sources found here and there at the end of this post.</p> <h2>1. Override setter in <code>Acme\UserBundle\Entity\User</code></h2> <pre><code>public function setEmail($email) { $email = is_null($email) ? '' : $email; parent::setEmail($email); $this-&gt;setUsername($email); return $this; } </code></pre> <h2>2. Remove the username field from your form type</h2> <p>(in both <code>RegistrationFormType</code> and <code>ProfileFormType</code>)</p> <pre><code>public function buildForm(FormBuilder $builder, array $options) { parent::buildForm($builder, $options); $builder-&gt;remove('username'); // we use email as the username //.. } </code></pre> <h2>3. Validation constraints</h2> <p>As shown by @nurikabe, we have to get rid of the validation constraints provided by <code>FOSUserBundle</code> and create our own. This means that we will have to recreate all the constraints that were previously created in <code>FOSUserBundle</code> and remove the ones that concern the <code>username</code> field. The new validation groups that we will be creating are <code>AcmeRegistration</code> and <code>AcmeProfile</code>. We are therefore completely overriding the ones provided by the <code>FOSUserBundle</code>.</p> <h3>3.a. Update config file in <code>Acme\UserBundle\Resources\config\config.yml</code></h3> <pre><code>fos_user: db_driver: orm firewall_name: main user_class: Acme\UserBundle\Entity\User registration: form: type: acme_user_registration validation_groups: [AcmeRegistration] profile: form: type: acme_user_profile validation_groups: [AcmeProfile] </code></pre> <h3>3.b. Create Validation file <code>Acme\UserBundle\Resources\config\validation.yml</code></h3> <p>That's the long bit:</p> <pre><code>Acme\UserBundle\Entity\User: properties: # Your custom fields in your user entity, here is an example with FirstName firstName: - NotBlank: message: acme_user.first_name.blank groups: [ &quot;AcmeProfile&quot; ] - Length: min: 2 minMessage: acme_user.first_name.short max: 255 maxMessage: acme_user.first_name.long groups: [ &quot;AcmeProfile&quot; ] # Note: We still want to validate the email # See FOSUserBundle/Resources/config/validation/orm.xml to understand # the UniqueEntity constraint that was originally applied to both # username and email fields # # As you can see, we are only applying the UniqueEntity constraint to # the email field and not the username field. FOS\UserBundle\Model\User: constraints: - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: fields: email errorPath: email message: fos_user.email.already_used groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot; ] properties: email: - NotBlank: message: fos_user.email.blank groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot; ] - Length: min: 2 minMessage: fos_user.email.short max: 255 maxMessage: fos_user.email.long groups: [ &quot;AcmeRegistration&quot;, &quot;ResetPassword&quot; ] - Email: message: fos_user.email.invalid groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot; ] plainPassword: - NotBlank: message: fos_user.password.blank groups: [ &quot;AcmeRegistration&quot;, &quot;ResetPassword&quot;, &quot;ChangePassword&quot; ] - Length: min: 2 max: 4096 minMessage: fos_user.password.short groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot;, &quot;ResetPassword&quot;, &quot;ChangePassword&quot;] FOS\UserBundle\Model\Group: properties: name: - NotBlank: message: fos_user.group.blank groups: [ &quot;AcmeRegistration&quot; ] - Length: min: 2 minMessage: fos_user.group.short max: 255 maxMessage: fos_user.group.long groups: [ &quot;AcmeRegistration&quot; ] FOS\UserBundle\Propel\User: properties: email: - NotBlank: message: fos_user.email.blank groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot; ] - Length: min: 2 minMessage: fos_user.email.short max: 255 maxMessage: fos_user.email.long groups: [ &quot;AcmeRegistration&quot;, &quot;ResetPassword&quot; ] - Email: message: fos_user.email.invalid groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot; ] plainPassword: - NotBlank: message: fos_user.password.blank groups: [ &quot;AcmeRegistration&quot;, &quot;ResetPassword&quot;, &quot;ChangePassword&quot; ] - Length: min: 2 max: 4096 minMessage: fos_user.password.short groups: [ &quot;AcmeRegistration&quot;, &quot;AcmeProfile&quot;, &quot;ResetPassword&quot;, &quot;ChangePassword&quot;] FOS\UserBundle\Propel\Group: properties: name: - NotBlank: message: fos_user.group.blank groups: [ &quot;AcmeRegistration&quot; ] - Length: min: 2 minMessage: fos_user.group.short max: 255 maxMessage: fos_user.group.long groups: [ &quot;AcmeRegistration&quot; ] </code></pre> <h2>4. End</h2> <p>That's it! You should be good to go!</p> <hr /> <p><em>Documents used for this post:</em></p> <ul> <li><a href="https://groups.google.com/forum/#!topic/symfony2/kqyS6xi0I_4" rel="noreferrer">Best way to remove usernames from FOSUserBundle</a></li> <li><a href="https://github.com/symfony/symfony/issues/3224" rel="noreferrer">[Validation] Doesn't override properly</a></li> <li><a href="http://symfony.com/doc/current/reference/constraints/UniqueEntity.html" rel="noreferrer">UniqueEntity</a></li> <li><a href="https://stackoverflow.com/questions/12276327/validating-fosuserbundle-registration-form">Validating fosuserbundle registration form</a></li> <li><a href="http://marcjuch.li/blog/2013/04/21/how-to-use-validation-groups-in-symfony/" rel="noreferrer">How to use validation groups in Symfony</a></li> <li><a href="https://stackoverflow.com/questions/7322441/symfony2-using-validation-groups-in-form">Symfony2 using validation groups in form</a></li> </ul>
57,475,144
How to sign code built using Azure Pipelines using a certificate/key in Azure Key Vault?
<p>We're in the process of moving from on-premise build servers to Azure Pipelines. We produce "shrink-wrap" desktop software so clearly we need to sign all our binaries before releasing. Our current build infrastructure does this using a USB hardware token from GlobalSign, but clearly that isn't going to work when we're doing cloud builds - sadly, clouds are not equipped with USB ports :D</p> <p>Now, GlobalSign has recently started <a href="https://www.globalsign.com/en/code-signing-certificate/" rel="noreferrer">advertising</a> Azure Key Vault as a key storage option, and they're perfectly happy to sell this to us, but I'm not sure how we'd actually integrate that with our build pipelines (or indeed whether that's even possible).</p> <p>Has anyone actually made this work?</p>
57,934,787
3
0
null
2019-08-13 09:45:57.917 UTC
14
2021-10-16 14:50:18.817 UTC
2019-08-21 12:45:08.987 UTC
null
82,561
null
82,561
null
1
37
azure-devops|azure-pipelines|azure-keyvault
18,408
<h1>Code Signing</h1> <p>I've been battling with Azure Key Vault and Azure Pipelines to get our code signed, and succeeded. So here's what I found out.</p> <p>Critically, Extended Validation (EV) certificates used for code signing are very different animals to 'normal' SSL certificates. The standard ones can be exported as much as you like, which means you can upload it to Azure Pipelines and use it with the standard Microsoft Sign Tool.</p> <p>However, once an EV certificate is in Azure Key Vault, it isn't coming out in any usual fashion. You must call it from Pipelines using the excellent <a href="https://github.com/vcsjones/AzureSignTool" rel="noreferrer">Azure Sign Tool</a> as discovered by <a href="https://stackoverflow.com/a/57490154/5363308">Anodyne above</a></p> <p>Get your certificate into Key Vault. You can use any certificate authority you like to generate the certificate, as long as they understand that you'll need an EV certificate, and critically one that has a <strong>hardware security module (HSM)</strong>, and <strong>not</strong> one with a physical USB key. Any cloud based system like Key Vault will need an HSM version.</p> <p>To get the permissions to access this certificate externally you can <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal" rel="noreferrer">follow this page</a> but <strong>beware</strong> it misses a step. So read that document first, then these summarised steps, to get the Key Vault set up:</p> <ol> <li>Open the Azure portal, go to the <code>Azure Active Directory</code> area, and create an <code>App registration</code>: put in a memorable name, ignore the <code>Redirect URI</code>, and save it.</li> <li>Go to your specific <code>Key Vault</code>, then <code>Access control (IAM)</code>, then <code>Add role assignment</code>. Type the name of the app you just created into the <code>select</code> input box. Also choose a <code>Role</code>, I suggest <code>Reader</code> and then save.</li> <li><strong>The Missing Part:</strong> Still in the Key Vault, click the <code>Access policies</code> menu item. Click <code>Add Access Policy</code> and add your application. The <code>Certificate Permissions</code> need to have the <code>Get</code> ticked. And the <code>Key Permissions</code>, despite the fact that you may not have any keys at all in this vault, need to have <code>Get</code> and <code>Sign</code>. You would have thought these two would be in the certificate perms...</li> <li>Go back to the application you just created. Select the <code>Certificates &amp; secrets</code>, and either choose to upload a certificate (a new one purely for accessing the Key Vault remotely) or create a <code>client secret</code>. If the latter, keep a copy of the password, you won't see it again!</li> <li>In the <code>Overview</code> section of the app will be the <code>Application (client) ID</code>. This, and the password or certificate, is what will be fed to the Azure Sign Tool later on in a Pipelines task.</li> </ol> <p>Handling the actual code signing from Azure requires a number of steps. The following applies to Microsoft hosted agents, although similar issues will affect any private agents that you have.</p> <ol> <li><p>The Azure Sign Tool needs the .NET Core SDK to be installed, but a version that's at least version 2.x, and since the <strong>latest</strong> .NET Core SDK is <a href="https://docs.microsoft.com/en-us/dotnet/core/versions/selection" rel="noreferrer">always used</a>, this means as long as the version of Windows is current enough, you don't need to install it yourself. And you can see which version of the <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops#use-a-microsoft-hosted-agent" rel="noreferrer">SDK is shipped with which Windows agent</a>.</p> <p>The current <code>Hosted</code> OS version in Azure Pipelines, also called <code>Default Hosted</code>, is, at the time of writing, Windows Server 2012 R2. Which isn't up to date enough. Installing a newer .NET Core SDK to overcome this is a time drag on every build, and although the installation works, calling the Azure Sign Tool may not work. It seems to be finding only older versions of the SDK, and throws this error: <code>Unable to find an entry point named 'SignerSignEx3' in DLL 'mssign32'.</code></p> <p>So the easiest thing to do is change your build to use a later OS image. Windows 2019 works like a charm. And there is no need to install any version of .NET Core.</p> </li> <li><p>Then create a command line task to install the Azure Sign Tool. You can use a .NET Core CLI task as well, but there is no need. In the task, type this:</p> <pre><code>set DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true dotnet tool install --global AzureSignTool --version 2.0.17 </code></pre> <p>Naturally using whichever version that you want.</p> <p>The DOTNET_SKIP_FIRST_TIME_EXPERIENCE environment variable isn't strictly necessary, but setting it speeds things up quite a bit (<a href="http://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds" rel="noreferrer">see here for an explanation</a>).</p> </li> <li><p>Finally, create another command line task and type in the Azure Sign Tool command that you wish to run with. On Windows this would be something like below, note with <code>^</code> not <code>/</code> as a line continuation marker. Naturally, see <a href="https://github.com/vcsjones/AzureSignTool" rel="noreferrer">here for more parameter information</a>:</p> <pre><code> AzureSignTool.exe sign -du &quot;MY-URL&quot; ^ -kvu https://MY-VAULT-NAME.vault.azure.net ^ -kvi CLIENT-ID-BIG-GUID ^ -kvs CLIENT-PASSWORD ^ -kvc MY-CERTIFICATE-NAME ^ -tr http://timestamp.digicert.com ^ -v ^ $(System.DefaultWorkingDirectory)/Path/To/My/Setup/Exe </code></pre> </li> </ol> <p>And in theory, you should have success! The output of the sign tool is rather good, and usually nails where the problem is.</p> <h1>Re-issuing Certificates</h1> <p>If you need to re-issue a certificate, the situation is quite different.</p> <ol> <li><p>In Azure, go to the certificate and click on it, opening a page showing the versions of that certificate, both current and older versions.</p> </li> <li><p>Click the 'New Version' button, probably accepting the defaults (depending on the choices you wish to make) and click 'Create'.</p> </li> <li><p>This takes you back to the Versions page, and there will be a message box stating 'The creation of certificate XXXX is currently pending'. Click there (or on the 'Certificate Operation' button) to open the 'Certificate Operation' side page. Once there, download the CSR (certificate signing request).</p> </li> <li><p>In GlobalSign, follow their instructions to <a href="https://support.globalsign.com/digital-certificates/digital-certificates-life-cycle/reissue-certificate-client-digital-certificates" rel="noreferrer">re-issue</a> the existing certificate. Once it has been re-issued, they will send an email describing how to download it.</p> </li> <li><p>Log into GlobalSign again, and after entering the temporary password, open the CSR and copy the whole text (which starts with <code>-----BEGIN CERTIFICATE REQUEST-----</code>) into GlobalSign. Submit it.</p> </li> <li><p>Download using the 'Install My Certificate' button. Then in the Azure 'Certificate Operation' side page - use the 'Merge Signed Request' button that to upload the .CER file to Azure. This creates the new version of the certificate.</p> </li> <li><p>Disable the old version of the certificate.</p> </li> </ol>
48,111,459
How to define a property that can be string or null in OpenAPI (Swagger)?
<p>I have JSON schema file where one of the properties is defined as either <code>string</code> or <code>null</code>:</p> <pre><code>"type":["string", "null"] </code></pre> <p>When converted to YAML (for use with OpenAPI/Swagger), it becomes:</p> <pre class="lang-yaml prettyprint-override"><code>type: - 'null' - string </code></pre> <p>but the Swagger Editor shows an error:</p> <blockquote> <p>Schema "type" key must be a string</p> </blockquote> <p>What is the correct way to define a nullable property in OpenAPI?</p>
48,114,322
1
1
null
2018-01-05 10:17:52.597 UTC
13
2021-02-16 19:53:28.997 UTC
2018-01-05 13:23:15.353 UTC
null
113,116
null
6,827,572
null
1
122
swagger|openapi
88,392
<p>This depends on the OpenAPI version.</p> <h3>OpenAPI 3.1</h3> <p>Your example is valid in OpenAPI 3.1, which is fully compatible with JSON Schema 2020-12.</p> <pre class="lang-yaml prettyprint-override"><code>type: - 'null' # Note the quotes around 'null' - string # same as type: ['null', string] </code></pre> <p>The above is equivalent to:</p> <pre class="lang-yaml prettyprint-override"><code>oneOf: - type: 'null' # Note the quotes around 'null' - type: string </code></pre> <p>The <code>nullable</code> keyword used in OAS 3.0.x (see below) does not exist in OAS 3.1, it was removed in favor of the <code>'null'</code> type.</p> <h3>OpenAPI 3.0.x</h3> <p>Nullable strings are defined as follows:</p> <pre class="lang-yaml prettyprint-override"><code>type: string nullable: true </code></pre> <p>This is different from JSON Schema syntax because OpenAPI versions up to 3.0.x use their own <a href="https://swagger.io/docs/specification/data-models/keywords/" rel="noreferrer">flavor of JSON Schema</a> (&quot;extended subset&quot;). One of the differences is that the <code>type</code> must be a single type and cannot be a list of types. Also there's no <code>'null'</code> type; instead, the <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#schemaNullable" rel="noreferrer"><code>nullable</code></a> keyword serves as a <code>type</code> modifier to allow <code>null</code> values.</p> <h3>OpenAPI 2.0</h3> <p>OAS2 does not support <code>'null'</code> as the data type, so you are out of luck. You can only use <code>type: string</code>. However, some tools support <code>x-nullable: true</code> as a vendor extension, even though nulls are not part of the OpenAPI 2.0 Specification.</p> <p>Consider migrating to OpenAPI v. 3 to get proper support for nulls.</p>
47,997,966
Git failed with a > fatal error. could not read Username for
<p>I've been struggling with that issue for a couple days now. </p> <p>I'm unable to connect to my Git project (stored in VisualStudio.com) from a specific computer (it works on my second PC). Whenever I try to Sync or Clone my repository, VS2017 asks for my user credentials (twice) and the I get the following error : </p> <blockquote> <p>Error: cannot spawn askpass: No such file or directory Error encountered while cloning the remote repository: Git failed with a fatal error. could not read Username for 'https://.visualstudio.com': terminal prompts disabled</p> </blockquote> <p>Can't remember if I changed anything that could've caused that...</p>
48,000,893
13
1
null
2017-12-27 20:01:10.463 UTC
4
2021-08-09 19:06:13.04 UTC
null
null
null
null
527,123
null
1
30
git|visual-studio|visual-studio-2017|azure-devops
61,010
<p>It’s mainly caused by the credentials have been remembered by <strong>Credential Manager</strong>. You should remove the credentials for xxx.visualstudio.com which have been stored in Credential Manager.</p> <p>Such as if the pc’s OS is windows, you can open Credential Manager -> Windows Credentials -> under Generic Credentials -> remove the credentials like git:<a href="https://xxx.visualstudio.com" rel="noreferrer">https://xxx.visualstudio.com</a>.</p> <p><a href="https://i.stack.imgur.com/tPuJA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tPuJA.png" alt="enter image description here"></a></p> <p>Then clone again, git will let you input the credential for the repo. After inputing the username(email address) and password which can access the VSTS account, the repo should be cloned successful.</p>
19,689,127
How to update progressbar in a ListView item
<p>I have a <code>ListView</code> attached to an <code>ArrayAdapter</code>. When the user clicks a download button for an item in the <code>ListView</code> a download starts using the <code>DownloadManager</code>.</p> <p>What I want to do is to track the download progress with a progress bar (placed in the item layout). How can this be achieved?</p> <p>The way Pocket Cast does it is exacly what I'm after:</p> <p><a href="http://www.mrcrab.net/images/thumb_big/9982-Pocket_Casts_Apk_v4.3.2_Android-0.jpg">Pocket Cast exampel http://www.mrcrab.net/images/thumb_big/9982-Pocket_Casts_Apk_v4.3.2_Android-0.jpg</a></p> <p><em>Note: I know how to work with the <code>DownloadManager</code>, it's the instant update of the progress bar that is tricky.</em></p>
20,198,539
2
0
null
2013-10-30 16:55:44.073 UTC
10
2013-11-25 17:23:16.007 UTC
2013-10-30 17:02:06.723 UTC
null
412,390
null
412,390
null
1
15
android|android-listview|android-progressbar|android-download-manager
12,841
<p>This is the way I finally solved it (after many iterations and different implementations). It's a bit tricky but basically you need three things:</p> <ol> <li>An AsyncTask that gathers meta data</li> <li>A scroll listener that tells us when the user has stopped scrolling/flinging</li> <li>A clever algorithm that finds any visible row that needs updating and asks the adapter to only update that specific row</li> </ol> <p>This is the way I designed and implemented it:</p> <p><img src="https://raw.github.com/slidese/SGU/master/2013-11-25-14.45.00.png" alt="Screenshot"></p> <p>I wrote in more detail about <a href="http://slidese.github.io/slidese/2013/11/25/update_listview_item.html" rel="noreferrer">it here</a>, and please see the <a href="https://github.com/slidese/SGU/blob/3be1888115ba56b4a015b127b249c35af5dc11d0/src/se/slide/sgu/ContentFragment.java" rel="noreferrer">github code</a> for the complete imlementation.</p> <pre><code> private class UpdaterAsyncTask extends AsyncTask&lt;Void, Void, Void&gt; { boolean isRunning = true; public void stop() { isRunning = false; } @Override protected Void doInBackground(Void... params) { while (isRunning) { // Gather data about your adapter objects // If an object has changed, mark it as dirty publishProgress(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Void... params) { super.onProgressUpdate(); // Update only when we're not scrolling, and only for visible views if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) { int start = mListview.getFirstVisiblePosition(); for(int i = start, j = mListview.getLastVisiblePosition(); i&lt;=j; i++) { View view = mListview.getChildAt(i-start); if (((Content)mListview.getItemAtPosition(i)).dirty) { mListview.getAdapter().getView(i, view, mListview); // Tell the adapter to update this view } } } } } </code></pre>
33,743,394
Matplotlib DateFormatter for axis label not working
<p>I'm trying to adjust the formatting of the date tick labels of the x-axis so that it only shows the Year and Month values. From what I've found online, I have to use <code>mdates.DateFormatter</code>, but it's not taking effect at all with my current code as is. Anyone see where the issue is? (the dates are the index of the pandas Dataframe)</p> <pre><code>import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd fig = plt.figure(figsize = (10,6)) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) basicDF['some_column'].plot(ax=ax, kind='bar', rot=75) ax.xaxis_date() </code></pre> <p><a href="https://i.stack.imgur.com/i3otd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/i3otd.png" alt="enter image description here"></a></p> <p><strong>Reproducible scenario code:</strong></p> <pre><code>import numpy as np import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd rng = pd.date_range('1/1/2014', periods=20, freq='m') blah = pd.DataFrame(data = np.random.randn(len(rng)), index=rng) fig = plt.figure(figsize = (10,6)) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) blah.plot(ax=ax, kind='bar') ax.xaxis_date() </code></pre> <p>Still can't get just the year and month to show up.</p> <p>If I set the format after .plot , get an error like this:</p> <blockquote> <p>ValueError: DateFormatter found a value of x=0, which is an illegal date. This usually occurs because you have not informed the axis that it is plotting dates, e.g., with a<code>x.xaxis_date()</code>. </p> </blockquote> <p>It's the same for if I put it before ax.xaxis_date() or after.</p>
33,746,112
4
1
null
2015-11-16 19:48:04.593 UTC
12
2021-02-24 17:34:32.75 UTC
2019-01-02 04:01:42.417 UTC
null
541,136
null
4,698,759
null
1
31
python|date|pandas|matplotlib
56,585
<p>pandas just doesn't work well with custom date-time formats.</p> <p>You need to just use raw matplotlib in cases like this.</p> <pre><code>import numpy import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas N = 20 numpy.random.seed(N) dates = pandas.date_range('1/1/2014', periods=N, freq='m') df = pandas.DataFrame( data=numpy.random.randn(N), index=dates, columns=['A'] ) fig, ax = plt.subplots(figsize=(10, 6)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) ax.bar(df.index, df['A'], width=25, align='center') </code></pre> <p>And that gives me:</p> <p><a href="https://i.stack.imgur.com/kh2En.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kh2En.png" alt="enter image description here"></a></p>
23,027,315
Does application.yml support environment variables?
<p>I tried using env variables in my application.yml configration like:</p> <pre><code>spring: main: show_banner: false --- spring: profiles: production server: address: $OPENSHIFT_DIY_IP port: $OPENSHIFT_DIY_PORT </code></pre> <p>but the env variables are not resolved. Do I have to provide a different notation?</p> <p>In Rails you can e.g. use &lt;%= ENV['FOOVAR'] %></p> <p>The only alternative is to run the app like:</p> <pre><code>java -jar my.jar --server.address=$OPENSHIFT_DIY_IP --server.port=$OPENSHIFT_DIY_PORT </code></pre>
23,027,709
4
0
null
2014-04-12 07:03:13.407 UTC
22
2022-08-08 11:11:41.393 UTC
null
null
null
null
1,458,877
null
1
167
java|spring|yaml|spring-boot
153,861
<p>Try <code>${OPENSHIFT_DIY_PORT}</code> (the usual Spring placeholder notation). See <a href="https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.files.property-placeholders" rel="noreferrer">here</a> for docs.</p>
23,122,639
How do I write a computation expression builder that accumulates a value and also allows standard language constructs?
<p>I have a computation expression builder that builds up a value as you go, and has many custom operations. However, it does not allow for standard F# language constructs, and I'm having a lot of trouble figuring out how to add this support.</p> <p>To give a stand-alone example, here's a dead-simple and fairly pointless computation expression that builds F# lists:</p> <pre><code>type Items&lt;'a&gt; = Items of 'a list type ListBuilder() = member x.Yield(()) = Items [] [&lt;CustomOperation("add")&gt;] member x.Add(Items current, item:'a) = Items [ yield! current; yield item ] [&lt;CustomOperation("addMany")&gt;] member x.AddMany(Items current, items: seq&lt;'a&gt;) = Items [ yield! current; yield! items ] let listBuilder = ListBuilder() let build (Items items) = items </code></pre> <p>I can use this to build lists just fine:</p> <pre><code>let stuff = listBuilder { add 1 add 5 add 7 addMany [ 1..10 ] add 42 } |&gt; build </code></pre> <p>However, this is a compiler error:</p> <pre><code>listBuilder { let x = 5 * 39 add x } // This expression was expected to have type unit, but // here has type int. </code></pre> <p>And so is this:</p> <pre><code>listBuilder { for x = 1 to 50 do add x } // This control construct may only be used if the computation expression builder // defines a For method. </code></pre> <p>I've read all the documentation and examples I can find, but there's something I'm just not getting. Every <code>.Bind()</code> or <code>.For()</code> method signature I try just leads to more and more confusing compiler errors. Most of the examples I can find either build up a value as you go along, or allow for regular F# language constructs, but I haven't been able to find one that does both.</p> <p>If someone could point me in the right direction by showing me how to take this example and add support in the builder for <code>let</code> bindings and <code>for</code> loops (at minimum - <code>using</code>, <code>while</code> and <code>try/catch</code> would be great, but I can probably figure those out if someone gets me started) then I'll be able to gratefully apply the lesson to my actual problem.</p>
23,124,468
4
0
null
2014-04-17 00:38:34.317 UTC
8
2020-05-13 14:31:58.34 UTC
null
null
null
null
24,380
null
1
13
f#|computation-expression
2,093
<p>The best place to look is the <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818835">spec</a>. For example,</p> <pre><code>b { let x = e op x } </code></pre> <p>gets translated to</p> <pre><code> T(let x = e in op x, [], fun v -&gt; v, true) =&gt; T(op x, {x}, fun v -&gt; let x = e in v, true) =&gt; [| op x, let x = e in b.Yield(x) |]{x} =&gt; b.Op(let x = e in in b.Yield(x), x) </code></pre> <p>So this shows where things have gone wrong, though it doesn't present an obvious solution. Clearly, <code>Yield</code> needs to be generalized since it needs to take arbitrary tuples (based on how many variables are in scope). Perhaps more subtly, it also shows that <code>x</code> is not in scope in the call to <code>add</code> (see that unbound <code>x</code> as the second argument to <code>b.Op</code>?). To allow your custom operators to use bound variables, their arguments need to have the <code>[&lt;ProjectionParameter&gt;]</code> attribute (and take functions from arbitrary variables as arguments), and you'll also need to set <code>MaintainsVariableSpace</code> to <code>true</code> if you want bound variables to be available to later operators. This will change the final translation to: </p> <pre><code>b.Op(let x = e in b.Yield(x), fun x -&gt; x) </code></pre> <p>Building up from this, it seems that there's no way to avoid passing the set of bound values along to and from each operation (though I'd love to be proven wrong) - this will require you to add a <code>Run</code> method to strip those values back off at the end. Putting it all together, you'll get a builder which looks like this:</p> <pre><code>type ListBuilder() = member x.Yield(vars) = Items [],vars [&lt;CustomOperation("add",MaintainsVariableSpace=true)&gt;] member x.Add((Items current,vars), [&lt;ProjectionParameter&gt;]f) = Items (current @ [f vars]),vars [&lt;CustomOperation("addMany",MaintainsVariableSpace=true)&gt;] member x.AddMany((Items current, vars), [&lt;ProjectionParameter&gt;]f) = Items (current @ f vars),vars member x.Run(l,_) = l </code></pre>
30,845,910
How do I set state of sibling components easily in React?
<p>I have got the beginnings of a clickable list component that will serve to drive a select element. As you can see from the below, <code>onClick</code> of the <code>ListItem</code>, I'm passing the state of a child element (<code>ListItem</code> in this case) to the parents (<code>SelectableList</code>, and <code>CustomSelect</code> component). This is working fine. However, what I would also like to do is change the state of the <em>sibling</em> components (the other ListItems) so that I can toggle their selected states when one of the ListItems is clicked. </p> <p>At the moment, I'm simply using <code>document.querySelectorAll('ul.cs-select li)</code> to grab the elements and change the class to selected when it doesn't match the index of the clicked <code>ListItem</code>. This works - to an extent. However, after a few clicks, the state of the component has not been updated by React (only by client side JS), and things start to break down. What I would like to do is change the <code>this.state.isSelected</code> of the sibling list items, and use this state to refresh the SelectableList component. Could anyone offer a better alternative to what I've written below?</p> <pre><code>var React = require('react'); var SelectBox = require('./select-box'); var ListItem = React.createClass({ getInitialState: function() { return { isSelected: false }; }, toggleSelected: function () { if (this.state.isSelected == true) { this.setState({ isSelected: false }) } else { this.setState({ isSelected: true }) } }, handleClick: function(listItem) { this.toggleSelected(); this.props.onListItemChange(listItem.props.value); var unboundForEach = Array.prototype.forEach, forEach = Function.prototype.call.bind(unboundForEach); forEach(document.querySelectorAll('ul.cs-select li'), function (el) { // below is trying to // make sure that when a user clicks on a list // item in the SelectableList, then all the *other* // list items get class="selected" removed. // this works for the first time that you move through the // list clicking the other items, but then, on the second // pass through, starts to fail, requiring *two clicks* before the // list item is selected again. // maybe there's a better more "reactive" method of doing this? if (el.dataset.index != listItem.props.index &amp;&amp; el.classList.contains('selected') ) { el.classList.remove('selected'); } }); }, render: function() { return ( &lt;li ref={"listSel"+this.props.key} data-value={this.props.value} data-index={this.props.index} className={this.state.isSelected == true ? 'selected' : '' } onClick={this.handleClick.bind(null, this)}&gt; {this.props.content} &lt;/li&gt; ); } }); var SelectableList = React.createClass({ render: function() { var listItems = this.props.options.map(function(opt, index) { return &lt;ListItem key={index} index={index} value={opt.value} content={opt.label} onListItemChange={this.props.onListItemChange.bind(null, index)} /&gt;; }, this); return &lt;ul className="cs-select"&gt;{ listItems }&lt;/ul&gt;; } }) var CustomSelect = React.createClass({ getInitialState: function () { return { selectedOption: '' } }, handleListItemChange: function(listIndex, listItem) { this.setState({ selectedOption: listItem.props.value }) }, render: function () { var options = [{value:"One", label: "One"},{value:"Two", label: "Two"},{value:"Three", label: "Three"}]; return ( &lt;div className="group"&gt; &lt;div className="cs-select"&gt; &lt;SelectableList options={options} onListItemChange={this.handleListItemChange} /&gt; &lt;SelectBox className="cs-select" initialValue={this.state.selectedOption} fieldName="custom-select" options={options}/&gt; &lt;/div&gt; &lt;/div&gt; ) } }) module.exports = CustomSelect; </code></pre>
30,846,426
3
0
null
2015-06-15 13:03:10.26 UTC
11
2018-04-17 00:10:54.107 UTC
2015-06-15 13:19:32.937 UTC
null
52,092
null
52,092
null
1
31
reactjs|siblings
29,441
<p>The parent component should pass a callback to the children, and each child would trigger that callback when its state changes. You could actually hold all of the state in the parent, using it as a single point of truth, and pass the "selected" value down to each child as a prop.</p> <p>In that case, the child could look like this:</p> <pre><code>var Child = React.createClass({ onToggle: function() { this.props.onToggle(this.props.id, !this.props.selected); }, render: function() { return &lt;button onClick={this.onToggle}&gt;Toggle {this.props.label} - {this.props.selected ? 'Selected!' : ''}!&lt;/button&gt;; } }); </code></pre> <p>It has no state, it just fires an <code>onToggle</code> callback when clicked. The parent would look like this:</p> <pre><code>var Parent = React.createClass({ getInitialState: function() { return { selections: [] }; }, onChildToggle: function(id, selected) { var selections = this.state.selections; selections[id] = selected; this.setState({ selections: selections }); }, buildChildren: function(dataItem) { return &lt;Child id={dataItem.id} label={dataItem.label} selected={this.state.selections[dataItem.id]} onToggle={this.onChildToggle} /&gt; }, render: function() { return &lt;div&gt;{this.props.data.map(this.buildChildren)}&lt;/div&gt; } }); </code></pre> <p>It holds an array of selections in state and when it handles the callback from a child, it uses <code>setState</code> to re-render the children by passing its state down in the <code>selected</code> prop to each child.</p> <p>You can see a working example of this here:</p> <p><a href="https://jsfiddle.net/fth25erj/">https://jsfiddle.net/fth25erj/</a></p>
47,349,528
Binding an Angular Material Selection List
<p>I am creating a Toolbar with a selection list (checkboxes with each list item) using Angular Material 2. I just cannot figure out how to set the checkboxes before the list is displayed and then get the selected items following user interaction.</p> <p>I am trying the control within a Form thinking I may need this to bind to ngModel, but this doesn't seem to help. My html so far is:</p> <pre class="lang-xml prettyprint-override"><code>&lt;form novalidate #areaSelectForm="ngForm"&gt; &lt;div&gt; &lt;mat-selection-list #areasList="ngModel" [(ngModel)]="model" id="areaListControl" name="areaListControl" (ngModelChange)="onAreaListControlChanged($event)"&gt; &lt;mat-list-option *ngFor="let tta of taskTypeAreas" (click)="onCheckboxClick($event)" [value]="tta"&gt; {{tta}} &lt;/mat-list-option&gt; &lt;/mat-selection-list&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>This must be a well trodden path but the documentation is difficult to interpret and I cannot seem to find any suitable examples.</p> <p>Any guidance very welcome please.</p>
47,353,504
3
0
null
2017-11-17 11:22:15.827 UTC
14
2020-04-29 15:35:15.47 UTC
2019-01-22 02:06:04.733 UTC
null
430,885
null
1,730,723
null
1
47
angular|angular-material
97,056
<p>As of version <a href="https://github.com/angular/material2/releases/tag/5.0.0" rel="noreferrer">5.0.0</a>, angular material now supports <code>ngModel</code> for selection list.</p> <p>So the code can be simplified to</p> <pre class="lang-xml prettyprint-override"><code>&lt;mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)"&gt; &lt;mat-list-option *ngFor="let tta of taskTypeAreas" [value]="tta.name"&gt; {{tta.name}} &lt;/mat-list-option&gt; &lt;/mat-selection-list&gt; </code></pre> <p>The release also exposes an <code>ngModelChange</code> event for selection list. Here is the updated <a href="https://stackblitz.com/edit/material-selection-list-5-0-0?file=app/app.component.html" rel="noreferrer">stack blitz</a></p> <hr> <p><em>(Original answer before Angular 5.0.0)</em></p> <p>It appears mat-selection-list does not currently support ngModel (<a href="https://github.com/angular/material2/pull/7456" rel="noreferrer">https://github.com/angular/material2/pull/7456</a>), but it looks like it will be supported in the near future. In the meantime you can use a reference variable <code>#list</code> to grab the selected options.</p> <pre><code>// component.html </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;mat-selection-list #list&gt; &lt;mat-list-option *ngFor="let tta of taskTypeAreas" [selected]="tta.selected" (click)="onAreaListControlChanged(list)" [value]="tta.name"&gt; {{tta.name}} &lt;/mat-list-option&gt; &lt;/mat-selection-list&gt; </code></pre> <p>Then pass in the reference variable to your <code>onAreaListControlChanged(list)</code> method so you can parse out the selected options.</p> <pre><code>// component.ts </code></pre> <pre class="lang-typescript prettyprint-override"><code>onAreaListControlChanged(list){ this.selectedOptions = list.selectedOptions.selected.map(item =&gt; item.value); } </code></pre> <p>To select the checkboxes on load, you can use the <code>[selected]</code> property of each <code>&lt;mat-list-option&gt;</code>. </p> <pre class="lang-xml prettyprint-override"><code>&lt;mat-list-option ... [selected]="tta.selected" ...&gt; </code></pre> <p>To do this you'll need to add another property to your array.</p> <pre><code>// component.ts </code></pre> <pre class="lang-typescript prettyprint-override"><code>taskTypeAreas: { name: string; selected: boolean; }[] = [ { name: 'Area 1', selected: false }, { name: 'Area 2', selected: false }, { name: 'Area 3', selected: true }, ]; </code></pre> <p>This will make <code>Area 3</code> be selected on load. Here is a <a href="https://stackblitz.com/edit/base-angular-material-jyycr7?file=app%2Fapp.component.ts" rel="noreferrer">stackblitz</a> demoing this.</p> <hr>
47,313,732
Jupyter notebook never finishes processing using multiprocessing (Python 3)
<p><a href="https://i.stack.imgur.com/CYdGJ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CYdGJ.jpg" alt="enter image description here"></a></p> <h1>Jupyter Notebook</h1> <p>I am using multiprocessing module basically, I am still learning the capabilities of multiprocessing. I am using the book by Dusty Phillips and this code belongs to it. </p> <pre><code>import multiprocessing import random from multiprocessing.pool import Pool def prime_factor(value): factors = [] for divisor in range(2, value-1): quotient, remainder = divmod(value, divisor) if not remainder: factors.extend(prime_factor(divisor)) factors.extend(prime_factor(quotient)) break else: factors = [value] return factors if __name__ == '__main__': pool = Pool() to_factor = [ random.randint(100000, 50000000) for i in range(20)] results = pool.map(prime_factor, to_factor) for value, factors in zip(to_factor, results): print("The factors of {} are {}".format(value, factors)) </code></pre> <p>On the Windows PowerShell (not on jupyter notebook) I see the following </p> <pre><code>Process SpawnPoolWorker-5: Process SpawnPoolWorker-1: AttributeError: Can't get attribute 'prime_factor' on &lt;module '__main__' (built-in)&gt; </code></pre> <p>I do not know why the cell never ends running? </p>
47,374,811
5
0
null
2017-11-15 17:26:45.947 UTC
16
2022-04-05 08:19:31.393 UTC
2017-11-19 07:24:23.823 UTC
null
4,058,737
null
4,058,737
null
1
52
python-3.x|debugging|multiprocessing|jupyter
30,797
<p>It seems that the problem in Jupyter notebook as in different ide is the design feature. Therefore, we have to write the function (prime_factor) into a different file and import the module. Furthermore, we have to take care of the adjustments. For example, in my case, I have coded the function into a file known as defs.py </p> <pre><code>def prime_factor(value): factors = [] for divisor in range(2, value-1): quotient, remainder = divmod(value, divisor) if not remainder: factors.extend(prime_factor(divisor)) factors.extend(prime_factor(quotient)) break else: factors = [value] return factors </code></pre> <p>Then in the jupyter notebook I wrote the following lines</p> <pre><code>import multiprocessing import random from multiprocessing import Pool import defs if __name__ == '__main__': pool = Pool() to_factor = [ random.randint(100000, 50000000) for i in range(20)] results = pool.map(defs.prime_factor, to_factor) for value, factors in zip(to_factor, results): print("The factors of {} are {}".format(value, factors)) </code></pre> <p>This solved my problem</p> <p><a href="https://i.stack.imgur.com/zw15Y.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zw15Y.jpg" alt="enter image description here"></a></p>
30,201,391
how to write a recurrence relation for a given piece of code
<p>In my algorithm and data structures class we were given a few recurrence relations either to solve or that we can see the complexity of an algorithm. </p> <p>At first, I thought that the mere purpose of these relations is to jot down the complexity of a recursive divide-and-conquer algorithm. Then I came across a question in the MIT assignments, where one is asked to provide a recurrence relation for an iterative algorithm. </p> <p>How would I actually come up with a recurrence relation myself, given some code? What are the necessary steps? </p> <p>Is it actually correct that I can jot down any case i.e. worst, best, average case with such a relation? </p> <p>Could possibly someone give a simple example on how a piece of code is turned into a recurrence relation? </p> <p>Cheers, Andrew</p>
30,207,013
2
0
null
2015-05-12 21:05:36.597 UTC
6
2017-12-05 18:30:19.247 UTC
null
null
null
null
3,925,905
null
1
18
algorithm|recurrence
60,544
<p>Okay, so in algorithm analysis, a recurrence relation is a function relating the amount of work needed to solve a problem of size n to that needed to solve smaller problems (this is closely related to its meaning in math).</p> <p>For example, consider a Fibonacci function below:</p> <pre><code>Fib(a) { if(a==1 || a==0) return 1; return Fib(a-1) + Fib(a-2); } </code></pre> <p>This does three operations (comparison, comparison, addition), and also calls itself recursively. So the recurrence relation is <code>T(n) = 3 + T(n-1) + T(n-2)</code>. To solve this, you would use the iterative method: start expanding the terms until you find the pattern. For this example, you would expand <code>T(n-1)</code> to get <code>T(n) = 6 + 2*T(n-2) + T(n-3)</code>. Then expand <code>T(n-2)</code> to get <code>T(n) = 12 + 3*T(n-3) + 2*T(n-4)</code>. One more time, expand <code>T(n-3)</code> to get <code>T(n) = 21 + 5*T(n-4) + 3*T(n-5)</code>. Notice that the coefficient of the first T term is following the Fibonacci numbers, and the constant term is the sum of them times three: looking it up, that is <code>3*(Fib(n+2)-1)</code>. More importantly, we notice that the sequence increases exponentially; that is, the complexity of the algorithm is O(2<sup>n</sup>).</p> <p>Then consider this function for merge sort:</p> <pre><code>Merge(ary) { ary_start = Merge(ary[0:n/2]); ary_end = Merge(ary[n/2:n]); return MergeArrays(ary_start, ary_end); } </code></pre> <p>This function calls itself on half the input twice, then merges the two halves (using O(n) work). That is, <code>T(n) = T(n/2) + T(n/2) + O(n)</code>. To solve recurrence relations of this type, you should use the <a href="http://en.wikipedia.org/wiki/Master_theorem">Master Theorem</a>. By this theorem, this expands to <code>T(n) = O(n log n)</code>.</p> <p>Finally, consider this function to calculate Fibonacci:</p> <pre><code>Fib2(n) { two = one = 1; for(i from 2 to n) { temp = two + one; one = two; two = temp; } return two; } </code></pre> <p>This function calls itself no times, and it iterates O(n) times. Therefore, its recurrence relation is <code>T(n) = O(n)</code>. This is the case you asked about. It is a special case of recurrence relations with no recurrence; therefore, it is very easy to solve.</p>
61,947,941
Material-ui Autocomplete warning The value provided to Autocomplete is invalid
<p>I am working with React and material-ui.. I just realize i have a warning with the Autocomplete component when i try to submit the form, so i tried to do something really basic just like in the documentation:</p> <pre><code>let Form = props =&gt; { return( &lt;form noValidate onSubmit={handleSubmit} &gt; &lt;Autocomplete id="combo-box-demo" options={[{id:1,name:"test"},{id:2, name:"test2"}]} getOptionLabel={(option) =&gt; option.name} style={{ width: 300 }} renderInput={(params) =&gt; &lt;TextField {...params} label="Combo box" variant="outlined" /&gt;} /&gt; </code></pre> <p>and when i try to submit the form i get the following error: </p> <p>Material-UI: The value provided to Autocomplete is invalid. None of the options match with <code>{"id":1,"name":"test"}</code>. You can use the <code>getOptionSelected</code> prop to customize the equality test. </p> <p>I also realize that if i set the options in the state of the component there is no warning (just when they are set like a constant). So i wonder if some of you have any idea of this behavior? thank you so much in advance.</p>
65,347,275
6
0
null
2020-05-22 04:35:01.843 UTC
10
2022-07-06 08:14:27.633 UTC
null
null
null
null
8,151,873
null
1
47
reactjs|autocomplete|material-ui
51,995
<p>Basically the reason why you get the warning is a default implementation of <code>getOptionSelected</code> in version 4.x.x:</p> <pre class="lang-js prettyprint-override"><code> getOptionSelected = (option, value) =&gt; option === value </code></pre> <p>In your case, selecting a value the following comparison happens:</p> <pre><code>// option === value: {id:1, name:&quot;test&quot;} === {id:1, name:&quot;test&quot;} // false </code></pre> <p>Obviously, it can be <code>true</code> in some circumstances. In this particular case, it's <code>false</code> because of objects pointing to the different instances.</p> <p><strong>Solution!</strong> You have to overwrite <code>getOptionSelected</code> implementation:</p> <pre><code>&lt;Autocomplete getOptionSelected={(option, value) =&gt; option.id === value.id} ...otherProps /&gt; </code></pre> <p><strong>[Update]</strong> Note, in version 5.x.x the prop was renamed:</p> <pre><code>- getOptionSelected={(option, value) =&gt; option.id === value.id} + isOptionEqualToValue={(option, value) =&gt; option.id === value.id} </code></pre>
27,205,809
What is userland caching APCu extension in PHP?
<p>Just a question related to OPcache cause I didn't understand it and find an answer on Google: </p> <p>When we talk about userland caching, what does it mean? I know PHP is pre-bundled with the new Zend OPcache extension and that this extension caches op code into ram in order not to stress too much the processor which should convert to op code the PHP source at every request, but what about the APCu when they say that it implements userland caching?</p> <p>What is userland caching? Is it possible to keep APCu and Zend OPcache together, or not? Should Zend OPcache be used instead of APCu?</p>
27,215,230
1
0
null
2014-11-29 18:57:15.797 UTC
4
2019-09-04 12:01:38.06 UTC
2019-09-04 12:01:38.06 UTC
null
3,885,376
null
3,019,105
null
1
30
php|opcache
12,760
<p>APCu was really developed by Joe Watkins in response to OPcache. APC supports both opcode caching and data caching, but has been dogged with stability problems in support opcode caching since PHP 5.4. After Zend Inc opened the source of Opcache and placed it under the PHP licence, it became the core and preferred opcode cache from PHP 5.5. <em>But</em> it only supports opcode caching and not data caching.</p> <p>Joe's APCu is in essence a stripped out version of APC that only includes the data caching code, and is designed to be used along side OpCache <em>if</em> you need data caching.</p> <p>Note that whereas Opcode caching is transparent at a source code level, data caching is not. Your application needs to be coded explicitly to use it. (Though standard PHP apps such as Wordpress, Drupal, phpBB, MediaWiki, ... include this support by default).</p>
30,612,995
How to update just one library from the Cartfile with Carthage?
<p>My Cartfile has many libraries. When I do <code>carthage update</code> it goes through all the libraries. That can take very long time.</p> <p>Is there a way to update just a single library with carthage? Something like this? (this will not work)</p> <pre><code>carthage update "evgenyneu/moa" </code></pre>
36,421,394
9
0
null
2015-06-03 07:00:08.553 UTC
17
2021-04-23 09:37:01.933 UTC
null
null
null
null
297,131
null
1
94
carthage
44,856
<p>From <a href="https://github.com/Carthage/Carthage/releases/tag/0.12" rel="noreferrer">0.12 version</a> <code>build</code>, <code>checkout</code>, and <code>update</code> take an optional space separated list of dependencies</p> <p>For a Cartfile like the following</p> <pre><code>github "Alamofire/Alamofire" github "ReactiveX/RxSwift" </code></pre> <p>You could choose to update one dependency</p> <pre><code>carthage update Alamofire </code></pre> <p>or multiple dependencies</p> <pre><code>carthage update Alamofire RxSwift </code></pre> <p>If you need to add flags, add them last:</p> <pre><code>carthage update Alamofire --platform iOS </code></pre>
43,008,036
The prop `history` is marked as required in `Router`, but its value is `undefined`. in Router
<p>I am new to ReactJs. This is my code: </p> <pre><code>var React = require('react'); var ReactDOM = require('react-dom'); var {Route, Router, IndexRoute, hashHistory} = require('react-router'); var Main = require('Main'); ReactDOM.render( &lt;Router history={hashHistory}&gt; &lt;Route path="/" component={Main}&gt;&lt;/Route&gt; &lt;/Router&gt;, document.getElementById('app')); </code></pre> <p>and compiling it with webpack. Also I added Main component to my aliases. The console throws these errors: <a href="https://i.stack.imgur.com/DjRVq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DjRVq.png" alt=""></a> I also read these links : </p> <p><a href="https://stackoverflow.com/questions/42845303/react-router-failed-prop-history-is-undefined">React Router failed prop 'history', is undefined</a></p> <p><a href="https://teamtreehouse.com/community/how-do-i-resolve-history-is-marked-required-when-value-is-undefined" rel="noreferrer">How do I resolve history is marked required, when value is undefined?</a></p> <p><a href="https://stackoverflow.com/questions/37355265/upgrading-react-router-and-replacing-hashhistory-with-browserhistory">Upgrading React-Router and replacing hashHistory with browserHistory</a></p> <p>and many searches around the web, but I couldn't fix this issue. React Router is version 4</p>
43,106,758
8
0
null
2017-03-24 19:51:51.693 UTC
23
2022-06-08 16:10:31.13 UTC
2017-05-23 12:18:21.613 UTC
null
-1
null
5,158,372
null
1
108
reactjs|react-router
82,917
<p>If you are using react-router v4 you need to install react-router-dom as well. After that, import BrowserRouter from react-router-dom and switch Router for BrowserRouter. It seems that v4 change several things. Also, the react-router documentation is outdated. This is my working code:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route } from 'react-router-dom' import App from './components/App'; ReactDOM.render(( &lt;BrowserRouter&gt; &lt;Route path="/" component={App}/&gt; &lt;/BrowserRouter&gt; ), document.getElementById('root') ); </code></pre> <p><a href="https://stackoverflow.com/a/42895076/3943197">Source</a></p>
43,732,835
GetItem from Secondary Index with DynamoDB
<p>I'm just getting started using DynamoDB and have setup an 'accounts' table. </p> <p>I've set-up a secondary index so I can query an api user and user key. Neither of these values are the primary key, as they are both volatile and can be changed.</p> <p>The Table is built with </p> <pre><code>TableName: "Accounts", KeySchema: [ { AttributeName: "id", KeyType: "HASH" }, { AttributeName: "email", KeyType: "RANGE" } ], AttributeDefinitions: [ { AttributeName: "id", AttributeType: "S" }, { AttributeName: "email", AttributeType: "S" } ] </code></pre> <p>And the Index is</p> <pre><code> TableName: 'Accounts', AttributeDefinitions: [ {AttributeName: 'name', AttributeType: 'S'}, {AttributeName: 'apiKey', AttributeType: 'S'} ], GlobalSecondaryIndexUpdates: [ { Create: { IndexName: "ApiAccounts", ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 }, KeySchema: [ {AttributeName: 'name', KeyType: "HASH"}, {AttributeName: 'apiKey', KeyType: "STRING"} ], Projection: { ProjectionType: "KEYS_ONLY" }, </code></pre> <p>I'm now trying to get a uses account by querying the <code>ApiAccounts</code> index.</p> <p>I'm trying </p> <pre><code> dynamoClient.get({ TableName: 'Accounts', IndexName: 'ApiAccounts', Key: { name: nameKeyArray[0], apiKey: nameKeyArray[1] }, callback) </code></pre> <p>But I am getting an error <code>One of the required keys was not given a value</code>, which leads me to believe I can't do a 'get' on a Index? Or I'm not referring the index properly. Can somebody clarify for me? </p> <p>Name and API Key are unique, so I think I want to avoid a query or scan if possible</p>
43,733,229
1
0
null
2017-05-02 07:53:39.873 UTC
2
2019-08-07 02:37:59.283 UTC
null
null
null
null
48,067
null
1
33
amazon-dynamodb
26,240
<p>I guess its not so clear from the official docs. You may perform <code>Scan</code> or <code>Query</code> operation on <code>GSI</code> index, but not the <code>GetItem</code> operation. </p> <p>For every record / item in a <code>Table</code>, they must have unique <code>HASH</code> and <code>RANGE</code> keys.</p> <p>i.e.</p> <pre><code>// assume dummy api putItem(id, email, name, apiKey) account.putItem("1", "[email protected]", "john", "key1") // OK account.putItem("1", "[email protected]", "john", "key1") // NOT OK, id and email are table HASH and RANGE keys, must be unique </code></pre> <p>But for <code>Index</code>'es, <code>Hash</code> and <code>Range</code> keys are not unique, they may contain duplicated records / items.</p> <p>i.e.</p> <pre><code>// assume dummy api putItem(id, email, name, apiKey) account.putItem("1", "[email protected]", "john", "key1") // OK account.putItem("1", "[email protected]", "john", "key1") // OK </code></pre> <p>i.e.</p> <pre><code>// assume dummy api putItem(id, email, name, apiKey) account.putItem("1", "[email protected]", "john", "key1") // OK account.putItem("2", "[email protected]", "john", "key1") // OK </code></pre> <p><strong>Java</strong></p> <p><a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/document/Index.html" rel="noreferrer">http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/document/Index.html</a></p> <p><code>Index</code> implements <code>QueryApi</code> and <code>ScanApi</code> but not <code>GetItemApi</code>.</p> <p><strong>JavaScript</strong></p> <p><a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property" rel="noreferrer">http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property</a></p> <p><code>GetItem</code> does <strong>not</strong> accept <code>IndexName</code> as a parameter.</p> <p><a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property" rel="noreferrer">http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property</a></p> <p><code>Query</code> accepts <code>IndexName</code> as a parameter.</p> <p><a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property" rel="noreferrer">http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property</a></p> <p><code>Scan</code> accepts <code>IndexName</code> as a parameter.</p>
45,022,566
Create Python CLI with select interface
<p>I'd like to create a Python CLI with an item selection interface that allows users to choose an item from a list. Something like:</p> <pre><code>Select a fruit (up/down to select and enter to confirm): [x] Apple [ ] Banana [ ] Orange </code></pre> <p>I'd like users to be able to change their selection using the up/down arrows and press <code>Enter</code> to confirm.</p> <p>Does a Python module exist with this functionality? I tried searching but couldn't find exactly what I wanted.</p> <p>The <a href="https://www.npmjs.com/package/select-shell" rel="nofollow noreferrer" title="select-shell">select-shell Node.js package</a> does exactly what I want.</p> <p>The <a href="https://github.com/wong2/pick" rel="nofollow noreferrer">pick Python module</a> does what I want, but it uses curses and opens up a simple GUI. I would like to avoid creating a GUI and keep all output in the terminal: this likely requires updating lines displayed to the terminal.</p> <p>I'm currently using <a href="http://click.pocoo.org/5/" rel="nofollow noreferrer">click</a> but I don't believe it supports this functionality. I'm not sure how exactly to implement this kind of feature using <code>cmd</code>/<code>readline</code> and would appreciate any insight.</p>
45,033,647
3
0
null
2017-07-10 22:22:41.427 UTC
6
2022-09-22 16:36:45.58 UTC
2022-09-22 16:36:45.58 UTC
null
5,365,899
null
5,365,899
null
1
32
python|terminal|command-line-interface
20,954
<p>After a bit of searching, I found two libraries that met my needs!</p> <p>The first is <a href="https://github.com/magmax/python-inquirer" rel="noreferrer">python-inquirer</a>, a Python port of <a href="https://github.com/SBoudrias/Inquirer.js/" rel="noreferrer">Inquirer.js</a>, a CLI library used by projects like Yeoman. I found this library to have a really nice API (built on top of <a href="https://pypi.python.org/pypi/blessings/" rel="noreferrer">blessings</a>) but lacks polish when it comes to design/features.</p> <p>The second (which I will be using) is <a href="https://github.com/finklabs/whaaaaat" rel="noreferrer">whaaaaat</a>, another Python port of Inquirer. This library offers functionality much closer to the original Inquirer.js and is exactly what I needed. The API is less clean than that of python-inquirer, however.</p> <p>Examples:</p> <p><code>python-inquirer</code> example:</p> <pre class="lang-py prettyprint-override"><code>from pprint import pprint import inquirer questions = [ inquirer.List( "size", message="What size do you need?", choices=["Jumbo", "Large", "Standard", "Medium", "Small", "Micro"], ), ] answers = inquirer.prompt(questions) pprint(answers) </code></pre> <p><code>whaaaaat</code> example:</p> <pre class="lang-py prettyprint-override"><code>from whaaaaat import prompt, print_json, Separator questions = [ { "type": "list", "name": "theme", "message": "What do you want to do?", "choices": [ "Order a pizza", "Make a reservation", Separator(), "Ask for opening hours", {"name": "Contact support", "disabled": "Unavailable at this time"}, "Talk to the receptionist", ], }, { "type": "list", "name": "size", "message": "What size do you need?", "choices": ["Jumbo", "Large", "Standard", "Medium", "Small", "Micro"], "filter": lambda val: val.lower(), }, ] answers = prompt(questions) print_json(answers) </code></pre>
7,427,094
Generate diagrams for Haskell code
<p>Is there something that is kind of a cross between graphmod and haddock? I want a diagram like graphmod showing dependencies/relationships, but I want to include additional documentation in the diagram.</p>
7,427,813
1
0
null
2011-09-15 07:11:19.567 UTC
10
2011-09-15 12:31:55.237 UTC
2011-09-15 12:31:55.237 UTC
null
380,816
null
315,734
null
1
15
haskell|documentation|visualization
2,116
<p>Not an existing one. Here are the list of available Haskell visualisation utilities (at least those on Hackage):</p> <ul> <li><p><a href="http://hackage.haskell.org/package/graphmod">graphmod</a> which you've already found: visualise module dependencies.</p></li> <li><p><a href="http://hackage.haskell.org/package/prof2dot">prof2dot</a> visualise profiling reports</p></li> <li><p><a href="http://hackage.haskell.org/package/hs2dot">hs2dot</a> visualise Haskell code</p></li> <li><p><a href="http://hackage.haskell.org/package/vacuum">vacuum</a> (and related packages) visualises the data structures at run-time</p></li> <li><p><a href="http://hackage.haskell.org/package/SourceGraph">SourceGraph</a> (disclaimer: this is mine) aims to provide different forms of visualisation of the call graphs and perform some analyses; haven't had much time to work on this lately though.</p></li> <li><p><a href="http://hackage.haskell.org/package/graphtype">graphtype</a> is for comparing data types</p></li> </ul> <p>It may be possible to use doxygen to generate documentation with visualisation, but a quick Google didn't reveal any work on providing support for Haskell in doxygen (and it would require different markup than what Haddock uses).</p>
22,466,858
Decryption Exception - length of the data to decrypt is invalid
<p>I am working in a C# application. We have common methods to store data on a file. These methods encrypt the data and store them on the file system. when we need the data, ReadData method decrypts the data and returns me plain text.</p> <p>This code works fine in normal cases if size of the text in small. but for a example text given below, the decryption code is throwing exception - length of the data to decrypt is invalid.</p> <p>The exception occurs at line </p> <pre><code> // close the CryptoStream x_cryptostream.Close(); </code></pre> <p>I tried different ways but no luck. Can some pls help.</p> <p>Why am I encrypting already encrypted data - I am just trying to store in a file using common method of the huge application. The common methods <code>storedata(key,data)</code> nad <code>readdata(key)</code> do the encryption/decryption I can't avoid.</p> <pre><code> public static byte[] Decrypt(byte[] ciphertext, string Key, string IV) { byte[] k = Encoding.Default.GetBytes(Key); byte[] iv = Encoding.Default.GetBytes(IV); // create the encryption algorithm SymmetricAlgorithm x_alg = SymmetricAlgorithm.Create("Rijndael"); x_alg.Padding = PaddingMode.PKCS7; // create an ICryptoTransform that can be used to decrypt data ICryptoTransform x_decryptor = x_alg.CreateDecryptor(k, iv); // create the memory stream MemoryStream x_memory_stream = new MemoryStream(); // create the CryptoStream that ties together the MemoryStream and the // ICryptostream CryptoStream x_cryptostream = new CryptoStream(x_memory_stream, x_decryptor, CryptoStreamMode.Write); // write the ciphertext out to the cryptostream x_cryptostream.Write(ciphertext, 0, ciphertext.Length); // close the CryptoStream x_cryptostream.Close(); // get the plaintext from the MemoryStream byte[] x_plaintext = x_memory_stream.ToArray(); </code></pre> <p>Below is the code of encrypt method.</p> <pre><code> public static byte[] Encrypt(string strplain, string Key, string IV) { byte[] k = Encoding.Default.GetBytes(Key); byte[] iv = Encoding.Default.GetBytes(IV); byte[] plaintext = Encoding.Default.GetBytes(strplain); // create the encryption algorithm SymmetricAlgorithm x_alg = SymmetricAlgorithm.Create("Rijndael"); x_alg.Padding = PaddingMode.PKCS7; // create an ICryptoTransform that can be used to encrypt data ICryptoTransform x_encryptor = x_alg.CreateEncryptor(k, iv); // create the memory stream MemoryStream x_memory_stream = new MemoryStream(); // create the CryptoStream that ties together the MemoryStream and // the ICryptostream CryptoStream x_cryptostream = new CryptoStream(x_memory_stream, x_encryptor, CryptoStreamMode.Write); // write the plaintext out to the cryptostream x_cryptostream.Write(plaintext, 0, plaintext.Length); // close the CryptoStream x_cryptostream.Close(); // get the ciphertext from the MemoryStream byte[] x_ciphertext = x_memory_stream.ToArray(); // close memory stream x_memory_stream.Close(); // convert from array to string string cipher_Tx = Encoding.Default.GetString(x_ciphertext, 0, x_ciphertext.Length); x_encryptor.Dispose(); x_alg.Clear(); byte[] cipher = Encoding.Default.GetBytes(cipher_Tx); return cipher; } </code></pre>
22,467,144
2
0
null
2014-03-17 22:35:45.313 UTC
3
2022-08-10 15:38:02.257 UTC
2014-03-17 23:31:05.78 UTC
null
2,921,323
null
2,921,323
null
1
11
c#|encryption|cryptography|rijndael
46,231
<p>Your problem is <code>string cipher_Tx = Encoding.Default.GetString(x_ciphertext, 0, x_ciphertext.Length);</code>.</p> <p><code>x_ciphertext</code> is not a valid byte representation of text, it has many unpresentable characters and when you do your <code>byte[]</code> to <code>string</code> conversion you are losing information. The correct way to do it is use a string format that is designed to represent binary data using something like <a href="http://msdn.microsoft.com/en-us/library/system.convert.tobase64string%28v=vs.110%29.aspx" rel="nofollow noreferrer"><code>Convert.ToBase64String(byte[])</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.convert.frombase64string%28v=vs.110%29.aspx" rel="nofollow noreferrer"><code>Convert.FromBase64String(string)</code></a>.</p> <pre><code>string cipher_Tx = Convert.ToBase64String(x_ciphertext) x_encryptor.Dispose(); x_alg.Clear(); byte[] cipher = Convert.FromBase64String(cipher_Tx) </code></pre> <p>That being said, there is a lot of other &quot;odd&quot; things about your code, for example you don't use <code>using</code> statements and you really should. Also that whole conversion to string and back is totally unnecessary, just return <code>x_ciphertext</code>. There may be other problems with the code too (like where did the strings for <code>Key</code> and <code>IV</code> come from) and many other best practices (like you should be generating a random IV and writing it out in to the output and the key should be generated using a key derivation function not straight from user text), but I stopped checking after I found the string conversion issue.</p>
50,436,618
Why can't I enter the url on my phone's browser to view my live site?
<p>I use an extension called <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer" rel="nofollow noreferrer">Live Server</a> in Visual Studio Code. When I run live, the browser opens and the url is <a href="http://127.0.0.1:5500/index.html" rel="nofollow noreferrer">http://127.0.0.1:5500/index.html</a>. Why can't I open this url on my phone's browser to see the live site on the phone. Is there a way to do this (Live reload on phone and browser)?</p> <p><strong>Note:</strong> I also develop using ionic and when I <code>ionic serve</code> I can see it on browser and when I open the ionic dev app (not ionic view!), I can see the live app on the phone. I can view it on multiple devices with the condition of all devices being in the same network which I am fine with.</p>
50,445,905
6
1
null
2018-05-20 15:48:30.293 UTC
9
2021-03-01 07:13:18.99 UTC
null
null
null
null
5,561,177
null
1
2
server
29,207
<p><strong>127.0.0.1</strong> is a special-purpose IPv4 address reserved for loopback purposes. That is, this IP refers to your computer itself. </p> <p>By entering <a href="http://127.0.0.1:5500/index.html" rel="noreferrer">http://127.0.0.1:5500/index.html</a> in your browser, you're requesting web page <strong>within</strong> your computer. </p> <p>In normal case, your computer will be in a NAT network (under same wi-fi AP for instance), and you'll be assigned with a virtual IP. Normally it's 192.168.x.x.</p> <p>You may enter the following command in your command prompt to see your IP address.</p> <pre><code>ipconfig </code></pre> <p>If you're using Mac or Linux, use this instead. </p> <pre><code>ifconfig </code></pre> <p>As a result, under your network interface card, you'll get your <strong>IP Address</strong>.</p> <p>If the IP address belongs to virtual IP, then you may access it with your phone using</p> <pre><code>http://&lt; Your IP Address &gt;:5500/index.html </code></pre> <p>If it's not virtual IP, it is Public IP. Then, you'll have to configure appropriate <strong>Firewall</strong> settings under this circumstance. </p> <p>Hope this will help.</p>
22,390,709
How can I open the Atom editor from the command line in OS X?
<p>I have the Atom editor and was wondering how you can open a file or folder from the terminal in Atom. I am using a Mac. I am looking for a way to do this:</p> <pre><code>atom . (opens folder) atom file.js (opens file) atom (opens editor) </code></pre> <p>Is this possible and how do I set it up?</p>
22,399,909
20
0
null
2014-03-13 20:55:47.2 UTC
78
2021-08-27 06:57:59.973 UTC
2021-07-15 08:22:07.08 UTC
null
63,550
null
388,573
null
1
433
macos|command-line-interface|atom-editor
341,831
<p>When Atom installs, it automatically creates a <a href="https://en.wikipedia.org/wiki/Symbolic_link" rel="noreferrer">symbolic link</a> in your <em>/usr/local/bin</em> folder. However, in case it hasn't, you can create it yourself on your Mac:</p> <pre><code>ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom </code></pre> <p>Now you can use <code>atom folder_name</code> to open a folder and <code>atom file_name</code> to open a file.</p>
37,310,264
pandas DataFrame diagonal
<p>What is an efficient way to get the diagonal of a square <code>DataFrame</code>. I would expect the result to be a <code>Series</code> with a <code>MultiIndex</code> with two levels, the first being the index of the <code>DataFrame</code> the second level being the columns of the <code>DataFrame</code>.</p> <h1>Setup</h1> <pre><code>import pandas as pd import numpy as np np.random.seed([3, 1415]) df = pd.DataFrame(np.random.rand(3, 3) * 5, columns = list('abc'), index = list('ABC'), dtype=np.int64 ) </code></pre> <p>I want to see this:</p> <pre><code>print df.stack().loc[[('A', 'a'), ('B', 'b'), ('C', 'c')]] A a 2 B b 2 C c 3 </code></pre>
37,310,433
3
0
null
2016-05-18 21:17:51.4 UTC
3
2016-05-18 21:41:23.123 UTC
null
null
null
null
2,336,654
null
1
38
python|numpy|pandas
38,328
<p>If you don't mind using numpy you could use <code>numpy.diag</code></p> <pre><code>pd.Series(np.diag(df), index=[df.index, df.columns]) A a 2 B b 2 C c 3 dtype: int64 </code></pre>
30,721,061
How to make a CocoaPods project work on OS X El Capitan & Xcode 7 Beta?
<p>I've updated to OS X El Capitan &amp; Xcode 7 Beta released today and now my CocoaPods projects no longer work because of the new Swift syntax requirements. The automated Xcode project update breaks the code. Has anyone already figured this out already? Thanks.</p>
30,729,966
4
0
null
2015-06-09 00:13:04.943 UTC
9
2019-01-30 13:54:04.607 UTC
2015-06-09 18:31:40.063 UTC
null
1,438
null
405,487
null
1
19
xcode|xcode7|osx-elcapitan
12,510
<p>Until Cocoapods supports Swift 2, at the very least you should be able to continue to use Xcode 6 until it does. If Xcode 7 has stomped all over your Cocoapods already, this link shows you how to clean it up <a href="https://gist.github.com/mbinna/4202236">https://gist.github.com/mbinna/4202236</a>.</p> <p>Basically, from inside any project using Cocoapods:</p> <pre><code>rm -rf "${HOME}/Library/Caches/CocoaPods" rm -rf "`pwd`/Pods/" pod update </code></pre> <p>Then rebuild using Xcode 6 and everything should be back to normal.</p>
42,118,782
Replace callbacks with observables from RxJava
<p>Im using listeners as callbacks to observe asynchronous operations with Android, but I think that could be great replacing this listeners with RxJava, Im new using this library but I really like it and Im always using it with Android projects.</p> <p>Here is my code to refactor:</p> <pre><code>public void getData( final OnResponseListener listener ){ if(data!=null &amp;&amp; !data.isEmpty()){ listener.onSuccess(); } else{ listener.onError(); } } </code></pre> <p>A simple callback:</p> <pre><code>public interface OnResponseListener { public void onSuccess(); public void onError(); } </code></pre> <p>And the "observer":</p> <pre><code>object.getData( new OnResponseListener() { @Override public void onSuccess() { Log.w(TAG," on success"); } @Override public void onError() { Log.e(TAG," on error"); } }); </code></pre> <p>Thanks!</p>
42,119,268
4
1
null
2017-02-08 16:39:26.187 UTC
7
2017-12-04 21:46:34.247 UTC
2017-08-14 18:15:14.107 UTC
null
2,510,655
null
3,994,630
null
1
36
java|rx-java
24,435
<p>For example you can use <em>Observable.fromCallable</em> to create observable with your data.</p> <pre><code>public Observable&lt;Data&gt; getData(){ return Observable.fromCallable(() -&gt; { Data result = null; //do something, get your Data object return result; }); } </code></pre> <p>then use your data </p> <pre><code> getData().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(data -&gt; { //do something with your data }, error -&gt; { //do something on error }); </code></pre> <p>Used rxjava 1.x and lambda expressions.</p> <p><strong>edit:</strong></p> <p>if I understand you well, you wanted to replace that listener, not wrap it into observable. I added other example in reference to your comment. Oh.. also you should use <em>Single</em> if you are expecting only one item. </p> <pre><code>public Single&lt;Data&gt; getData() { return Single.create(singleSubscriber -&gt; { Data result = object.getData(); if(result == null){ singleSubscriber.onError(new Exception("no data")); } else { singleSubscriber.onSuccess(result); } }); } getData().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(data -&gt; { //do something with your data }, error -&gt; { //do something on error }); </code></pre>
36,186,276
Is the Json.NET JsonSerializer threadsafe?
<p>I'm trying to reduce the amount of garbage my web service generates, and I noticed that we're creating a new Json.NET <code>JsonSerializer</code> instance for each request. It is not the most lightweight object ever, so I'm wondering if I can just create a single instance and reuse it for all requests. Primarily this requires that it be threadsafe during serialization and deserialization.</p> <p><a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializer.htm">The documentation</a> doesn't say whether it's threadsafe or not. </p> <p>Inspecting <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/ce2a08dba228341742d96e8c8edfede6748d5bdc/Src/Newtonsoft.Json/JsonSerializer.cs">the code</a> it appears that the serialization and deserialization methods are threadsafe, as long as you don't change any settings on the object at the same time. However, it's a complex class so I'm not 100% sure of my analysis. </p> <p>Has anyone tried reusing instances of <code>JsonSerializer</code> and had it work or not? Are there any known problems with reusing it?</p>
36,189,439
4
2
null
2016-03-23 18:42:39.017 UTC
1
2019-04-18 20:10:14.637 UTC
null
null
null
null
76,263
null
1
43
c#|json.net
11,323
<blockquote> <p>Inspecting the code it appears that the serialization and deserialization methods are threadsafe, as long as you don't change any settings on the object at the same time.</p> </blockquote> <p>Correct, JsonSerializer is threadsafe.</p> <p>No state is shared while serializing but if you change a setting on the JsonSerializer while in the middle of serializing an object then those will automatically be used.</p>
5,614,572
JSON->String in python
<p>Say I get this line of JSON</p> <pre><code>[{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}] </code></pre> <p>How can I convert those separate values to strings? So I can say</p> <pre><code>Print Status </code></pre> <p>And it returns</p> <pre><code>active </code></pre>
5,615,192
3
1
null
2011-04-10 20:41:34.037 UTC
3
2011-04-10 23:00:52.023 UTC
null
null
null
null
585,510
null
1
18
python|json
47,268
<p>That is NOT a "line of JSON" as received from an external source. It looks like the result of <code>json.loads(external_JSON_string)</code>. Also <code>Print Status</code> won't work; you mean <code>print status</code>.</p> <pre><code>&gt;&gt;&gt; result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}] &gt;&gt;&gt; print result[0]['status'] active </code></pre> <p>This is what a "line of JSON" looks like:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(result) '[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]' &gt;&gt;&gt; </code></pre> <p>EDIT: If using Python 2.5, use <code>import simplejson as json</code> instead of <code>import json</code>. Make your code a bit more future-proof by doing this:</p> <pre><code>try: import json except ImportError: import simplejson as json </code></pre>
6,056,683
Practical usage of the Unit Of Work & Repository patterns
<p>I'm building an ORM, and try to find out what are the exact responsibilities of each pattern. Let's say I want to transfer money between two accounts, using the Unit Of Work to manage the updates in a single database transaction. Is the following approach correct?</p> <ol> <li>Get them from the Repository</li> <li>Attach them to my Unit Of Work</li> <li>Do the business transaction &amp; commit?</li> </ol> <p>Example:</p> <pre><code>from = acccountRepository.find(fromAccountId); to = accountRepository.find(toAccountId); unitOfWork.attach(from); unitOfWork.attach(to); unitOfWork.begin(); from.withdraw(amount); to.deposit(amount); unitOfWork.commit(); </code></pre> <p>Should, as in this example, the Unit Of Work and the Repository be used independently, or:</p> <ul> <li>Should the Unit Of Work use internally a Repository and have the ability to load objects?</li> <li>... or should the Repository use internally a Unit Of Work and automatically attach any loaded entity?</li> </ul> <p>All comments are welcome!</p>
6,159,651
3
3
null
2011-05-19 09:40:40.667 UTC
10
2013-10-15 02:37:48.823 UTC
2012-12-15 12:49:24.533 UTC
null
759,866
null
759,866
null
1
20
orm|domain-driven-design|repository-pattern|unit-of-work|domain-model
5,889
<p>The short answer would be that the Repository would be using the UoW in some way, but I think the relationship between these patterns is less concrete than it would initially seem. The goal of the Unit Of Work is to create a way to essentially lump a group of database related functions together so they can be executed as an atomic unit. There is often a relationship between the boundaries created when using UoW and the boundaries created by transactions, but this relationship is more coincidence.</p> <p>The Repository pattern, on the other hand, is a way to create an abstraction resembling a collection over an Aggregate Root. More often than not the sorts of things you see in a repository are related to querying or finding instances of the Aggregate Root. A more interesting question (and one which doesn't have a single answer) is whether it makes sense to add methods that deal with something other than querying for Aggregates. On the one hand there could be some valid cases where you have operations that would apply to multiple Aggregates. On the other it could be argued that if you're performing operations on more than one Aggregate you are actually performing a single action on another Aggregate. If you are only querying data I don't know if you really need to create the boundaries implied by the UoW. It all comes down to the domain and how it is modeled.</p> <p>The two patterns are dealing at very different levels of abstraction, and the involvement of the Unit Of Work is going to be dependent on how the Aggregates are modeled as well. The Aggregates may want to delegate work related to persistence to the Entities its managing, or there could be another layer of abstraction between the Aggregates and the actual ORM. If your Aggregates/Entities are dealing with persistence themselves, then it may be appropriate for the Repositories to also manage that persistence. If not, then it doesn't make sense to include UoW in your Repository.</p> <p>If you're wanting to create something for general public consumption outside of your organization, then I would suggest creating your Repository interfaces/base implementations in a way that would allow them to interact directly with your ORM or not depending on the needs of the user of your ORM. If this is internal, and you are doing the persistence work in your Aggregates.Entities, then it makes sense for your Repository to make use of your UoW. For a generic Repository it would make sense to provide access to the UoW object from within Repository implementations that can make sure it is initialized and disposed of appropriately. On that note, there will also be times when you would likely want to utilize multiple Repositories within what would be a single UoW boundary, so you would want to be able to pass in an already primed UoW to the Repository in that case.</p>
5,901,300
How do I view previous diff commits using Git?
<p>How do I view previous diff commits using Git?</p> <p>I have a file that I've made several commits on, but I want to view previous versions of the file AND its diff's at different stages. Seeing where I made mistakes and how I fixed them is really helping my code. By the way, I'm using Tower as a GUI on top of Git.</p>
5,901,385
3
0
null
2011-05-05 16:44:31.8 UTC
12
2018-07-19 20:35:55.31 UTC
2018-07-19 20:35:55.31 UTC
null
63,550
null
259,912
null
1
60
git|diff
28,510
<pre><code>git log --full-diff -p your_file_path </code></pre> <p>Check out: <br> <a href="http://git-scm.com/docs/git-log">http://git-scm.com/docs/git-log</a></p>
6,107,905
Which command to use for checking whether python is 64bit or 32bit
<p>I am not able to find any command to check if my python is compiled for 32bit system or 64bit system.</p> <p>I tried </p> <blockquote> <p>python</p> </blockquote> <p>and it only tells the version</p> <p>Also when I go to python download site they have one version of python for linux but two versions for mac i.e 32bit and 64bit.</p>
6,107,982
4
4
null
2011-05-24 08:49:38.457 UTC
8
2022-04-07 05:50:34.603 UTC
2013-04-05 06:23:20.563 UTC
null
617,450
null
767,244
null
1
32
python|linux|macos|32bit-64bit
40,565
<p>For Python 2.6 and above, you can use <code>sys.maxsize</code> as documented <a href="http://docs.python.org/library/platform.html#cross-platform" rel="noreferrer">here</a>:</p> <pre><code>import sys is_64bits = sys.maxsize &gt; 2**32 </code></pre> <p>UPDATE: I notice that I didn't really answer the question posed. While the above test does accurately tell you whether the interpreter is running in a 32-bit or a 64-bit architecture, it doesn't and can't answer the question of what is the complete set of architectures that this interpreter was built for and could run in. As was noted in the question, this is important for example with Mac OS X universal executables where one executable file may contain code for multiple architectures. One way to answer that question is to use the operating system <code>file</code> command. On most systems it will report the supported architectures of an executable file. Here's how to do it in one line from a shell command line on most systems:</p> <pre><code>file -L $(python -c 'import sys; print(sys.executable)') </code></pre> <p>Using the default system Python on OS X 10.6, the output is:</p> <pre><code>/usr/bin/python: Mach-O universal binary with 3 architectures /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O executable ppc </code></pre> <p>On one Linux system:</p> <pre><code>/usr/bin/python: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, stripped </code></pre> <p>BTW, here's an example of why <code>platform</code> is not reliable for this purpose. Again using the system Python on OS X 10.6:</p> <pre><code>$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize &gt; 2**32' 64bit True $ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize &gt; 2**32' 64bit False </code></pre>
6,225,537
Convert .class to .java
<p>I have some .class files that I need to convert to .java so I did:</p> <pre><code>javap -c ClassName.class </code></pre> <p>and all the time I have the same error</p> <pre><code>ERROR:Could not find ClassName.class </code></pre> <p>Do you guys have any idea of what might be the cause? I did man javap and as far as I know, the syntax is correct. If there is another way to convert it to a .java file, I am more than willing to try.</p>
6,225,559
4
2
null
2011-06-03 09:53:31.757 UTC
8
2021-01-14 16:04:02.927 UTC
2021-01-14 16:04:02.927 UTC
null
11,573,842
null
663,672
null
1
39
java
274,121
<h2>Invoking <code>javap</code> to read the bytecode</h2> <p>The <code>javap</code> command takes class-names without the <code>.class</code> extension. Try</p> <pre><code>javap -c ClassName </code></pre> <h2>Converting .class files back to .java files</h2> <p><code>javap</code> will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.</p> <p>To actually <em>decompile</em> (i.e., do the reverse of <code>javac</code>) you will have to use proper decompiler. See for instance the following related question:</p> <ul> <li><a href="https://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files">How do I &quot;decompile&quot; Java class files?</a></li> </ul>
1,690,422
GDI+ performance tricks
<p>Does anyone know of any reliable (and, hopefully, extensive) books/websites that discuss GDI+ performance (beyond the obvious)?</p> <p>For example, I recently came across <a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=467752" rel="nofollow noreferrer">this excellent experiment</a>. I also recently noticed that <code>Graphics.FillPath()</code> is way, way faster than <code>Graphics.DrawPath()</code>. I'd love to know what other vital bits of information I'm missing.</p> <p>Goodwill, David</p>
1,961,966
2
0
null
2009-11-06 21:02:39.917 UTC
10
2011-02-08 16:46:10.903 UTC
null
null
null
null
81,947
null
1
4
.net|performance|gdi|system.drawing
10,241
<p>Hmmm. There is no gain in knowing that FillPath is faster than DrawPath if you need to draw the path's outline!</p> <p>The best way to optimise GDI+ is exactly the same as for any other code: Firstly, don't optimise it. Instead:</p> <ul> <li>Start by writing it so it simply works, and then decide if it is actually too slow.</li> <li>Then examine your "algorithm": <ul> <li>Simplify what you are drawing (reduce the number of things you are drawing) and it will go faster (and in most cases will look better for having reduced the clutter).</li> <li>Are you drawing your entire display every time, or are you using the clip rectangle to avoid drawing parts of the image that don't need to be updated? </li> <li>Examine how you draw things. Are you creating and destroying resources (e.g. brushes and pens) for every redraw? Cache them in a member variable. Are you over-drawing the same pixel multiple times? (e.g. drawing the background then drawing a bitmap on top then drawing a rectangle on top of that - perhaps you can avoid some of these redraws). Are you drawing a curve using 100 polygon segments when it looks good enough with only 10 segments? When the window scrolls, do you get the OS to move the existing image so you only need to redraw the newly exposed strip, or do you waste time redrawing the entire window?</li> <li>Are you using transforms or are you doing lengthy positioning calculations in your code?</li> <li>Check any loops and make sure you move as much code out of them as possible - precalculate values you use within the loop, etc. Make sure your loops iterate over your data in a cpu-cache-friendly direction/manner where possible.</li> <li>Is there anything in your data that you are processing during the redraw? Perhaps some of this can be precalculated or organised in a more rendering-optimal form. e.g. Would a different type of list be faster to enumerate your data from? Are you processing 1000 data items to find the 10 you need to draw?</li> <li>Can you achieve the same look with a different approach? e.g. You can draw a chess board by drawing 64 squares in alternating black and white. It might be faster to draw 32 black and then 32 white squares so you avoid state changes between the rects. But you can actually draw it using a white background clear, 4 black rectangles, and 4 XOR rectangles (8 rects instead of 64 => much faster algorithm).</li> </ul></li> <li>Are there parts of the image that don't change often? Try caching them in an offscreen bitmap to minimise the amount you have to "rebuild" for each redraw. Remember that you can still render the offscreen bitmap(s) and then layer graphics primitives on top of them, so you may find a lot more "static" image area than you realise.</li> <li>Are you rendering bitmap images? Try converting them to the screen's pixel format and cache them in that "native" form rather than making GDI+ convert them every time they are drawn.</li> <li>Turn down the quality settings if you are happy with the trade-off of lower quality for faster rendering</li> </ul> <p>Once you have done all these things you can start looking for books about optimising the rendering. If it is still too slow, of course. Run a profiler to find out which parts of the rendering are the slowest.</p> <p>Where you think you might be able to make gains, try different ways of rendering things (e.g. it's likely that Graphics.Clear() will be much faster than filling the background with FillRectangle()), or different rendering orders (draw all the things of one colour first, in case state changes cost you time - batching operations is often very important with modern graphics cards. A single call that draws multiple polygons is usually faster than making multiple single-polygon calls, so can you accumulate all your polys into a deferred-rendering buffer and then commit them all at the end of your rendering pass?)</p> <p>After that, you may have to look at using GDI or DirectX to get closer to the hardware.</p>
57,070,052
create-react-app Typescript 3.5, Path Alias
<p>I am trying to setup Path alias in my project by adding these values to tsconfig.json:</p> <pre><code> "compilerOptions": { "baseUrl": "src", "paths": { "@store/*": ["store/*"] }, </code></pre> <p>And if I create an import, neither IntelliJ or VSCode bother me:</p> <pre><code>import { AppState } from '@store/index'; </code></pre> <p>But when I compile the application I get this warning:</p> <pre><code>The following changes are being made to your tsconfig.json file: - compilerOptions.paths must not be set (aliased imports are not supported) </code></pre> <p>And it bombs saying it cannot find the reference:</p> <pre><code>TypeScript error in C:/xyz.tsx(2,26): Cannot find module '/store'. TS2307 </code></pre> <p>Is there any workaround or it is not supported by <code>create-react-app --typescript</code>?</p>
60,598,134
8
2
null
2019-07-17 06:49:53.25 UTC
16
2022-06-04 07:32:44.363 UTC
null
null
null
null
236,243
null
1
51
typescript|create-react-app
44,659
<p>The alias solution for craco or rewired <em>create-react-app</em> is <strong><a href="https://github.com/oklas/react-app-alias" rel="nofollow noreferrer">react-app-alias</a></strong> for systems as: <a href="https://github.com/gsoft-inc/craco/blob/master/packages/craco" rel="nofollow noreferrer">craco</a>, <a href="https://github.com/timarney/react-app-rewired" rel="nofollow noreferrer">react-app-rewired</a>, <a href="https://github.com/arackaf/customize-cra" rel="nofollow noreferrer">customize-cra</a></p> <p>According docs of mentioned systems replace <code>react-scripts</code> in <code>package.json</code> and configure next:</p> <h2><strong>react-app-rewired</strong></h2> <pre class="lang-js prettyprint-override"><code>// config-overrides.js const {aliasWebpack, aliasJest} = require('react-app-alias') const options = {} // default is empty for most cases module.exports = aliasWebpack(options) module.exports.jest = aliasJest(options) </code></pre> <h2>craco</h2> <pre><code>// craco.config.js const {CracoAliasPlugin} = require('react-app-alias') module.exports = { plugins: [ { plugin: CracoAliasPlugin, options: {} } ] } </code></pre> <h2>all</h2> <p>Configure aliases in json like this:</p> <pre class="lang-js prettyprint-override"><code>// tsconfig.paths.json { &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;.&quot;, &quot;paths&quot;: { &quot;example/*&quot;: [&quot;example/src/*&quot;], &quot;@library/*&quot;: [&quot;library/src/*&quot;] } } } </code></pre> <p>And add this file in <code>extends</code> section of main typescript config file:</p> <pre class="lang-js prettyprint-override"><code>// tsconfig.json { &quot;extends&quot;: &quot;./tsconfig.paths.json&quot;, // ... } </code></pre>
5,939,353
How do you keep the value of global variables between different Action Methods calls in MVC3?
<p>I am developing an ASP.NET MVC 3 web application using Razor and C#. </p> <p>I just discovered that I have some problems with global variables, probably because I am relatively new to MVC.</p> <p>I have a controller with some global variables and action methods. I declared a global variable in order to allow the action methods to manipulate it and reflect the manipulations to all the action methods. I have the following situation:</p> <pre><code>public class myController : Controller { private string _MyGlobalVariable; public ActionResult Index() { _MyGlobalVariable = "Hello"; //other code return View("MyView"); } public ActionResult Print() { _MyGlobalVariable += "Print"; return View("PrintView", _MyGlobalVariable); } } </code></pre> <p>The <strong>Print()</strong> action method is called with an <strong>Html.ActionLink()</strong> from the <strong>MyView</strong> View.</p> <p>The surprising thing is that the value of _MyGlobalVariable is not kept! So the value of <strong>_MyGlobalVariable</strong> before the instruction <code>_MyGlobalVariable += "Print"</code> is equal to null.</p> <p>Am I making some mistake? How can I keep the value of global variables between calls to Views?</p> <p>Thanks</p> <p>Francesco</p> <p>PS: in my specific case the global variable is a <code>Dictionary&lt;K,V&gt;</code> but I guess it does not change the logic.</p> <p>PPS: I know you can use ViewModels instead of global variables to pass data between action methods but in my case is much less code if I use a <code>Dictionary&lt;K,V&gt;</code> which usually I don't wrap in ViewModels (I use <strong>POCOs</strong> or <code>Lists&lt;T&gt;</code>)</p>
5,939,393
5
5
null
2011-05-09 15:51:21.457 UTC
2
2018-06-01 17:19:03.797 UTC
null
null
null
null
675,082
null
1
17
c#|asp.net-mvc-3|global-variables
78,192
<p>Each request gets a fresh controller instance.<br> Since your "variable" is an instance field, it doesn't persist.</p> <p>You can fix that by making it <code>static</code>, or by using application state.</p> <p>However, <strong>don't</strong>.<br> You should never use mutable global state in a web application.</p> <p>In particular, if you get two request at the same time, your field will get messed up.</p> <p>Depending on what you're trying to do, you may want to use Session state or cookies.</p>
6,193,574
Save Javascript objects in sessionStorage
<p>SessionStorage and LocalStorage allows to save key/value pairs in a web browser. The value must be a string, and save js objects is not trivial.</p> <pre><code>var user = {'name':'John'}; sessionStorage.setItem('user', user); var obj = sessionStorage.user; // obj='[object Object]' Not an object </code></pre> <p>Nowadays, you can avoid this limitation by serializing objects to JSON, and then deserializing them to recover the objects. But the Storage API always pass through the <code>setItem</code> and <code>getItem</code> methods.</p> <pre><code>sessionStorage.setItem('user', JSON.stringify(user)); var obj = JSON.parse(sessionStorage.getItem('user')); // An object :D </code></pre> <p>Can I avoid this limitation?</p> <p>I just want to execute something like this:</p> <pre><code>sessionStorage.user.name; // 'John' sessionStorage.user.name = 'Mary'; sessionStorage.user.name // 'Mary' </code></pre> <p>I have tried the <code>defineGetter</code> and <code>defineSetter</code> methods to intercept the calls but its a tedious job, because I have to define all properties and my target is not to know the future properties.</p>
6,193,783
10
5
null
2011-05-31 21:08:05.843 UTC
45
2022-07-13 08:49:54.333 UTC
2017-02-14 13:42:12.63 UTC
null
460,750
null
497,477
null
1
181
javascript|session-storage
321,359
<p>Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.</p> <p>I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.</p>
6,079,492
How to print a debug log?
<p>I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me. </p> <p><strong>How should I print a log in PHP code?</strong></p> <p>The usual <code>print</code>/<code>printf</code> seems to go to HTML output not the console.</p> <p>I have Apache server executing the PHP code. </p>
6,079,566
15
5
null
2011-05-21 03:51:56.12 UTC
51
2018-09-12 09:36:23.843 UTC
2018-09-12 09:36:23.843 UTC
null
505,893
null
433,570
null
1
154
php|debugging|logging
297,386
<p>A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so <code>file_put_contents('php://stderr', print_r($foo, TRUE))</code> will nicely dump the value of <code>$foo</code> into the Apache error log.</p>
13,968,928
calling Servlet's method from JSP
<p>I am developing a web application using JSP and Servlets. </p> <p>I wants to call servlet's method from JSP page when user click's on the Update button. </p> <pre><code>&lt;input type="button" value="Update" onclick="&lt;%MyServletName.Update(request, response);%&gt;"&gt;&lt;/input&gt; </code></pre> <p>When I click on Update button then this method is calling the servlet, But the problem is that when form is loaded then this method is called automatically.</p> <p>Thanks in advance.....</p> <p>Source Code....</p> <pre><code>&lt;%@page import="MyPackageName.MyServletName"%&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Update&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;% String[][] data = (String[][])request.getAttribute("data"); String[] columnNames = (String[])request.getAttribute("columnNames"); //fill the table data if(columnNames.length!=0 &amp;&amp; data.length!=0) { %&gt;&lt;table&gt;&lt;% } for(int i=0;i&lt;data.length;i++){ %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= columnNames[0] %&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="text1" value="&lt;%= data[i][0] %&gt;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;%= columnNames[1] %&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="text2" value="&lt;%= data[i][1] %&gt;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;%= columnNames[2] %&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="text3" value="&lt;%= data[i][2] %&gt;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="button" value="Update" onclick="&lt;%PlanProtocolEdit.Update(request, response);%&gt;"&gt;&lt;/input&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is there any way that I can call the servlet method other than dogGet() and doPost() without invoking the servlets dogGet() and doPost() methods?</p>
13,968,960
3
2
null
2012-12-20 09:28:32.933 UTC
1
2016-01-06 16:31:53.24 UTC
2012-12-20 10:15:19.05 UTC
null
1,551,233
null
1,551,233
null
1
2
java|html|jsp|servlets
45,635
<p>You should specify the action on the form itself not the actual input button.</p> <p>If you define an action on the form. E.g.</p> <p>The forms submit button will submit the form to that URL. E.g.</p> <pre><code>&lt;form action="/mypath/someurl"&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; </code></pre> <p>You can add an additional attribute to the <code>form</code> tag to specify whether you want the request to be a <code>get</code> or a <code>post</code>. </p> <pre><code>&lt;form action="/mypath/someurl" method="POST"&gt; </code></pre> <p>Would send a post request, you can then pick this up in your Servlet with the <code>handlePost</code> method</p> <p>The above approach should be used, currently you are trying to call a Java method on a javascript onclick event. This is incorrect and it is not doing what you think it is.</p> <p>The code in <code>PlanProtocolEdit</code>. Update should be in a <code>doGet</code> or <code>doPost</code> method of a servlet which will be triggered by configuring your form as described above.</p>
24,781,027
How do you sort an array of structs in swift
<p>I have an array of a struct and I would like to be able to sort it by either of the two variables using sort() if possible</p> <pre><code>struct{ var deadline = 0 var priority = 0 } </code></pre> <p>I looked at sort() in the documentation for the Swift programming language but it shows only simple arrays. can sort() be used or will I have to build my own?</p>
24,781,216
1
1
null
2014-07-16 12:39:44.67 UTC
5
2014-07-18 12:29:19.563 UTC
null
null
null
null
1,110,450
null
1
30
arrays|sorting|swift
16,384
<h1>Sort within the same array variable</h1> <p>Sort functions bellow are exactly the same, the only difference how short and expressive they are:</p> <p>Full declaration:</p> <pre><code>myArr.sort { (lhs: EntryStruct, rhs: EntryStruct) -&gt; Bool in // you can have additional code here return lhs.deadline &lt; rhs.deadline } </code></pre> <p>Shortened closure declaration:</p> <pre><code>myArr.sort { (lhs:EntryStruct, rhs:EntryStruct) in return lhs.deadline &lt; rhs.deadline } // ... or even: myArr.sort { (lhs, rhs) in return lhs.deadline &lt; rhs.deadline } </code></pre> <p>Compact closure declaration:</p> <pre><code>myArr.sort { $0.deadline &lt; $1.deadline } </code></pre> <h1>Sort to a new array variable</h1> <p>Full declaration:</p> <pre><code>let newArr = myArr.sorted { (lhs: EntryStruct, rhs: EntryStruct) -&gt; Bool in // you can have additional code here return lhs.deadline &lt; rhs.deadline } </code></pre> <p>Shortened closure declaration:</p> <pre><code>let newArr = myArr.sorted { (lhs:EntryStruct, rhs:EntryStruct) in return lhs.deadline &lt; rhs.deadline } // ... or even: let newArr = myArr.sorted { (lhs, rhs) in return lhs.deadline &lt; rhs.deadline } </code></pre> <p>Compact closure declaration:</p> <pre><code>let newArr = myArr.sorted { $0.deadline &lt; $1.deadline } </code></pre>
32,704,336
How to access Activity from a React Native Android module?
<p>I'm attempting to bridge over the Android functionality of keeping the screen on to React Native. I figured I could do this with a simple module, however I don't know how to get access to the current Android Activity from said module.</p> <p>I need the Activity reference so I can call <code>.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);</code> on it</p> <p>I tried to get the activity via casting like so <code>((Activity)getReactApplicationContext().getBaseContext())</code>, but this throws a "cannot be cast to Android.app.Activity" error</p>
32,825,290
11
1
null
2015-09-21 20:50:39.487 UTC
14
2022-06-30 03:12:35 UTC
null
null
null
null
3,178,793
null
1
42
android|react-native
63,450
<p><code>CustomReactPackage.java</code>:</p> <pre><code>public class CustomReactPackage implements ReactPackage { private Activity mActivity = null; public CustomReactPackage(Activity activity) { mActivity = activity; } @Override public List&lt;NativeModule&gt; createNativeModules(ReactApplicationContext reactContext) { List&lt;NativeModule&gt; modules = new ArrayList&lt;&gt;(); // Add native modules here return modules; } public List&lt;Class&lt;? extends JavaScriptModule&gt;&gt; createJSModules() { return Collections.emptyList(); } public List&lt;ViewManager&gt; createViewManagers(ReactApplicationContext reactContext) { List&lt;ViewManager&gt; modules = new ArrayList&lt;&gt;(); // Add native UI components here modules.add(new LSPlayerManager(mActivity)); return modules; } } </code></pre> <p><code>LSPlayerManager</code> is my native UI component. I define a constructor so that I can pass in the activity:</p> <pre><code>public LSPlayerManager(Activity activity) { mActivity = activity; } </code></pre> <p>And finally in <code>MainActivity.java</code> where the <code>ReactInstanceManager</code> is defined, we can pass the activity to our custom React package:</p> <pre><code>mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle") .setJSMainModuleName("src/index.android") .addPackage(new MainReactPackage()) .addPackage(new CustomReactPackage(this)) // &lt;--- LIKE THIS! .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); </code></pre> <hr> <p><strong>UPDATE FOR REACT NATIVE 0.29.0</strong></p> <p>This is no longer how you access activity in a native module. See <a href="https://github.com/facebook/react-native/releases/tag/v0.29.0" rel="noreferrer">https://github.com/facebook/react-native/releases/tag/v0.29.0</a> for migration instructions</p>
33,036,487
One liner to flatten nested object
<p>I need to flatten a nested object. Need a one liner. Not sure what the correct term for this process is. I can use pure Javascript or libraries, I particularly like underscore.</p> <p>I've got ...</p> <pre><code>{ a:2, b: { c:3 } } </code></pre> <p>And I want ...</p> <pre><code>{ a:2, c:3 } </code></pre> <p>I've tried ...</p> <pre><code>var obj = {"fred":2,"jill":4,"obby":{"john":5}}; var resultObj = _.pick(obj, "fred") alert(JSON.stringify(resultObj)); </code></pre> <p>Which works but I also need this to work ...</p> <pre><code>var obj = {"fred":2,"jill":4,"obby":{"john":5}}; var resultObj = _.pick(obj, "john") alert(JSON.stringify(resultObj)); </code></pre>
33,037,683
18
2
null
2015-10-09 10:56:46.923 UTC
16
2022-07-30 04:14:43.283 UTC
2015-10-09 11:20:28.707 UTC
null
1,205,871
null
1,205,871
null
1
62
javascript|underscore.js
110,616
<p>Here you go:</p> <pre><code>Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k =&gt; typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject)) </code></pre> <p>Summary: recursively create an array of one-property objects, then combine them all with <code>Object.assign</code>.</p> <p>This uses ES6 features including <code>Object.assign</code> or the spread operator, but it should be easy enough to rewrite not to require them.</p> <p>For those who don't care about the one-line craziness and would prefer to be able to actually read it (depending on your definition of readability):</p> <pre><code>Object.assign( {}, ...function _flatten(o) { return [].concat(...Object.keys(o) .map(k =&gt; typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]}) ) ); }(yourObject) ) </code></pre>
33,190,613
What does a Kotlin function signature with T.() mean?
<p>This is a standard Kotlin function (as far as I know)</p> <pre><code>inline fun&lt;T&gt; with(t: T, body: T.() -&gt; Unit) { t.body() } </code></pre> <p>But could anyone write in simple English what does exactly the signature mean? It's a generic function for T, with first argument "t" of type T and second, "body" of function type, accepting a function of ???? and returning nothing (Unit)</p> <p>I see this notation Something.() -> Something is used pretty frequently, i.e. for Anko:</p> <pre><code>inline fun Activity.coordinatorLayout(init: CoordinatorLayout.() -&gt; Unit) = ankoView({ CoordinatorLayout(it) },init) </code></pre> <p>but I don't think it was explained anywhere what .() means...</p>
33,191,900
3
2
null
2015-10-17 19:20:07.223 UTC
16
2020-05-13 05:16:11.597 UTC
2017-08-13 12:00:24.907 UTC
null
4,230,345
null
1,332,872
null
1
49
kotlin
13,679
<p><code>T.() -&gt; Unit</code> is an extension function type with receiver.</p> <p>Besides ordinary functions, Kotlin supports extension functions. Such function differs from an ordinary one in that it has a receiver type specification. Here it's a generic <code>T.</code> part.</p> <p>The <code>this</code> keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot), so you can call its methods directly (referring to <code>this</code> from parent scopes is still possible <a href="https://kotlinlang.org/docs/reference/this-expressions.html" rel="noreferrer">with qualifiers</a>).</p> <p><br/> Function <code>with</code> is a standard one, yes. It's current code:</p> <pre><code>/** * Calls the specified function [block] with the given [receiver] as its receiver and returns its result. * * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with). */ public inline fun &lt;T, R&gt; with(receiver: T, block: T.() -&gt; R): R = receiver.block() </code></pre> <p>So it's a generic function for <code>T</code> and <code>R</code>, with first argument "receiver" of type <code>T</code> and second, <code>f</code> of extension function type, which extends <code>T</code>, returning type <code>R</code> which in turn returned by the <code>with</code>.</p> <p>For example, you can use it like this:</p> <pre><code>val threadInfoString = with (Thread.currentThread()) { // isDaemon() &amp; getPriority() are called with new property syntax for getters &amp; setters "${getName()}[isDaemon=$isDaemon,priority=$priority]" } </code></pre> <p><br/> See documentation for extension functions here:<br/> <a href="https://kotlinlang.org/docs/reference/lambdas.html#extension-function-expressions" rel="noreferrer">kotlinlang.org/docs/reference/lambdas.html#extension-function-expressions</a><br/> <a href="https://kotlinlang.org/docs/reference/scope-functions.html#with" rel="noreferrer">kotlinlang.org/docs/reference/scope-functions.html#with</a> <a href="https://kotlinlang.org/docs/reference/extensions.html" rel="noreferrer">kotlinlang.org/docs/reference/extensions.html</a></p> <hr/> <p><strong>Added:</strong></p> <blockquote> <p>So the only valid <code>f</code> would be any 0-argument function defined for T?</p> </blockquote> <p>Not really. In Kotlin <a href="http://blog.jetbrains.com/kotlin/2015/04/upcoming-change-function-types-reform/" rel="noreferrer">function types and extension function types are unified</a>, so that they can be used interchangeably. For example, we can pass String::length where a function <code>(String) -&gt; Int</code> is expected.</p> <pre><code>// map() expects `(String) -&gt; Int` // argument has type `String.() -&gt; Int` strings.map(String::length) </code></pre> <p>Types like <code>Thread.() -&gt; String</code> &amp; <code>(Thread) -&gt; String</code> are the same from the background side – receiver, in fact, is the first argument.</p> <p>So any of the following functions is suitable for <code>Thread.() -&gt; String</code> argument:</p> <pre><code>fun main(args: Array&lt;String&gt;) { val f1 = fun Thread.(): String = name val f2 = fun Thread.() = name val f3: Thread.() -&gt; String = { name } val f4: (Thread) -&gt; String = { it.name } val f5 = { t: Thread -&gt; t.name } val f6: (Thread) -&gt; String = Thread::getNameZ val f7: Thread.() -&gt; String = Thread::getNameZ val f8 = Thread::getNameZ } fun Thread.getNameZ() = name </code></pre> <p>Or you can simply use <a href="https://kotlinlang.org/docs/reference/lambdas.html#function-literal-syntax" rel="noreferrer">function literal</a> (<code>{}</code>) as in the example with <code>threadInfoString</code>, but it works only when the receiver type can be inferred from the context.</p>
10,626,766
Minimax explanation "for dummies"
<p>I'm quite new to algorithms and i was trying to understand the minimax, i read a lot of articles,but i still can't get how to implement it into a tic-tac-toe game in python. Can you try to explain it to me as easy as possible maybe with some pseudo-code or some python code?. </p> <p>I just need to understand how it works. i read a lot of stuff about that and i understood the basic, but i still can't get how it can return a move.</p> <p>If you can please don't link me tutorials and samples like (http://en.literateprograms.org/Tic_Tac_Toe_(Python)) , i know that they are good, but i simply need a idiot explanation.</p> <p>thank you for your time :)</p>
10,638,736
2
1
null
2012-05-16 21:10:07.577 UTC
9
2012-05-17 15:29:14.783 UTC
2012-05-16 21:12:49.81 UTC
null
164,966
null
1,397,148
null
1
10
python|algorithm
5,650
<p>the idea of "minimax" is that there in a two-player game, one player is trying to maximize some form of score and another player is trying to minimize it. For example, in Tic-Tac-Toe the win of X might be scored as +1 and the win of O as -1. X would be the max player, trying to maximize the final score and O would be the min player, trying to minimize the final score.</p> <p>X is called the max player because when it is X's move, X needs to choose a move that maximizes the outcome after that move. When O players, O needs to choose a move that minimizes the outcome after that move. These rules are applied recursively, so that e.g. if there are only three board positions open to play, the best play of X is the one that forces O to choose a minimum-value move whose value is as high as possible.</p> <p>In other words, the game-theoretic minimax value V for a board position B is defined as</p> <pre><code> V(B) = 1 if X has won in this position V(B) = -1 if O has won in this position V(B) = 0 if neither player has won and no more moves are possible (draw) </code></pre> <p>otherwise</p> <pre><code> V(B) = max(V(B1), ..., V(Bn)) where board positions B1..Bn are the positions available for X, and it is X's move V(B) = min(V(B1), ..., V(Bn)) where board positions B1..Bn are the positions available for O, and it is O's move </code></pre> <p>The optimal strategy for X is always to move from B to Bi such that V(Bi) is maximum, i.e. corresponds to the gametheoretic value V(B), and for O, analogously, to choose a minimum successor position.</p> <p>However, this is not usually possible to calculate in games like chess, because in order to calculate the gametheoretic value one needs to enumerate the whole game tree until final positions and that tree is usually extremely large. Therefore, a standard approach is to coin an "evaluation function" that maps board positions to scores that are hopefully correlated with the gametheoretic values. E.g. in chess programs evaluation functions tend to give positive score for material advantage, open columns etc. A minimax algorithm them minimaximizes the evaluation function score instead of the actual (uncomputable) gametheoretic value of a board position.</p> <p>A significant, standard optimization to minimax is "alpha-beta pruning". It gives the same results as minimax search but faster. Minimax can be also casted in terms of "negamax" where the sign of the score is reversed at every search level. It is just an alternative way to implement minimax but handles players in a uniform fashion. Other game tree search methods include iterative deepening, proof-number search, and more.</p>
10,492,839
How to re-index all subarray elements of a multidimensional array?
<p>The question is how to reset key e.g. for an array:</p> <pre><code>Array ( [1_Name] =&gt; Array ( [1] =&gt; leo [4] =&gt; NULL ) [1_Phone] =&gt; Array ( [1] =&gt; 12345 [4] =&gt; 434324 ) ) </code></pre> <p>reset to :</p> <pre><code>Array ( [1_Name] =&gt; Array ( [0] =&gt; leo [1] =&gt; NULL ) [1_Phone] =&gt; Array ( [0] =&gt; 12345 [1] =&gt; 434324 ) ) </code></pre>
10,492,870
6
1
null
2012-05-08 05:06:21.93 UTC
16
2020-10-04 22:37:50.463 UTC
2020-10-04 22:37:50.463 UTC
null
2,943,403
null
1,280,996
null
1
143
php|multidimensional-array|reindex
257,079
<p>To reset the keys of all arrays in an array:</p> <pre><code>$arr = array_map('array_values', $arr); </code></pre> <p>In case you just want to reset first-level array keys, use <a href="http://php.net/manual/en/function.array-values.php" rel="noreferrer"><code>array_values()</code></a> without <a href="http://php.net/manual/en/function.array-map.php" rel="noreferrer"><code>array_map</code></a>.</p>
19,266,391
@XmlElement and useless 'required' parameter
<p>I put <strong>@XmlElement(name = "title",required = true)</strong> before the javabean property <strong>int some_property</strong>, and didn't assign a value to <strong>some_property</strong>. For some reason this property is not occurred in generated XML. So, please, explain the meaning of <strong>required</strong></p> <p>some meaningful parts of the code:</p> <pre><code>@XmlRootElement(name = "book") @XmlType(propOrder = { "author", "name", "publisher", "isbn" }) public class Book { private String name; private String author; private String publisher; private String isbn; // If you like the variable name, e.g. "name", you can easily change this // name for your XML-Output: @XmlElement(name = "title",required = true) public String getName() { return name; } .... </code></pre> <p>Somewhere int the <strong>Main</strong> :</p> <pre><code> // create books Book book1 = new Book(); book1.setIsbn("978-0060554736"); book1.setAuthor("Neil Strauss"); book1.setPublisher("Harpercollins"); bookList.add(book1); Book book2 = new Book(); book2.setIsbn("978-3832180577"); book2.setName("Feuchtgebiete"); book2.setAuthor("Charlotte Roche"); book2.setPublisher("Dumont Buchverlag"); bookList.add(book2); JAXBContext context = JAXBContext.newInstance(Bookstore.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to System.out m.marshal(bookstore, System.out); // Write to File m.marshal(bookstore, new File(BOOKSTORE_XML)); // get variables from our xml file, created before System.out.println(); System.out.println("Output from our XML File: "); Unmarshaller um = context.createUnmarshaller(); Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(BOOKSTORE_XML)); ArrayList&lt;Book&gt; list = bookstore2.getBooksList(); </code></pre>
19,273,820
3
0
null
2013-10-09 08:08:27.82 UTC
5
2015-05-29 21:38:13.66 UTC
2015-05-29 21:38:13.66 UTC
user2254651
3,885,376
user2254651
null
null
1
17
java|jaxb
45,812
<h2>What <code>required</code> Does on <code>@XmlElement</code></h2> <p>The <code>required</code> property on the <code>@XmlElement</code> annotation affects the XML schema that is generated from Java classes.</p> <p><strong>Domain Model (Root)</strong></p> <p>Below is a simple Java model. Note how the <code>bar</code> property has <code>required=true</code> and the <code>foo</code> property does not.</p> <pre><code>import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Root { @XmlElement private String foo; @XmlElement(required=true) private String bar; @XmlElement(nillable=true) private String baz; } </code></pre> <p><strong>Demo Code</strong></p> <p>Below is some code that demonstrates how to generate an XML schema using the <code>JAXBContext</code>.</p> <pre><code>import java.io.IOException; import javax.xml.bind.*; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; public class GenerateSchema { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); jc.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { StreamResult result = new StreamResult(System.out); result.setSystemId(suggestedFileName); return result; } }); } } </code></pre> <p><strong>Generated XML Schema</strong></p> <p>Below is the resulting XML schema note how the XML element corresponding to the <code>foo</code> field has <code>minOccurs="0"</code> while the XML element corresponding to the <code>bar</code> field (which was annotated with <code>@XmlElement(required=true)</code> does not. This is because the default <code>minOccurs</code> is 1 meaning it's required.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="root" type="root"/&gt; &lt;xs:complexType name="root"&gt; &lt;xs:sequence&gt; &lt;xs:element name="foo" type="xs:string" minOccurs="0"/&gt; &lt;xs:element name="bar" type="xs:string"/&gt; &lt;xs:element name="baz" type="xs:string" nillable="true" minOccurs="0"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <h2>If You Want an Element for <code>null</code> Values</h2> <p><strong>Domain Model (Root)</strong></p> <p>The <code>baz</code> field has been annotated with <code>@XmlElement(nillable=true)</code>. If the value is null the resulting XML element will leverage the <code>xsi:nil</code> attribute. Without this annotation null values will be treated as absent nodes.</p> <pre><code>import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Root { @XmlElement private String foo; @XmlElement(required=true) private String bar; @XmlElement(nillable=true) private String baz; } </code></pre> <p><strong>Demo Code</strong></p> <pre><code>import javax.xml.bind.*; public class MarshalDemo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Root root = new Root(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } </code></pre> <p><strong>Output</strong></p> <p>Below is the resulting XML from running the demo code.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;root&gt; &lt;baz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/&gt; &lt;/root&gt; </code></pre>
18,992,219
How to assign more memory to Netbeans?
<p>I have 24 GB of RAM on my PC, but sometimes when Netbeans compiles my projects, it says not enough memory to compile it, I looked at the memory useage, it shows : 586/590 M.</p> <p>So how to tell Netbeans, there are plenty of RAM, use as much as you need ?</p>
18,992,956
1
1
null
2013-09-24 21:17:57.427 UTC
8
2018-05-25 11:19:42.833 UTC
null
null
null
null
32,834
null
1
48
memory|netbeans
48,040
<p>In the <strong>etc</strong> directory under your Netbeans-Home, edit the file <strong>netbeans.conf</strong> file. <strong>-Xms</strong> and <strong>-Xmx</strong> should be increased to the values that allow your program to compile.</p> <p>Here are the instructions in <strong>netbeans.conf</strong>:</p> <pre><code># Note that default -Xmx and -XX:MaxPermSize are selected for you automatically. # You can find these values in var/log/messages.log file in your userdir. # The automatically selected value can be overridden by specifying -J-Xmx or # -J-XX:MaxPermSize= here or on the command line. </code></pre> <p>Put the values in the <strong>netbeans_default_options</strong> string. Here is mine (remove linebreaks, added for readability):</p> <pre><code>netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Dsun.awt.disableMixing=true -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd --laf Nimbus" </code></pre> <p><strong>EDIT:</strong> <code>-J-Xms</code> sets the minimum Java heap size, <code>-J-Xmx</code> sets the maximum Java heap size.</p>
38,042,028
How to add actions to UIAlertController and get result of actions (Swift)
<p>I want to set up a <code>UIAlertController</code> with four action buttons, and the titles of the buttons to be set to "hearts", "spades", "diamonds", and "clubs". When a button is pressed, I want to return its title. </p> <p>In short, here is my plan:</p> <pre><code>// TODO: Create a new alert controller for i in ["hearts", "spades", "diamonds", "clubs"] { // TODO: Add action button to alert controller // TODO: Set title of button to i } // TODO: return currentTitle() of action button that was clicked </code></pre>
38,042,992
2
1
null
2016-06-26 18:51:45.813 UTC
4
2018-05-18 08:55:13.323 UTC
2016-12-13 09:34:55.063 UTC
user6596937
null
null
5,592,754
null
1
18
ios|xcode|swift|uialertcontroller
51,163
<p>Try this:</p> <pre><code>let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert) for i in ["hearts", "spades", "diamonds", "hearts"] { alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething) } self.presentViewController(alert, animated: true, completion: nil) </code></pre> <p>And handle the action here:</p> <pre><code>func doSomething(action: UIAlertAction) { //Use action.title } </code></pre> <p>For future reference, you should take a look at <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/" rel="noreferrer">Apple's Documentation on UIAlertControllers</a></p>
35,516,318
Plot colored polygons with geodataframe in folium
<p>I'm trying to plot radar data in folium, and I'm almost there. I followed this example (<a href="https://stackoverflow.com/questions/34886899/contour-plot-data-lat-lon-value-within-boundaries-and-export-geojson">Contour plot data (lat,lon,value) within boundaries and export GeoJSON</a>) to get my data into a GeoJson format. </p> <pre><code>nb_class = 20 collec_poly = plt.contourf(lons,lats,np.array(poshdata), nb_class,alpha=0.5) gdf = collec_to_gdf(collec_poly) # From link above gdf.to_json() colors = [p.get_facecolor().tolist()[0] for p in collec_poly.collections] gdf['RGBA'] = colors gdf </code></pre> <p>This outputs two columns: geometry and RGBA. </p> <pre><code> RGBA geometry 0 [0.0, 0.0, 0.713903743316, 1.0] (POLYGON ((-71.57032079644679 42.2775236331535... 1 [0.0, 0.0960784313725, 1.0, 1.0] (POLYGON ((-71.56719970703125 42.2721176147460... 2 [0.0, 0.503921568627, 1.0, 1.0] (POLYGON ((-71.55678558349609 42.2721176147460... 3 [0.0, 0.896078431373, 0.970904490829, 1.0] (POLYGON ((-71.52552795410156 42.2849182620049... 4 [0.325743200506, 1.0, 0.641998734978, 1.0] (POLYGON ((-71.49427795410156 42.2939676156927... 5 [0.641998734978, 1.0, 0.325743200506, 1.0] (POLYGON ((-71.47344207763672 42.3003084448852... 6 [0.970904490829, 0.959331880901, 0.0, 1.0] (POLYGON ((-71.26508331298828 42.3200411822557... 7 [1.0, 0.581699346405, 0.0, 1.0] (POLYGON ((-71.15048217773438 42.3333218460720... </code></pre> <p>From there I make my folium map:</p> <pre><code>import folium # Picked location between Sudbury and Somerville: maploc = folium.Map(location=[42.377157,-71.236088],zoom_start=11,tiles="Stamen Toner") folium.GeoJson(gdf).add_to(maploc) </code></pre> <p>This creates my nice folium map, but the polygons are not colored at all. How do I get the contours to be filled with the right colors? And fix the opacity?</p> <p><a href="https://i.stack.imgur.com/5pwtT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5pwtT.jpg" alt="enter image description here"></a></p>
35,559,074
3
1
null
2016-02-19 22:32:38.99 UTC
8
2020-07-09 23:57:56.873 UTC
2017-05-23 12:02:08.52 UTC
null
-1
null
4,544,147
null
1
13
python|geojson|folium
30,708
<p>I think I figured it out. In my previous code, polygon.get_facecolor() returns a list of RGBA values ranging from 0-1. I added this function (modified from <a href="https://stackoverflow.com/questions/21954792/gtk3-and-python-rgba-convert-to-hex">this</a> post):</p> <pre><code>def convert_to_hex(rgba_color) : red = str(hex(int(rgba_color[0]*255)))[2:].capitalize() green = str(hex(int(rgba_color[1]*255)))[2:].capitalize() blue = str(hex(int(rgba_color[2]*255)))[2:].capitalize() if blue=='0': blue = '00' if red=='0': red = '00' if green=='0': green='00' return '#'+ red + green + blue </code></pre> <p>to convert it to a hex string. Then:</p> <pre><code>gdf['RGBA'] = convert_to_hex(colors) </code></pre> <p>Then to plot the colors in folium, I do:</p> <pre><code>maploc = folium.Map(location=[42.377157,-71.236088],zoom_start=10,tiles="Stamen Toner") colors = [] folium.GeoJson( gdf, style_function=lambda feature: { 'fillColor': feature['properties']['RGBA'], 'color' : feature['properties']['RGBA'], 'weight' : 1, 'fillOpacity' : 0.5, } ).add_to(maploc) </code></pre> <p>and that created a really nice looking plot! (The property name is a bit misleading - it's not actually RGBA values, but hex strings.)</p>
35,359,358
Angular 2 change event on every keypress
<p>The change event is only called after the focus of the input has changed. How can I make it so that the event fires on every keypress? </p> <pre class="lang-xml prettyprint-override"><code>&lt;input type="text" [(ngModel)]="mymodel" (change)="valuechange($event)" /&gt; {{mymodel}} </code></pre> <p>The second binding changes on every keypress btw.</p>
43,776,147
13
1
null
2016-02-12 09:47:33.613 UTC
67
2021-10-20 09:39:40.2 UTC
2017-06-01 21:29:56.94 UTC
null
430,885
null
516,389
null
1
393
angular
651,774
<p>I just used the event input and it worked fine as follows:</p> <p>in .html file :</p> <pre class="lang-xml prettyprint-override"><code>&lt;input type="text" class="form-control" (input)="onSearchChange($event.target.value)"&gt; </code></pre> <p>in .ts file :</p> <pre class="lang-typescript prettyprint-override"><code>onSearchChange(searchValue: string): void { console.log(searchValue); } </code></pre>
35,517,239
SharedPreferences are not being cleared when I uninstall
<p>OK, this is a strange one that I didn't think was even possible.</p> <p>So, ever since I've been using a Nexus 5X, the SharedPreferences are not getting wiped when I uninstall my app.</p> <p>I install the app through Android Studio and test things. I then uninstall the app. I then resintall the app through Android Studio and all the SharedPreferences values are still there.</p> <p>I've tried clearing the data/cache in addition to uninstalling. The SharedPreferences are persistent through all those attempts.</p> <p>I am using stock Android 6.0 on a Nexus 5X. My device is not rooted. I am not using a custom ROM. I do not have this issue with my Nexus 4. </p> <p>Any ideas what might be causing this?</p>
35,517,411
3
2
null
2016-02-19 23:55:14.9 UTC
14
2020-12-02 10:24:10.997 UTC
null
null
null
null
1,255,125
null
1
89
android
17,772
<p>This is a new marshmallow feature. </p> <p>Add <code>android:allowBackup="false"</code> tag inside your <code>&lt;application&gt;</code> object in your app manifest to disable this behaviour.</p> <p>If <code>android:allowBackup</code> tag clashes with any other library you are using, you should add <code>tools:replace="android:allowBackup"</code> also.</p>
28,325,975
R function with FOR loop on a vector
<p>Surely a facepalm question, sorry. I have been trying to RTFM and google that but no luck.</p> <p>I am trying to make a silly function in R that takes a vector as argument, loops through it with a for loop and does a very simple addition to each component. </p> <pre><code>func1 &lt;- function(vector) { vr &lt;- c() ### an empty vector for (i in 1:length(vector)) { vr &lt;- vector[i]+i } } </code></pre> <p>To me this looks correct, but I am always getting a NULL vector. Why? </p>
28,326,141
2
2
null
2015-02-04 16:06:57.797 UTC
2
2015-02-04 17:25:53.967 UTC
null
null
null
null
2,850,382
null
1
7
r|function|for-loop|vector
58,728
<p>You could write that much more efficiently like this:</p> <pre><code>func1 &lt;- function(vector){ vector + seq_along(vector) } </code></pre> <p>This way you are taking advantage of vector addition.</p> <p>For the sake of completeness, let's benchmark these two solutions. Here is the general loop solution:</p> <pre><code>func2 &lt;- function(vector) { vr &lt;- c() ### an empty vector for (i in 1:length(vector)) { vr[i] &lt;- vector[i]+i } vr } </code></pre> <p>As a step up, there is also the in-place solution</p> <pre><code>func3 &lt;- function(vector) { for (i in 1:length(vector)) { vector[i] &lt;- vector[i]+i } vector } </code></pre> <p>Using <code>microbenchmark</code> we can see that the vectorized solution is by far the most efficient.</p> <pre><code>vec &lt;- sample(100000, 10000) library(microbenchmark) microbenchmark(func1(vec), func3(vec), func2(vec)) Unit: microseconds expr min lq mean median uq max neval cld func1(vec) 29.998 36.984 44.78312 42.736 44.38 399.006 100 a func3(vec) 12845.823 13666.432 14452.02863 14060.712 14708.53 25025.950 100 a func2(vec) 84898.055 87354.750 110046.26659 88634.566 91193.38 1042819.269 100 b </code></pre>
1,395,410
How to print R graphics to multiple pages of a PDF and multiple PDFs?
<p>I know that </p> <pre><code> pdf("myOut.pdf") </code></pre> <p>will print to a PDF in R. What if I want to</p> <ol> <li><p>Make a loop that prints subsequent graphs on new pages of a PDF file (appending to the end)?</p></li> <li><p>Make a loop that prints subsequent graphs to new PDF files (one graph per file)?</p></li> </ol>
1,395,443
3
0
null
2009-09-08 18:02:51.473 UTC
22
2020-07-20 02:13:08.353 UTC
null
null
null
null
23,929
null
1
54
graphics|r|plot
97,604
<p>Did you look at help(pdf) ?</p> <blockquote> <p>Usage:</p> <pre><code> pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot%03d.pdf"), width, height, onefile, family, title, fonts, version, paper, encoding, bg, fg, pointsize, pagecentre, colormodel, useDingbats, useKerning) </code></pre> <p>Arguments:</p> <pre><code>file: a character string giving the name of the file. For use with 'onefile=FALSE' give a C integer format such as '"Rplot%03d.pdf"' (the default in that case). (See 'postscript' for further details.) </code></pre> </blockquote> <p>For 1), you keep onefile at the default value of TRUE. Several plots go into the same file.</p> <p>For 2), you set onefile to FALSE and choose a filename with the C integer format and R will create a set of files.</p>
2,315,520
In Python, how do I loop through the dictionary and change the value if it equals something?
<p>If the value is None, I'd like to change it to "" (empty string).</p> <p>I start off like this, but I forget:</p> <pre><code>for k, v in mydict.items(): if v is None: ... right? </code></pre>
2,315,529
3
0
null
2010-02-23 01:19:42.48 UTC
23
2019-05-07 22:01:37.24 UTC
null
null
null
null
179,736
null
1
101
python|dictionary
154,495
<pre><code>for k, v in mydict.iteritems(): if v is None: mydict[k] = '' </code></pre> <p>In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using <code>items</code> to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does <em>not</em> incur any problem, so, in Python 2.any, it's better to use <code>iteritems</code>.</p> <p>In <strong>Python3</strong> however the code gives <code>AttributeError: 'dict' object has no attribute 'iteritems'</code> error. Use <code>items()</code> instead of <code>iteritems()</code> here. </p> <p>Refer to <a href="https://stackoverflow.com/questions/30418481/error-dict-object-has-no-attribute-iteritems/30418498">this post.</a></p>
9,010,128
Echo query before execution and without execution in codeigniter Active Record
<p>I am looking for a way to see generated string of the query but <strong>without</strong> executing it.</p> <p>Note that the query hasn't been executed before. (I do not want <code>$this-&gt;db-&gt;last_query();</code>)</p> <p>I hope there be a method with a name like <code>$this-&gt;db-&gt;echo_query_string($table_name = '');</code> to be used <strong>exactly like</strong> <code>$this-&gt;db-&gt;get($table_name = '');</code> <strong>BUT THE ONLY DIFFERENCE BE THAT</strong> <code>get()</code> executes the code, but <code>echo_query_string()</code> just echoes the string of query <strong>without execution</strong>.</p>
9,010,204
6
1
null
2012-01-25 20:54:08.173 UTC
10
2021-04-26 15:43:00.083 UTC
2013-01-28 13:26:10.983 UTC
null
315,550
null
315,550
null
1
26
php|mysql|codeigniter|activerecord
78,861
<p>You can see the compiled query by either of these functions</p> <pre><code>/* SELECT */ $this-&gt;db-&gt;_compile_select(); /* INSERT */ $this-&gt;db-&gt;_insert(); /* UPDATE */ $this-&gt;db-&gt;_update(); </code></pre>