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
39,462,371
Gitlabs artifact of one project used in further projects
<h1>Question</h1> <ul> <li>What is the best way to carry artifacts (jar, class, war) among projects when using docker containers in CI phase.</li> </ul> <p>Let me explain my issue in details, please don't stop the reading... =)</p> <h2>Gitlabs project1</h2> <ul> <li>unit tests</li> <li>etc...</li> <li>package</li> </ul> <h2>Gitlabs project2</h2> <ul> <li>unit test</li> <li>etc...</li> <li>build (failing) <ul> <li>here I need one artifact (jar) generated in project1</li> </ul></li> </ul> <h2>Current scenario / comments</h2> <ul> <li>I'm using dockers so in each .gitlab-ci.yml I'll have independent containers</li> <li>All is working fine in project1</li> <li>If I use "shell" instead of dockers in my .gitlab-ci.yml I can keep the jar file from the project1 in the disk and use when project2 kicks the build</li> <li>Today my trigger on call project2 when project1 finish is working nicely</li> <li>My artifact is not an RPM so I'll not add into my repo</li> </ul> <h2>Possible solutions</h2> <ul> <li>I can commit the artifact of project1 and checkout when need to build project2</li> <li>I need to study if cache feature from gitlabs is designed for this purpose (<a href="https://stackoverflow.com/questions/33940384/gitlab-8-2-1-how-to-use-cache-in-gitlab-ci-yml">gitlab 8.2.1, How to use cache in .gitlab-ci.yml</a>)</li> </ul>
39,472,680
5
1
null
2016-09-13 04:48:09.693 UTC
9
2021-02-26 17:08:00.64 UTC
2017-05-23 10:31:16.803 UTC
null
-1
null
114,308
null
1
16
continuous-integration|gitlab|gitlab-ci|gitlab-ci-runner
16,068
<p>Hello you must take a look at a script named <code>get-last-successful-build-artifact.sh</code> and developed by <code>morph027</code>.</p> <p><a href="https://gitlab.com/morph027/gitlab-ci-helpers" rel="noreferrer">https://gitlab.com/morph027/gitlab-ci-helpers</a></p> <p>This script allow to download an artifact and unzip it in the project root. It use Gitlab API to retrieve latest successful build and download corresponding artifact. You can combine multiple artifacts and unzip wherever you want just by updating the script a little.</p> <p>I'm also currently starting a <a href="https://github.com/shulard/laravel-build-artifacts" rel="noreferrer">PHP library</a> to handle build artifacts but it's in a very early stage and tied with laravel for the moment.</p> <p>For the moment there is no easy way to handle artifact usage between projects, you must build your own using that tools.</p> <p>I think using shell executor is not the right solution, it's very dangerous because you can't verify the file on the server used during the build !</p> <p>Hope this help :)</p>
26,557,873
Spark: produce RDD[(X, X)] of all possible combinations from RDD[X]
<p>Is it possible in Spark to implement '.combinations' function from scala collections?</p> <pre><code> /** Iterates over combinations. * * @return An Iterator which traverses the possible n-element combinations of this $coll. * @example `"abbbc".combinations(2) = Iterator(ab, ac, bb, bc)` */ </code></pre> <p>For example how can I get from RDD[X] to RDD[List[X]] or RDD[(X,X)] for combinations of size = 2. And lets assume that all values in RDD are unique.</p>
26,565,173
4
1
null
2014-10-24 23:51:09.8 UTC
10
2017-03-10 11:37:51.797 UTC
2014-10-25 00:21:56.123 UTC
null
1,177,991
null
1,177,991
null
1
25
scala|apache-spark
28,742
<p>Cartesian product and combinations are two different things, the cartesian product will create an RDD of size <code>rdd.size() ^ 2</code> and combinations will create an RDD of size <code>rdd.size() choose 2</code> </p> <pre><code>val rdd = sc.parallelize(1 to 5) val combinations = rdd.cartesian(rdd).filter{ case (a,b) =&gt; a &lt; b }`. combinations.collect() </code></pre> <p>Note this will only work if an ordering is defined on the elements of the list, since we use <code>&lt;</code>. This one only works for choosing two but can easily be extended by making sure the relationship <code>a &lt; b</code> for all a and b in the sequence</p>
6,778,759
Copying and pasting data using VBA code
<p>I have a button on a spreadsheet that, when pressed, should allow the user to open a file, then copy columns A-G of the spreadsheet "Data", then paste the data from those columns on the current sheet. </p> <p>I have a logic error in the code; it runs, but it pastes the selection in the wrong place. </p> <p>I am having trouble referencing the two workbooks.</p> <p>Here is my code:</p> <pre><code>Sub Button1_Click() Dim excel As excel.Application Dim wb As excel.Workbook Dim sht As excel.Worksheet Dim f As Object Set f = Application.FileDialog(3) f.AllowMultiSelect = False f.Show Set excel = CreateObject("excel.Application") Set wb = excel.Workbooks.Open(f.SelectedItems(1)) Set sht = wb.Worksheets("Data") sht.Activate sht.Columns("A:G").Select Selection.Copy Range("A1").Select ActiveSheet.Paste wb.Close End Sub </code></pre>
6,779,118
2
0
null
2011-07-21 15:38:16.507 UTC
3
2016-01-22 03:13:13.59 UTC
2016-01-22 03:13:13.59 UTC
null
4,539,709
null
844,678
null
1
13
vba|excel|excel-2010
311,559
<p>Use the PasteSpecial method:</p> <pre><code>sht.Columns("A:G").Copy Range("A1").PasteSpecial Paste:=xlPasteValues </code></pre> <p>BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).</p>
57,594,159
SwiftUI NavigationLink loads destination view immediately, without clicking
<p>With following code: </p> <pre><code>struct HomeView: View { var body: some View { NavigationView { List(dataTypes) { dataType in NavigationLink(destination: AnotherView()) { HomeViewRow(dataType: dataType) } } } } } </code></pre> <p>What's weird, when <code>HomeView</code> appears, <code>NavigationLink</code> immediately loads the <code>AnotherView</code>. As a result, all <code>AnotherView</code> dependencies are loaded as well, even though it's not visible on the screen yet. The user has to click on the row to make it appear. My <code>AnotherView</code> contains a <code>DataSource</code>, where various things happen. The issue is that whole <code>DataSource</code> is loaded at this point, including some timers etc.</p> <p>Am I doing something wrong..? How to handle it in such way, that <code>AnotherView</code> gets loaded once the user presses on that <code>HomeViewRow</code>?</p>
61,234,030
6
2
null
2019-08-21 14:44:31.483 UTC
23
2021-08-11 15:51:49.24 UTC
null
null
null
null
849,616
null
1
79
ios|swift|swiftui
19,003
<p>The best way I have found to combat this issue is by using a Lazy View. </p> <pre><code>struct NavigationLazyView&lt;Content: View&gt;: View { let build: () -&gt; Content init(_ build: @autoclosure @escaping () -&gt; Content) { self.build = build } var body: Content { build() } } </code></pre> <p>Then the NavigationLink would look like this. You would place the View you want to be displayed inside <code>()</code></p> <pre><code>NavigationLink(destination: NavigationLazyView(DetailView(data: DataModel))) { Text("Item") } </code></pre>
7,533,772
How to swipe between several jquery mobile pages?
<p>Here is the code extract which works well with 2 pages:</p> <pre class="lang-html prettyprint-override"><code>&lt;script&gt; $(document).ready(function() { window.now = 1; $('#device1').live("swipeleft", function(){ window.now++ $.mobile.changePage("#device"+window.now, "slide", false, true); }); $('#device2').live("swiperight", function(){ window.now--; $.mobile.changePage("#device"+window.now, "slide", true, true); }); }); &lt;/script&gt; ... &lt;div data-role="page" id="device1"&gt; ... &lt;/div&gt;&lt;!-- /page --&gt; &lt;div data-role="page" id="device2"&gt; ... &lt;/div&gt;&lt;!-- /page --&gt; </code></pre> <p>How can I make it more universal to work with huge number of pages?</p>
7,535,201
3
0
null
2011-09-23 19:19:34.34 UTC
10
2013-04-12 16:14:45.827 UTC
2011-09-23 19:54:30.733 UTC
null
604,388
null
604,388
null
1
2
jquery-mobile
22,744
<p>This seems to do what you want</p> <pre><code>&lt;script&gt; $(document).ready(function() { $('.ui-slider-handle').live('touchstart', function(){ // When user touches the slider handle, temporarily unbind the page turn handlers doUnbind(); }); $('.ui-slider-handle').live('mousedown', function(){ // When user touches the slider handle, temporarily unbind the page turn handlers doUnbind(); }); $('.ui-slider-handle').live('touchend', function(){ //When the user let's go of the handle, rebind the controls for page turn // Put in a slight delay so that the rebind does not happen until after the swipe has been triggered setTimeout( function() {doBind();}, 100 ); }); $('.ui-slider-handle').live('mouseup', function(){ //When the user let's go of the handle, rebind the controls for page turn // Put in a slight delay so that the rebind does not happen until after the swipe has been triggered setTimeout( function() {doBind();}, 100 ); }); // Set the initial window (assuming it will always be #1 window.now = 1; //get an Array of all of the pages and count windowMax = $('div[data-role="page"]').length; doBind(); }); // Functions for binding swipe events to named handlers function doBind() { $('div[data-role="page"]').live("swipeleft", turnPage); $('div[data-role="page"]').live("swiperight", turnPageBack); } function doUnbind() { $('div[data-role="page"]').die("swipeleft", turnPage); $('div[data-role="page"]').die("swiperight", turnPageBack); } // Named handlers for binding page turn controls function turnPage(){ // Check to see if we are already at the highest numbers page if (window.now &lt; windowMax) { window.now++ $.mobile.changePage("#device"+window.now, "slide", false, true); } } function turnPageBack(){ // Check to see if we are already at the lowest numbered page if (window.now != 1) { window.now--; $.mobile.changePage("#device"+window.now, "slide", true, true); } } &lt;/script&gt; </code></pre> <h2>UPDATE: I tested this with the iPhone emulator and the Android emulator and it worked as expected in both.</h2> <p>UPDATE: Changed answer to address the user's comment about using a slider causing swipe left/right.</p>
7,027,644
C# : Generating Code 128 Barcode (width of bars/spaces)
<p>So I inherited this code, or should I say, someone developed this and moved on and now we are having a problem with it and I'm looking into it... </p> <p>We are generating c128 barcodes and upon having them certified they noticed an issue that I can't see to figure out. The width of a bars/spaces is 10.5 mils and they acceptable range is 15-21 mils (1 mil = .001 inch). </p> <p>The rendering code is based off this library: <a href="http://www.codeproject.com/KB/GDI-plus/GenCode128.aspx">http://www.codeproject.com/KB/GDI-plus/GenCode128.aspx</a> but has been modified some...</p> <p>The barcodes being generated are all alpha-numeric, no special characters. I thought the width of the bar + space was dependent on the character being encoded.</p> <p>Here are the settings being used:</p> <pre><code>settings.Font = new Font ( FontFamily.GenericSansSerif, 12 ); settings.TopMargin = 10 settings.BottomMargin = 10 settings.LeftMargin = 10 settings.RightMargin = 10 settings.BarCodeHeight = 80 settings.DrawText = true settings.BarCodeToTextGapHeight = 10 settings.InterCharacterGap = 2 </code></pre> <p>If I was guessing, I think it's because the width of the bars is being based on the height of the barcode instead of the height of the barcode being based on the length of the text and barcode. But I'm not too familiar with the spec (even after reviewing it), and I'm a novice C# programmer at best...</p>
7,027,810
3
1
null
2011-08-11 14:27:53.543 UTC
4
2015-01-22 05:42:01.393 UTC
2011-08-11 15:37:59.737 UTC
null
155,110
null
155,110
null
1
9
c#|barcode|code128
51,226
<p>This isn't a direct answer BUT I would strongly recommend to use a well-tested library for generating barcodes... getting barcodes right isn't easy since there are some pitfalls... there are tons of libraries out there some commercial, some free...</p> <p>2 free barcode libraries for .NET:<br/> <a href="http://barcoderender.codeplex.com/" rel="noreferrer">http://barcoderender.codeplex.com/</a><br/> <a href="http://www.codeproject.com/KB/graphics/BarcodeLibrary.aspx" rel="noreferrer">http://www.codeproject.com/KB/graphics/BarcodeLibrary.aspx</a><br/></p>
7,326,601
Android - ImageView On Click
<p>Im trying to trace a click when my image view is clicked, but I cannot seem to pick up the touch, any ideas?</p> <pre><code>imgView.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { Log.v(TAG, " click"); } }); </code></pre>
7,326,806
3
0
null
2011-09-06 21:53:11.767 UTC
5
2020-01-06 16:00:46.557 UTC
null
null
null
null
931,561
null
1
19
android|touch
78,671
<p>Images normally aren't clickable, therefore I would suggest that you put the definition </p> <pre><code>android:clickable="true" android:focusable="true" </code></pre> <p>in your layout.xml to the imageView.</p> <p>If this is not helping, please edit+update your question and show us the part of your layout, where you define the image to have a look at it.</p> <p>EDIT: Tried it, and your code worked with me too - even with the upper case id name. Can you please have a close look at your LogCat? Mine sometimes doesn't really update, as long as I don't choose the device again.</p> <p>To do so in Eclipse, go to the View "Devices" (or show it first via "Window") and click once on your device / virtual device.</p> <p>If you still don't find your log entry in the LogCat-View, try to create a filter (via the green plus and giving it the String you defined with <code>TAG</code> as "by Log Tag").</p> <p>Have a look at <a href="http://developer.android.com/guide/developing/debugging/ddms.html#using-ddms" rel="noreferrer">android developers > Using DDMS</a> at the section "Using LogCat"</p>
7,657,457
Finding key from value in Python dictionary:
<p>Fairly new to Python, still struggling with so much information. </p> <p>All the documentation I've seen about dictionaries explain various ways of getting a value via a key - but I'm looking for a pythonic way to do the opposite - get a key via a value.</p> <p>I know I can loop through the keys and inspect their values until I find the value I'm looking for and then grab the key, but I'm looking for a direct route.</p>
7,657,712
4
0
null
2011-10-05 06:27:03.1 UTC
3
2017-12-05 14:37:14.84 UTC
2014-07-15 05:21:29.977 UTC
null
712,579
null
712,579
null
1
15
python|dictionary|key
45,071
<p>There is no direct route. It's pretty easy with list comprehensions, though;</p> <pre><code>[k for k, v in d.iteritems() if v == desired_value] </code></pre> <p>If you need to do this occasionally and don't think it's worth while indexing it the other way as well, you could do something like:</p> <pre><code>class bidict(dict): def key_with_value(self, value, default=None): for k, v in self.iteritems(): if v == value: return v return default def keys_with_value(self, value, default=None): return [v for k, v in self.iteritems() if v == value] </code></pre> <p>Then <code>d.key_with_value</code> would behave rather like <code>d.get</code>, except the other way round.</p> <p>You could also make a class which indexed it both ways automatically. Key and value would both need to be hashable, then. Here are three ways it could be implemented:</p> <ul> <li><p>In two separate dicts, with the exposing some dict-like methods; you could perhaps do <code>foo.by_key[key]</code> or <code>foo.by_value[value]</code>. (No code given as it's more complicated and I'm lazy and I think this is suboptimal anyway.)</p></li> <li><p>In a different structure, so that you could do <code>d[key]</code> and <code>d.inverse[value]</code>:</p> <pre><code>class bidict(dict): def __init__(self, *args, **kwargs): self.inverse = {} super(bidict, self).__init__(key, value) def __setitem__(self, key, value): super(bidict, self).__setitem__(key, value) self.inverse[value] = key def __delitem__(self, key): del self.inverse[self[key]] super(bidict, self).__delitem__(key) </code></pre></li> <li><p>In the same structure, so that you could do <code>d[key]</code> and <code>d[value]</code>:</p> <pre><code>class bidict(dict): def __setitem__(self, key, value): super(bidict, self).__setitem__(key, value) super(bidict, self).__setitem__(value, key) def __delitem__(self, key): super(bidict, self).__delitem__(self[key]) super(bidict, self).__delitem__(key) </code></pre></li> </ul> <p>(Notably absent from these implementations of a <code>bidict</code> is the <code>update</code> method which will be slightly more complex (but <code>help(dict.update)</code> will indicate what you'd need to cover). Without <code>update</code>, <code>bidict({1:2})</code> wouldn't do what it was intended to, nor would <code>d.update({1:2})</code>.)</p> <p>Also consider whether some other data structure would be more appropriate.</p>
7,330,834
How to check the state of a semaphore
<p>I want to check the state of a <code>Semaphore</code> to see if it is signalled or not (so if t is signalled, I can release it). How can I do this? </p> <p><strong>EDIT1:</strong></p> <p>I have two threads, one would wait on semaphore and the other should release a <code>Semaphore</code>. The problem is that the second thread may call <code>Release()</code> several times when the first thread is not waiting on it. So the second thread should detect that if it calls <code>Release()</code> it generate any error or not (it generate an error if you try to release a semaphore if nobody waiting on it). How can I do this? I know that I can use a flag to do this, but it is ugly. Is there any better way? </p>
7,334,538
4
2
null
2011-09-07 08:22:56.767 UTC
1
2017-08-30 08:50:48.82 UTC
2011-09-07 08:57:43.98 UTC
null
485,076
null
654,019
null
1
23
c#|.net|multithreading|semaphore
38,743
<p>You can check to see if a <code>Semaphore</code> is signaled by calling <code>WaitOne</code> and passing a timeout value of 0 as a parameter. This will cause <code>WaitOne</code> to return immediately with a true or false value indicating whether the semaphore was signaled. This, of course, could change the state of the semaphore which makes it cumbersome to use.</p> <p>Another reason why this trick will not help you is because a semaphore is said to be signaled when at least one count is available. It sounds like you want to know when the semaphore has all counts available. The <code>Semaphore</code> class does not have that exact ability. You can use the return value from <code>Release</code> to infer what the count is, but that causes the semaphore to change its state and, of course, it will still throw an exception if the semaphore already had all counts available prior to making the call.</p> <p>What we need is a semaphore with a release operation that does not throw. This is not terribly difficult. The <code>TryRelease</code> method below will return true if a count became available or false if the semaphore was already at the <code>maximumCount</code>. Either way it will never throw an exception.</p> <pre><code>public class Semaphore { private int count = 0; private int limit = 0; private object locker = new object(); public Semaphore(int initialCount, int maximumCount) { count = initialCount; limit = maximumCount; } public void Wait() { lock (locker) { while (count == 0) { Monitor.Wait(locker); } count--; } } public bool TryRelease() { lock (locker) { if (count &lt; limit) { count++; Monitor.PulseAll(locker); return true; } return false; } } } </code></pre>
24,068,576
How to receive json data using HTTP POST request in Django 1.6?
<p>I am learning <a href="https://www.djangoproject.com/">Django</a> 1.6.<br> I want to post some <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> using HTTP POST request and I am using Django for this task for learning.<br> I tried to use <code>request.POST['data']</code>, <code>request.raw_post_data</code>, <code>request.body</code> but none are working for me.<br> my views.py is </p> <pre><code>import json from django.http import StreamingHttpResponse def main_page(request): if request.method=='POST': received_json_data=json.loads(request.POST['data']) #received_json_data=json.loads(request.body) return StreamingHttpResponse('it was post request: '+str(received_json_data)) return StreamingHttpResponse('it was GET request') </code></pre> <p>I am posting JSON data using <a href="http://docs.python-requests.org/en/latest/">requests</a> module. </p> <pre><code>import requests import json url = "http://localhost:8000" data = {'data':[{'key1':'val1'}, {'key2':'val2'}]} headers = {'content-type': 'application/json'} r=requests.post(url, data=json.dumps(data), headers=headers) r.text </code></pre> <p><code>r.text</code> should print that message and posted data but I am not able to solve this simple problem. please tell me how to collect posted data in Django 1.6?</p>
24,119,878
3
1
null
2014-06-05 19:25:31.043 UTC
35
2021-08-22 11:32:08.747 UTC
null
null
null
null
1,762,051
null
1
79
python|django|django-views|http-post|python-requests
115,593
<p>You're confusing form-encoded and JSON data here. <code>request.POST['foo']</code> is for form-encoded data. You are posting raw JSON, so you should use <code>request.body</code>.</p> <pre><code>received_json_data=json.loads(request.body) </code></pre>
24,104,210
BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed
<p>I am getting this error while on of my <code>.Net</code> application are trying to make a connection to oracle database.</p> <p>The error says that <code>This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed.</code>. <a href="https://stackoverflow.com/questions/15498391/attempt-to-load-oracle-client-libraries-threw-badimageformatexception">But I have made sure</a> many times that the client installed in <code>x64</code> bit not <code>32</code>.</p> <pre><code>Date Time: 6/8/2014 10:57:55 AM: System.InvalidOperationException: Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed. ---&gt; System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Data.Common.UnsafeNativeMethods.OCILobCopy2(IntPtr svchp, IntPtr errhp, IntPtr dst_locp, IntPtr src_locp, UInt64 amount, UInt64 dst_offset, UInt64 src_offset) at System.Data.OracleClient.OCI.DetermineClientVersion() --- End of inner exception stack trace --- at System.Data.OracleClient.OCI.DetermineClientVersion() at System.Data.OracleClient.OracleInternalConnection.OpenOnLocalTransaction(String userName, String password, String serverName, Boolean integratedSecurity, Boolean unicode, Boolean omitOracleConnectionName) at System.Data.OracleClient.OracleInternalConnection..ctor(OracleConnectionString connectionOptions) at System.Data.OracleClient.OracleConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OracleClient.OracleConnection.Open() at CustomizedSetupInstaller.Runscripts.InitializeDBObjects(String connectionString, String dbProvider) </code></pre>
24,120,100
21
2
null
2014-06-08 08:10:27.377 UTC
33
2021-09-08 11:09:57.253 UTC
2017-05-23 12:18:27.56 UTC
null
-1
null
971,741
null
1
45
.net|oracle|oracle11g
267,578
<p>One solution is to install both x86 (32-bit) and x64 Oracle Clients on your machine, then it does not matter on which architecture your application is running.</p> <p>Here an instruction to install x86 and x64 Oracle client on one machine:</p> <p>Assumptions: <em>Oracle Home is called <code>OraClient11g_home1</code>, Client Version is 11gR2</em></p> <ul> <li><p>Optionally remove any installed Oracle client (see <a href="https://stackoverflow.com/questions/8450726/how-to-uninstall-completely-remove-oracle-11g-client">How to uninstall / completely remove Oracle 11g (client)?</a> if you face problems)</p> </li> <li><p>Download and install Oracle x86 Client, for example into <code>C:\Oracle\11.2\Client_x86</code></p> </li> <li><p>Download and install Oracle x64 Client <strong>into different folder</strong>, for example to <code>C:\Oracle\11.2\Client_x64</code></p> </li> <li><p>Open command line tool, go to folder <code>%WINDIR%\System32</code> (typically <code>C:\Windows\System32</code>) and create a symbolic link <code>ora112</code> to folder <code>C:\Oracle\11.2\Client_x64</code> (see commands section below)</p> </li> <li><p>Change to folder <code>%WINDIR%\SysWOW64</code> (typically <code>C:\Windows\SysWOW64</code>) and create a symbolic link <code>ora112</code> to folder <code>C:\Oracle\11.2\Client_x86</code>, (see below)</p> </li> <li><p>Modify the <code>PATH</code> environment variable, replace all entries like <code>C:\Oracle\11.2\Client_x86</code> and <code>C:\Oracle\11.2\Client_x64</code> by <code>C:\Windows\System32\ora112</code>, respective their <code>\bin</code> subfolder. Note: <code>C:\Windows\SysWOW64\ora112</code> must not be in PATH environment.</p> </li> <li><p>If needed set your <code>ORACLE_HOME</code> environment variable to <code>C:\Windows\System32\ora112</code></p> </li> <li><p>Open your Registry Editor. Set Registry value <code>HKLM\Software\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME</code> to <code>C:\Windows\System32\ora112</code></p> </li> <li><p>Set Registry value <code>HKLM\Software\Wow6432Node\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME</code> to <code>C:\Windows\System32\ora112</code> (not <code>C:\Windows\SysWOW64\ora112</code>)</p> </li> <li><p>You are done! Now you can use x86 and x64 Oracle client seamless together, i.e. an x86 application will load the x86 libraries, an x64 application loads the x64 libraries without any further modification on your system.</p> </li> <li><p>Probably it is a wise option to set your <code>TNS_ADMIN</code> environment variable (resp. <code>TNS_ADMIN</code> entries in Registry) to a common location, for example <code>TNS_ADMIN=C:\Oracle\Common\network</code>.</p> </li> </ul> <p>Commands to create symbolic links:</p> <pre><code>cd C:\Windows\System32 mklink /d ora112 C:\Oracle\11.2\Client_x64 cd C:\Windows\SysWOW64 mklink /d ora112 C:\Oracle\11.2\Client_x86 </code></pre> <p>Notes:</p> <p>Both symbolic links must have the same name, e.g. <code>ora112</code>.</p> <p>Despite of their names folder <code>C:\Windows\System32</code> contains the x64 libraries, whereas <code>C:\Windows\SysWOW64</code> contains the x86 (32-bit) libraries. Don't get confused.</p>
8,320,486
Structure for multiple JSF projects with shared code
<p>I have two JSF projects that share a lot of code - java classes, xhtml files, tag libraries, css and javascript files etc. My dev environment/platform consists mainly of Eclipse, Ant, Perforce and Tomcat.</p> <p>Has anyone found a way to create and organize the shared code so that the common code can stay within one set of folders?</p> <p>Eclipse makes it easy to add external folders for java sources, but falls short on the other file types. I'd appreciate any ideas.</p>
8,320,738
1
0
null
2011-11-30 02:38:34.823 UTC
36
2021-06-24 11:51:42.67 UTC
null
null
null
null
1,072,538
null
1
35
eclipse|jsf|structure|projects
22,938
<p>Create a new &quot;Java Project&quot; in Eclipse. Add it as another project to the <em>Deployment Assembly</em> property of the main dynamic web project. This way it will automatically end up as a JAR in <code>/WEB-INF/lib</code> of the build of the web project. Since newer Eclipse versions, you can also create the project as &quot;Web Fragment Project&quot;. This way the <em>Deployment Assembly</em> step will be done automatically.</p> <p>Put all those shared resource files in <code>/META-INF/resources</code> folder of the Java project. Just treat it like <code>WebContent/resources</code> of the main web project. Tagfiles can just be kept in their own <code>/META-INF/tags</code> folder.</p> <p>E.g.</p> <pre class="lang-none prettyprint-override"><code>CommonWebProject |-- META-INF | |-- resources | | `-- common | | |-- css | | | `-- some.css | | |-- js | | | `-- some.js | | |-- images | | | `-- some.png | | |-- components | | | `-- somecomposite.xhtml | | `-- sometemplate.xhtml | |-- tags | | `-- sometag.xhtml | |-- beans.xml | |-- faces-config.xml | |-- some.taglib.xml | |-- web-fragment.xml | `-- MANIFEST.MF : </code></pre> <p>with</p> <pre><code>&lt;h:outputStylesheet library=&quot;common&quot; name=&quot;css/some.css&quot; /&gt; &lt;h:outputScript library=&quot;common&quot; name=&quot;js/some.js&quot; /&gt; &lt;h:graphicImage library=&quot;common&quot; name=&quot;images/some.png&quot; /&gt; &lt;common:somecomposite /&gt; &lt;common:sometag /&gt; &lt;ui:include src=&quot;/common/sometemplate.xhtml&quot; /&gt; ... </code></pre> <p>In case you're using Maven, the <code>/META-INF</code> folder has to be placed in <code>src/main/resources</code> and thus NOT <code>src/main/java</code>!</p> <p>If you want to trigger the JSF annotation scanner as well so that you can put <code>@FacesValidator</code>, <code>@FacesConverter</code>, <code>@FacesComponent</code>, <code>@FacesRenderer</code> and consorts in that project as well, then create a <code>/META-INF/faces-config.xml</code> file as well. Below is a JSF 2.3 compatible one:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;faces-config xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd&quot; version=&quot;2.3&quot;&gt; &lt;!-- Put shared faces-config.xml config here. --&gt; &lt;/faces-config&gt; </code></pre> <p>The <code>/META-INF/web-fragment.xml</code> is mandatory for the JAR to be recognized by the servletcontainer as a &quot;Web Fragment Project&quot; and should already be generated by your IDE, but for sake of completeness here is how it should look like for a Servlet 4.0 compatible one:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;web-fragment xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-fragment_4_0.xsd&quot; version=&quot;4.0&quot;&gt; &lt;!-- Put shared web.xml config here. --&gt; &lt;/web-fragment&gt; </code></pre> <p>That's all.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/30046979/splitting-up-web-xml-in-hierarchical-parts/">Splitting up shared code and web.xml from WAR project to common JAR project</a></li> <li><a href="https://stackoverflow.com/questions/9290482/jsf-facelets-template-packaging/">JSF facelets template packaging</a></li> <li><a href="https://stackoverflow.com/questions/13292272/obtaining-uidecorate-template-file-from-an-external-filesystem-or-datab/">Obtaining Facelets templates/files from an external filesystem or database</a></li> </ul>
21,493,178
Need a datetime column in SQL Server that automatically updates when the record is modified
<p>I need to create a new <code>DATETIME</code> column in SQL Server that will always contain the date of when the record was created, and then it needs to automatically update whenever the record is modified. I've heard people say I need a trigger, which is fine, but I don't know how to write it. Could somebody help with the syntax for a trigger to accomplish this?</p> <p>In MySQL terms, it should do exactly the same as this MySQL statement:</p> <pre><code>ADD `modstamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP </code></pre> <p>Here are a few requirements:</p> <ul> <li>I can't alter my <code>UPDATE</code> statements to set the field when the row is modified, because I don't control the application logic that writes to the records.</li> <li>Ideally, I would not need to know the names of any other columns in the table (such as the primary key)</li> <li>It should be short and efficient, because it will happen very often.</li> </ul>
21,493,217
5
2
null
2014-02-01 01:53:46.903 UTC
11
2021-04-18 11:29:56.707 UTC
2021-04-18 11:29:21.057 UTC
null
13,302
null
260,516
null
1
37
sql-server|tsql|timestamp
91,365
<p>SQL Server doesn't have a way to define a default value for <code>UPDATE</code>.</p> <p>So you need to add a column with default value for inserting:</p> <pre><code>ADD modstamp DATETIME2 NULL DEFAULT GETDATE() </code></pre> <p>And add a trigger on that table:</p> <pre><code>CREATE TRIGGER tgr_modstamp ON **TABLENAME** AFTER UPDATE AS UPDATE **TABLENAME** SET ModStamp = GETDATE() WHERE **ID** IN (SELECT DISTINCT **ID** FROM Inserted) </code></pre> <p>And yes, you need to specify a identity column for each trigger.</p> <p>CAUTION: take care when inserting columns on tables where you don't know the code of the application. If your app have INSERT VALUES command without column definition, it will raise errors even with default value on new columns.</p>
2,294,588
Python : How to plot 3d graphs using Python?
<p>I am using matplotlib for doing this</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [6,3,6,9,12,24] y = [3,5,78,12,23,56] ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z') plt.show() </code></pre> <p>Now this builds a graph that is horizontal in the 3d space. How do I make the graph vertical so that it faces the user?</p> <p>What I want to do is build multiple such vertical graphs that are separated by some distance and are facing the user.</p>
2,294,994
4
2
null
2010-02-19 06:57:13.47 UTC
10
2012-09-08 12:48:51.657 UTC
2010-02-19 11:19:10.57 UTC
null
207,432
null
204,623
null
1
24
python|matplotlib
50,419
<p>bp's answer might work fine, but there's a much simpler way.</p> <p>Your current graph is 'flat' on the z-axis, which is why it's horizontal. You want it to be vertical, which means that you want it to be 'flat' on the y-axis. This involves the tiniest modification to your code:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [6,3,6,9,12,24] y = [3,5,78,12,23,56] # put 0s on the y-axis, and put the y axis on the z-axis ax.plot(xs=x, ys=[0]*len(x), zs=y, zdir='z', label='ys=0, zdir=z') plt.show() </code></pre> <p>Then you can easily have multiple such graphs by using different values for the ys parameter (for example, <code>ys=[2]*len(x)</code> instead would put the graph slightly behind).</p>
52,568,006
How do you unsplit terminals in VSCode?
<p>There is a button to split terminal, there is none to unsplit terminal ?</p>
52,796,484
7
4
null
2018-09-29 11:40:17.187 UTC
null
2022-03-29 08:33:46.113 UTC
null
null
null
null
310,291
null
1
33
visual-studio-code
10,162
<p>click on the sub-terminal (added terminal when you split main terminal) and then click on the trash icon. it will only kill that sub-terminal and leave the main terminal.</p>
26,349,491
How to hide web.config from directory browsing?
<p>I use IIS8 and I'm trying to hide web.config from the files list on my site but I just can't seem to find a solution for that. Can you help me please? :)</p>
26,394,141
2
2
null
2014-10-13 21:55:02.95 UTC
3
2016-12-09 23:52:55.673 UTC
null
null
null
null
4,125,274
null
1
28
iis
19,741
<p>Right click the file and mark it as hidden. It will stop showing up in IIS directory browsing.</p>
7,530,627
HCL color to RGB and backward
<p>I need an algorithm to convert the HCL color to RGB and backward RGB to HCL keeping in mind that these color spaces have different gamuts (I need to constrain the HCL colors to those that can be reproduced in RGB color space). What is the algorithm for this (the algorithm is intended to be implemented in <a href="http://www.wolfram.com/mathematica/" rel="noreferrer">Wolfram <em>Mathematica</em></a> that supports natively only RGB color)? I have no experience in working with color spaces.</p> <p>P.S. Some articles about HCL color:</p> <p><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.125.3833&amp;rep=rep1&amp;type=pdf" rel="noreferrer">M. Sarifuddin (2005). A new perceptually uniform color space with associated color similarity measure for content–based image and video retrieval.</a></p> <p><a href="http://epub.wu.ac.at/1692/1/document.pdf" rel="noreferrer">Zeileis, Hornik and Murrell (2009): Escaping RGBland: Selecting Colors for Statistical Graphics // Computational Statistics &amp; Data Analysis Volume 53, Issue 9, 1 July 2009, Pages 3259-3270</a></p> <p><strong>UPDATE:</strong> As pointed out by <a href="https://stackoverflow.com/users/439839/jonathan-jansson">Jonathan Jansson</a>, in the above two articles different color spaces are described by the name &quot;HCL&quot;: &quot;The second article uses L<em>C</em>h(uv) which is the same as L<em>u</em>v* but described in polar coordiates where h(uv) is the angle of the u* and v* coordinate and C* is the magnitude of that vector&quot;. So in fact I need an algorithm for converting RGB to L<em>u</em>v* and backward.</p>
7,561,257
6
4
null
2011-09-23 14:31:50.757 UTC
9
2022-02-07 17:01:02.303 UTC
2022-02-07 17:01:02.303 UTC
null
86,643
null
590,388
null
1
21
algorithm|colors|wolfram-mathematica|color-conversion
15,122
<p>I was just learing about the HCL colorspace too. The colorspace used in the two articles in your question seems to be different color spaces though.</p> <p>The second article uses L*C*h(uv) which is the same as L*u*v* but described in polar coordiates where h(uv) is the angle of the u* and v* coordiate and C* is the magnitude of that vector.</p> <p>The LCH color space in the first article seems to describe another color space than that uses a more algorithmical conversion. There is also another version of the first paper here: <a href="http://isjd.pdii.lipi.go.id/admin/jurnal/14209102121.pdf" rel="noreferrer">http://isjd.pdii.lipi.go.id/admin/jurnal/14209102121.pdf</a></p> <p>If you meant to use the CIE L*u*v* you need to first convert sRGB to CIE XYZ and then convert to CIE L*u*v*. RGB actually refers to sRGB in most cases so there is no need to convert from RGB to sRGB.</p> <p><a href="http://easyrgb.com/" rel="noreferrer">All source code needed</a></p> <p><a href="http://www.ryanjuckett.com/programming/graphics/27-rgb-color-space-conversion" rel="noreferrer">Good article about how conversion to XYZ works</a></p> <p><a href="http://davengrace.com/dave/cspace/" rel="noreferrer">Nice online converter</a></p> <p>But I can't answer your question about how to constrain the colors to the sRGB space. You could just throw away RGB colors which are outside the range 0 to 1 after conversion. Just clamping colors can give quite weird results. Try to go to the converter and enter the color RGB 0 0 255 and convert to L*a*b* (similar to L*u*v*) and then increase L* to say 70 and convert it back and the result is certainly not blue anymore.</p> <p>Edit: Corrected the URL Edit: Merged another answer into this answer</p>
7,426,085
jQuery - Getting form values for ajax POST
<p>I am trying to post form values via AJAX to a php file. How do I collect my form values to send inside of the "data" parameter?</p> <pre><code>$.ajax({ type: "POST", data: "submit=1&amp;username="+username+"&amp;email="+email+"&amp;password="+password+"&amp;passconf="+passconf, url: "http://rt.ja.com/includes/register.php", success: function(data) { //alert(data); $('#userError').html(data); $("#userError").html(userChar); $("#userError").html(userTaken); } }); </code></pre> <p>HTML:</p> <pre><code>&lt;div id="border"&gt; &lt;form action="/" id="registerSubmit"&gt; &lt;div id="userError"&gt;&lt;/div&gt; Username: &lt;input type="text" name="username" id="username" size="10"/&gt;&lt;br&gt; &lt;div id="emailError" &gt;&lt;/div&gt; Email: &lt;input type="text" name="email" size="10" id="email"/&gt;&lt;br&gt; &lt;div id="passError" &gt;&lt;/div&gt; Password: &lt;input type="password" name="password" size="10" id="password"/&gt;&lt;br&gt; &lt;div id="passConfError" &gt;&lt;/div&gt; Confirm Password: &lt;input type="password" name="passconf" size="10" id="passconf"/&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Register" /&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
7,426,130
6
2
null
2011-09-15 05:03:37.263 UTC
12
2016-09-18 03:46:35.403 UTC
2016-09-18 03:46:35.403 UTC
null
212,378
null
547,794
null
1
78
jquery|ajax
258,364
<p>Use the serialize method:</p> <pre><code>$.ajax({ ... data: $("#registerSubmit").serialize(), ... }) </code></pre> <p>Docs: <a href="https://api.jquery.com/serialize/">serialize()</a></p>
7,361,253
How to determine whether a substring is in a different string
<p>I have a sub-string:</p> <pre><code>substring = "please help me out" </code></pre> <p>I have another string:</p> <pre><code>string = "please help me out so that I could solve this" </code></pre> <p>How do I find if <code>substring</code> is a subset of <code>string</code> using Python?</p>
7,361,274
10
0
null
2011-09-09 11:55:39.593 UTC
17
2022-03-27 14:52:29.2 UTC
2016-09-09 00:50:35.157 UTC
null
128,421
null
936,208
null
1
113
python|string
214,755
<p>with <code>in</code>: <code>substring in string</code>:</p> <pre><code>&gt;&gt;&gt; substring = "please help me out" &gt;&gt;&gt; string = "please help me out so that I could solve this" &gt;&gt;&gt; substring in string True </code></pre>
14,231,292
CMake and compiler warnings
<p>I use <code>CMake</code> to generate unix makefiles. After that I compile project using <code>make</code> utility. Problem is that I can't see any warnings! For example, this results in clean build without warnings:</p> <pre><code>#include &lt;iostream&gt; class Foo { int first; int second; public: Foo(int a, int b) : second(a) // invalid initialization order , first(b) { } }; int main(int argc, char** argv) { int unused; // unused variable int x; double y = 3.14159; x = y; // invalid cast Foo foo(1,2); std::cout &lt;&lt; y &lt;&lt; std::endl; return 0; } </code></pre> <p>Unused variable and lossy variable cast - no warnings! My <code>CMakeLists.txt</code> file is minimalistic:</p> <pre><code>cmake_minimum_required(VERSION 2.8) add_executable(main main.cpp) </code></pre> <p>When I run <code>cmake</code> and then <code>make</code> my output looks like this:</p> <pre><code>[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o Linking CXX executable main [100%] Built target main </code></pre> <p>But when I add this line of code:</p> <pre><code>#warning ("Custom warning") </code></pre> <p>resulting output contains warning:</p> <pre><code>[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o ../src/main.cpp:15:2: warning: #warning ("Custom Warning") [-Wcpp] Linking CXX executable main [100%] Built target main </code></pre> <p>I use Ubuntu 12.04 LTS and GCC as a compiler. Maybe CMake passes some flag to compiler that results in absence of warnings. How can I check it? I can't read makefiles generated by CMake, they are a little bit cryptic.</p>
14,235,055
2
1
null
2013-01-09 08:46:41.227 UTC
5
2021-10-25 08:32:47.487 UTC
2013-01-09 11:19:34.083 UTC
null
42,371
null
42,371
null
1
28
gcc|cmake
64,823
<p>The positions on compiler warnings are divided. There are package maintainers who will tell you that they know what they are doing, and compiler warnings should be ignored in any case. (I think they couldn't be more wrong.) But I guess that is why CMake mostly leaves the warning settings alone.</p> <p>If you want to be a bit more sophisticated about it, check for the compiler being used, and add the flag to the specific property of the specific target.</p> <h2>Apply to a Single Target</h2> <pre><code>if ( CMAKE_COMPILER_IS_GNUCC ) target_compile_options(main PRIVATE -Wall -Wextra) endif() if ( MSVC ) target_compile_options(main PRIVATE /W4) endif() </code></pre> <h2>Apply to All Targets</h2> <pre><code>if ( CMAKE_COMPILER_IS_GNUCC ) set(CMAKE_CXX_FLAGS &quot;${CMAKE_CXX_FLAGS} -Wall -Wextra&quot;) endif() if ( MSVC ) set(CMAKE_CXX_FLAGS &quot;${CMAKE_CXX_FLAGS} /W4&quot;) endif() </code></pre> <p>Note: add <code>-Werror</code> for GCC or <code>/WX</code> for MSVC to treat all warnings as errors. This will treat all warnings as errors. This can be handy for new projects to enforce warning strictness.</p> <p>Also, <code>-Wall -Wextra</code> does not mean &quot;all errors&quot;; historically <code>-Wall</code> meant &quot;all errors <em>that everybody could agree on</em>&quot;, and <code>-Wextra</code> &quot;some more&quot;. Start with that, then peruse the manual for <em>your</em> version of GCC, and find what <em>else</em> the compiler can do for you with regards to warnings...</p>
13,852,444
How to add call back for $resource methods in AngularJS
<p>It could be a common case that we need to show an error/success message to the user after he updates/creates some data, how can we implement it in AngularJS?<br> I want to add callbacks but could not find a solution. Using $http.post().success().error() works, but I wonder if I can do it with the higher lever API $resource.<br> Or, we should write directives or use $watch()?<br> Thanks for your help in advance.</p>
13,853,125
2
0
null
2012-12-13 03:25:20.18 UTC
6
2019-05-17 14:20:42.753 UTC
null
null
null
null
1,890,956
null
1
30
resources|callback|angularjs
49,056
<p>Actions from the <strong>Resource</strong> class can be passed success and error callbacks just like the lower level <strong>$http</strong> service</p> <p><a href="https://docs.angularjs.org/api/ngResource/service/$resource" rel="nofollow noreferrer">From the docs</a></p> <ul> <li>HTTP GET "class" actions: Resource.action([parameters], [success], [error])</li> <li>non-GET "class" actions: Resource.action([parameters], postData, [success], [error])</li> </ul> <p>Non-get actions are prefixed with <code>$</code>.</p> <p>So you can do this</p> <pre><code>User.get({userId:123}, function(u, getResponseHeaders){ // this is get's success callback u.abc = true; u.$save(function(u, putResponseHeaders) { // This is $save's success callback, invoke notification from here }); }); </code></pre> <hr> <p>Edit: here's <a href="http://plnkr.co/edit/gV2zwc2kKAXXESe9HME4?p=preview" rel="nofollow noreferrer">another example from a previous plunker</a>. The get request will fail since it request a non existing json file. The error callback will be run.</p> <pre><code>someResource.get(function(data){ console.log('success, got data: ', data); }, function(err){ alert('request failed'); }); </code></pre>
14,124,913
Measure Android app startup time
<p>What is the most precise way to measure startup time of an Android app?</p> <p>By startup time I mean the difference between 2. and 3. :</p> <ol> <li>The app process is not running</li> <li>User clicks on app icon in the launcher</li> <li>Main Activity is fully initialized</li> </ol> <p>So I basically need to somehow get time elapsed since JVM started and log it.</p>
42,714,441
9
2
null
2013-01-02 15:48:43.947 UTC
10
2020-12-07 11:38:42.09 UTC
null
null
null
null
243,225
null
1
31
android
21,921
<p>I understand I am too late to answer, nonetheless, this precisely answers the question.</p> <p>This information gets logged on Logcat by default for API version 19 or higher.</p> <blockquote> <p>From Android 4.4 (API level 19), logcat includes an output line containing a value called Displayed. This value represents the amount of time elapsed between launching the process and finishing drawing the corresponding activity on the screen.</p> <p>ActivityManager: Displayed com.android.myexample/.StartupTiming: +3s534ms</p> </blockquote> <p>The key is <em>looking for it in the right place</em> -</p> <blockquote> <p>If you’re tracking logcat output from the command line, or in a terminal, finding the elapsed time is straightforward. To find elapsed time in Android Studio, you must disable filters in your logcat view. Disabling the filters is necessary because the system server, not the app itself, serves this log.</p> </blockquote> <p>The extracts are from the <a href="https://developer.android.com/topic/performance/launch-time.html#time-initial" rel="noreferrer">documentation</a>.</p>
14,113,057
How to have a drop down <select> field in a rails form?
<p>I am creating a scaffold -</p> <pre><code>rails g scaffold Contact email:string email_provider:string </code></pre> <p>but I want the email provider to be a drop down (with gmail/yahoo/msn as options) and not a text field. How can I do this ? </p>
14,113,150
8
0
null
2013-01-01 18:27:49.35 UTC
33
2019-06-09 20:44:50.827 UTC
2015-07-06 17:17:18.533 UTC
null
444,991
null
692,622
null
1
84
ruby-on-rails|ruby-on-rails-3|drop-down-menu|input|selectlist
202,544
<p>You can take a look at <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select">the Rails documentation</a> . Anyways , in your form :</p> <pre><code> &lt;%= f.collection_select :provider_id, Provider.order(:name),:id,:name, include_blank: true %&gt; </code></pre> <p>As you can guess , you should predefine email-providers in another model -<code>Provider</code> , to have where to select them from . </p>
13,944,956
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
<p>When I attempt to connect to a MySQL server from PHP, I see the following error:</p> <blockquote> <p>Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /path/to/filename.php on line 123</p> </blockquote> <p>The code on the referenced line is:</p> <pre><code>mysql_connect($server, $username, $password); </code></pre> <p>I am certain that the arguments are correct, and this exact code has been working for years without problem. Indeed, I obtained it from a well-sourced tutorial on PHP.</p> <ol> <li><p>Why is this happening?</p></li> <li><p>How can I fix it?</p></li> <li><p>I understand that it's possible to suppress deprecation errors by setting <code>error_reporting</code> in <code>php.ini</code> to exclude <code>E_DEPRECATED</code>:</p> <pre><code>error_reporting = E_ALL ^ E_DEPRECATED </code></pre> <p>What will happen if I do that?</p></li> </ol>
13,944,958
1
5
null
2012-12-19 03:11:43.407 UTC
35
2016-06-17 08:46:29.683 UTC
null
null
null
null
623,041
null
1
171
mysql|deprecated|php
393,279
<ol> <li><blockquote> <p>Why is this happening?</p> </blockquote> <p>The entire <code>ext/mysql</code> PHP extension, which provides all functions named with the prefix <code>mysql_</code>, was <a href="http://php.net/manual/en/changelog.mysql.php" rel="noreferrer">officially deprecated in PHP v5.5.0</a> and <a href="https://secure.php.net/manual/en/migration70.removed-exts-sapis.php" rel="noreferrer">removed in PHP v7</a>.</p> <p>It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.</p> <p>The manual has contained warnings against its use in new code since June 2011.</p></li> <li><blockquote> <p>How can I fix it?</p> </blockquote> <p>As the error message suggests, there are two other MySQL extensions that you can consider: <a href="http://php.net/manual/en/book.mysqli.php" rel="noreferrer">MySQLi</a> and <a href="http://php.net/manual/en/ref.pdo-mysql.php" rel="noreferrer">PDO_MySQL</a>, either of which can be used instead of <code>ext/mysql</code>. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away&mdash;i.e. without any installation effort.</p> <p>They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing <a href="https://stackoverflow.com/a/60496">the best way</a> to defeat <a href="https://stackoverflow.com/q/332365">SQL injection attacks</a>). PHP developer Ulf Wendel has written <a href="http://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/" rel="noreferrer">a thorough comparison of the features</a>.</p> <p>Hashphp.org has an <a href="http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers" rel="noreferrer">excellent tutorial on migrating from <code>ext/mysql</code> to PDO</a>.</p></li> <li><blockquote> <p>I understand that it's possible to suppress deprecation errors by setting <code>error_reporting</code> in <code>php.ini</code> to exclude <code>E_DEPRECATED</code>:</p> <pre><code>error_reporting = E_ALL ^ E_DEPRECATED </code></pre> <p>What will happen if I do that?</p> </blockquote> <p>Yes, it is possible to suppress such error messages and continue using the old <code>ext/mysql</code> extension for the time being. But <strong>you really shouldn't do this</strong>&mdash;this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application <em>now</em>, before it's too late.</p> <p>Note also that this technique will suppress <em>all</em> <code>E_DEPRECATED</code> messages, not just those to do with the <code>ext/mysql</code> extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's <a href="http://php.net/manual/en/language.operators.errorcontrol.php" rel="noreferrer">error control operator</a>&mdash;i.e. prepending the relevant line with <code>@</code>&mdash;however this will suppress <em>all</em> errors raised by that expression, not just <code>E_DEPRECATED</code> ones.</p></li> </ol> <hr> <h3>What should you do?</h3> <ul> <li><p><strong>You are starting a new project.</strong></p> <p>There is <em>absolutely no reason</em> to use <code>ext/mysql</code>&mdash;choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.</p></li> <li><p><strong>You have (your own) legacy codebase that currently depends upon <code>ext/mysql</code>.</strong></p> <p>It would be wise to perform regression testing: you really shouldn't be changing <em>anything</em> (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.</p> <ul> <li><p><strong>Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.</strong></p> <p>Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.</p></li> <li><p><strong>The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.</strong></p> <p>Consider whether you really need to upgrade to PHP v5.5 at this time.</p> <p>You should begin planning to replace <code>ext/mysql</code> with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.</p> <p>However, if you have an <em>urgent</em> need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.</p></li> </ul></li> <li><p><strong>You are using a third party project that depends upon <code>ext/mysql</code>.</strong></p> <p>Consider whether you really need to upgrade to PHP v5.5 at this time.</p> <p>Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an <em>urgent</em> need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.</p> <p>It is absolutely essential to perform regression testing.</p></li> </ul>
47,236,769
Failed to load optimized model - GoogleMaps SDK IOS
<p>I am getting this error after installing Google Maps SDK from CocoaPods.</p> <pre><code>CoreData: annotation: Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo' CoreData: annotation: Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo' CoreData: annotation: Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo' </code></pre> <p>I have tried pod update and pod install again but same issue.</p>
47,308,301
5
3
null
2017-11-11 10:14:13.803 UTC
5
2019-01-28 08:54:32.157 UTC
2018-05-25 12:17:26.083 UTC
null
3,515,033
null
894,846
null
1
30
ios|google-maps|sdk|swift4|xcode9.1
19,624
<p>If you have already double-checked the basic setup for the "google maps ios-sdk" with an APIkey for your app's bundle identifier <a href="https://developers.google.com/maps/documentation/ios-sdk/start" rel="noreferrer">here</a> and still have the same problem then probably you have not enabled the google maps API. Go to your app-project's dashboard on <a href="https://console.developers.google.com" rel="noreferrer">https://console.developers.google.com</a> and click the "ENABLE APIS AND SERVICES". There, under the MAPS section select "the Google maps sdk for ios" and enable it. </p>
43,859,750
How to connect broken lines in a binary image using Python/Opencv
<p>How can I make these lines connect at the target points? The image is a result of a skeletonization process.</p> <p><img src="https://i.stack.imgur.com/Jpu2c.jpg" alt="Resulting Image From Skeletonization"></p> <p><img src="https://i.stack.imgur.com/2iSVu.jpg" alt="Points That I Need To Connect"></p> <p>I'm trying to segment each line as a region using Watershed Transform.</p>
43,863,448
3
1
null
2017-05-09 01:48:32.773 UTC
12
2020-01-20 08:51:59.783 UTC
2018-07-01 08:00:06.153 UTC
null
1,714,410
null
7,982,530
null
1
17
python|opencv|image-processing|image-segmentation|edge-detection
22,237
<p><a href="https://stackoverflow.com/a/43862917/1714410">MikeE</a>'s answer is quite good: using dilation and erosion morphological operations can help a lot in this context.<br> I want to suggest a little improvement, taking advantage of the specific structure of the image at hand. Instead of using dilation/erosion with a general kernel, I suggest using a <strong>horizontal kernel</strong> that will connect the endpoints of the horizontal lines, but will not connect adjacent lines to one another.</p> <p>Here's a sketch of code (assuming the input image is stored in <code>bw</code> numpy 2D array):</p> <pre><code>import cv2, numpy as np kernel = np.ones((1,20), np.uint8) # note this is a horizontal kernel d_im = cv2.dilate(bw, kernel, iterations=1) e_im = cv2.erode(d_im, kernel, iterations=1) </code></pre> <p>What you get is the dilated image:<br> <a href="https://i.stack.imgur.com/KRdy4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KRdy4.png" alt="enter image description here"></a></p> <p>Note how the gaps are closed, while maintaining the distinct horizontal lines</p> <p>And the eroded image:<br> <a href="https://i.stack.imgur.com/UmUne.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UmUne.png" alt="enter image description here"></a></p> <p>To remove artifacts created by dilate/erode, I suggest to extract the skeleton again.<br> If you further apply skeleton morphological operation to the eroded image you can get this result:<br> <a href="https://i.stack.imgur.com/RpyAc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RpyAc.png" alt="enter image description here"></a></p> <p>Once you have the curves connected you do not need to use watershed segmentation, but rather use connected components to label each curve.</p>
29,880,083
PostgreSQL UUID type performance
<p>I'm not trying to restart the UUID vs serial integer key debate. I know there are valid points to either side. I'm using UUID's as the primary key in several of my tables.</p> <ul> <li>Column type: <code>"uuidKey" text NOT NULL</code></li> <li>Index: <code>CREATE UNIQUE INDEX grand_pkey ON grand USING btree ("uuidKey")</code> </li> <li>Primary Key Constraint: <code>ADD CONSTRAINT grand_pkey PRIMARY KEY ("uuidKey");</code></li> </ul> <p>Here is my first question; with PostgreSQL 9.4 is there any performance benefit to setting the column type to UUID?</p> <p>The documentation <a href="http://www.postgresql.org/docs/9.4/static/datatype-uuid.html" rel="noreferrer">http://www.postgresql.org/docs/9.4/static/datatype-uuid.html</a> describes UUID's, but is there any benefit aside from type safety for using this type instead of <code>text</code> type? In the character types documentation it indicates that <code>char(n)</code> would not have any advantage over <code>text</code> in PostgreSQL. </p> <blockquote> <p>Tip: There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.</p> </blockquote> <p>I'm not worried about disk space, I'm just wondering if it's worth my time benchmarking UUID vs text column types?</p> <p>Second question, hash vs b-tree indexes. No sense in sorting UUID keys so would b-tree have any other advantages over hash index?</p>
56,453,329
2
5
null
2015-04-26 16:10:38.747 UTC
8
2019-06-05 01:47:18.483 UTC
null
null
null
null
1,098,059
null
1
41
postgresql|indexing|hash|uuid
24,432
<p>We had a table with about 30k rows that (for a specific unrelated architectural reason) had UUIDs stored in a text field and indexed. I noticed that the query perf was slower than I'd have expected. I created a new UUID column, copied in the text uuid primary key and compared below. 2.652ms vs 0.029ms. Quite a difference! </p> <pre><code> -- With text index QUERY PLAN Index Scan using tmptable_pkey on tmptable (cost=0.41..1024.34 rows=1 width=1797) (actual time=0.183..2.632 rows=1 loops=1) Index Cond: (primarykey = '755ad490-9a34-4c9f-8027-45fa37632b04'::text) Planning time: 0.121 ms Execution time: 2.652 ms -- With a uuid index QUERY PLAN Index Scan using idx_tmptable on tmptable (cost=0.29..2.51 rows=1 width=1797) (actual time=0.012..0.013 rows=1 loops=1) Index Cond: (uuidkey = '755ad490-9a34-4c9f-8027-45fa37632b04'::uuid) Planning time: 0.109 ms Execution time: 0.029 ms </code></pre>
44,691,829
Pytesseract foreign language extraction using python
<p>I am using Python 2.7, Pytesseract-0.1.7 and Tesseract-ocr 3.05.01 on a Windows machine. </p> <p>I tried to extract text for Korean and Russian languages, and I am positive that I extracted. </p> <p>And now I need to compare with the string and string got extracted from the image. </p> <p>I can't compare the strings and to get the correct result, it just says not match.</p> <p>Here is my code :</p> <pre><code># -*- coding: utf-8 -*- from PIL import Image import pytesseract import argparse ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", required=True, help="path to the image") args = vars(ap.parse_args()) img = Image.open(args["input"]) img.load() text = pytesseract.image_to_string(img) print(text) text = text.encode('ascii') print(text) i = 'Сред. Скорость' print i if ( text == i): print "Match" else : print "Not Match" </code></pre> <p>The image used to extract text is attached.</p> <p>Now I need a way to match it. And also I need to know the string extracted from pytesseract will be in Unicode or what? and if there is way to convert it into Unicode (like we have option in wordpad for converting character into Unicode)</p> <p><a href="https://i.stack.imgur.com/T9esw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T9esw.png" alt="Russian text image"></a></p>
44,693,503
1
3
null
2017-06-22 06:34:19.87 UTC
9
2018-05-21 08:20:08.937 UTC
2017-06-22 08:22:34.133 UTC
null
2,128,166
null
8,197,840
null
1
11
python|unicode|ocr
33,907
<p>You are using Tesseract with a language other than English, so first of all, make sure, that you have learning dataset for your language installed, as it is shown <a href="https://askubuntu.com/questions/793634/how-do-i-install-a-new-language-pack-for-tesseract-on-16-04">here</a> (linux instructions only).</p> <p>Secondly, I strongly suggest you to switch to Python 3 if you are working with non ascii langugages (as I do, as a slovenian). Python 3 works with Unicode out of the box, so it really saves you tons of pain with encoding and decoding strings...</p> <pre><code># python3 obligatory !!! from PIL import Image import pytesseract img = Image.open("T9esw.png") img.load() text = pytesseract.image_to_string(img, lang="rus") #Specify language to look after! print(text) i = 'Сред. Скорость' print(i) if (text == i): print("Match") else : print("Not Match") </code></pre> <p>Which outputs:</p> <pre><code>Фред скорасть Сред. Скорость Not Match </code></pre> <p>This means the words didn't quite match, but still, considering the minimal coding effort and awful quality of input image, it think that the performance is quite amazing. Anyways, the example shows that encoding and decoding should no longer be a problem.</p>
19,422,214
How can I inspect disappearing element in a browser?
<p><strong>How can I inspect an element which disappears when my mouse moves away?</strong> <img src="https://i.stack.imgur.com/FVOVx.png" alt="Example dropdown which disappears"></p> <p>I don't know it's ID, class or anything but want to inspect it.</p> <p><strong>Solutions I have tried:</strong></p> <p>Run jQuery selector inside console <code>$('*:contains("some text")')</code> but didn't have any luck mainly because the element is not hidden but probably removed from the DOM tree.</p> <p>Manually inspecting DOM tree for changes gives me nothing as it seems to be just too fast to notice what have changed.</p> <p><strong>SUCCESS:</strong></p> <p>I have been successful with Event breakpoints. Specifically - mousedown in my case. Just go to <code>Sources-&gt; Event Listener Breakpoints-&gt; Mouse-&gt; mousedown</code> in Chrome. After that I clicked the element I wanted to inspect and inside <code>Scope Variables</code> I saw some useful directions.</p>
34,095,731
12
2
null
2013-10-17 08:57:42.483 UTC
72
2022-07-31 07:54:40.693 UTC
2013-10-17 09:56:54.57 UTC
null
649,632
null
649,632
null
1
237
javascript|google-chrome|firefox|firebug|opera-dragonfly
125,626
<p><s>(This answer only applies to Chrome Developer Tools.</s> See update below.)</p> <p>Find an element that contains the disappearing element. Right click on the element and apply &quot;Break on... &gt; Subtree Modifications.&quot; This will throw a debugger pause before the element disappears, which will allow you to interact with the element in a paused state.</p> <p><a href="https://i.stack.imgur.com/8OiFt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8OiFt.png" alt="enter image description here" /></a></p> <p><strong>Update Oct 22 2019:</strong> with the release of v. 70, it looks like FireFox finally supports this kind of debugging <a href="https://hacks.mozilla.org/2019/10/firefox-70-a-bountiful-release-for-all/" rel="noreferrer">2</a> <a href="https://wiki.developer.mozilla.org/en-US/docs/Tools/Debugger/Break_on_DOM_mutation" rel="noreferrer">3</a>:</p> <p><a href="https://i.stack.imgur.com/U4ll1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U4ll1.png" alt="enter image description here" /></a></p> <p><strong>Update Sep 15 2020:</strong> Chrome has an &quot;Emulate a focused page&quot; option (you can get it from the [⌘]+[P] Command Menu, or Global Preferences) for this exact need. <a href="https://twitter.com/sulco/status/1305841873945272321" rel="noreferrer">5 - h/t @sulco on Twitter</a></p>
45,217,642
Mouse wheel events in Reactjs
<p>How do you go about getting mouse wheel events in reactjs?</p> <p>I have tried onWheel</p> <pre><code> render: function() { return &lt;div onWheel = {this.wheel} &gt; &lt; /div&gt;; }, </code></pre> <p>and I have tried onScroll</p> <pre><code> render: function() { return &lt;div onScroll = {this.wheel} &gt; &lt; /div&gt;; }, </code></pre> <p>But neither of these events are picked up. See the fiddle below :</p> <p><a href="https://jsfiddle.net/812jnppf/2/" rel="noreferrer">https://jsfiddle.net/812jnppf/2/</a></p>
45,219,306
2
1
null
2017-07-20 14:28:24.897 UTC
3
2017-07-20 15:37:26.637 UTC
null
null
null
null
1,022,330
null
1
18
reactjs
50,379
<p>First, your div is 0 height, so you don't scroll on it. You don't have to bind this as it is a class (and not an es6 react component). Just do a call to the function with the event as parameter on onWheel event:</p> <p><a href="https://jsfiddle.net/812jnppf/9/" rel="noreferrer">https://jsfiddle.net/812jnppf/9/</a></p> <pre><code>render: function() { return &lt;div style={{height:300, width:300}} onWheel = {(e) =&gt; this.wheel(e)} &gt; &lt; /div&gt;; }, </code></pre> <p>Of course, you have to clean code to style your div with a var or in css.</p> <p>EDIT : I set it onWheel and not on onScroll (witch doesn't exist I guess ? confirm it if you know). I saw a SO post about adding scroll event to your component easilly : <a href="https://stackoverflow.com/a/29726000/4099279">https://stackoverflow.com/a/29726000/4099279</a></p>
45,235,992
What are levels in a pandas DataFrame?
<p>I've been reading through the documentation and many explanations and examples use <code>levels</code> as something taken for granted. Imho the docs lack a bit on a fundamental explanation of the data structure and definitions. </p> <p>What are levels in a data frame? What are levels in a <code>MultiIndex</code> index? </p>
50,110,162
2
2
null
2017-07-21 11:01:02.633 UTC
11
2019-11-01 11:23:55.153 UTC
2017-07-21 12:36:37.807 UTC
null
1,812,322
null
5,069,105
null
1
30
python|pandas|dataframe|multi-index
27,803
<p>I stumbled across this question while analyzing the answer to <a href="https://stackoverflow.com/a/50109058/672018">my own question</a>, but I didn't find the John's answer satisfying enough. After a few experiments though I think I understood the levels and decided to share:</p> <p><strong>Short answer:</strong></p> <p>Levels are parts of the index or column.</p> <p><strong>Long answer:</strong></p> <p>I think this multi-column <code>DataFrame.groupby</code> example illustrates the index levels quite nicely.</p> <p>Let's say we have the time logged on issues report data:</p> <pre><code>report = pd.DataFrame([ [1, 10, 'John'], [1, 20, 'John'], [1, 30, 'Tom'], [1, 10, 'Bob'], [2, 25, 'John'], [2, 15, 'Bob']], columns = ['IssueKey','TimeSpent','User']) IssueKey TimeSpent User 0 1 10 John 1 1 20 John 2 1 30 Tom 3 1 10 Bob 4 2 25 John 5 2 15 Bob </code></pre> <p>The index here has only 1 level (there is only one index value identifying every row). The index is artificial (running number) and consists of values form 0 to 5.</p> <p>Say we want to merge (sum) all logs created by <strong>the same user</strong> to <strong>the same issue</strong> (to get the total time spent on the issue by the user)</p> <pre><code>time_logged_by_user = report.groupby(['IssueKey', 'User']).TimeSpent.sum() IssueKey User 1 Bob 10 John 30 Tom 30 2 Bob 15 John 25 </code></pre> <p>Now our data index has 2 levels, as multiple users logged time to the same issue. The levels are <code>IssueKey</code> and <code>User</code>. The levels are parts of the index (only together they can identify a row in a DataFrame / Series).</p> <p>Levels being parts of the index (as a tuple) can be nicely observed in the Spyder Variable explorer:</p> <p><a href="https://i.stack.imgur.com/sp7VC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sp7VC.png" alt="enter image description here"></a></p> <p>Having levels gives us opportunity to aggregate values within groups in respect to an index part (<strong>level</strong>) of our choice. E.g. if we want to assign the max time spent on an issue by any user, we can:</p> <pre><code>max_time_logged_to_an_issue = time_logged_by_user.groupby(level='IssueKey').transform('max') IssueKey User 1 Bob 30 John 30 Tom 30 2 Bob 25 John 25 </code></pre> <p>Now the first 3 rows have the value <code>30</code>, as they correspond to the issue <code>1</code> (<code>User</code> level was ignored in the code above). The same story for the issue <code>2</code>.</p> <p>This can be useful e.g. if we want to find out which users spent most time on every issue:</p> <pre><code>issue_owners = time_logged_by_user[time_logged_by_user == max_time_logged_to_an_issue] IssueKey User 1 John 30 Tom 30 2 John 25 </code></pre>
1,136,416
How does the Levenberg–Marquardt algorithm work in detail but in an understandable way?
<p>Im a programmer that wants to learn how the Levenberg–Marquardt curvefitting algorithm works so that i can implement it myself. Is there a good tutorial anywhere that can explain how it works in detail with the reader beeing a programmer and not a mathemagician.</p> <p>My goal is to implement this algorithm in opencl so that i can have it run hardware accelerated.</p>
1,136,481
5
2
null
2009-07-16 09:25:08.603 UTC
14
2019-07-08 19:08:13.267 UTC
null
null
null
null
85,148
null
1
15
c|algorithm|opencl|curve-fitting
25,227
<ul> <li>Try <a href="http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Levenberg–Marquardt_algorithm</a></li> <li><a href="http://ananth.in/docs/lmtut.pdf" rel="noreferrer">PDF Tutorial</a> from Ananth Ranganathan</li> <li><a href="http://scribblethink.org/Computer/Javanumeric/index.html" rel="noreferrer">JavaNumerics</a> has a pretty readable implementation</li> <li>The ICS has a <a href="http://www.ics.forth.gr/~lourakis/levmar/" rel="noreferrer">C/C++</a> implementation</li> </ul>
669,764
How to Consume WCF Service with Android
<p>I am creating a server in .NET and a client application for Android. I would like to implement an authentication method which sends username and password to server and a server sends back a session string.</p> <p>I'm not familiar with WCF so I would really appreciate your help.</p> <p>In java I've written the following method:</p> <pre><code>private void Login() { HttpClient httpClient = new DefaultHttpClient(); try { String url = "http://192.168.1.5:8000/Login?username=test&amp;password=test"; HttpGet method = new HttpGet( new URI(url) ); HttpResponse response = httpClient.execute(method); if ( response != null ) { Log.i( "login", "received " + getResponse(response.getEntity()) ); } else { Log.i( "login", "got a null response" ); } } catch (IOException e) { Log.e( "error", e.getMessage() ); } catch (URISyntaxException e) { Log.e( "error", e.getMessage() ); } } private String getResponse( HttpEntity entity ) { String response = ""; try { int length = ( int ) entity.getContentLength(); StringBuffer sb = new StringBuffer( length ); InputStreamReader isr = new InputStreamReader( entity.getContent(), "UTF-8" ); char buff[] = new char[length]; int cnt; while ( ( cnt = isr.read( buff, 0, length - 1 ) ) &gt; 0 ) { sb.append( buff, 0, cnt ); } response = sb.toString(); isr.close(); } catch ( IOException ioe ) { ioe.printStackTrace(); } return response; } </code></pre> <p>But on the server side so far I haven't figured out anything.</p> <p>I would be really thankful if anyone could explain how to create an appropriate method string Login(string username, string password) with appropriate App.config settings and Interface with appropriate [OperationContract] signature in order to read these two parameters from client and reply with session string.</p> <p>Thanks!</p>
675,920
5
1
null
2009-03-21 18:48:26.95 UTC
59
2015-02-25 11:05:11.38 UTC
null
null
null
niko
22,996
null
1
79
.net|android|wcf|rest
103,515
<p>To get started with WCF, it might be easiest to just use the default SOAP format and HTTP POST (rather than GET) for the web-service bindings. The easiest HTTP binding to get working is "basicHttpBinding". Here is an example of what the ServiceContract/OperationContract might look like for your login service:</p> <pre><code>[ServiceContract(Namespace="http://mycompany.com/LoginService")] public interface ILoginService { [OperationContract] string Login(string username, string password); } </code></pre> <p>The implementation of the service could look like this:</p> <pre><code>public class LoginService : ILoginService { public string Login(string username, string password) { // Do something with username, password to get/create sessionId // string sessionId = "12345678"; string sessionId = OperationContext.Current.SessionId; return sessionId; } } </code></pre> <p>You can host this as a windows service using a ServiceHost, or you can host it in IIS like a normal ASP.NET web (service) application. There are a lot of tutorials out there for both of these.</p> <p>The WCF service config might look like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="LoginServiceBehavior"&gt; &lt;serviceMetadata /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service name="WcfTest.LoginService" behaviorConfiguration="LoginServiceBehavior" &gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://somesite.com:55555/LoginService/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;endpoint name="LoginService" address="" binding="basicHttpBinding" contract="WcfTest.ILoginService" /&gt; &lt;endpoint name="LoginServiceMex" address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p>(The MEX stuff is optional for production, but is needed for testing with WcfTestClient.exe, and for exposing the service meta-data).</p> <p>You'll have to modify your Java code to POST a SOAP message to the service. WCF can be a little picky when inter-operating with non-WCF clients, so you'll have to mess with the POST headers a little to get it to work. Once you get this running, you can then start to investigate security for the login (might need to use a different binding to get better security), or possibly using WCF REST to allow for logins with a GET rather than SOAP/POST.</p> <p>Here is an example of what the HTTP POST should look like from the Java code. There is a tool called "<a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">Fiddler</a>" that can be really useful for debugging web-services.</p> <pre><code>POST /LoginService HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "http://mycompany.com/LoginService/ILoginService/Login" Host: somesite.com:55555 Content-Length: 216 Expect: 100-continue Connection: Keep-Alive &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;s:Body&gt; &lt;Login xmlns="http://mycompany.com/LoginService"&gt; &lt;username&gt;Blah&lt;/username&gt; &lt;password&gt;Blah2&lt;/password&gt; &lt;/Login&gt; &lt;/s:Body&gt; &lt;/s:Envelope&gt; </code></pre>
282,459
What is the C# equivalent to Java's isInstance()?
<p>I know of <code>is</code> and <code>as</code> for <code>instanceof</code>, but what about the reflective <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isInstance(java.lang.Object)" rel="noreferrer">isInstance()</a> method?</p>
282,469
5
0
null
2008-11-11 23:09:50.523 UTC
9
2016-09-21 20:21:09.53 UTC
2016-09-21 20:01:10.703 UTC
erickson
1,968
diegogs
36,744
null
1
93
c#|reflection|introspection|instanceof
78,331
<p>The equivalent of Java’s <code>obj.getClass().isInstance(otherObj)</code> in C# is as follows:</p> <pre><code>bool result = obj.GetType().IsAssignableFrom(otherObj.GetType()); </code></pre> <p>Note that while both Java and C# work on the runtime type object (Java <code>java.lang.Class</code> ≣ C# <code>System.Type</code>) of an <code>obj</code> (via <code>.getClass()</code> vs <code>.getType()</code>), Java’s <code>isInstance</code> takes an object as its argument, whereas C#’s <code>IsAssignableFrom</code> expects another <code>System.Type</code> object.</p>
1,151,032
javascript - blank space validation
<pre><code>function validation(reg) { str = document.reg; if (str.name.value == "") { alert("Enter your name"); str.name.focus(); return false; } </code></pre> <p>Validation will working fine if input is empty. </p> <p>Problem</p> <ol> <li>User can enter a blank space on the first.</li> <li>Also user can enter space only on the name.</li> </ol> <p>How to prevent it?</p>
1,151,040
6
0
null
2009-07-19 22:17:31.423 UTC
2
2015-04-07 14:12:45.753 UTC
null
null
null
null
106,111
null
1
7
javascript
88,716
<p>Here are some trim functions.</p> <p><a href="http://www.somacon.com/p355.php" rel="noreferrer">http://www.somacon.com/p355.php</a></p> <p>and using it</p> <pre><code>function validation(reg) { str = document.reg; if (str.name.value.trim() == "") { alert("Enter your name"); str.name.focus(); return false; } </code></pre>
286,945
What is the JSON format?
<p>What is the JSON (JavaScript Object Notation) format?</p>
286,978
6
7
null
2008-11-13 13:47:48.953 UTC
10
2022-03-24 20:46:36.663 UTC
2022-03-24 20:46:36.663 UTC
null
5,446,749
yesraaj
22,076
null
1
9
json
2,421
<blockquote> <p><strong>JSON (JavaScript Object Notation) is a lightweight data-interchange format</strong>. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.</p> </blockquote> <p>Ref.: <a href="http://www.json.org/" rel="nofollow noreferrer">json.org</a></p> <p>An <strong>object</strong> is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).</p> <p><a href="https://i.stack.imgur.com/BGm5b.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BGm5b.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.json.org/object.gif" rel="nofollow noreferrer">json.org</a>)</sub> </p> <p>An <strong>array</strong> is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).</p> <p><a href="https://i.stack.imgur.com/NIBbZ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIBbZ.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.json.org/array.gif" rel="nofollow noreferrer">json.org</a>)</sub> </p> <p>A <strong>value</strong> can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.</p> <p><a href="https://i.stack.imgur.com/oaws0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oaws0.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.json.org/value.gif" rel="nofollow noreferrer">json.org</a>)</sub> </p> <p>A <strong>string</strong> is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.</p> <p><a href="https://i.stack.imgur.com/JYA8X.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYA8X.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.json.org/string.gif" rel="nofollow noreferrer">json.org</a>)</sub> </p> <p>A <strong>number</strong> is very much like a C or Java number, except that the octal and hexadecimal formats are not used. <a href="https://i.stack.imgur.com/IgEnH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IgEnH.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.json.org/number.gif" rel="nofollow noreferrer">json.org</a>)</sub> </p> <p>Here is an example:</p> <pre><code>{ "menu": { "id": "file", "value": "File", "popup": { "menuitem": [{ "onclick": "CreateNewDoc()" }, { "value": "Open", "onclick": "OpenDoc()" }, { "value": "Close", "onclick": "CloseDoc()" }] } } } </code></pre> <p>And in XML the same thing would have been:</p> <pre><code>&lt;menu id="file" value="File"&gt; &lt;popup&gt; &lt;menuitem value="New" onclick="CreateNewDoc()" /&gt; &lt;menuitem value="Open" onclick="OpenDoc()" /&gt; &lt;menuitem value="Close" onclick="CloseDoc()" /&gt; &lt;/popup&gt; &lt;/menu&gt; </code></pre> <p>Ref.: <a href="http://www.json.org/" rel="nofollow noreferrer">json.org</a></p> <p>Hope you now get an idea of what is JSON.</p>
758,757
Rails Notification Message plugin?
<p>I am about to code something for a Rails app of mine and didn't want to reinvent the wheel, hence my question:</p> <p>Do you guys know any Rails Plugin that would allow an application to display notification messages that could be user specific and also allow the user to mark them as "don't show this again"?</p> <p>My vision is to display a top div (like the one StackOverflow added recently), in different color with the message "title" and that would be clickable. Once clicked, it would pop up the entire message and then allow the user to mark it to prevent it to be shown again.</p> <p>Is there anything like that out there? :-)</p> <p>I found so far this two plugins:</p> <ul> <li><a href="http://github.com/jstewart/system_messages/tree/master" rel="noreferrer">http://github.com/jstewart/system_messages/tree/master</a></li> <li><a href="http://github.com/arya/site_notifications/tree/master" rel="noreferrer">http://github.com/arya/site_notifications/tree/master</a></li> </ul> <p>But those are rather incomplete parts of my vision</p> <p>-- Felipe.</p>
1,544,780
6
1
null
2009-04-17 02:23:54.36 UTC
9
2012-07-20 08:29:52.81 UTC
null
null
null
null
14,540
null
1
17
ruby-on-rails|ruby|message|notifications
5,609
<p>It seems like <a href="http://github.com/jstewart/system_messages" rel="nofollow noreferrer">system_messages</a> (which you linked to) mostly does what you want. The <code>SystemMessage</code> model has <code>header</code>, <code>message</code>, and <code>dismissed</code> fields. </p> <p>It would take just a bit of JavaScript to show an intially hidden message field when the header is clicked. The plugin already allows dismissal of the message via JavaScript if you use Prototype.</p>
44,542
Algorithm / pseudo-code to create paging links?
<p>Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?</p> <p>I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.</p> <p>Example: <code>1 ... 5 6 7 ... 593</code></p>
44,844
6
0
null
2008-09-04 19:20:15.25 UTC
14
2019-11-19 14:17:52.583 UTC
2012-05-08 11:13:20.267 UTC
Jeff Atwood
1,097
Geoff
1,097
null
1
18
algorithm|paging
12,462
<p>There are several other answers already, but I'd like to show you the approach I took to solve it: First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: <a href="https://stackoverflow.com/questions/tagged/usability">usability</a> works today. We can see nothing is displayed, which makes sense.</p> <p>How about 2 pages? Find a tag that has between 11 and 20 entries (<a href="https://stackoverflow.com/questions/tagged/emacs">emacs</a> works today). We see: "<strong>1</strong> 2 Next" or "Prev 1 <strong>2</strong>", depending on which page we're on.</p> <p>3 pages? "<strong>1</strong> 2 3 ... 3 Next", "Prev 1 <strong>2</strong> 3 Next", and "Prev 1 ... 2 <strong>3</strong>". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display "<strong>1</strong> 2 ... 3 Next"</p> <p>4 pages? "<strong>1</strong> 2 3 ... 4 Next", "Prev 1 <strong>2</strong> 3 ... 4 Next", "Prev 1 ... 2 <strong>3</strong> 4 Next" and "Prev 1 ... 3 <strong>4</strong>"</p> <p>Finally let's look at the general case, N pages: "<strong>1</strong> 2 3 ... N Next", "Prev 1 <strong>2</strong> 3 ... N Next", "Prev 1 ... 2 <strong>3</strong> 4 ... N Next", "Prev 1 ... 3 <strong>4</strong> 5 ... N Next", etc.</p> <p>Let's generalize based on what we've seen: The algorithm seems to have these traits in common:</p> <ul> <li>If we're not on the first page, display link to Prev</li> <li>Always display the first page number</li> <li>Always display the current page number</li> <li>Always display the page before this page, and the page after this page.</li> <li>Always display the last page number</li> <li>If we're not on the last page, display link to Next</li> </ul> <p>Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)</p> <pre><code>function printPageLinksFirstTry(num totalPages, num currentPage) if ( currentPage &gt; 1 ) print "Prev" print "1" print "..." print currentPage - 1 print currentPage print currentPage + 1 print "..." print totalPages if ( currentPage &lt; totalPages ) print "Next" endFunction </code></pre> <p>This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.</p> <pre><code>function printPageLinksHandleCloseToEnds(num totalPages, num currentPage) if ( currentPage &gt; 1 ) print "Prev" print "1" if ( currentPage &gt; 2 ) print "..." if ( currentPage &gt; 2 ) print currentPage - 1 print currentPage if ( currentPage &lt; totalPages - 1 ) print currentPage + 1 if ( currentPage &lt; totalPages - 1 ) print "..." print totalPages if ( currentPage &lt; totalPages ) print "Next" endFunction </code></pre> <p>As you can see, we have some duplication here. We can go ahead and clean that up for readibility:</p> <pre><code>function printPageLinksCleanedUp(num totalPages, num currentPage) if ( currentPage &gt; 1 ) print "Prev" print "1" if ( currentPage &gt; 2 ) print "..." print currentPage - 1 print currentPage if ( currentPage &lt; totalPages - 1 ) print currentPage + 1 print "..." print totalPages if ( currentPage &lt; totalPages ) print "Next" endFunction </code></pre> <p>There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go:</p> <pre><code>function printPageLinksFinal(num totalPages, num currentPage) if ( totalPages == 1 ) return if ( currentPage &gt; 1 ) print "Prev" print "1" if ( currentPage &gt; 2 ) print "..." print currentPage - 1 if ( currentPage != 1 and currentPage != totalPages ) print currentPage if ( currentPage &lt; totalPages - 1 ) print currentPage + 1 print "..." print totalPages if ( currentPage &lt; totalPages ) print "Next" endFunction </code></pre> <p>Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of "<strong>1</strong> 2 ... 10 Next" you get "<strong>1</strong> 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:</p> <pre><code>function printPageLinksFinalReally(num totalPages, num currentPage) if ( totalPages == 1 ) return if ( currentPage &gt; 1 ) print "Prev" print "1" if ( currentPage &gt; 2 ) print "..." if ( currentPage == totalPages and totalPages &gt; 3 ) print currentPage - 2 print currentPage - 1 if ( currentPage != 1 and currentPage != totalPages ) print currentPage if ( currentPage &lt; totalPages - 1 ) print currentPage + 1 if ( currentPage == 1 and totalPages &gt; 3 ) print currentPage + 2 print "..." print totalPages if ( currentPage &lt; totalPages ) print "Next" endFunction </code></pre> <p>I hope this helps!</p>
506,093
Why is thread local storage so slow?
<p>I'm working on a custom mark-release style memory allocator for the D programming language that works by allocating from thread-local regions. It seems that the thread local storage bottleneck is causing a huge (~50%) slowdown in allocating memory from these regions compared to an otherwise identical single threaded version of the code, even after designing my code to have only one TLS lookup per allocation/deallocation. This is based on allocating/freeing memory a large number of times in a loop, and I'm trying to figure out if it's an artifact of my benchmarking method. My understanding is that thread local storage should basically just involve accessing something through an extra layer of indirection, similar to accessing a variable via a pointer. Is this incorrect? How much overhead does thread-local storage typically have?</p> <p>Note: Although I mention D, I'm also interested in general answers that aren't specific to D, since D's implementation of thread-local storage will likely improve if it is slower than the best implementations.</p>
506,150
6
1
null
2009-02-03 05:28:37.513 UTC
18
2012-10-18 13:53:13.07 UTC
2012-10-18 13:53:13.07 UTC
null
72,178
dsimcha
23,903
null
1
38
multithreading|performance|d|thread-local-storage
23,161
<p>The speed depends on the TLS implementation. </p> <p>Yes, you are correct that TLS can be as fast as a pointer lookup. It can even be faster on systems with a memory management unit. </p> <p>For the pointer lookup you need help from the scheduler though. The scheduler must - on a task switch - update the pointer to the TLS data. </p> <p>Another fast way to implement TLS is via the Memory Management Unit. Here the TLS is treated like any other data with the exception that TLS variables are allocated in a special segment. The scheduler will - on task switch - map the correct chunk of memory into the address space of the task. </p> <p>If the scheduler does not support any of these methods, the compiler/library has to do the following:</p> <ul> <li>get current ThreadId</li> <li>Take a semaphore</li> <li>Lookup the pointer to the TLS block by the ThreadId (may use a map or so)</li> <li>Release the semaphore</li> <li>Return that pointer.</li> </ul> <p>Obviously doing all this for each TLS data access takes a while and may need up to three OS calls: Getting the ThreadId, Take and Release the semaphore.</p> <p>The semaphore is btw required to make sure no thread reads from the TLS pointer list while another thread is in the middle of spawning a new thread. (and as such allocate a new TLS block and modify the datastructure).</p> <p>Unfortunately it's not uncommon to see the slow TLS implementation in practice. </p>
822,468
Is there an open-source DRM solution?
<p>Is there some open-sourced, well-documented and used DRM framework/library?</p> <p>I want to write some framework for buying and selling digital stuff, where I want to implement, somehow, for the seller to have the possibility to lock the files with some sort of DRM, where only authorised computers would be able to open it (something like iTunes FairPlay). </p> <p>It can, and probably has to, involve contacting my server with some login credentials.</p> <p>On the other hand, I want the client to be open-sourced, and probably the server too .. is that even possible? Security through obscurity does not work, but DRM is not exactly "security"...</p> <p>All I was able to find is <a href="http://it.slashdot.org/article.pl?sid=08/01/22/0230217" rel="noreferrer">this discussion on slashdot with the exact same problem</a>, but it ended with "DRM IS BAD", and Sun's DReaM project, but I have no clue how to get to the <a href="http://www.openmediacommons.org/" rel="noreferrer">actual code/usage of the framework on their site</a>.</p> <p>If you think Open Sourced DRM is not possible, tell me so.</p>
822,745
6
6
null
2009-05-04 22:43:54.427 UTC
22
2016-09-16 17:31:55.977 UTC
2009-05-05 00:34:18.857 UTC
null
6,010
null
101,152
null
1
53
drm
67,782
<p>This claims to be an open source implementation of OMA DRM2. I assume it contains the software components needed to build the server and client, leaving the hardware as an exercise for the reader:</p> <p><a href="http://sourceforge.net/projects/openipmp" rel="noreferrer">http://sourceforge.net/projects/openipmp</a></p> <p>License is MPL, which is a non-GPL-compatible FOSS license.</p> <p>I have no experience of this implementation, but a little of OMA DRM, and it seemed at the time to be a workable DRM scheme, as much as any DRM scheme is workable. The OMA DRM standard is well-documented, and is (or at least has been) widely-used by the mobile phone industry.</p> <p>The fundamental problem with open-source DRM is that although all of the algorithms and source code can be published without harming the scheme, client devices have to be "trusted" by the rights issuer to respect the rights, i.e. not do anything forbidden. This is incompatible with FOSS, which says that the user of a device should have full control over what it does.</p> <p><i>Security through obscurity does not work, but DRM is not exactly "security"</i></p> <p>Security through obscurity <em>of algorithms</em> is usually weak. Security through secrecy <em>of information</em> is the only way to do crypto, signing, etc. DRM does not require obscurity of algorithms (which is why OMA DRM is a published standard, and how come the source for an implementation can be published and freely usable), but it does require that the player device have access to information (some kind of key) which the user of the device does not, and which is not part of the algorithm/source.</p> <p>Normally, security protects the owner/user of a device from a threat model of external attackers. In the DRM threat model, the owner/user of the device <em>is</em> the attacker, and the rights owner is being defended. If the device's user has full control over it, then clearly in principle this is game over. </p> <p>In practice it may not be quite that immediate, but in the open source case, allowing people to write their own DRM clients which prevent them from copying your rights-protected data would be asking them to be astonishingly honest.</p> <p>Users can sometimes be persuaded to be law-abiding, in which case DRM takes on the role of reminding them that if they're jumping through hoops to work around the restrictions, then they may be breaking the law.</p>
925,638
Add values to app.config and retrieve them
<p>I need to insert key value pairs in app.Config as follows:</p> <pre><code>&lt;configuration&gt; &lt;appSettings&gt; &lt;add key="Setting1" value="Value1" /&gt; &lt;add key="Setting2" value="Value2" /&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <p>When I searched in google I got the following code snippet</p> <pre><code>System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Add an Application Setting. config.AppSettings.Settings.Add("ModificationDate", DateTime.Now.ToLongTimeString() + " "); // Save the changes in App.config file. config.Save(ConfigurationSaveMode.Modified); </code></pre> <p>The above code is not working as ConfigurationManager is not found in System.Configuration namespace I'm using .NET 2.0. How to add key-value pairs to app.Config programatically and retrieve them?</p>
925,644
6
1
null
2009-05-29 11:52:54.173 UTC
13
2019-10-03 20:43:15.853 UTC
null
null
null
null
94,169
null
1
79
c#
177,958
<p>Are you missing the reference to System.Configuration.dll? <code>ConfigurationManager</code> class lies there.</p> <p>EDIT: The <code>System.Configuration</code> namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...</p>
32,234,733
Javascript: what lookup is faster: array.indexOf vs object hash?
<p>I have to perform a <em>LOT</em> of lookups, while parsing xmlStream if i need some tag or not.</p> <p>I can do it with array.indexOf method (i have about ~15 items in array) or using object[key] lookup.</p> <p>Second solution seems more efficient in theory for me, but does not look line nice in my code. But if it is really more efficient, i would leave it as it is.</p> <p>E.g.:</p> <pre><code>var tags = [ 'tag1', 'tag2', 'tag3', ... ]; var tags2 = { 'tag1' : null, 'tag2' : null, 'tag3' : null, } tags.indexOf(value) // exists? tags2[value] // exists? </code></pre>
32,235,009
2
7
null
2015-08-26 19:05:32.3 UTC
7
2018-12-21 03:40:42.767 UTC
null
null
null
null
1,391,074
null
1
39
javascript|arrays|object
12,255
<p>Well, the performance depends on your set size and your access pattern. In general, the indexOf is O(n) and hash is O(1), however, since you only have about 15 items in the set and let's say each access is completely independent and equiprobable, the advantage of hash isn't really there.</p>
13,253,834
div under another div
<p>with css, can I put a div under another div without using absolute positioning? </p> <p>I have these two divs, and I would like the solid white one to appear directly under the one with the yellow opacity (but not direct in the corner, at the corner of the outline).</p> <p>How can this be accomplished. I've been experimenting with <code>z-index</code> and relative positioning, but to no avail.</p> <p>Thanks <a href="http://jsfiddle.net/loren_hibbard/WtGsv/" rel="nofollow">http://jsfiddle.net/loren_hibbard/WtGsv/</a></p>
13,253,905
6
6
null
2012-11-06 15:08:08.827 UTC
null
2021-10-05 09:03:26.603 UTC
null
null
null
null
1,252,748
null
1
3
html|css
47,871
<p>Without using positioning, I added a style to your content div using negative margins:</p> <pre><code>.content { margin-top:-100px; } </code></pre> <p>Working demo here: <a href="http://jsfiddle.net/WtGsv/3/" rel="nofollow">http://jsfiddle.net/WtGsv/3/</a></p> <p>I suggest adding an id to your <code>.fixed_width</code> div which houses the <code>.content</code> div though, and using the id to give the negative margin to, that way the parent div has the negative margin, not the child div.</p> <p>However if you want to use absolute positioning, I have updated your jsfiddle here: <a href="http://jsfiddle.net/WtGsv/12/" rel="nofollow">http://jsfiddle.net/WtGsv/12/</a></p> <p>Basically, you add a parent div with <code>position:relative;</code> around your other two divs that you want to use <code>position:absolute;</code></p>
37,890,284
.ini file load environment variable
<p>I am using <a href="http://alembic.readthedocs.io/en/latest/" rel="noreferrer">Alembic</a> for migrations implementation in a <code>Flask</code> project. There is a <code>alembic.ini</code> file where the database configs must be specified:</p> <p><code>sqlalchemy.url = driver://user:password@host/dbname</code></p> <p>Is there a way to specify the parameters from the environment variables? I've tried to load them in this way <code>$(env_var)</code> but with no success. Thanks!</p>
37,891,036
3
4
null
2016-06-17 20:58:40.33 UTC
5
2022-07-26 17:05:21.36 UTC
null
null
null
null
2,523,726
null
1
47
python|flask|ini|alembic
15,484
<p>I've solved the problem by setting <code>sqlalchemy.url</code> in <code>env.py</code> as @dirn suggested.</p> <p><code>config.set_main_option('sqlalchemy.url', &lt;db_uri&gt;)</code> did the trick, where <code>&lt;db_uri&gt;</code> can be loaded from environment or config file.</p>
44,276,080
How do I rotate something 15 degrees in Flutter?
<p>The Flutter docs show an example of rotating a "div" by 15 degrees, both for HTML/CSS and Flutter code:</p> <p>The Flutter code is:</p> <pre><code>var container = new Container( // gray box child: new Center( child: new Transform( child: new Text( "Lorem ipsum", ), alignment: FractionalOffset.center, transform: new Matrix4.identity() ..rotateZ(15 * 3.1415927 / 180), ), ), ); </code></pre> <p>And the relevant parts are <code>new Transform</code> and <code>alignment: FractionalOffset.center</code> and <code>transform: new Matrix4.identity()..rotateZ(15 * 3.1415927 / 180)</code></p> <p>I'm curious, is there a simpler way to rotate a <code>Container</code> in Flutter? Is there a short-hand for the case of "15 degrees" ?</p> <p>Thanks!</p>
44,288,456
5
1
null
2017-05-31 05:04:50.893 UTC
14
2022-05-22 19:42:50.25 UTC
2017-05-31 05:20:38.653 UTC
null
123,471
null
123,471
null
1
101
dart|flutter
92,907
<p>In mobile apps, I think it's kind of rare to have things start out rotated 15 degrees and just stay there forever. So that may be why Flutter's support for rotation is better if you're planning to adjust the rotation over time.</p> <p>It feels like overkill, but a <a href="https://docs.flutter.io/flutter/widgets/RotationTransition-class.html" rel="noreferrer"><code>RotationTransition</code></a> with an <a href="https://docs.flutter.io/flutter/animation/AlwaysStoppedAnimation-class.html" rel="noreferrer"><code>AlwaysStoppedAnimation</code></a> would accomplish exactly what you want.</p> <p><a href="https://i.stack.imgur.com/nkaKc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nkaKc.png" alt="screenshot"></a></p> <pre><code>new RotationTransition( turns: new AlwaysStoppedAnimation(15 / 360), child: new Text("Lorem ipsum"), ) </code></pre> <p>If you want to rotate something 90, 180, or 270 degrees, you can use a <a href="https://docs.flutter.io/flutter/widgets/RotatedBox-class.html" rel="noreferrer"><code>RotatedBox</code></a>.</p> <p><a href="https://i.stack.imgur.com/zVLoH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zVLoH.png" alt="screenshot"></a></p> <pre><code>new RotatedBox( quarterTurns: 1, child: new Text("Lorem ipsum") ) </code></pre>
17,853,573
How to send a message to an actor's parent in Akka Classic?
<p>What is the method for an actor to send a message to its parent?</p> <p>I'm using Akka 2.2</p>
17,854,718
3
0
null
2013-07-25 09:05:22.817 UTC
4
2020-12-11 16:02:37.89 UTC
2020-12-08 22:17:01.303 UTC
null
2,756,409
null
798,502
null
1
28
java|akka
12,932
<p>You are looking for</p> <pre><code>getContext().parent() </code></pre> <p>which gives you the ActorRef of the parent, so you can do</p> <pre><code>getContext().parent().tell(...) </code></pre>
2,045,869
Nginx Proxy to Files on Local Disk or S3
<p>So I'm moving my site away from Apache and onto Nginx, and I'm having trouble with this scenario:</p> <p>User uploads a photo. This photo is resized, and then copied to S3. If there's suitable room on disk (or the file cannot be transferred to S3), a local version is kept.</p> <p>I want requests for these images (such as <a href="http://www.mysite.com/p/1_1.jpg" rel="noreferrer">http://www.mysite.com/p/1_1.jpg</a>) to first look in the p/ directory. If no local file exists, I want to proxy the request out to S3 and render the image (but not redirect).</p> <p>In Apache, I did this like so:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^p/([0-9]+_[0-9]+\.jpg)$ http://my_bucket.s3.amazonaws.com/$1 [P,L] </code></pre> <p>My attempt to replicate this behavior in Nginx is this:</p> <pre><code>location /p/ { if (-e $request_filename) { break; } proxy_pass http://my_bucket.s3.amazonaws.com/; } </code></pre> <p>What happens is that every request attempts to hit Amazon S3, even if the file exists on disk (and if it doesn't exist on Amazon, I get errors.) If I remove the proxy_pass line, then requests for files on disk DO work.</p> <p>Any ideas on how to fix this?</p>
11,112,646
5
1
null
2010-01-12 00:13:05.67 UTC
23
2017-06-25 21:53:01.653 UTC
2013-07-30 18:33:01.15 UTC
null
344,643
null
204,286
null
1
14
proxy|amazon-s3|nginx
23,020
<p>Shouldn't this be an example of using <code>try_files</code>?</p> <pre><code>location /p/ { try_files $uri @s3; } location @s3{ proxy_pass http://my_bucket.s3.amazonaws.com; } </code></pre> <p>Make sure there isn't a following slash on the S3 url</p>
2,211,200
Composing a Controller class with Dependency Injection in PHP
<p>How to solve the problem of <strong>composing a Controller</strong> class in PHP, which should be:</p> <ul> <li>easily <strong>testable</strong> by employing Dependency Injection, </li> <li>provide <strong>shared objects</strong> for end programmer</li> <li>provide a way to <strong>load new user libraries</strong></li> </ul> <p><em>Look down, for controller instantiation with a Dependency injection framework</em></p> <hr> <p>The problem is, that derived Controllers may use whatever resources the programmer wants to (eg. the framework provides). How to create a unified access to shared resources (DB, User, Storage, Cache, Helpers), user defined Classes or another libraries? </p> <h2>Elegant solution?</h2> <p>There are several possible solutions to my problem, but neither one looks to be a elegant</p> <ul> <li>Try to pass all shared objects by <strong>constructor</strong>? (may create constructor even with 10 placeholders)</li> <li>Create <strong>getters, settters</strong>? (bloated code) <code>$controller-&gt;setApplication($app)</code></li> <li>Apply <strong>singletons on shared resources</strong>? <code>User::getInstance()</code> or <code>Database::getInstance()</code></li> <li>Use <strong>Dependency Injection container</strong> as a singleton for object sharing inside the controller?</li> <li>provide one <strong>global application singleton</strong> as a factory? (this one looks very used in php frameworks, hovewer it goes strongly against DI principles and Demeter's law)</li> </ul> <p>I understand, that creating strongly coupled classes is discouraged and banished for :), however I don't know how this paradigm applies to a starting point for other programmers (a Controller class), in which they should be able to access shared resources provided to the MVC architecture. I believe, that breaking up the controller class into smaller classes would somehow destroy the practical meaning of MVC.</p> <hr> <h2>Dependency Injection Framework</h2> <p>DI Framework looks like a viable choice. However the problem still persists. A class like Controller does not reside in the Application layer, but in the RequestHandler/Response layer. </p> <p><strong>How should this layer instantiate the controller?</strong></p> <ul> <li>pass the DI injector into this layer?</li> <li>DI Framework as a singleton?</li> <li>put isolated DI framework config only for this layer and create separate DI injector instance?</li> </ul>
2,262,561
5
5
2010-02-12 11:39:38.413 UTC
2010-02-05 23:29:24.083 UTC
15
2021-11-18 22:41:32.667 UTC
2010-02-14 18:51:01.82 UTC
null
179,542
null
179,542
null
1
20
php|model-view-controller|dependency-injection|instantiation
5,334
<p>Are you developing a framework yourself? If not, your question does not apply, because you have to choose from <a href="https://en.wikipedia.org/wiki/Comparison_of_server-side_web_frameworks#PHP" rel="nofollow noreferrer">already existing frameworks</a> and their existing solutions. In this case your question must be reformulated like &quot;how do I do unit testing/dependency injection in framework X&quot;.</p> <p>If you are developing a framework on you own, you should check first how already existing ones approach this issue. And you must also elaborate your own requirements, and then just go with the simplest possible solution. Without requirements, your question is purely aesthetic and argumentative.</p> <p>In my humble opinion the simplest solution is to have public properties which initialize to defaults provided by your framework, otherwise you can inject your mocks here. (This equals to your getters/setters solution, but without the mentioned bloat. You do not always need getters and setters.) Optionally, if you really need it, you may provide a constructor to initialize those in one call (as you suggested).</p> <p>Singletons are an elegant solution, but again, you must ask yourself, is it applicable in your case? If you have to have different instances of the same type of object in your application, you can't go with it (e.g. if you wish to mock a class only in half of your app).</p> <p>Of course it is really awesome to have all the options. You can have getters/setter, constructors, and when initialization is omitted, default are taken from a singleton factory. But having too many options when not needed, is not awesome, it is disturbing as the programmer has to figure out which convention, option and pattern to use. I definitely do not want to make dozens of design decisions just to get a simple CRUD running.</p> <p>If you look at other frameworks you will see that there is no silver bullet. Often a single framework utilizes different techniques depending on the context. In controllers, DI is a really straightforward thing, look at CakePHP's $helpers, $components variables, which instruct to inject appropriate variables into the controller class. For the application itself a singleton is still a good thing, as there is always just a single application. Properties less often changed/mocked are injected utilizing public properties. In case of an MVC, subclassing is perfectly viable option as well: just as AppController, AppView, AppModel in CakePHP. They are inserted into the class hierarchy between the frameworks's and all your particular Controller, View and Model classes. This way you have a single point to declare globals for your main type of classes.</p> <p>In Java, because of dynamic class loaders and reflection, you have even much more options to choose from. But on the other hand, you have to support much more requirements as well: parallel requests, shared objects and states between worker threads, distributed app servers etc.</p> <p>You can only answer the question what is right for you, if you know what you need in the first place. But actually, why do you write just another new framework anyway?</p>
1,378,129
How to create installers with Maven
<p>I'm migrating a medium sized Java application's build from Ant to Maven. I could easily migrate the basic building stuff, but I would also like to create the installer packages from the Maven build. The easiest way would be to call the original Ant scripts through the Ant plugin, but I thought maybe I should look around first for some Maven support.</p> <p>I'd need to create several different installers for different platforms:</p> <ul> <li>Windows 32/64 bit</li> <li>Linux 32/64 bit</li> <li>MacOS 32/64 bit</li> </ul> <p>For Linux now I think we only have a tar.gz and some Bash scripts to start the daemons - a Debian/RPM package would be much nicer, maybe with dependent package definitions, too. For the Windows installers we use NullSoft installer. I have no idea how the MacOS bundle is assembled now.</p> <p>Are there any tools out there to do this (or at least part of it) from Maven?</p>
1,385,587
6
1
null
2009-09-04 09:18:48.72 UTC
12
2015-09-15 12:09:01.88 UTC
2009-09-06 12:42:24.55 UTC
null
123,582
null
104,894
null
1
25
java|maven-2|installation
20,818
<p>I'd use the <a href="https://izpack.atlassian.net/wiki/display/IZPACK/Compiling+Using+Maven" rel="nofollow noreferrer">IzPack maven plugin</a> if you need a full-blown installer, or the <a href="http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/" rel="nofollow noreferrer">appassembler-maven-plugin</a> if you simply need to generate daemons for java services. </p> <p>There are also plugins for <a href="http://mojo.codehaus.org/nsis-maven-plugin/" rel="nofollow noreferrer">NSIS</a>, <a href="http://mojo.codehaus.org/deb-maven-plugin/" rel="nofollow noreferrer">Debian</a>, and <a href="http://mojo.codehaus.org/rpm-maven-plugin/" rel="nofollow noreferrer">RPM</a> packaging, but using those means you have to maintain configurations for each platform, on the other hand IzPack allows you to generate an installer for Windows XP / Vista / 2003 / 2000, Mac OS X, Solaris, Linux and *BSD. </p> <hr> <p>The appassembler plugin provides a goal to generate JSW daemons for each platform. Here is an example configuration:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;appassembler-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;execution&gt; &lt;id&gt;generate-jsw-scripts&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;generate-daemons&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;daemons&gt; &lt;daemon&gt; &lt;id&gt;myApp&lt;/id&gt; &lt;mainClass&gt;name.seller.rich.MainClass&lt;/mainClass&gt; &lt;commandLineArguments&gt; &lt;commandLineArgument&gt;start&lt;/commandLineArgument&gt; &lt;/commandLineArguments&gt; &lt;platforms&gt; &lt;platform&gt;jsw&lt;/platform&gt; &lt;/platforms&gt; &lt;/daemon&gt; &lt;/daemons&gt; &lt;target&gt;${project.build.directory}/appassembler&lt;/target&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/plugin&gt; </code></pre>
1,409,358
ADO.NET |DataDirectory| where is this documented?
<p>In AppConfig it is possible to use <code>|DataDirectory|</code> but I can't find any doc ?</p>
1,409,378
6
1
null
2009-09-11 06:48:23.09 UTC
31
2015-04-04 08:23:15.79 UTC
2011-08-08 05:57:37.95 UTC
null
368,070
null
149,141
null
1
64
c#|ado.net|datadirectory
73,362
<p><code>|DataDirectory|</code> is a substitution string so you can configure the location of your database file separately.</p> <p>So instead of:</p> <pre><code>SqlConnection c = new SqlConnection ( @"Data Source=.\SQLDB; AttachDbFilename=C:\MyDB\Database.mdf;Initial Catalog=Master"); </code></pre> <p>you do the following:</p> <pre><code>// Set |DataDirectory| value AppDomain.CurrentDomain.SetData("DataDirectory", "C:\myDB"); // SQL Connection String with |DataDirectory| substitution string SqlConnection c = new SqlConnection ( @"Data Source=.\SQLDB; AttachDbFilename=|DataDirectory|\Database.mdf;Initial Catalog=Master"); </code></pre>
1,971,738
Regex for all strings not containing a string?
<p>Ok, so this is something completely stupid but this is something I simply never learned to do and its a hassle.</p> <p>How do I specify a string that does not contain a sequence of other characters. For example I want to match all lines that do NOT end in '.config'</p> <p>I would think that I could just do</p> <pre><code>.*[^(\.config)]$ </code></pre> <p>but this doesn't work (why not?)</p> <p>I know I can do</p> <pre><code>.*[^\.][^c][^o][^n][^f][^i][^g]$ </code></pre> <p>but please please please tell me that there is a better way</p>
1,971,762
7
5
null
2009-12-28 21:47:31.563 UTC
12
2014-01-19 22:10:56.823 UTC
null
null
null
null
5,056
null
1
30
regex
95,881
<p>You can use <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">negative lookbehind</a>, e.g.: </p> <pre><code>.*(?&lt;!\.config)$ </code></pre> <p>This matches all strings except those that end with ".config"</p>
2,217,068
Why should I care about RTTI in Delphi?
<p>I've heard a lot about the new/improved <a href="http://www.malcolmgroves.com/blog/?p=476" rel="noreferrer">RTTI capabilities of Delphi 2010</a>, but I must admit my ignorance...I don't understand it. I know every version of Delphi has supported RTTI...and I know that RTTI (Runtime Type Information) allows me to access type information while my application is running.</p> <p>But what exactly does that <em>mean</em>? Is Delphi 2010's RTTI support the same thing as <a href="http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.71%29.aspx" rel="noreferrer">reflection in .NET</a>?</p> <p>Could someone please explain why RTTI is useful? Pretend I'm your pointy haired boss and help me understand why RTTI is cool. How might I use it in a real-world application?</p>
2,217,243
7
1
null
2010-02-07 14:32:37.023 UTC
17
2013-07-27 13:05:48.27 UTC
null
null
null
null
12,458
null
1
43
delphi|reflection|delphi-2010|rtti
9,131
<p>RTTI in Delphi is still not <em>quite</em> as full-featured as Reflection in .NET or other managed languages, because it is operating on compiled code, not an Intermediate Language (bytecode). However, it is a very similar concept, and the new RTTI system in Delphi 2010 brings it a <em>lot</em> closer to reflection, exposing an entire object-oriented API.</p> <p>Pre-D2010, the RTTI was pretty limited. About the only thing I ever remember doing with it was converting an <a href="http://theroadtodelphi.wordpress.com/2009/10/27/convert-enum-to-string-using-delphi/" rel="noreferrer">enumerated type to a string</a> (or <a href="http://theroadtodelphi.wordpress.com/2009/10/27/convert-string-to-enum-using-delphi/" rel="noreferrer">vice versa</a>) for use in drop-down lists. I may have used it at one point for <a href="http://www.delphigeist.com/2009/11/saveload-controls-from-inifile-using.html" rel="noreferrer">control persistence</a>.</p> <p>With the new RTTI in D2010 you can do a lot more things:</p> <ul> <li><p><a href="http://robstechcorner.blogspot.com/2009/10/xml-serialization-basic-usage.html" rel="noreferrer">XML Serialization</a></p></li> <li><p><a href="http://www.malcolmgroves.com/blog/?p=476" rel="noreferrer">Attribute</a>-based metadata (<code>TCustomAttribute</code>). Typical use cases would be automatic validation of properties and automated permission checks, two things that you normally have to write a lot of code for.</p></li> <li><p>Adding <a href="http://delphihaven.wordpress.com/2009/09/02/d2010-rtti-and-active-scripting/" rel="noreferrer">Active Scripting</a> support (i.e. using the Windows script control)</p></li> <li><p>Building a plug-in system; you could do this before, but there were a lot of headaches. I wasn't able to find a really good example of someone doing this from top to bottom, but all of the necessary functions are available now.</p></li> <li><p>It looks like someone's even trying to implement <a href="http://code.google.com/p/delphi-spring-framework/" rel="noreferrer">Spring</a> (DI framework) for Delphi 2010.</p></li> </ul> <p>So it's definitely very useful, although I'm not sure how well you'd be able to explain it to a PHB; most of its usefulness is probably going to be realized through 3rd-party libraries and frameworks, much the same way it works in the .NET community today - it's rare to see reflection code sitting in the business logic, but a typical app will make use of several reflection-based components like an Object-Relational Mapper or IoC Container.</p> <p>Have I answered the question?</p>
2,109,171
C# naming conventions for acronyms
<p>Regarding C# naming for acronyms, if I was writing a library related to the Windows API is there any strong convention toward either WindowsApi or WindowsAPI or is it just personal preference?</p>
2,109,187
8
0
null
2010-01-21 12:38:22.323 UTC
28
2022-01-21 10:24:47.783 UTC
2013-09-03 05:47:00.59 UTC
null
1,630
null
144,152
null
1
97
c#|naming-conventions
44,487
<p>There is a convention, and it specifies initial uppercase, the rest lowercase, for all acronyms that are more than 2 characters long. Hence <code>HttpContext</code> and <code>ClientID</code>.</p>
1,480,236
Does a TCP socket connection have a "keep alive"?
<p>I have heard of HTTP keep-alive but for now I want to open a socket connection with a remote server.<br> Now will this socket connection remain open forever or is there a timeout limit associated with it similar to HTTP keep-alive?</p>
1,480,246
8
1
null
2009-09-26 02:09:20.587 UTC
54
2022-05-06 20:48:28.24 UTC
2015-11-25 17:52:57.87 UTC
null
446,554
null
142,299
null
1
99
java|sockets|http|tcp|keep-alive
187,810
<p>TCP sockets remain open till they are closed.</p> <p>That said, it's very difficult to detect a broken connection (broken, as in a router died, etc, as opposed to closed) without actually sending data, so most applications do some sort of ping/pong reaction every so often just to make sure the connection is still actually alive.</p>
1,724,587
How to store PHP sessions in APC Cache?
<p>Storing sessions in disk very slow and painful for me. I'm having very high traffic. I want to store session in Advanced PHP Cache, how can I do this?</p>
13,782,396
9
5
null
2009-11-12 19:05:34.063 UTC
10
2014-01-14 11:22:29.177 UTC
2012-12-08 16:33:45.463 UTC
null
815,724
null
209,868
null
1
21
php|session|caching|scalability
11,707
<p>I tried to lure better answers by offering 100 points as a bounty, but none of the answers were really satisfying.</p> <p>I would aggregate the recommended solutions like this: </p> <h2>Using APC as a session storage</h2> <p>APC cannot really be used as a session store, because there is no mechanism available to APC that allows proper locking, But this locking is essential to ensure nobody alters the initially read session data before writing it back.</p> <p>Bottom line: Avoid it, it won't work.</p> <h2>Alternatives</h2> <p>A number of session handlers might be available. Check the output of <code>phpinfo()</code> at the <code>Session</code> section for "Registered save handlers".</p> <h3>File storage on RAM disk</h3> <p>Works out-of-the-box, but needs a file system mounted as RAM disk for obvious reasons.</p> <h3>Shared memory (mm)</h3> <p>Is available when PHP is compiled with <code>mm</code> enabled. This is builtin on windows.</p> <h3>Memcache(d)</h3> <p>PHP comes with a dedicated session save handler for this. Requires installed memcache server and PHP client. Depending on which of the two memcache extensions is installed, the save handler is either called <code>memcache</code> or <code>memcached</code>.</p>
1,395,301
How to get R to recognize your working directory as its working directory?
<p>I use R under Windows on several machines.</p> <p>I know you can set the working directory from within an R script, like this</p> <pre><code>setwd("C:/Documents and Settings/username/My Documents/x/y/z") </code></pre> <p>... but then this breaks the portability of the script. It's also annoying to have to reverse all the slashes (since Windows gives you backslashes)</p> <p>Is there a way to start R in a particular working directory so that you don't need to do this at the script level?</p>
1,396,410
10
0
null
2009-09-08 17:42:57.113 UTC
8
2021-04-06 05:21:03.153 UTC
2013-01-24 01:00:32.03 UTC
null
1,288
null
23,929
null
1
27
r|path|installation|working-directory
84,668
<p>You should copy shortcut to R (R.lnk file) to desire folder. Then in "Properties" (right mouse button -> last option) delete anything in field "Start in..." in second tab ("Shortcut"?). If you start R with this shortcut working directory will be that one where the shortcut is.</p> <p>I don't have english version of Windows so I'm not sure about field names, but they should be easy to find.</p> <p>Similar questions were in R-windows-faq:</p> <p><a href="http://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-run-it_003f" rel="noreferrer">2.5 How do I run it?</a></p> <p><a href="http://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-can-I-keep-workspaces-for-different-projects-in-different-directories_003f" rel="noreferrer">2.10 How can I keep workspaces for different projects in different directories?</a></p> <p><a href="http://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f" rel="noreferrer">2.14 What are HOME and working directories?</a> </p> <p>In 2.14 is mentioned that </p> <blockquote> <p>The working directory is the directory from which Rgui or Rterm was launched, unless a shortcut was used when it is given by the `Start in' field of the shortcut's properties. </p> </blockquote>
2,158,660
Why doesn't Objective-C support private methods?
<p>I've seen a number of strategies for declaring semi-private methods in <strong>Objective-C</strong>, but there does not seem to be a way to make a truly private method. I accept that. But, why is this so? Every explanation I've essentially says, "you can't do it, but here's a close approximation."</p> <p>There are a number of keywords applied to <code>ivars</code> (members) that control their scope, e.g. <code>@private</code>, <code>@public</code>, <code>@protected</code>. Why can't this be done for methods as well? It seems like something the runtime should be able to support. Is there an underlying philosophy I'm missing? Is this deliberate?</p>
2,159,027
10
4
null
2010-01-28 22:56:44.593 UTC
45
2014-07-31 15:31:41.517 UTC
2013-06-23 04:26:18.59 UTC
null
1,262,634
null
153,959
null
1
123
objective-c|objective-c-runtime
23,999
<p>The answer is... well... simple. Simplicity and consistency, in fact.</p> <p>Objective-C is purely dynamic at the moment of method dispatch. In particular, every method dispatch goes through the exact same dynamic method resolution point as every other method dispatch. At runtime, every method implementation has the exact same exposure and all of the APIs provided by the Objective-C runtime that work with methods and selectors work equally the same across all methods.</p> <p>As many have answered (both here and in other questions), compile-time private methods are supported; if a class doesn't declare a method in its publicly available interface, then that method might as well not exist as far as your code is concerned. In other words, you can achieve all of the various combinations of visibility desired at compilation time by organizing your project appropriately.</p> <p>There is little benefit to duplicating the same functionality into the runtime. It would add a tremendous amount of complexity and overhead. And even with all of that complexity, it still wouldn't prevent all but the most casual developer from executing your supposedly "private" methods.</p> <blockquote> <p>EDIT: One of the assumptions I've noticed is that private messages would have to go through the runtime resulting in a potentially large overhead. Is this absolutely true?</p> <blockquote> <p>Yes, it is. There's no reason to suppose that the implementor of a class would not want to use all of the Objective-C feature set in the implementation, and that means that dynamic dispatch must happen. <em>However</em>, there is no particular reason why private methods couldn't be dispatched by a special variant of <code>objc_msgSend()</code>, since the compiler would know that they were private; i.e. this could be achieved by adding a private-only method table to the <code>Class</code> structure.</p> </blockquote> <p>There would be no way for a private method to short-circuit this check or skip the runtime?</p> <blockquote> <p>It couldn't skip the runtime, but the runtime <em>wouldn't</em> necessarily have to do any checking for private methods.</p> <p>That said, there's no reason that a third-party couldn't deliberately call <code>objc_msgSendPrivate()</code> on an object, outside of the implementation of that object, and some things (KVO, for example) would have to do that. In effect, it would just be a convention and little better in practice than prefixing private methods’ selectors or not mentioning them in the interface header.</p> </blockquote> </blockquote> <p>To do so, though, would undermine the pure dynamic nature of the language. No longer would every method dispatch go through an identical dispatch mechanism. Instead, you would be left in a situation where most methods behave one way and a small handful are just different.</p> <p>This extends beyond the runtime as there are many mechanisms in Cocoa built on top of the consistent dynamism of Objective-C. For example, both Key Value Coding and Key Value Observation would either have to be very heavily modified to support private methods — most likely by creating an exploitable loophole — or private methods would be incompatible.</p>
2,156,634
Why is a pure virtual function initialized by 0?
<p>We always declare a pure virtual function as:</p> <pre><code>virtual void fun () = 0 ; </code></pre> <p>I.e., it is always assigned to 0.</p> <p>What I understand is that this is to initialize the vtable entry for this function to NULL and any other value here results in a compile time error. Is this understanding correct or not?</p>
2,156,670
11
3
null
2010-01-28 17:48:37.697 UTC
53
2021-04-19 21:46:36.91 UTC
2017-04-20 20:51:54.303 UTC
null
63,550
null
240,857
null
1
163
c++|abstract-class|pure-virtual
56,475
<p>The reason <code>=0</code> is used is that Bjarne Stroustrup didn't think he could get another keyword, such as &quot;pure&quot; past the C++ community at the time the feature was being implemented. This is described in his book, <a href="//www.stroustrup.com/dne.html" rel="noreferrer">The Design &amp; Evolution of C++</a>, section 13.2.3:</p> <blockquote> <p>The curious =0 syntax was chosen ... because at the time I saw no chance of getting a new keyword accepted.</p> </blockquote> <p>He also states explicitly that this need not set the vtable entry to NULL, and that doing so is not the best way of implementing pure virtual functions.</p>
2,329,816
jQuery: Hide popup if click detected elsewhere
<p>I'm trying to hide a div if the user clicks anywhere BUT the popup OR its children. This is the code I have so far:</p> <pre><code>$("body").click(function(){ var $target = $(event.target); if(!$target.is(".popup") || !$target.is(".popup").children()){ $("body").find(".popup").fadeOut().removeClass('active'); } }); </code></pre> <p>This works for the .popup div, but if any of its children are clicked, it hides it anyway.</p>
2,329,858
12
0
null
2010-02-24 21:46:32.943 UTC
14
2020-05-13 08:23:42.377 UTC
2020-05-13 08:23:42.377 UTC
null
-1
null
255,256
null
1
41
jquery
98,246
<p>You really could simplify this a bit I think:</p> <pre><code>// If an event gets to the body $("body").click(function(){ $(".popup").fadeOut().removeClass("active"); }); // Prevent events from getting pass .popup $(".popup").click(function(e){ e.stopPropagation(); }); </code></pre> <p>Clicking on the popup, or any of its children will cause propagation to stop before it reaches the body.</p> <p>Demo of stopping event-propagation: <a href="http://jsbin.com/ofeso3/edit" rel="noreferrer">http://jsbin.com/ofeso3/edit</a></p>
1,441,202
Why is it called 'business logic'? Where did this term come from?
<p>I'm going through all sorts of WPF documentation, and I'm feeling unnecessarily confused. The term 'business logic' is scattered throughout it, as if everyone should know what it is. </p> <p>I can see what business logic is, according to this question here: <a href="https://stackoverflow.com/questions/39288/what-exactly-consists-of-business-logic-in-an-application">What exactly consists of &#39;Business Logic&#39; in an application?</a></p> <p>But where did the term come from? Why is it called 'business logic' and not, say, 'core logic' or 'main algorithms' or any other more generic terms? Very few of the programs I write have anything to do with 'business logic', and when I think of 'business logic' I think of things handling credit card transactions, customer database maintenance, and the like. In other words, things that relate to a fraction of the entirety of computer science. When I write an imaging application, there is no 'business' involved, no customers, no money-based transactions, nothing of the sort. So saying that I have 'business logic' really confuses me, since I'm not conducting business, I'm processing images.</p>
1,441,222
13
5
null
2009-09-17 20:38:07.49 UTC
12
2020-11-09 02:45:17.38 UTC
2017-05-23 12:00:28.833 UTC
null
-1
null
21,981
null
1
35
business-logic|nomenclature
4,571
<p>For the same reason that the end of a gun which the bullets come out of is called the “business end”. It's where the primary action happens.</p>
1,440,265
How to add a string to a string[] array? There's no .Add function
<pre><code>private string[] ColeccionDeCortes(string Path) { DirectoryInfo X = new DirectoryInfo(Path); FileInfo[] listaDeArchivos = X.GetFiles(); string[] Coleccion; foreach (FileInfo FI in listaDeArchivos) { //Add the FI.Name to the Coleccion[] array, } return Coleccion; } </code></pre> <p>I'd like to convert the <code>FI.Name</code> to a string and then add it to my array. How can I do this?</p>
1,440,274
15
0
null
2009-09-17 17:38:24.913 UTC
30
2022-02-03 18:16:07.927 UTC
2012-02-13 17:08:34.127 UTC
null
783,175
null
112,355
null
1
271
c#|arrays|long-filenames
914,927
<p>You can't add items to an array, since it has fixed length. What you're looking for is a <code>List&lt;string&gt;</code>, which can later be turned to an array using <code>list.ToArray()</code>, e.g.</p> <pre><code>List&lt;string&gt; list = new List&lt;string&gt;(); list.Add("Hi"); String[] str = list.ToArray(); </code></pre>
1,945,618
Tracing XML request/responses with JAX-WS
<p>Is there an easy way (aka: not using a proxy) to get access to the raw request/response XML for a webservice published with JAX-WS reference implementation (the one included in JDK 1.5 and better) ? Being able to do that via code is what I need to do. Just having it logged to a file by clever logging configurations would be nice but enough.</p> <p>I know that other more complex and complete frameworks exist that might do that, but I would like to keep it as simple as possible and axis, cxf, etc all add considerable overhead that I want to avoid.</p> <p>Thanks!</p>
1,957,777
20
2
null
2009-12-22 10:54:40.083 UTC
95
2021-03-11 21:58:00.583 UTC
2009-12-22 11:33:55.633 UTC
null
236,773
null
236,773
null
1
196
java|web-services|jax-ws
285,580
<p>Here is the solution in raw code (put together thanks to stjohnroe and Shamik):</p> <pre><code>Endpoint ep = Endpoint.create(new WebserviceImpl()); List&lt;Handler&gt; handlerChain = ep.getBinding().getHandlerChain(); handlerChain.add(new SOAPLoggingHandler()); ep.getBinding().setHandlerChain(handlerChain); ep.publish(publishURL); </code></pre> <p>Where SOAPLoggingHandler is (ripped from linked examples):</p> <pre><code>package com.myfirm.util.logging.ws; import java.io.PrintStream; import java.util.Map; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.soap.SOAPMessage; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.handler.soap.SOAPHandler; import javax.xml.ws.handler.soap.SOAPMessageContext; /* * This simple SOAPHandler will output the contents of incoming * and outgoing messages. */ public class SOAPLoggingHandler implements SOAPHandler&lt;SOAPMessageContext&gt; { // change this to redirect output if desired private static PrintStream out = System.out; public Set&lt;QName&gt; getHeaders() { return null; } public boolean handleMessage(SOAPMessageContext smc) { logToSystemOut(smc); return true; } public boolean handleFault(SOAPMessageContext smc) { logToSystemOut(smc); return true; } // nothing to clean up public void close(MessageContext messageContext) { } /* * Check the MESSAGE_OUTBOUND_PROPERTY in the context * to see if this is an outgoing or incoming message. * Write a brief message to the print stream and * output the message. The writeTo() method can throw * SOAPException or IOException */ private void logToSystemOut(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outboundProperty.booleanValue()) { out.println("\nOutbound message:"); } else { out.println("\nInbound message:"); } SOAPMessage message = smc.getMessage(); try { message.writeTo(out); out.println(""); // just to add a newline } catch (Exception e) { out.println("Exception in handler: " + e); } } } </code></pre>
2,315,862
Make UINavigationBar transparent
<p>How do you make a <strong>UINavigationBar transparent</strong>? Though I want its bar items to remain visible.</p>
18,969,823
20
0
null
2010-02-23 03:06:06.633 UTC
102
2022-06-14 20:27:28.567 UTC
2015-12-25 13:07:22.067 UTC
null
4,601,170
null
128,875
null
1
247
ios|iphone|objective-c|uinavigationbar|transparency
140,708
<p>If anybody is wondering how to achieve this in iOS 7+, here's a solution (iOS 6 compatible too)</p> <p>In Objective-C</p> <pre><code>[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; self.navigationBar.shadowImage = [UIImage new]; self.navigationBar.translucent = YES; </code></pre> <p>In swift 3 (iOS 10)</p> <pre><code>self.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationBar.shadowImage = UIImage() self.navigationBar.isTranslucent = true </code></pre> <p>In swift 2</p> <pre><code>self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationBar.shadowImage = UIImage() self.navigationBar.translucent = true </code></pre> <hr /> <h3>Discussion</h3> <p>Setting <code>translucent</code> to <code>YES</code> on the navigation bar does the trick, due to a behavior discussed in the <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationBar_Class/Reference/UINavigationBar.html#//apple_ref/occ/instp/UINavigationBar/translucent" rel="noreferrer"><code>UINavigationBar</code></a> documentation. I'll report here the relevant fragment:</p> <blockquote> <p>If you set this property to <code>YES</code> on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.</p> </blockquote>
8,511,490
Calculating length in UTF-8 of Java String without actually encoding it
<p>Does anyone know if the standard Java library (any version) provides a means of calculating the length of the binary encoding of a string (specifically UTF-8 in this case) without actually generating the encoded output? In other words, I'm looking for an efficient equivalent of this:</p> <pre><code>"some really long string".getBytes("UTF-8").length </code></pre> <p>I need to calculate a length prefix for potentially long serialized messages.</p>
8,512,877
4
2
null
2011-12-14 20:53:45.533 UTC
6
2017-04-03 22:01:33.577 UTC
null
null
null
null
123,336
null
1
50
java|utf-8
25,892
<p>Here's an implementation based on the <a href="https://www.rfc-editor.org/rfc/rfc3629#section-3" rel="nofollow noreferrer">UTF-8 specification</a>:</p> <pre><code>public class Utf8LenCounter { public static int length(CharSequence sequence) { int count = 0; for (int i = 0, len = sequence.length(); i &lt; len; i++) { char ch = sequence.charAt(i); if (ch &lt;= 0x7F) { count++; } else if (ch &lt;= 0x7FF) { count += 2; } else if (Character.isHighSurrogate(ch)) { count += 4; ++i; } else { count += 3; } } return count; } } </code></pre> <p>This implementation is not tolerant of malformed strings.</p> <p>Here's a JUnit 4 test for verification:</p> <pre><code>public class LenCounterTest { @Test public void testUtf8Len() { Charset utf8 = Charset.forName(&quot;UTF-8&quot;); AllCodepointsIterator iterator = new AllCodepointsIterator(); while (iterator.hasNext()) { String test = new String(Character.toChars(iterator.next())); Assert.assertEquals(test.getBytes(utf8).length, Utf8LenCounter.length(test)); } } private static class AllCodepointsIterator { private static final int MAX = 0x10FFFF; //see http://unicode.org/glossary/ private static final int SURROGATE_FIRST = 0xD800; private static final int SURROGATE_LAST = 0xDFFF; private int codepoint = 0; public boolean hasNext() { return codepoint &lt; MAX; } public int next() { int ret = codepoint; codepoint = next(codepoint); return ret; } private int next(int codepoint) { while (codepoint++ &lt; MAX) { if (codepoint == SURROGATE_FIRST) { codepoint = SURROGATE_LAST + 1; } if (!Character.isDefined(codepoint)) { continue; } return codepoint; } return MAX; } } } </code></pre> <p>Please excuse the compact formatting.</p>
18,077,325
Scale Image to fill ImageView width and keep aspect ratio
<p>I have a <code>GridView</code>. The data of <code>GridView</code> is request from a server.</p> <p>Here is the item layout in <code>GridView</code>:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/analysis_micon_bg" android:gravity="center_horizontal" android:orientation="vertical" android:paddingBottom="@dimen/half_activity_vertical_margin" android:paddingLeft="@dimen/half_activity_horizontal_margin" android:paddingRight="@dimen/half_activity_horizontal_margin" android:paddingTop="@dimen/half_activity_vertical_margin" &gt; &lt;ImageView android:id="@+id/ranking_prod_pic" android:layout_width="fill_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="centerCrop" /&gt; &lt;TextView android:id="@+id/ranking_rank_num" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/ranking_prod_num" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/ranking_prod_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>I request data from server, get image url and load image to <code>Bitmap</code></p> <pre><code>public static Bitmap loadBitmapFromInputStream(InputStream is) { return BitmapFactory.decodeStream(is); } public static Bitmap loadBitmapFromHttpUrl(String url) { try { return loadBitmapFromInputStream((InputStream) (new URL(url).getContent())); } catch (Exception e) { Log.e(TAG, e.getMessage()); return null; } } </code></pre> <p>and there is the code of <code>getView(int position, View convertView, ViewGroup parent)</code> method in adapter</p> <pre><code>Bitmap bitmap = BitmapUtil.loadBitmapFromHttpUrl(product.getHttpUrl()); prodImg.setImageBitmap(bitmap); </code></pre> <p>The image size is <code>210*210</code>. I run my application on my Nexus 4. The image does fill <code>ImageView</code> width, but the <code>ImageView</code> height does not scale. <code>ImageView</code> does not show the whole image.</p> <p>How do I solve this problem?</p>
25,069,883
16
0
null
2013-08-06 10:15:49.06 UTC
86
2020-12-28 07:50:49.447 UTC
2015-04-29 20:56:47.223 UTC
null
1,486,275
null
1,844,078
null
1
236
android|imageview
299,954
<p>Without using any custom classes or libraries:</p> <pre><code>&lt;ImageView android:id="@id/img" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitCenter" /&gt; </code></pre> <p><code>scaleType="fitCenter"</code> (default when omitted)</p> <ul> <li>will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.</li> </ul> <p><code>scaleType="centerInside"</code></p> <ul> <li>if the intrinsic width of <code>src</code> is smaller than parent width<br>will center the image horizontally </li> <li>if the intrinsic width of <code>src</code> is larger than parent width<br>will make it as wide as the parent allows and down-scale keeping aspect ratio.</li> </ul> <p>It doesn't matter if you use <code>android:src</code> or <code>ImageView.setImage*</code> methods and the key is probably the <code>adjustViewBounds</code>.</p>
6,374,809
Is JavaScript 's “new” Keyword Considered Harmful (Part 2)?
<p>Reading through the following <a href="https://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful">question</a>, I feel the majority of the answers miss the point of why some people (Crockford) choose not to use the "new" keyword. It's not to prevent accidental calling of a function without the "new" keyword. </p> <p>According to the following <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow noreferrer">article</a> by Crockford regarding prototypal inheritance, he implements an object creation technique that more clearly demonstrates the prototypal nature of JS. This technique is now even implemented in <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create" rel="nofollow noreferrer">JS 1.8.5</a>.</p> <p>His argument against using new can be more clearly summed up as:</p> <p><em>"This indirection was intended to make the language seem more familiar to classically trained programmers, but failed to do that, as we can see from the very low opinion Java programmers have of JavaScript. JavaScript's constructor pattern did not appeal to the classical crowd. It also obscured JavaScript's true prototypal nature. As a result, there are very few programmers who know how to use the language effectively."</em></p> <p>I don't necessarily consider "new" harmful, but I do agree that it does "obscure JavaScript's true prototypal nature," and therefore I do have to agree with Crockford on this point.</p> <p>What is your opinion of using a "clearer" prototypal object creation technique, over using the "new" keyword?</p>
6,375,254
3
10
2011-06-16 18:20:47.237 UTC
2011-06-16 15:54:12.53 UTC
12
2015-12-16 18:54:11.303 UTC
2017-05-23 12:25:17.597 UTC
null
-1
null
131,640
null
1
12
javascript
2,252
<p>You right, using <code>new</code> is considered harmful as it doesn't place enough emphasis on OO in JavaScript being prototypical. The main issue is that acts too much like classical classes and one <em>should not</em> think about <code>class</code>. One should think about Object's and creating new Objects with existing objects as blueprints. </p> <p><code>new</code> is a remnant of the days where JavaScript accepted a Java like syntax for gaining "popularity".</p> <p>These days <em>we</em> do Prototypical OO with <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create" rel="nofollow noreferrer"><code>Object.create</code></a> and use the <a href="https://github.com/kriskowal/es5-shim" rel="nofollow noreferrer">ES5 shim</a>.</p> <p>There is no need for <code>new</code> anymore.</p> <p>Before the days of ES5 being commonly implemented (only FF3.6 and IE8 are slacking) we used <code>new</code> because we had little choice. <code>someFunction.prototype</code> was the way to do prototypical inheritance.</p> <p>I recently wrote up a <a href="https://stackoverflow.com/questions/6337879/oop-programming-in-javascript-with-node-js/6339819#6339819">"nice" demonstration of <code>Object.create</code></a> although I still need to iron out some kinks in the usage. The important thing is to separate Objects from factory functions.</p>
6,607,552
What is Google's Dremel? How is it different from Mapreduce?
<p>Google's Dremel is <a href="http://research.google.com/pubs/pub36632.html" rel="noreferrer">described here</a>. What's the difference between Dremel and Mapreduce?</p>
6,609,776
3
0
null
2011-07-07 08:03:39.52 UTC
20
2019-05-09 20:20:44.357 UTC
2013-12-29 20:59:06.93 UTC
null
881,229
null
290,128
null
1
36
hadoop|mapreduce|google-bigquery|abstraction
38,623
<p>Check this <a href="http://www.quora.com/How-will-Googles-Dremel-change-future-Hadoop-releases" rel="noreferrer">article</a> out. Dremel is the what the future of hive should (and will) be. </p> <p>The major issue of MapReduce and solutions on top of it, like Pig, Hive etc, is that they have an inherent latency between running the job and getting the answer. Dremel uses a totally novel approach (came out in 2010 in that paper by google) which... </p> <blockquote> <p>...uses a novel query execution engine based on aggregator trees...</p> </blockquote> <p>...to run <strong>almost realtime</strong> , <strong>interactive</strong> AND <strong>adhoc</strong> queries both of which MapReduce cannot. And Pig and Hive aren't <strong>real time</strong></p> <p>You should keep an eye on <a href="http://code.google.com/p/dremel/" rel="noreferrer">projects</a> coming out of this. Is is pretty new for me too... so any other expert comments are welcome!</p> <p><strong>Edit:</strong> Dremel is what the future of <strong>HIVE</strong> (and not MapReduce as I mentioned before) should be. Hive right now provides a SQL like interface to run MapReduce jobs. Hive has very high latency, and so is not practical in ad-hoc data analysis. Dremel provides a very fast SQL like interface to the data by using a different technique than MapReduce.</p>
6,534,191
undefined reference to "only some math.h" functions
<p>I am having a strange problem.</p> <p>The math libraries has been added to my makefile.</p> <pre><code># include standard C library LDFLAGS += -lc # include standard math library LDFLAGS += -lm </code></pre> <p>and in the output file (.map) I can see that everything has been linked properly:</p> <pre><code>LOAD c:/gnu/powerpc-eabi/3pp.ronetix.powerpc-eabi/bin/../lib/gcc/powerpc-eabi/4.3.3/nof\libgcc.a LOAD c:/gnu/powerpc-eabi/3pp.ronetix.powerpc-eabi/bin/../lib/gcc/powerpc-eabi/4.3.3/../../../../powerpc-eabi/lib/nof\libc.a LOAD c:/gnu/powerpc-eabi/3pp.ronetix.powerpc-eabi/bin/../lib/gcc/powerpc-eabi/4.3.3/../../../../powerpc-eabi/lib/nof\libm.a </code></pre> <p>when I do </p> <pre><code>z = pow((double) 2, (double) 3); </code></pre> <p>it works fine. But if I test another function like:</p> <pre><code>double result = asin(x); </code></pre> <p>I´ll get:</p> <pre><code>undefined reference to `asin' collect2: ld returned 1 exit status </code></pre> <p>How can this be? both <strong>pow</strong> and <strong>asin</strong> are available in <strong>math.h</strong>, see below:</p> <pre><code>/* Non reentrant ANSI C functions. */ #ifndef _REENT_ONLY #ifndef __math_6881 extern double acos _PARAMS((double)); extern double asin _PARAMS((double)); extern double atan2 _PARAMS((double, double)); extern double cosh _PARAMS((double)); extern double sinh _PARAMS((double)); extern double exp _PARAMS((double)); extern double ldexp _PARAMS((double, int)); extern double log _PARAMS((double)); extern double log10 _PARAMS((double)); extern double pow _PARAMS((double, double)); extern double sqrt _PARAMS((double)); extern double fmod _PARAMS((double, double)); #endif /* ! defined (__math_68881) */ #endif /* ! defined (_REENT_ONLY) */ </code></pre> <p><em>how can one work and the other one generate linker issue?</em> If I run <strong>-nm</strong> on <strong>libm.a</strong> I´ll get the following result: (sorry for the huge output, I have only copied the sections with the word <strong><em>sin</em></strong>)</p> <pre><code>lib_a-e_asin.o: U __adddf3 U __divdf3 U __gtdf2 00000000 T __ieee754_asin U __ieee754_sqrt U __muldf3 U __subdf3 U fabs lib_a-e_j0.o: U __adddf3 U __divdf3 U __gtdf2 00000470 T __ieee754_j0 U __ieee754_log U __ieee754_sqrt 000009b8 T __ieee754_y0 U __ltdf2 U __muldf3 U __subdf3 U cos U fabs 000000b0 r pR2 00000108 r pR3 00000058 r pR5 00000000 r pR8 000000e0 r pS2 00000138 r pS3 00000088 r pS5 00000030 r pS8 00000004 t pzero 00000220 r qR2 00000280 r qR3 000001c0 r qR5 00000160 r qR8 00000250 r qS2 000002b0 r qS3 000001f0 r qS5 00000190 r qS8 00000218 t qzero U sin lib_a-e_j1.o: U __adddf3 U __divdf3 U __gtdf2 00000470 T __ieee754_j1 U __ieee754_log U __ieee754_sqrt 00000950 T __ieee754_y1 U __muldf3 U __subdf3 U cos U fabs 00000004 t pone 000000b0 r pr2 00000108 r pr3 00000058 r pr5 00000000 r pr8 000000e0 r ps2 00000138 r ps3 00000088 r ps5 00000030 r ps8 00000218 t qone 00000220 r qr2 00000280 r qr3 000001c0 r qr5 00000160 r qr8 00000250 r qs2 000002b0 r qs3 000001f0 r qs5 00000190 r qs8 U sin lib_a-e_jn.o: U __adddf3 U __divdf3 U __floatsidf U __gedf2 U __gtdf2 U __ieee754_j0 U __ieee754_j1 00000434 T __ieee754_jn U __ieee754_log U __ieee754_sqrt U __ieee754_y0 U __ieee754_y1 00000000 T __ieee754_yn U __ltdf2 U __muldf3 U __subdf3 U cos U fabs U sin lib_a-e_sinh.o: U __adddf3 U __divdf3 U __gtdf2 U __ieee754_exp 00000000 T __ieee754_sinh U __muldf3 U __subdf3 U expm1 U fabs lib_a-ef_asin.o: U __addsf3 U __divsf3 U __gtsf2 00000000 T __ieee754_asinf U __ieee754_sqrtf U __mulsf3 U __subsf3 U fabsf lib_a-ef_j0.o: U __addsf3 U __divsf3 U __gtsf2 0000035c T __ieee754_j0f U __ieee754_logf U __ieee754_sqrtf 000006cc T __ieee754_y0f U __ltsf2 U __mulsf3 U __subsf3 U cosf U fabsf 00000058 r pR2 00000084 r pR3 0000002c r pR5 00000000 r pR8 00000070 r pS2 0000009c r pS3 00000044 r pS5 00000018 r pS8 00000004 t pzerof 00000110 r qR2 00000140 r qR3 000000e0 r qR5 000000b0 r qR8 00000128 r qS2 00000158 r qS3 000000f8 r qS5 000000c8 r qS8 000001a0 t qzerof U sinf lib_a-ef_j1.o: U __addsf3 U __divsf3 U __gtsf2 0000031c T __ieee754_j1f U __ieee754_logf U __ieee754_sqrtf 0000062c T __ieee754_y1f U __mulsf3 U __subsf3 U cosf U fabsf 00000004 t ponef 00000058 r pr2 00000084 r pr3 0000002c r pr5 00000000 r pr8 00000070 r ps2 0000009c r ps3 00000044 r ps5 00000018 r ps8 000001a0 t qonef 000000b0 r qr2 000000e0 r qr8 000000c8 r qs2 000000f8 r qs8 U sinf lib_a-ef_sinh.o: U __addsf3 U __divsf3 U __gtsf2 U __ieee754_expf 00000000 T __ieee754_sinhf U __mulsf3 U __subsf3 U expm1f U fabsf lib_a-er_lgamma.o: U __adddf3 U __divdf3 U __eqdf2 U __fixdfsi U __floatsidf 00000004 T __ieee754_lgamma_r U __ieee754_log U __kernel_cos U __kernel_sin U __ltdf2 U __muldf3 U __nedf2 U __subdf3 U fabs U floor lib_a-erf_lgamma.o: U __addsf3 U __divsf3 U __eqsf2 U __fixsfsi U __floatsisf 00000004 T __ieee754_lgammaf_r U __ieee754_logf U __kernel_cosf U __kernel_sinf U __ltsf2 U __mulsf3 U __nesf2 U __subsf3 U fabsf U floorf lib_a-k_sin.o: U __adddf3 U __fixdfsi 00000000 T __kernel_sin U __muldf3 U __subdf3 lib_a-kf_sin.o: U __addsf3 U __fixsfsi 00000000 T __kernel_sinf U __mulsf3 U __subsf3 lib_a-s_asinh.o: U __adddf3 U __divdf3 U __gtdf2 U __ieee754_log U __ieee754_sqrt U __muldf3 00000000 T asinh U fabs U log1p lib_a-s_cos.o: U __ieee754_rem_pio2 U __kernel_cos U __kernel_sin U __subdf3 00000000 T cos lib_a-s_isinf.o: 00000000 T isinf lib_a-s_isinfd.o: 00000000 T __isinfd lib_a-s_sin.o: U __ieee754_rem_pio2 U __kernel_cos U __kernel_sin U __subdf3 00000000 T sin lib_a-sf_asinh.o: U __addsf3 U __divsf3 U __gtsf2 U __ieee754_logf U __ieee754_sqrtf U __mulsf3 00000000 T asinhf U fabsf U log1pf lib_a-sf_cos.o: U __ieee754_rem_pio2f U __kernel_cosf U __kernel_sinf U __subsf3 00000000 T cosf lib_a-sf_isinf.o: 00000000 T isinff lib_a-sf_isinff.o: 00000000 T __isinff lib_a-sf_sin.o: U __ieee754_rem_pio2f U __kernel_cosf U __kernel_sinf U __subsf3 00000000 T sinf lib_a-w_asin.o: U __errno U __fdlib_version U __gtdf2 U __ieee754_asin U __isnand 00000004 T asin U fabs U matherr U nan lib_a-w_sincos.o: U cos U sin 00000000 T sincos lib_a-w_sinh.o: U __errno U __fdlib_version U __gtdf2 U __ieee754_sinh U finite U matherr 00000004 T sinh lib_a-wf_asin.o: U __errno U __extendsfdf2 U __fdlib_version U __gtsf2 U __ieee754_asinf U __truncdfsf2 00000004 T asinf U fabsf U isnanf U matherr U nan lib_a-wf_sincos.o: U cosf 00000000 T sincosf U sinf lib_a-wf_sinh.o: U __errno U __extendsfdf2 U __fdlib_version U __gtsf2 U __ieee754_sinhf U __truncdfsf2 U finitef U matherr 00000004 T sinhf </code></pre> <p><em><strong>EDIT1:</em></strong> I tested some more and the problem is as follows (not what I originally stated above):</p> <pre><code>double aa; double bb = 1.0; double cc; aa = sin(1.0); cc = sin (bb); </code></pre> <p>What happens when I try to build is that I get a '<em>undefined reference</em>' at the last line, meaning that when I use constants it is fine, but when I pass variables to the sin functions it will not link. I also tested many of the other math function and I´ll get the exact same linker issue. As soon as I pass a variable to a math function I can not link any more. any ideas?</p>
31,351,654
4
14
null
2011-06-30 11:44:22.773 UTC
4
2016-09-27 09:37:12.653 UTC
2011-07-01 14:53:31.03 UTC
null
576,671
null
576,671
null
1
12
c|math|gcc|embedded|newlib
39,853
<p>The linker isn't complaining about <code>pow((double) 2, (double) 3)</code> because the compiler is replacing it with a constant <code>8.0</code>. You shouldn't depend on this behavior; instead, you should always use the <code>-lm</code> option properly. (BTW, that's more clearly written as <code>pow(2.0, 3.0)</code>.</p> <p>Consider the following program:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int main(void) { double x = 0.1; printf("%g\n", pow(2.0, 3.0)); printf("%g\n", asin(x)); return 0; } </code></pre> <p>When I compile and link it on my system using</p> <pre><code>gcc c.c -o c </code></pre> <p>I get:</p> <pre><code>/tmp/ccXx8ZRL.o: In function `main': c.c:(.text+0x36): undefined reference to `asin' collect2: ld returned 1 exit status </code></pre> <p>Note that it complains about <code>asin</code> but not about <code>pow</code>.</p> <p>If I change the <code>pow</code> call to <code>pow(x, 3.0)</code>, I get:</p> <pre><code>/tmp/ccOeSaBK.o: In function `main': c.c:(.text+0x24): undefined reference to `pow' c.c:(.text+0x52): undefined reference to `asin' collect2: ld returned 1 exit status </code></pre> <p>Normally if you want to call a standard math library function, you need to have <code>#include &lt;math.h&gt;</code> at the top of the source file (I presume you already have that) <em>and</em> you need to pass the <code>-lm</code> option to the compiler <em>after</em> the file that needs it. (The linker keeps track of references that haven't been resolved yet, so it needs to see the object file that refers to <code>asin</code> first, so it can resolve it when it sees the math library.)</p> <p>The linker isn't complaining about the call to <code>pow(2.0, 3.0)</code> because gcc is clever enough to resolve it to a constant <code>8.0</code>. There's no call to the <code>pow</code> function in the compiled object file, so the linker doesn't need to resolve it. If I change <code>pow(2.0, 3.0)</code> to <code>pow(x, 3.0)</code>, the compiler doesn't know what the result is going to be, so it generates the call.</p>
6,387,238
What does "javax.naming.NoInitialContextException" mean?
<p>As the title suggests, what does "javax.naming.NoInitialContextException" mean in non technical terms? And what are some general suggestions to fix it?</p> <p>EDIT (From the console):</p> <pre><code>javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288) at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325) at javax.naming.InitialContext.lookup(InitialContext.java:392) at cepars.app.ConnectionHelper.getConnection(ConnectionHelper.java:25) at cepars.app.ConnectionHelper.getConnection(ConnectionHelper.java:10) at cepars.review.ReviewDAO.getJobList(ReviewDAO.java:30) at cepars.review.Test.main(Test.java:43) java.lang.NullPointerException at cepars.review.ReviewDAO.getJobList(ReviewDAO.java:31) at cepars.review.Test.main(Test.java:43) cepars.app.DAOException at cepars.review.ReviewDAO.getJobList(ReviewDAO.java:39) at cepars.review.Test.main(Test.java:43) </code></pre>
6,387,328
4
4
null
2011-06-17 14:20:50.533 UTC
2
2015-11-19 14:00:39.2 UTC
2015-11-19 14:00:39.2 UTC
null
3,885,376
null
713,898
null
1
21
java|jdbc|jndi
115,026
<p>It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,</p> <blockquote> <p>This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.</p> </blockquote> <p>And if you dutifully have a look at the javadocs for <a href="http://download.oracle.com/javase/6/docs/api/javax/naming/InitialContext.html">InitialContext</a>, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.</p> <p>If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.</p>
18,236,048
Combining concatenate and if in Excel formulas
<p>How would I add the <code>IF(ISBLANK</code> formula to this formula </p> <pre><code>=CONCATENATE(TEXT('Unapplied Report'!A5,"0000"),TEXT('Unapplied Report'!C5,"000"),TEXT('Unapplied Report'!D5,"0000")) </code></pre> <p>without getting any errors. I've tried it a couple times and just get formula error messages.</p>
18,236,826
2
3
null
2013-08-14 15:33:28.247 UTC
null
2014-09-10 12:16:21.703 UTC
2014-09-10 12:16:21.703 UTC
null
1,578,604
null
2,619,327
null
1
3
excel|excel-2007|excel-formula
57,482
<p>Maybe you're looking for this instead?</p> <pre><code>=CONCATENATE(IF(ISBLANK('Unapplied Report'!A5),"",TEXT('Unapplied Report'!A5,"0000")), IF(ISBLANK('Unapplied Report'!C5),"",TEXT('Unapplied Report'!C5,"000")), IF(ISBLANK('Unapplied Report'!D5),"",TEXT('Unapplied Report'!D5,"0000"))) </code></pre> <p>This will concatenate only those cells that are not blank.</p>
15,845,241
TypeError: bad operand type for unary -: 'str'
<p>I've got a problem with Python 2.7.3-32bits on Windows. I put this code to see if anyone can help me out with this error. The comments are in Spanish but it don't affect the code.</p> <pre><code> import gtk import numpy import math import os #Pedimos el nombre de la imagen de origen nombreFich = input("Por favor, introduzca el nombre de la imagen de origen:") #Validar que existe el fichero imagen1 = gtk.Image() imagen1.set_from_file('C:\\Users\\xxx\\Desktop\\xxxx.png') pb1 = imagen1.get_pixbuf() pm1 = pb1.get_pixels_array() #Hacemos una copia de la imagen pm2 = pm1.copy() #Validamos los puntos de distorsion hasta que sean validos puntos = " " arrayPuntos = " " while(puntos == " " and len(arrayPuntos) &lt; 4): print"Por favor, introduzca los puntos de distorsión xc yc r e:" puntos= raw_input() arrayPuntos = puntos.split(" ") #Sacamos los puntos separando la cadena por el caracter espacio xc =(puntos[0]) yc =(puntos[1]) r =(puntos[2]) e =(puntos[3]) #función que calcula el grado de distorsión def grado(self,z,e): if(z&gt;1): return 1 elif(e&lt;0): return (1/z)**(-e/(1-e)) else: return z**e #Distorsionamos la imagen def distors(xc,yc,r,e,x,y): d = math.sqrt(x**2+y**2)#Sacamos la distancia z = d/r if(z!=0): g=grado(z,e) xm=x*g ym=y*g return xm,ym else: xm=x ym=y return xm,ym def recorrido (pm1, xc, yc, r, e): pm2 = pm1.copy() x= str(--r) y= str(--r) while (y &lt;= r): while (x &lt;= r): xm, ym = mover(xc, yc, r, e, x, y) pm2[yc+y][xc+x] = pm1[yc+ym][xc+xm] x = x+1 y= y+1 x= -r return pm2 pm2 = recorrido(pm1, xc, yc, r, e) #Guardamos los cambios pb2 = gtk.gdk.pixbuf_new_from_array(pm2,pb1.get_colorspace(),pb1.get_bits_per_sample()) nomfich2 = nombreFich+"_copia" ext = os.path.splitext("C:\\Users\xxx\Desktop\xxxx.png_copia")[1][1:].lower() pb2.save("C:\\Users\xxx\Desktop\xxxx.png_copia",ext) print"FINISH" </code></pre> <p>When I run the python code I get the following error:</p> <pre><code> Traceback (most recent call last): File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 71, in &lt;module&gt; pm2 = recorrido(pm1, xc, yc, r, e) File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 59, in recorrido x= str(--r) TypeError: bad operand type for unary -: 'str' </code></pre>
15,845,315
2
0
null
2013-04-05 23:32:26.633 UTC
4
2017-08-24 18:51:51.197 UTC
2017-08-24 18:51:51.197 UTC
null
1,391,441
null
2,250,977
null
1
7
python|string|python-2.7|typeerror
71,316
<p>The error message is telling you that <code>r</code> is a string. You can't negate a string.</p> <p>Why is it a string? Well, it seems to come from here:</p> <pre><code># ... puntos= raw_input() arrayPuntos = puntos.split(" ") # ... r =(puntos[2]) </code></pre> <p>The <code>split</code> method on a string returns a list of strings.</p> <p>So, how do you solve this? Well, if <code>r</code> is, say, the string "22", then <code>float(r)</code> is the float <code>22.0</code>, and <code>int(r)</code> is the integer <code>22</code>. One of those is probably what you want.</p> <p>Once you add, say, <code>r=int(r)</code>, your <code>--r</code> will no longer be an exception.</p> <hr> <p>But it probably isn't what you want. In Python, <code>--r</code> just means the negation of the negation of <code>r</code>—in other words, it's the same as <code>-(-(r))</code>, which is just <code>r</code>. You're probably looking for the equivalent of the C prefix operator<code>--</code>, which decrements the variable and returns the new value. There is no such operator in Python; in fact, there are no operators that modify a variable and then return the value.</p> <p>This is part of a larger issue. Python is designed to make statements and expressions as distinct as possible, to avoid confusion. C is designed to make as many things as possible expressions, to save typing. So, you often can't just translate one into the other line by line.</p> <p>In this case, you have to do it in two steps, as Thanasis Petsas shows:</p> <pre><code>r -= 1 x = str(r) </code></pre>
40,075,065
Using Docker I get the error: "SQLSTATE[HY000] [2002] No such file or directory"
<p>I'm using Docker to create a container to test my web app built on PHP and MySQL on my Mac. My PHP app is built using Fat-Free Framework for MVC and routing. I have two Dockerfiles, one for MySQL and one for PHP. I've used test Docker applications successfully, so I believe my images are installed correctly.</p> <p>The main part of the error:</p> <pre><code>Internal Server Error SQLSTATE[HY000] [2002] No such file or directory [fatfree/lib/DB/SQL.php:466] PDO-&gt;__construct('mysql:host=127.0.0.1;port=3306;dbname=robohome','root','password',array(1002=&gt;'SET NAMES utf8;')) [fatfree/app/Controllers/Controller.php:24] DB\SQL-&gt;__construct('mysql:host=127.0.0.1;port=3306;dbname=robohome','root','password') </code></pre> <p>Note, if I connect using <code>127.0.0.1</code> instead of <code>localhost</code> I get a slightly different error that says: <code>SQLSTATE[HY000] [2002] Connection refused</code></p> <p>My PHP Dockerfile:</p> <pre><code>FROM php:5.6-apache RUN docker-php-ext-install mysqli pdo pdo_mysql RUN a2enmod rewrite </code></pre> <p>My MySQL Dockerfile:</p> <pre><code>FROM mysql:5.7 ENV MYSQL_ROOT_PASSWORD password ENV MYSQL_DATABASE robohome COPY ./schema.sql /docker-entrypoint-initdb.d/ </code></pre> <p>My <code>Controller.php</code> file where the error mentions line 24:</p> <pre><code>&lt;?php namespace Controllers; class Controller { protected $f3; protected $db; public function __construct() { $f3 = \Base::instance(); $this-&gt;f3 = $f3; $mysqlServerName = $f3-&gt;get("MYSQL_SERVERNAME"); $mysqlDatabseName = $f3-&gt;get("MYSQL_DBNAME"); //$container = \DI\ContainerBuilder::buildDevContainer(); &lt;-Not used currently //Below is line 24 referred to in the error $db = new \DB\SQL( "mysql:host={$mysqlServerName};port=3306;dbname={$mysqlDatabseName}", $f3-&gt;get("MYSQL_USERNAME"), $f3-&gt;get("MYSQL_PASSWORD") ); $this-&gt;db = $db; } </code></pre> <p>Those <code>MYSQL_*</code> values are pulled from an <code>.ini</code> file:</p> <pre><code>MYSQL_SERVERNAME = "localhost" &lt;-This is what I've tried changing to 127.0.0.1 MYSQL_USERNAME = "root" MYSQL_PASSWORD = "password" MYSQL_DBNAME = "robohome" </code></pre> <p>My Docker compose file:</p> <pre><code>version: '2' services: web: build: ./docker/php ports: - 80:80 volumes: - .:/var/www/html/ links: - db db: build: ./docker/mysql ports: - 3306 </code></pre> <p>I run this by doing <code>docker-compose up --build -d</code>. The output I can then get from <code>docker ps</code> is:</p> <pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f35066a16586 robohomeweb_mysql "docker-entrypoint.sh" 3 minutes ago Up 2 seconds 0.0.0.0:32777-&gt;3306/tcp robohomeweb_mysql_1 86d34eb34583 robohomeweb_php "apache2-foreground" 3 minutes ago Up 2 seconds 0.0.0.0:80-&gt;80/tcp robohomeweb_php_1 </code></pre> <p>If I run in the foreground instead, I get the following output:</p> <pre><code>Building php Step 1 : FROM php:5.6-apache ---&gt; 8f9b7e57129a Step 2 : RUN docker-php-ext-install mysqli pdo pdo_mysql ---&gt; Using cache ---&gt; fadd8f9e7207 Step 3 : RUN a2enmod rewrite ---&gt; Using cache ---&gt; 9dfed7fdc60f Successfully built 9dfed7fdc60f Building mysql Step 1 : FROM mysql:5.7 ---&gt; eda6a4884645 Step 2 : ENV MYSQL_ROOT_PASSWORD password ---&gt; Using cache ---&gt; 759895ac5772 Step 3 : ENV MYSQL_DATABASE robohome ---&gt; Using cache ---&gt; e926c5ecc088 Step 4 : COPY ./schema.sql /docker-entrypoint-initdb.d/ ---&gt; Using cache ---&gt; cf5d00aa8020 Successfully built cf5d00aa8020 Starting robohomeweb_php_1 Starting robohomeweb_mysql_1 Attaching to robohomeweb_mysql_1, robohomeweb_php_1 php_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message php_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message php_1 | [Sun Oct 16 20:21:17.944575 2016] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.10 (Debian) PHP/5.6.26 configured -- resuming normal operations php_1 | [Sun Oct 16 20:21:17.946919 2016] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND' mysql_1 | 2016-10-16T20:21:18.036272Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). mysql_1 | 2016-10-16T20:21:18.038330Z 0 [Note] mysqld (mysqld 5.7.16) starting as process 1 ... mysql_1 | 2016-10-16T20:21:18.043331Z 0 [Note] InnoDB: PUNCH HOLE support available mysql_1 | 2016-10-16T20:21:18.043603Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins mysql_1 | 2016-10-16T20:21:18.043951Z 0 [Note] InnoDB: Uses event mutexes mysql_1 | 2016-10-16T20:21:18.044077Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier mysql_1 | 2016-10-16T20:21:18.044260Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 mysql_1 | 2016-10-16T20:21:18.044414Z 0 [Note] InnoDB: Using Linux native AIO mysql_1 | 2016-10-16T20:21:18.045150Z 0 [Note] InnoDB: Number of pools: 1 mysql_1 | 2016-10-16T20:21:18.045620Z 0 [Note] InnoDB: Using CPU crc32 instructions mysql_1 | 2016-10-16T20:21:18.047629Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M mysql_1 | 2016-10-16T20:21:18.057705Z 0 [Note] InnoDB: Completed initialization of buffer pool mysql_1 | 2016-10-16T20:21:18.059988Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority(). mysql_1 | 2016-10-16T20:21:18.074670Z 0 [Note] InnoDB: Highest supported file format is Barracuda. mysql_1 | 2016-10-16T20:21:18.101209Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables mysql_1 | 2016-10-16T20:21:18.101433Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ... mysql_1 | 2016-10-16T20:21:18.354806Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB. mysql_1 | 2016-10-16T20:21:18.356928Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active. mysql_1 | 2016-10-16T20:21:18.357158Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active. mysql_1 | 2016-10-16T20:21:18.358049Z 0 [Note] InnoDB: Waiting for purge to start mysql_1 | 2016-10-16T20:21:18.412987Z 0 [Note] InnoDB: 5.7.16 started; log sequence number 12179647 mysql_1 | 2016-10-16T20:21:18.414470Z 0 [Note] Plugin 'FEDERATED' is disabled. mysql_1 | 2016-10-16T20:21:18.421833Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool mysql_1 | 2016-10-16T20:21:18.424144Z 0 [Note] InnoDB: Buffer pool(s) load completed at 161016 20:21:18 mysql_1 | 2016-10-16T20:21:18.425607Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key mysql_1 | 2016-10-16T20:21:18.427018Z 0 [Note] Server hostname (bind-address): '*'; port: 3306 mysql_1 | 2016-10-16T20:21:18.427581Z 0 [Note] IPv6 is available. mysql_1 | 2016-10-16T20:21:18.427749Z 0 [Note] - '::' resolves to '::'; mysql_1 | 2016-10-16T20:21:18.428019Z 0 [Note] Server socket created on IP: '::'. mysql_1 | 2016-10-16T20:21:18.456023Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. mysql_1 | 2016-10-16T20:21:18.456354Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. mysql_1 | 2016-10-16T20:21:18.480237Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. mysql_1 | 2016-10-16T20:21:18.488758Z 0 [Note] Event Scheduler: Loaded 0 events mysql_1 | 2016-10-16T20:21:18.490880Z 0 [Note] mysqld: ready for connections. mysql_1 | Version: '5.7.16' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) </code></pre> <p>From my research, I've tried connecting using both <code>localhost</code> and <code>127.0.0.1</code> since they're technically treated differently. It could also be something related to trying to talk via sockets instead of TCP. Ideally I would like a solution that I can bake into my Dockerfiles so I don't have to worry about remembering commands or how I did something.</p>
40,077,166
5
3
null
2016-10-16 20:23:47.837 UTC
18
2022-09-05 23:36:01.897 UTC
2016-10-16 22:34:51.623 UTC
null
1,595,510
null
1,595,510
null
1
54
php|mysql|docker|docker-compose|dockerfile
67,532
<p>As someone pointed out in the comments, the docker-compose file you provided is very relevant to your question.</p> <p>The documentation for <a href="https://docs.docker.com/compose/compose-file/#links" rel="noreferrer"><code>links</code></a> in docker-compose files says</p> <blockquote> <p>Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.</p> </blockquote> <p>In your case, the database container is named <code>db</code>, so resolving <code>db</code> host from the PHP container should point you at the MySQL container. Replacing <code>localhost</code> with <code>db</code> in your config file should allow the PHP container to connect to MySQL.</p>
4,862,327
Is there a way to get the filename from a `FILE*`?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1188757/getting-filename-from-file-descriptor-in-c">Getting Filename from file descriptor in C</a> </p> </blockquote> <p>Is there a simple and (reasonably) portable way of getting the filename from a <code>FILE*</code>?</p> <p>I open a file using <code>f = fopen(filename, ...)</code> and then pass down <code>f</code> to various other functions, some of which may report an error. I'd like to report the filename in the error message but avoid having to pass around the extra parameter.</p> <p>I could create a custom wrapper <code>struct { FILE *f, const char *name }</code>, but is there perhaps a simpler way? (If the <code>FILE*</code> wasn't opened using <code>fopen</code> I don't care about the result.)</p>
4,862,476
2
9
null
2011-02-01 12:06:27.457 UTC
6
2012-11-21 16:04:57.397 UTC
2017-05-23 12:18:10.91 UTC
null
-1
null
73,706
null
1
16
c
38,854
<p>On some platforms (such as Linux), you may be able to fetch it by reading the link of <code>/proc/self/fd/&lt;number&gt;</code>, as so:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; int main(void) { char path[1024]; char result[1024]; /* Open a file, get the file descriptor. */ FILE *f = fopen("/etc/passwd", "r"); int fd = fileno(f); /* Read out the link to our file descriptor. */ sprintf(path, "/proc/self/fd/%d", fd); memset(result, 0, sizeof(result)); readlink(path, result, sizeof(result)-1); /* Print the result. */ printf("%s\n", result); } </code></pre> <p>This will, on my system, print out <code>/etc/passwd</code>, as desired.</p>
5,435,578
Get querystring from URLReferrer
<p>I am trying to get the QueryString value like this <code>Request.QueryString("SYSTEM")</code> from a UrlReferrer. I see i can use this <code>Request.UrlReferrer.Query()</code> but it doesn't allow me to specify the exact parameter </p> <p>I could parse the Query() value, but I want to know if it is possible to do something like this <code>Request.UrlReferrer.QueryString("SYSTEM")</code></p>
5,435,673
2
0
null
2011-03-25 16:53:32.54 UTC
null
2015-06-29 14:57:44.887 UTC
2013-10-11 04:20:04.293 UTC
null
168,868
null
618,186
null
1
29
asp.net|vb.net|query-string|http-referer|request.querystring
26,958
<p>You could do </p> <pre><code>HttpUtility.ParseQueryString(Request.UrlReferrer.Query)["SYSTEM"] </code></pre> <p>That is c# in vb is is probably something like</p> <pre><code>HttpUtility.ParseQueryString(Request.UrlReferrer.Query())("SYSTEM") </code></pre>
753,140
How do I determine if two convex polygons intersect?
<p>Suppose there are a number of convex polygons on a plane, perhaps a map. These polygons can bump up against each other and share an edge, but cannot overlap.</p> <p><img src="https://i.stack.imgur.com/AkGPs.jpg" alt="alt text"></p> <p>To test if two polygons <strong>P</strong> and <strong>Q</strong> overlap, first I can test each edge in <strong>P</strong> to see if it intersects with any of the edges in <strong>Q</strong>. If an intersection is found, I declare that <strong>P</strong> and <strong>Q</strong> intersect. If none intersect, I then have to test for the case that <strong>P</strong> is completely contained by <strong>Q</strong>, and vice versa. Next, there's the case that <strong>P</strong>==<strong>Q</strong>. Finally, there's the case that share a few edges, but not all of them. (These last two cases can probably be thought of as the same general case, but that might not be important.)</p> <p>I have an algorithm that detects where two line segments intersect. If the two segments are co-linear, they are not considered to intersect for my purposes.</p> <p>Have I properly enumerated the cases? Any suggestions for testing for these cases?</p> <p>Note that I'm not looking to find the new convex polygon that is the intersection, I just want to know if an intersection exists. There are many well documented algorithms for finding the intersection, but I don't need to go through all the effort.</p>
753,214
7
1
null
2009-04-15 18:49:42.167 UTC
9
2017-11-29 21:16:34.497 UTC
2017-06-15 11:54:06.893 UTC
null
5,769,497
null
6,688
null
1
22
geometry|polygon|convex
46,222
<p>You could use <a href="http://web.archive.org/web/20141127210836/http://content.gpwiki.org/index.php/Polygon_Collision" rel="noreferrer">this collision algorithm</a>:</p> <blockquote> <p>To be able to decide whether two convex polygons are intersecting (touching each other) we can use the Separating Axis Theorem. Essentially:</p> <ul> <li>If two convex polygons are not intersecting, there exists a line that passes between them.</li> <li>Such a line only exists if one of the sides of one of the polygons forms such a line.</li> </ul> <p>The first statement is easy. Since the polygons are both convex, you'll be able to draw a line with one polygon on one side and the other polygon on the other side unless they are intersecting. The second is slightly less intuitive. Look at figure 1. Unless the closest sided of the polygons are parallel to each other, the point where they get closest to each other is the point where a corner of one polygon gets closest to a side of the other polygon. This side will then form a separating axis between the polygons. If the sides are parallel, they both are separating axes.</p> <p><img src="https://i.stack.imgur.com/8YZ54.png" alt=""></p> <p>So how does this concretely help us decide whether polygon A and B intersect? Well, we just go over each side of each polygon and check whether it forms a separating axis. To do this we'll be using some basic vector math to squash all the points of both polygons onto a line that is perpendicular to the potential separating line (see figure 2). Now the whole problem is conveniently 1-dimensional. We can determine a region in which the points for each polygon lie, and this line is a separating axis if these regions do not overlap.</p> <p><img src="https://i.stack.imgur.com/CNeSx.png" alt=""></p> <p>If, after checking each line from both polygons, no separating axis was found, it has been proven that the polygons intersect and something has to be done about it.</p> </blockquote>
193,438
What is a free tool to compare two SQL Server Databases?
<p>What is a free tool to compare two Sql Server tables (data and schema). </p> <p>It would be great if the tool can script the differences found.</p> <p>I also went through some older <a href="https://stackoverflow.com/questions/176316/compare-tools-to-generate-update-script-for-sql-server">posts</a>. The closest I have seen is <a href="http://sqldbtools.com/" rel="noreferrer">SQLDBDiff</a> but I would love to try more options.</p>
193,443
7
5
null
2008-10-11 00:13:11.063 UTC
27
2014-06-18 20:52:19.76 UTC
2017-05-23 11:46:54.377 UTC
Kevin Fairchild
-1
George
26,994
null
1
55
sql-server
83,618
<p>TableDiff.exe should have everything you need. It is one of the <a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx" rel="noreferrer">hidden gems in SQL Server 2005</a>. So you don't have to download anything.</p> <p>• Table Difference tool allows you to discover and reconcile differences between a source and destination table or a view. Tablediff Utility can report differences on schema and data. The most popular feature of tablediff is the fact that it can generate a script that you can run on the destination that will reconcile differences between the tables. TableDiff.exe takes 2 sets of input; • Connectivity - Provide source and destination objects and connectivity information. </p> <p>• Compare Options - Select one of the compare options • Compare schemas: Regular or Strict</p> <p>• Compare using Rowcounts, Hashes or Column comparisons</p> <p>• Generate difference scripts with I/U/D statements to synchronize destination to the source. TableDiff was intended for replication but can easily apply to any scenario where you need to compare data and schema. You can find more information about command line utilities and the Tablediff Utility in Books Online for SQL Server 2005.</p>
1,032,827
Select All Checkboxes By ID/Class
<p>I'm really bad at Javascript and I'm struggling to get my head round it.</p> <p>What I'm trying to do is get something to select all checkboxes. However everything I have found tries to do it by name, I want to do it by ID or class. Select all by name is just inpractical isn't it?</p>
1,032,859
8
0
null
2009-06-23 14:16:09.517 UTC
4
2018-08-22 00:15:51.257 UTC
2009-06-23 14:22:33.687 UTC
null
125,790
null
111,669
null
1
18
javascript
40,036
<p>Using <a href="http://www.jquery.com" rel="noreferrer">JQuery</a>, you can do this very easilly!</p> <pre><code>$(".ClassName").attr("checked", "true"); </code></pre> <p>or a single ID</p> <pre><code>$("#ID").attr("checked", "true"); </code></pre> <p>See: <a href="http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery" rel="noreferrer">Check All Checkboxes with JQuery</a>.</p>
666,601
What is the correct way of reading from a TCP socket in C/C++?
<p>Here's my code:</p> <pre><code>// Not all headers are relevant to the code snippet. #include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;netdb.h&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;unistd.h&gt; char *buffer; stringstream readStream; bool readData = true; while (readData) { cout &lt;&lt; "Receiving chunk... "; // Read a bit at a time, eventually "end" string will be received. bzero(buffer, BUFFER_SIZE); int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE); if (readResult &lt; 0) { THROW_VIMRID_EX("Could not read from socket."); } // Concatenate the received data to the existing data. readStream &lt;&lt; buffer; // Continue reading while end is not found. readData = readStream.str().find("end;") == string::npos; cout &lt;&lt; "Done (length: " &lt;&lt; readStream.str().length() &lt;&lt; ")" &lt;&lt; endl; } </code></pre> <p>It's a little bit of C and C++ as you can tell. The BUFFER_SIZE is 256 - should I just increase the size? If so, what to? Does it matter?</p> <p>I know that if "end" is not received for what ever reason, this will be an endless loop, which is bad - so if you could suggest a better way, please also do so.</p>
666,788
8
1
null
2009-03-20 15:21:31.48 UTC
26
2020-09-18 08:17:24.883 UTC
2009-03-22 21:24:50.717 UTC
Nick Bolton
47,775
Nick Bolton
47,775
null
1
42
c++|c|tcp
126,138
<p>Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.</p> <p>Assume that your header consist only of a 4 byte integer which denotes the length of the rest of your message. Then simply do the following.</p> <pre><code>// This assumes buffer is at least x bytes long, // and that the socket is blocking. void ReadXBytes(int socket, unsigned int x, void* buffer) { int bytesRead = 0; int result; while (bytesRead &lt; x) { result = read(socket, buffer + bytesRead, x - bytesRead); if (result &lt; 1 ) { // Throw your error. } bytesRead += result; } } </code></pre> <p>Then later in the code</p> <pre><code>unsigned int length = 0; char* buffer = 0; // we assume that sizeof(length) will return 4 here. ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&amp;length)); buffer = new char[length]; ReadXBytes(socketFileDescriptor, length, (void*)buffer); // Then process the data as needed. delete [] buffer; </code></pre> <p>This makes a few assumptions:</p> <ul> <li>ints are the same size on the sender and receiver.</li> <li>Endianess is the same on both the sender and receiver.</li> <li>You have control of the protocol on both sides</li> <li>When you send a message you can calculate the length up front.</li> </ul> <p>Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:</p> <pre><code>// These typedefs will vary across different platforms // such as linux, win32, OS/X etc, but the idea // is that a Int8 is always 8 bits, and a UInt32 is always // 32 bits regardless of the platform you are on. // These vary from compiler to compiler, so you have to // look them up in the compiler documentation. typedef char Int8; typedef short int Int16; typedef int Int32; typedef unsigned char UInt8; typedef unsigned short int UInt16; typedef unsigned int UInt32; </code></pre> <p>This would change the above to:</p> <pre><code>UInt32 length = 0; char* buffer = 0; ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&amp;length)); buffer = new char[length]; ReadXBytes(socketFileDescriptor, length, (void*)buffer); // process delete [] buffer; </code></pre> <p>I hope this helps.</p>
352,471
How do I create an immutable Class?
<p>I am working on creating an immutable class.<br> I have marked all the properties as read-only. </p> <p>I have a list of items in the class.<br> Although if the property is read-only the list can be modified. </p> <p>Exposing the IEnumerable of the list makes it immutable.<br> I wanted to know what is the basic rules one has to follow to make a class immutable ? </p>
352,493
8
4
null
2008-12-09 11:39:25.377 UTC
50
2020-11-11 21:02:55.19 UTC
2017-06-26 19:50:15.333 UTC
Biswanath
2,093,880
Biswanath
41,968
null
1
125
c#|.net|immutability
58,633
<p>I think you're on the right track -</p> <ul> <li>all information injected into the class should be supplied in the constructor</li> <li>all properties should be getters only</li> <li>if a collection (or Array) is passed into the constructor, it should be copied to keep the caller from modifying it later</li> <li>if you're going to return your collection, either return a copy or a read-only version (for example, using <a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.readonly.aspx" rel="noreferrer">ArrayList.ReadOnly</a> or similar - you can combine this with the previous point and <em>store</em> a read-only copy to be returned when callers access it), return an enumerator, or use some other method/property that allows read-only access into the collection</li> <li>keep in mind that you still may have the appearance of a mutable class if any of your members are mutable - if this is the case, you should copy away whatever state you will want to retain and avoid returning entire mutable objects, unless you copy them before giving them back to the caller - another option is to return only immutable "sections" of the mutable object - thanks to @Brian Rasmussen for encouraging me to expand this point</li> </ul>
87,621
How do I map XML to C# objects
<p>I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created.</p> <p>One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use? </p>
87,641
9
0
null
2008-09-17 21:00:32.103 UTC
21
2014-09-16 22:02:44.28 UTC
2008-09-26 19:11:47.2 UTC
Chris
2,134
null
9,855
null
1
29
c#|xml|serialization|xml-serialization
67,369
<p>You can generate serializable C# classes from a schema (xsd) using xsd.exe:</p> <pre><code>xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir </code></pre> <p>If the schema has dependencies (included/imported schemas), they must all be included on the same command line.</p>
441,717
What's wrong with "magic"?
<p>I'm trying to decide whether to use a Rails or a Django guru to create a web app for me. I've been recommended to use Django because it uses less "magic". From my perspective however, the "magic" of Rails seems like a good thing since it could make development more concise for my contractor resulting in fewer billable hours at my expense. I understand the advantage of Django might be greater fine-grained control but how will I know if I need this control? Is there an inherent problem with "magic"?</p>
442,088
9
0
null
2009-01-14 02:31:02.887 UTC
5
2017-12-06 12:21:41.003 UTC
2009-01-14 02:34:24.017 UTC
Ignacio Vazquez-Abrams
20,862
Gosuda
null
null
1
36
ruby-on-rails|django|black-box
8,773
<p>Well, consider a couple bits of Rails "magic": when you write a controller class, its methods have access to certain variables and certain other classes. But these variables and classes were neither defined nor imported by anything in the file of Ruby code you're looking at; Rails has done a lot of work behind the scenes to ensure they'll just be there automatically. And when you return something from a controller method, Rails makes sure the result is passed along to the appropriate template; you don't have to write any code to tell it which template to use, where to find it, etc., etc.</p> <p>In other words, it's as if these things happen by "magic"; you don't have to lift a finger, they just happen for you.</p> <p>By contrast, when you write a Django view, you have to import or define anything you plan to use, and you have to tell it, explicitly, which template to use and what values the template should be able to access.</p> <p>Rails' developers are of the opinion that this sort of "magic" is a good thing because it makes it easier to quickly get something working, and doesn't bore you with lots of details unless you want to reach in and start overriding things.</p> <p>Django's developers are of the opinion that this sort of "magic" is a bad thing because doesn't really save all that much time (a few <code>import</code> statements isn't a big deal in the grand scheme of things), and has the effect of hiding what's really going on, making it harder to work out how to override stuff, or harder to debug if something goes wrong.</p> <p>Both of these are, of course, valid stances to take, and generally it seems that people just naturally gravitate to one or the other; those who like the "magic" congregate around Rails or frameworks which try to emulate it, those who don't congregate around Django or frameworks which try to emulate it (and, in a broader sense, these stances are somewhat stereotypical of Ruby and Python developers; Ruby developers tend to like doing things one way, Python developers tend to like doing things another way).</p> <p>In the long run, it probably doesn't make a huge difference for the factor you say you're concerned with -- billable hours -- so let your developer choose whatever he or she is most comfortable with, since that's more likely to get useful results for <em>you</em>.</p>
946,011
SQLite add Primary Key
<p>I created a table in Sqlite by using the <code>CREATE TABLE AS</code> syntax to create a table based on a <code>SELECT</code> statement. Now this table has no primary key but I would like to add one.</p> <p>Executing <code>ALTER TABLE table_name ADD PRIMARY KEY(col1, col2,...)</code> gives a syntax error "near PRIMARY"</p> <p>Is there a way to add a primary key either during table creation or afterwards in Sqlite?</p> <p>By "during creation" I mean during creation with <code>CREATE TABLE AS</code>.</p>
946,119
10
1
null
2009-06-03 17:25:38.387 UTC
16
2022-08-04 08:21:56.067 UTC
2020-02-24 15:54:05.437 UTC
null
832,230
null
61,663
null
1
115
sqlite
162,192
<p>You can't modify SQLite tables in any significant way after they have been created. The accepted suggested solution is to create a new table with the correct requirements and copy your data into it, then drop the old table.</p> <p>here is the official documentation about this: <a href="http://sqlite.org/faq.html#q11" rel="noreferrer">http://sqlite.org/faq.html#q11</a></p>
954,597
How can I learn _really_ low-level network programming?
<p>So I want to learn all about networks. Well below the socket, down to raw sockets and stuff. And I want to understand hubs, routers, access points, etc. For example, I'd like to be able to write my own software to do this kind of stuff.* Is there a great source for this kind of information?</p> <p>I know that I'm asking a LOT here, and that to fully explain it all requires from high level down to low level. I guess I'm looking for a source similar in scope and depth to <a href="http://www.schneier.com/book-applied.html" rel="noreferrer">Applied Cryptography</a>, but about networks.</p> <p>Thanks to anyone who can help to point me (and others like me?) in the right direction.</p> <p>* Yes, I realize using any of my hand-crafted network stack code would be a huge security issue, and am only looking to do it to learn :)</p> <p>Similar Question: <a href="https://stackoverflow.com/questions/124968/lower-than-low-level-common-bsd-sockets">here</a>. However I'm looking for more than just 'what's below TCP/UDP sockets?'.</p> <p>Edited for Clarification: The depth I'm talking about is above the driver level. So assuming that the bits can make it to and from the other end of the wire, what next?</p>
954,623
11
1
null
2009-06-05 07:09:02.3 UTC
17
2015-06-09 12:09:14.47 UTC
2017-05-23 12:09:12.153 UTC
null
-1
null
10,307
null
1
33
networking|network-programming|network-protocols
20,837
<p>I learned IP networking from <a href="https://rads.stackoverflow.com/amzn/click/com/0201633469" rel="noreferrer" rel="nofollow noreferrer">TCP/IP Illustrated</a>. Highly recommended.</p>
334,686
How can I detect the operating system in Perl?
<p>I have Perl on Mac, Windows and Ubuntu. How can I tell from within the script which one is which? Thanks in advance.</p> <p><strong>Edit:</strong> I was asked what I am doing. It is a script, part of our cross-platform build system. The script recurses directories and figures out what files to build. Some files are platform-specific, and thus, on Linux I don't want to build the files ending with _win.cpp, etc.</p>
334,700
11
1
null
2008-12-02 16:59:00.137 UTC
16
2022-08-12 15:14:07.343 UTC
2008-12-04 01:23:51.99 UTC
mxcl
6,444
mxcl
6,444
null
1
60
perl|cross-platform
69,582
<p>Examine the <a href="http://perldoc.perl.org/perlvar.html#%24OSNAME" rel="noreferrer"><code>$^O</code></a> variable which will contain the name of the operating system:</p> <pre><code>print &quot;$^O\n&quot;; </code></pre> <p>Which prints <code>linux</code> on Linux and <code>MSWin32</code> on Windows.</p> <p>You can also refer to this variable by the name <a href="http://perldoc.perl.org/perlvar.html#%24OSNAME" rel="noreferrer"><code>$OSNAME</code></a> if you use the <a href="http://perldoc.perl.org/English.html" rel="noreferrer">English</a> module:</p> <pre><code>use English qw' -no_match_vars '; print &quot;$OSNAME\n&quot;; </code></pre> <p>According to <a href="http://perldoc.perl.org/perlport.html" rel="noreferrer">perlport</a>, <a href="http://perldoc.perl.org/perlvar.html#%24OSNAME" rel="noreferrer"><code>$^O</code></a> will be <code>darwin</code> on Mac OS X.</p> <hr /> <p>You can also use the <a href="http://perldoc.perl.org/Config.html" rel="noreferrer">Config</a> core module, which can provide the same information (and a lot more):</p> <pre><code>use Config; print &quot;$Config{osname}\n&quot;; print &quot;$Config{archname}\n&quot;; </code></pre> <p>Which on my Ubuntu machine prints:</p> <pre><code>linux i486-linux-gnu-thread-multi </code></pre> <p>Note that this information is based on the system that Perl was <em>built</em>, which is not necessarily the system Perl is currently running on (the same is true for <a href="http://perldoc.perl.org/perlvar.html#%24OSNAME" rel="noreferrer"><code>$^O</code></a> and <a href="http://perldoc.perl.org/perlvar.html#%24OSNAME" rel="noreferrer"><code>$OSNAME</code></a>); the OS won't likely be different but some information, like the architecture name, may very well be.</p>
871,399
Cross-browser method for detecting the scrollTop of the browser window
<p>What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight.</p>
872,537
11
0
null
2009-05-16 01:01:08.393 UTC
25
2019-07-25 13:16:03.407 UTC
null
null
null
Hot Pastrami
null
null
1
63
javascript|cross-browser
67,739
<pre><code>function getScrollTop(){ if(typeof pageYOffset!= 'undefined'){ //most browsers except IE before #9 return pageYOffset; } else{ var B= document.body; //IE 'quirks' var D= document.documentElement; //IE with doctype D= (D.clientHeight)? D: B; return D.scrollTop; } } alert(getScrollTop()) </code></pre>
1,232,097
PHP - include a php file and also send query parameters
<p>I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.</p> <pre><code>if(condition here){ include "myFile.php?id='$someVar'"; } </code></pre> <p>Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.</p> <p>Can someone please tell me how to achieve this? Thanks.</p>
1,232,114
13
1
null
2009-08-05 09:22:33.557 UTC
13
2021-06-04 20:36:04.757 UTC
2011-07-31 14:08:59.74 UTC
null
635,608
null
46,297
null
1
95
php|parameters|include
186,108
<p>Imagine the include as what it is: A copy &amp; paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).</p>
377,393
ASP.NET RadioButton messing with the name (groupname)
<p>I got a templated control (a repeater) listing some text and other markup. Each item has a radiobutton associated with it, making it possible for the user to select ONE of the items created by the repeater.</p> <p>The repeater writes the radiobutton setting its id and name generated with the default ASP.NET naming convention making each radiobutton a full 'group'. This means all radiobuttons are independent on each other, which again unfortunately means I can select all radiobuttons at the same time. The radiobutton has the clever attribute 'groupname' used to set a common name, so they get grouped together and thus should be dependant (so I can only select one at a time). The problem is - this doesn't work - the repeater makes sure the id and thus the name (which controls the grouping) are different.</p> <p>Since I use a repeater (could have been a listview or any other templated databound control) I can't use the RadioButtonList. So where does that leave me?</p> <p>I know I've had this problem before and solved it. I know almost every ASP.NET programmer must have had it too, so why can't I google and find a solid solution to the problem? I came across solutions to enforce the grouping by JavaScript (ugly!) or even to handle the radiobuttons as non-server controls, forcing me to do a <code>Request.Form[name]</code> to read the status. I also tried experimenting with overriding the name attribute on the <code>PreRender</code> event - unfortunately the owning page and masterpage again overrides this name to reflect the full id/name, so I end up with the same wrong result.</p> <p>If you have no better solution than what I posted, you are still very welcome to post your thoughts - at least I'll know that my friend 'jack' is right about how messed up ASP.NET is sometimes ;)</p>
377,455
14
1
null
2008-12-18 09:50:21.21 UTC
11
2020-06-21 18:58:50.217 UTC
2011-08-03 21:00:39.87 UTC
null
63,550
Hojou
11,619
null
1
36
asp.net|radio-button
46,605
<p>Google-fu: <a href="http://www.google.se/search?q=asp.net+radiobutton+repeater+problem&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a" rel="nofollow noreferrer">asp.net radiobutton repeater problem</a></p> <p>Indeed an unfortunate consequence of the id mangling. My take would be creating a - or picking one of the many available - custom control that adds support for same name on the client.</p>
415,260
How do you find out what users really want?
<p>I've read somewhere (I forget the source, sorry - I think the MS Office developer's blog?), that when you do a survey of users asking them about what features they would like to see in your software/website, they will more often than not say that they want every little thing, whereas collected metrics show that in the end, most people don't use 99% of these features. The general message from the blog post was that you shouldn't ask people what they use, you should track it for yourself.</p> <p>This leads to an unfortunate chicken-and-egg situation when trying to figure out what new feature to add next. Without the feature already in place, I can't measure how much it's actually being used. With finite (and severely stretched) resources, I also can't afford to add all the features and then remove the unused ones.</p> <p><strong>How do you find out what will be useful to your users?</strong> If a survey is the only option, do you have to structure your questions in certain ways (eg: don't show a list of possible features, since that would be leading them on)?</p>
415,301
27
0
null
2009-01-06 02:40:03.893 UTC
12
2012-11-19 15:57:57.783 UTC
null
null
null
nickf
9,021
null
1
20
user-experience
1,280
<p>Contrary to popular belief, you <em>don't</em> ask them. Well, you don't listen to them when they <em>tell</em> you what they want. You watch them while they use what they have right now. If they don't have anything, you listen to them enough to give them a prototype, then you watch them use that. How a person actually <em>uses</em> software tells you a lot more than what they actually say they want. Watch what they do to find out what they really need.</p>
6,674,183
Storing hex color values in strings.xml
<p>I'm trying to store the <code>hex color</code> value of my text in strings.xml so all the layout files will refer to that (to be able to quickly change all layout text for the project easily) however I'm having trouble referring to it.</p> <p>Using <code>android:textColor="#FFFFFF"</code> in my xml layout works fine. However using <code>android:textColor="@strings/textColor"</code> gives me an error both when I include a # and not include. </p> <p>When I don't include the # it asks for the #. When I do add the # DDMS reports: </p> <blockquote> <p>07-13 04:35:22.870: ERROR/AndroidRuntime(331): Caused by: android.content.res.Resources$NotFoundException: File #FF0000 from drawable resource ID #0x7f040003: .xml extension required</p> </blockquote> <p>Does anyone know how I can combine statements in the layout file? eg <code>textColor="#"+"@strings/textColor</code> and then just set the string to <code>"FFFFFF"</code> for example.</p>
6,674,241
5
0
null
2011-07-13 04:41:20.517 UTC
5
2015-01-20 11:38:54.35 UTC
2011-07-13 05:48:38.99 UTC
null
135,152
null
841,980
null
1
16
android|string|layout|hex
44,378
<p>You need to create a set of styles in your xml (regularly in res/values/styles.xml)</p> <pre><code>&lt;color name="gray"&gt;#eaeaea&lt;/color&gt; &lt;color name="titlebackgroundcolor"&gt;#00abd7&lt;/color&gt; &lt;color name="titlecolor"&gt;#666666&lt;/color&gt; </code></pre> <p>In the layout files you can call to the colors or styles:</p> <pre><code>android:textColor="@color/titlecolor" </code></pre> <p>Checkout some examples:</p> <p><a href="http://developer.android.com/guide/topics/ui/themes.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/themes.html</a></p>
6,368,206
Create multiple range slide handles in one slider
<p>I am trying to add multiple handles to a jQuery UI slider widget, as in 2 or 3 or more range sliders in one slider.</p> <p>I have tried searching on google and found an article that shows how to modify it to have multiple handles but I need them to work as range sliders.</p> <p>Is there anyway to make this work?</p> <pre><code>$("#slider-range").slider({ range: true, min: 0, max: 1439, values: [540, 1020], animate: true, slide: slideTime }); </code></pre> <p>Thanks</p>
7,950,368
6
6
null
2011-06-16 07:00:31.467 UTC
3
2018-02-28 10:27:32.9 UTC
2011-06-16 07:18:29.26 UTC
null
63,523
null
621,331
null
1
14
javascript|jquery|jquery-ui
38,576
<p>Take a look at <a href="http://www.bacubacu.com/colresizable/#samples" rel="nofollow noreferrer">colResizable jQuery</a> plugin. It allows you to resize table columns and also to create multiple range sliders: </p>
6,561,194
Force a core to dump from an active, normally running program on FreeBSD
<p>I'm writing error handling code for a server on FreeBSD. For extremely serious errors I want to avoid data corruption by immediately terminating. That's easy, <code>exit(3)</code>. Before I exit, I output my relevant variables that led me there. However, ideally, this termination would be accompanied by a <code>.core</code> so that I could fully investigate what got me to this catastrophic (and likely hard to reproduce) state.</p> <p>How can I force this to happen?</p>
6,561,201
6
0
null
2011-07-03 05:05:54.863 UTC
4
2022-08-10 21:43:31.767 UTC
2018-10-01 21:40:24.923 UTC
null
3,204,551
null
361,312
null
1
30
freebsd|coredump
56,688
<p><code>kill -QUIT process_id</code> will cause a core dump from a running process (assuming that resource limits allow it).</p> <p>Or see <code>man 3 abort</code> for causing a program to dump itself.</p> <p><strong>Added</strong>: From an interactive shell, a running program can be made to abort with the quit key, usually <kbd>Ctrl</kbd>+<kbd>\</kbd>, which sends a SIGQUIT just as the more common <kbd>Ctrl</kbd>+<kbd>C</kbd> sends a SIGINT. This is identical to the <code>kill -QUIT…</code> it's just easier to type if you are on the controlling terminal. See <code>man 1 stty</code> if your default quit key is different.</p>
6,821,455
Empty ILookup<K, T>
<p>I have a method that returns an <code>ILookup</code>. In some cases I want to return an empty <code>ILookup</code> as an early exit. What is the best way of constructing an empty <code>ILookup</code>?</p>
6,821,853
8
1
null
2011-07-25 19:46:12.327 UTC
2
2020-07-17 08:43:06.143 UTC
2011-07-25 19:47:20.37 UTC
null
13,302
null
184,581
null
1
37
c#|.net|ilookup
10,906
<p>Further to the answers from <a href="https://stackoverflow.com/questions/6821455/empty-ilookupk-t/6821545#6821545">mquander</a> and <a href="https://stackoverflow.com/questions/6821455/empty-ilookupk-t/6821565#6821565">Vasile Bujac</a>, you could create a nice, straightforward singleton-esque <code>EmptyLookup&lt;K,E&gt;</code> class as follows. (In my opinion, there doesn't seem much benefit to creating a full <code>ILookup&lt;K,E&gt;</code> implementation as per Vasile's answer.)</p> <pre><code>var empty = EmptyLookup&lt;int, string&gt;.Instance; // ... public static class EmptyLookup&lt;TKey, TElement&gt; { private static readonly ILookup&lt;TKey, TElement&gt; _instance = Enumerable.Empty&lt;TElement&gt;().ToLookup(x =&gt; default(TKey)); public static ILookup&lt;TKey, TElement&gt; Instance { get { return _instance; } } } </code></pre>
6,503,189
Fragments onResume from back stack
<p>I'm using the compatibility package to use Fragments with Android 2.2. When using fragments, and adding transitions between them to the backstack, I'd like to achieve the same behavior of onResume of an activity, i.e., whenever a fragment is brought to "foreground" (visible to the user) after poping out of the backstack, I'd like some kind of callback to be activated within the fragment (to perform certain changes on a shared UI resource, for instance).</p> <p>I saw that there is no built in callback within the fragment framework. is there s a good practice in order to achieve this?</p>
6,505,060
12
3
null
2011-06-28 07:42:07.243 UTC
32
2017-03-07 13:09:29.28 UTC
2013-10-08 20:17:07.877 UTC
null
356,895
null
258,429
null
1
104
android|android-fragments|compatibility|android-3.0-honeycomb|back-stack
112,827
<p>For a lack of a better solution, I got this working for me: Assume I have 1 activity (MyActivity) and few fragments that replaces each other (only one is visible at a time).</p> <p>In MyActivity, add this listener:</p> <pre><code>getSupportFragmentManager().addOnBackStackChangedListener(getListener()); </code></pre> <p>(As you can see I'm using the compatibility package).</p> <p><strong>getListener implementation:</strong></p> <pre><code>private OnBackStackChangedListener getListener() { OnBackStackChangedListener result = new OnBackStackChangedListener() { public void onBackStackChanged() { FragmentManager manager = getSupportFragmentManager(); if (manager != null) { MyFragment currFrag = (MyFragment) manager.findFragmentById(R.id.fragmentItem); currFrag.onFragmentResume(); } } }; return result; } </code></pre> <p><code>MyFragment.onFragmentResume()</code> will be called after a "Back" is pressed. few caveats though:</p> <ol> <li>It assumes you added all transactions to the backstack (using <code>FragmentTransaction.addToBackStack()</code>)</li> <li>It will be activated upon each stack change (you can store other stuff in the back stack such as animation) so you might get multiple calls for the same instance of fragment.</li> </ol>
6,965,107
Converting between strings and ArrayBuffers
<p>Is there a commonly accepted technique for efficiently converting JavaScript strings to <a href="https://developer.mozilla.org/en/JavaScript_typed_arrays/ArrayBuffer">ArrayBuffers</a> and vice-versa? Specifically, I'd like to be able to write the contents of an ArrayBuffer to <code>localStorage</code> and to read it back.</p>
37,902,334
28
9
null
2011-08-06 06:01:24.087 UTC
116
2022-07-27 12:23:52.227 UTC
2016-04-11 20:03:12.783 UTC
null
3,853,934
null
100,335
null
1
393
javascript|serialization|arraybuffer|typed-arrays
554,350
<p><strong>Update 2016</strong> - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.</p> <h2>TextEncoder</h2> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder" rel="noreferrer"><code>TextEncoder</code> represents</a>:</p> <blockquote> <p>The <code>TextEncoder</code> interface represents an encoder for a specific method, that is a specific character encoding, like <code>utf-8</code>, <del><code>iso-8859-2</code>, <code>koi8</code>, <code>cp1261</code>, <code>gbk</code>, ...</del> An encoder takes a stream of code points as input and emits a stream of bytes.</p> </blockquote> <p><strong>Change note since the above was written:</strong> (ibid.)</p> <blockquote> <p>Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*</p> </blockquote> <p>*) <a href="https://www.w3.org/TR/encoding/#dom-textencoder" rel="noreferrer">Updated specs</a> (W3) and <a href="https://encoding.spec.whatwg.org/#interface-textencoder" rel="noreferrer">here</a> (whatwg).</p> <p>After creating an instance of the <code>TextEncoder</code> it will take a string and encode it using a given encoding parameter:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if (!("TextEncoder" in window)) alert("Sorry, this browser does not support TextEncoder..."); var enc = new TextEncoder(); // always utf-8 console.log(enc.encode("This is a string converted to a Uint8Array"));</code></pre> </div> </div> </p> <p>You then of course use the <code>.buffer</code> parameter on the resulting <code>Uint8Array</code> to convert the underlaying <code>ArrayBuffer</code> to a different view if needed.</p> <p>Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.</p> <p>For general use you would use UTF-16 encoding for things like <code>localStorage</code>.</p> <h2>TextDecoder</h2> <p>Likewise, the opposite process <a href="https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder" rel="noreferrer">uses the <code>TextDecoder</code></a>:</p> <blockquote> <p>The <code>TextDecoder</code> interface represents a decoder for a specific method, that is a specific character encoding, like <code>utf-8</code>, <code>iso-8859-2</code>, <code>koi8</code>, <code>cp1261</code>, <code>gbk</code>, ... A decoder takes a stream of bytes as input and emits a stream of code points.</p> </blockquote> <p>All available decoding types can be found <a href="https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder/TextDecoder#Parameters" rel="noreferrer">here</a>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if (!("TextDecoder" in window)) alert("Sorry, this browser does not support TextDecoder..."); var enc = new TextDecoder("utf-8"); var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116, 56,65,114,114,97,121,32,99,111,110,118,101,114,116, 101,100,32,116,111,32,97,32,115,116,114,105,110,103]); console.log(enc.decode(arr));</code></pre> </div> </div> </p> <h2>The MDN StringView library</h2> <p>An alternative to these is to use the <a href="https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView" rel="noreferrer"><code>StringView</code> library</a> (licensed as lgpl-3.0) which goal is:</p> <blockquote> <ul> <li>to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface</li> <li>to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype</li> <li>to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings</li> <li>to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings</li> </ul> </blockquote> <p>giving much more flexibility. However, it would require us to link to or embed this library while <code>TextEncoder</code>/<code>TextDecoder</code> is being built-in in modern browsers.</p> <h1>Support</h1> <p>As of July/2018:</p> <p><a href="https://developer.mozilla.org/docs/Web/API/TextEncoder" rel="noreferrer"><code>TextEncoder</code></a> (Experimental, On Standard Track)</p> <pre class="lang-none prettyprint-override"><code> Chrome | Edge | Firefox | IE | Opera | Safari ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 19° | - | 25 | - Chrome/A | Edge/mob | Firefox/A | Opera/A |Safari/iOS | Webview/A ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 19° | ? | - | 38 °) 18: Firefox 18 implemented an earlier and slightly different version of the specification. WEB WORKER SUPPORT: Experimental, On Standard Track Chrome | Edge | Firefox | IE | Opera | Safari ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 20 | - | 25 | - Chrome/A | Edge/mob | Firefox/A | Opera/A |Safari/iOS | Webview/A ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 20 | ? | - | 38 Data from MDN - `npm i -g mdncomp` by epistemex </code></pre>
63,872,924
How can I send an HTTP request from my FastAPI app to another site (API)?
<p>I am trying to send 100 requests at a time to a server <code>http://httpbin.org/uuid</code> using the following code snippet <br></p> <pre><code>from fastapi import FastAPI from time import sleep from time import time import requests import asyncio app = FastAPI() URL= &quot;http://httpbin.org/uuid&quot; # @app.get(&quot;/&quot;) async def main(): r = requests.get(URL) # print(r.text) return r.text async def task(): tasks = [main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main(),main()] # print(tasks) # input(&quot;stop&quot;) result = await asyncio.gather(*tasks) print (result) @app.get('/') def f(): start = time() asyncio.run(task()) print(&quot;time: &quot;,time()-start) </code></pre> <p>I am using FastAPI with Asyncio to achieve the lowest time possible around 3 seconds or less but using the above method I am getting an overall time of 66 seconds that is more than a minute. I also want to keep the <code>main</code> function for additional operations on <code>r.text</code>. I understand that to achieve such low time, concurrency is required but I am not sure what mistake I'm doing here.</p>
63,881,674
2
10
null
2020-09-13 16:18:36.527 UTC
8
2022-05-31 12:36:11.92 UTC
2021-01-04 11:45:09.983 UTC
null
13,782,669
null
9,043,263
null
1
39
python|async-await|httprequest|python-asyncio|fastapi
29,437
<p><code>requests</code> is a synchronous library. You need to use an <code>asyncio</code>-based library to make requests asynchronously.</p> <h2><a href="https://www.python-httpx.org/async/" rel="noreferrer">httpx</a></h2> <p><code>httpx</code> is typically used in FastAPI applications to request external services. It provides synchronous and asynchronous clients which can be used in <code>def</code> and <code>async def</code> path operations appropriately. It is also recommended for <a href="https://fastapi.tiangolo.com/advanced/async-tests/" rel="noreferrer">asynchronous tests</a> of application. I would advice using it by default.</p> <pre><code>from fastapi import FastAPI from time import time import httpx import asyncio app = FastAPI() URL = &quot;http://httpbin.org/uuid&quot; async def request(client): response = await client.get(URL) return response.text async def task(): async with httpx.AsyncClient() as client: tasks = [request(client) for i in range(100)] result = await asyncio.gather(*tasks) print(result) @app.get('/') async def f(): start = time() await task() print(&quot;time: &quot;, time() - start) </code></pre> <p>Output</p> <pre><code>['{\n &quot;uuid&quot;: &quot;65c454bf-9b12-4ba8-98e1-de636bffeed3&quot;\n}\n', '{\n &quot;uuid&quot;: &quot;03a48e56-2a44-48e3-bd43-a0b605bef359&quot;\n}\n',... time: 0.5911855697631836 </code></pre> <h2><a href="https://docs.aiohttp.org/en/stable/client_quickstart.html" rel="noreferrer">aiohttp</a></h2> <p><code>aiohttp</code> can also be used in FastAPI applications, if you prefer one.</p> <pre><code>from fastapi import FastAPI from time import time import aiohttp import asyncio app = FastAPI() URL = &quot;http://httpbin.org/uuid&quot; async def request(session): async with session.get(URL) as response: return await response.text() async def task(): async with aiohttp.ClientSession() as session: tasks = [request(session) for i in range(100)] result = await asyncio.gather(*tasks) print(result) @app.get('/') async def f(): start = time() await task() print(&quot;time: &quot;, time() - start) </code></pre> <hr /> <p>If you want to limit the number of requests executing in parallel, you can use <code>asyncio.semaphore</code> like so:</p> <pre><code>MAX_IN_PARALLEL = 10 limit_sem = asyncio.Semaphore(MAX_IN_PARALLEL) async def request(client): async with limit_sem: response = await client.get(URL) return response.text </code></pre>
15,945,278
How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?
<p>I have a URL "<code>http://localhost:8888/api/rest/abc</code>" which will give following json data. I wants to get this data in my UI using Jquery or java script. I'm trying this from couple of hours but I'm unable to resolve it. Please Suggest me few solutions which will help me to resolve this problem.</p> <pre><code>{ "My-user": [ { "link": [ { "href": "http://localhost:8888/api/rest/abc/MI/CH", "rel": "self", "type": "application/my.My.My-user+xml", "title": "rln" }, { "href": "http://localhost:8888/api/rest/cabin?MI=mi&amp;CH=ch", "rel": "some relation", "type": "application/my.My.My-cabin+xml", "title": "rln1" } ], "My-user-list": [ { "name": "cuba", "Explanation": "bark" } ], "CH": "ch", "MI": "mi", "password": "xyz", }, { "link": [ { "href": "http://localhost:8888/api/rest/abc/DD/KN", "rel": "self", "type": "application/my.My.My-user+xml", "title": "rln" }, { "href": "http://localhost:8888/api/rest/cabin?DD=dd&amp;KN=kn", "rel": "some relation", "type": "application/my.My.My-cabin+xml", "title": "rln1" } ], "My-user-list": [ { "name": "Cuba1", "Explanation": "bark1" } ], "KN": "kn", "DD": "dd", "password": "xyz1", } ] } </code></pre> <hr> <p>I have tried Getjson which is not working out for me this is my code below Please correct me if the code is wrong.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script&gt; $.getJSON('/api/rest/abc', function(data) { console.log(data); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
15,945,449
5
2
null
2013-04-11 09:29:49.403 UTC
6
2022-06-17 22:32:32.957 UTC
2020-08-16 20:58:58.67 UTC
null
4,217,744
null
2,147,227
null
1
13
javascript|rest|jquery
107,739
<p>Send a ajax request to your server like this in your js and get your result in success function.</p> <pre><code>jQuery.ajax({ url: "/rest/abc", type: "GET", contentType: 'application/json; charset=utf-8', success: function(resultData) { //here is your json. // process it }, error : function(jqXHR, textStatus, errorThrown) { }, timeout: 120000, }); </code></pre> <p>at server side send response as json type.</p> <p>And you can use <a href="http://api.jquery.com/jQuery.getJSON/">jQuery.getJSON</a> for your application. </p>
15,542,145
Eclipse IDE - Open Call Hierarchy is empty/broken
<p>What should I do, if the "Open Call Hierarchy" is broken (empty for every method in a project)? It only shows the name of the method I wanted to see the call hierarchy for. This happens for all methods I try, even though they are all called by other methods.</p> <p>It is very useful for code navigation. I do not know how to work without it!</p> <p>I've tried:</p> <ol> <li>Opening <code>eclipse.exe -clean -refresh</code></li> <li>Restarting Eclipse</li> <li>Closing and reopening the project</li> <li>Updating the project</li> <li>Renaming the .metadata file</li> </ol> <p>I've checked that it searches the whole workspace, and there are no filters on.</p>
18,268,088
12
1
null
2013-03-21 07:59:17.323 UTC
2
2020-01-10 15:57:01.663 UTC
2019-04-21 21:25:43.973 UTC
null
294,317
null
513,393
null
1
35
eclipse|eclipse-juno|call-hierarchy
24,138
<p>The following may help:</p> <ul> <li>Calling eclipse with <code>eclipse.exe -clean -refresh</code> forces Eclipse to rebuild the index. After that the feature worked again.</li> <li>Closing and re-opening the project.</li> </ul>
15,875,128
Is there 'element rendered' event?
<p>I need to accurately measure the dimensions of text within my web app, which I am achieving by creating an element (with relevant CSS classes), setting its <code>innerHTML</code> then adding it to the container using <code>appendChild</code>.</p> <p>After doing this, there is a wait before the element has been rendered and its <code>offsetWidth</code> can be read to find out how wide the text is.</p> <p>Currently, I'm using <code>setTimeout(processText, 100)</code> to wait until the render is complete.</p> <p>Is there any callback I can listen to, or a more reliable way of telling when an element I have created has been rendered?</p>
21,043,017
8
3
null
2013-04-08 09:00:24.33 UTC
27
2021-09-20 19:26:51.037 UTC
2021-01-04 22:26:40.81 UTC
null
3,345,644
null
64,505
null
1
85
javascript|dom
80,003
<p>There is currently no DOM event indicating that an element has been fully rendered (eg. attached CSS applied and drawn). This can make some DOM manipulation code return wrong or random results (like getting the height of an element).</p> <p>Using setTimeout to give the browser some overhead for rendering is the simplest way. Using</p> <pre><code>setTimeout(function(){}, 0) </code></pre> <p>is perhaps the most practically accurate, as it puts your code at the end of the active browser event queue without any more delay - in other words your code is queued right after the render operation (and all other operations happening at the time).</p>
15,672,709
How to require a controller in an angularjs directive
<p>Can anyone tell me how to include a controller from one directive in another angularJS directive. for example I have the following code</p> <pre class="lang-js prettyprint-override"><code>var app = angular.module('shop', []). config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/', { templateUrl: '/js/partials/home.html' }) .when('/products', { controller: 'ProductsController', templateUrl: '/js/partials/products.html' }) .when('/products/:productId', { controller: 'ProductController', templateUrl: '/js/partials/product.html' }); }]); app.directive('mainCtrl', function () { return { controller: function ($scope) {} }; }); app.directive('addProduct', function () { return { restrict: 'C', require: '^mainCtrl', link: function (scope, lElement, attrs, mainCtrl) { //console.log(cartController); } }; }); </code></pre> <p>By all account I should be able to access the controller in the addProduct directive but I am not. Is there a better way of doing this? </p>
15,691,865
2
1
null
2013-03-28 01:34:29.647 UTC
46
2016-04-18 19:07:13.47 UTC
2014-01-27 09:51:39.657 UTC
null
547,020
null
1,914,652
null
1
89
javascript|angularjs|angularjs-directive
135,914
<p>I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".</p> <hr> <p>It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.</p> <p><strong>Share a Controller</strong></p> <p>Two directives can use the same controller by passing the same method to two directives, like so:</p> <pre class="lang-js prettyprint-override"><code>app.controller( 'MyCtrl', function ( $scope ) { // do stuff... }); app.directive( 'directiveOne', function () { return { controller: 'MyCtrl' }; }); app.directive( 'directiveTwo', function () { return { controller: 'MyCtrl' }; }); </code></pre> <p>Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.</p> <p><strong>Require a Controller</strong></p> <p>If you want to share the same <em>instance</em> of a controller, then you use <code>require</code>. </p> <p><code>require</code> ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can <em>require</em> the presence of the other directive and gain access to its controller methods. A common use case for this is to require <code>ngModel</code>.</p> <p><code>^require</code>, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.</p> <p>In either event, you have to use the two directives together for this to work. <code>require</code> is a way of communicating between components.</p> <p>Check out the Guide page of directives for more info: <a href="http://docs.angularjs.org/guide/directive">http://docs.angularjs.org/guide/directive</a></p>
15,806,448
Git: How to find out on which branch a tag is?
<p>I'm currently busy with a project with a lot of branches and I have a tag for last changes which where done on one of the branches. But it's not clear for me on which branch this tag is. </p> <p>How to find out on which branch a tag is?</p>
15,806,668
9
0
null
2013-04-04 08:45:34.193 UTC
19
2022-06-29 21:32:58.517 UTC
2019-03-20 13:08:45.757 UTC
null
6,714,194
null
1,442,283
null
1
113
git|tags|branch
85,734
<p>Even shorter:</p> <pre><code>git branch --contains tags/&lt;tag&gt; </code></pre> <p>(it works for any tree-ish reference)</p> <hr /> <p>If you can find <a href="https://stackoverflow.com/a/1863712/6309">which commit a tag refers to</a>:</p> <pre><code> git rev-parse --verify tags/&lt;tag&gt;^{commit} # or, shorter: git rev-parse tags/&lt;tag&gt;~0 </code></pre> <p>Then you can find <a href="https://stackoverflow.com/q/1419623/6309">which branch contain that commit</a>.</p> <pre><code>git branch --contains &lt;commit&gt; </code></pre> <hr /> <p>As <a href="https://stackoverflow.com/questions/15806448/git-how-to-find-out-on-which-branch-tag-is/15806668?noredirect=1#comment62261119_15806668">commented</a> below by <a href="https://stackoverflow.com/users/3356885/user3356885">user3356885</a>, for the fetched branches (branches in remotes namespace)</p> <pre><code>git branch -a --contains tags/&lt;tag&gt; git branch -a --contains &lt;commit&gt; </code></pre> <hr /> <p>As noted in <a href="https://stackoverflow.com/users/13726919/pyr3z">Pyr3z</a>'s <a href="https://stackoverflow.com/a/72093378/6309">answer</a>, for each candidate tag listed above, you can add:</p> <pre><code>git log -1 --pretty='%D' TAG </code></pre> <p>That will show the branches associated to that tag.</p>