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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41,129,504 | PyCharm with Pyenv | <p>How to use Pyenv virtualenv's with Pycharm 2016.3? In the earlier version of Pycharm, I could easily set up local interpreter to point anything installed on my machine. </p>
<p>My first idea was to add <code>.python-version</code> file on the root of the project. I Pyenv virtualenv installed so this will activate & run the project with correct environment automatically. However, Pycharm still doesn't see the correct interpreter causing it to though import and syntax errors. </p>
<p>How can I select my local Pyenv in new PyCharm 2016.3 I used to be able to set the path as variable now I can only browse the path using drop-down menu. It doesn't seem to show hidden files like default path for pyenv <code>~./.pyenv/versions{project}</code>.</p> | 51,545,578 | 5 | 1 | null | 2016-12-13 19:56:25.327 UTC | 13 | 2022-05-03 13:31:49.143 UTC | null | null | null | null | 2,335,820 | null | 1 | 82 | python|pycharm | 54,163 | <p>In Pycharm version 2017.3, you can go to
<strong>Pycharm -> Preferences -> Project -> Project Interpreter -> <code><</code>project_name<code>></code> -> settings button on the right of the python interpreter text box -> Add local</strong></p>
<p>This will open a new window with virtualenv Environment as one of the options on the left. On Selecting it, you will get an option to make a new virtualenv environment or use an existing virtual environment. Here next to the dropdown text box, you can click "..." and browse to your existing virtualenv created using pyenv and select it. It will select this virtualenv when you start terminal from Pycharm and also use the corresponding python interpreter as set while creating that virtualenv.</p>
<p><a href="https://i.stack.imgur.com/xNhiP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xNhiP.png" alt="enter image description here"></a></p> |
1,589,977 | Linking a shared library against a static library: must the static library be compiled differently than if an application were linking it? | <p>At least on Linux and Solaris, static libraries are really just a bunch of compiled .o's tossed into one big file. When compiling a static library, usually the -fpic flag is ommited, so the generated code is position dependent. </p>
<p>Now say my static library is B. I've built it and have the resulting .a file which is really just a glob of all of the position dependent .o files. Now I have a shared library I'd like to build, A, and I want it to statically link B. When I build A, naturally I'll use the -fpic flag to make the generated code position independent. But if I link against B, aren't I mixing position dependent and position independent object files?</p>
<p>I'm getting a lot of text relocation errors unless I also specify -mimpure-text, and I think this maybe the cause. It seems when I compile a library, I really need to compile it <em>3</em> times, a shared version, a static version, and a static-that-can-be-used-by-shared-libs version. Am I right? I could just keep using -mimpure-text but the g++ man page says that if you do that the object doesn't actually end up being shared (it's unclear if it's all unshared or just the statically linked parts though, does anyone know?). </p> | 1,590,050 | 3 | 1 | null | 2009-10-19 17:21:04.2 UTC | 11 | 2012-06-09 19:04:20.213 UTC | 2012-04-04 14:51:05.783 UTC | null | 50,385 | null | 50,385 | null | 1 | 32 | c|linker|shared-libraries|static-libraries|fpic | 19,916 | <p>You do not have to use PIC code in shared objects (as you have discovered you can use the -mimpure-text option to allow that).</p>
<p>That said, non-PIC code in shared objects are more heavyweight. With PIC code, the text pages in memory are just direct memory mappings of the text pages on disk. This means that if multiple processes are using the shared object, they can share the memory page.</p>
<p>But if you do not have PIC code, when the runtime linker loads the shared object, it will have to apply fixups to the text pages. This means that every processes that uses the shared object will have it's own unique version of any text page that has a fixup on it (even if the shared object is loaded at the same address as copy-on-write only notices that the page was modified and not that it was modified in the same way).</p>
<p>To me, the important issue is whether you will simultaneously have multiple processes running that each load the shared object. If you do, it is definitely worth making sure all the code within the SO is PIC.</p>
<p>But if that is not the case and only a single process has the shared object loaded, it's not nearly as critical.</p> |
1,537,951 | Generate table DDL via query on MySQL and SQL Server | <p>Is there an easy way to extract table DDL information, via a query, using either Ms or My SQL server? (preferably both?)</p>
<p>For example, using MySQL Administrator / Navicat for MySql, there is a "DDL" function, which generates the "create table foo (....)" script.</p>
<p>Is there any way to get this information from a query itself, such as:</p>
<pre><code>Select DDL from foo where table_name='bar';
</code></pre>
<p>Any have the "Create table bar (.....)" returned to me?</p>
<p>If not - any suggestions?</p> | 1,538,108 | 3 | 0 | null | 2009-10-08 13:54:30.63 UTC | 4 | 2020-08-14 13:57:29.013 UTC | 2017-01-11 16:09:55.723 UTC | null | 4,370,109 | Bob | null | null | 1 | 40 | mysql|database|ddl | 40,183 | <p>it's mysql-specific, but <code>SHOW CREATE TABLE <table-name></code> gives you the DDL for a table.</p> |
8,755,506 | Put checkmark in the left side of UITableViewCell | <p>I want to make something similar to the WiFi settings page: when you tap the table cell, put a checkbox in the left side of the cell, and have a disclosure button accessory view on the right to show more details.</p>
<p>My question: is there a way to put the checkmark in the left side of a UITableViewCell without building a custom UITableViewCell ?</p> | 12,664,922 | 6 | 1 | null | 2012-01-06 09:03:36.54 UTC | 23 | 2016-09-27 10:43:11.147 UTC | null | null | null | null | 460,750 | null | 1 | 30 | iphone|objective-c|ios|uitableview | 28,529 | <p>The answer is YES! You don't have to create a custom cell for that or add image views. To simulate checkboxes you only have to prepend a unicode symbol for a checkbox state to the cell text.</p>
<p>The unicode symbols I'm using for checkboxes are <code>\u2705</code> for checked and <code>\u2B1C</code> for unchecked (nearly the same as <code>\U0001F533</code> on iOS 5). iOS renders several <a href="https://stackoverflow.com/questions/6130475/adding-images-to-uiactionsheet-buttons-as-in-uidocumentinteractioncontroller/9779533#9779533">unicode symbols as icons</a>. </p>
<p>Here are some other symbols:</p>
<p><img src="https://i.stack.imgur.com/PQWjt.png" alt="enter image description here"></p>
<pre><code>@"\u2611", @"\u2B1C", @"\u2705", @"\u26AB", @"\u26AA", @"\u2714", @"\U0001F44D", @"\U0001F44E"
</code></pre>
<hr>
<p>Imitating the Wi-Fi settings page (with <code>UITableViewCellStyleValue1</code>): </p>
<p><img src="https://i.stack.imgur.com/XzRbJ.png" alt="enter image description here"></p>
<pre><code>cell.textLabel.text = @"\u2001 Wi-Fi 1";
cell.detailTextLabel.text = @"\U0001F512 \u268A";
cell.textLabel.text = @"\u2001 Wi-Fi 2";
cell.detailTextLabel.text = @"\U0001F512 \u268C";
cell.textLabel.text = @"\u2713 Wi-Fi 3";
cell.detailTextLabel.text = @"\U0001F513 \u2630";
</code></pre> |
8,706,930 | Converting nested hash keys from CamelCase to snake_case in Ruby | <p>I'm trying to build an API wrapper gem, and having issues with converting hash keys to a more Rubyish format from the JSON the API returns.</p>
<p>The JSON contains multiple layers of nesting, both Hashes and Arrays. What I want to do is to recursively convert all keys to snake_case for easier use.</p>
<p>Here's what I've got so far:</p>
<pre><code>def convert_hash_keys(value)
return value if (not value.is_a?(Array) and not value.is_a?(Hash))
result = value.inject({}) do |new, (key, value)|
new[to_snake_case(key.to_s).to_sym] = convert_hash_keys(value)
new
end
result
end
</code></pre>
<p>The above calls this method to convert strings to snake_case:</p>
<pre><code>def to_snake_case(string)
string.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
</code></pre>
<p>Ideally, the result would be similar to the following:</p>
<pre><code>hash = {:HashKey => {:NestedHashKey => [{:Key => "value"}]}}
convert_hash_keys(hash)
# => {:hash_key => {:nested_hash_key => [{:key => "value"}]}}
</code></pre>
<p>I'm getting the recursion wrong, and every version of this sort of solution I've tried either doesn't convert symbols beyond the first level, or goes overboard and tries to convert the entire hash, including values.</p>
<p>Trying to solve all this in a helper class, rather than modifying the actual Hash and String functions, if possible.</p>
<p>Thank you in advance.</p> | 8,707,236 | 7 | 1 | null | 2012-01-03 01:13:02.307 UTC | 4 | 2021-02-12 12:06:40.85 UTC | 2012-01-03 02:05:22.027 UTC | null | 38,765 | null | 945,848 | null | 1 | 38 | ruby|hash|key|camelcasing|hash-of-hashes | 31,902 | <p>You need to treat Array and Hash separately. And, if you're in Rails, you can use <a href="http://api.rubyonrails.org/classes/String.html#method-i-underscore" rel="noreferrer"><code>underscore</code></a> instead of your homebrew <code>to_snake_case</code>. First a little helper to reduce the noise:</p>
<pre><code>def underscore_key(k)
k.to_s.underscore.to_sym
# Or, if you're not in Rails:
# to_snake_case(k.to_s).to_sym
end
</code></pre>
<p>If your Hashes will have keys that aren't Symbols or Strings then you can modify <code>underscore_key</code> appropriately.</p>
<p>If you have an Array, then you just want to recursively apply <code>convert_hash_keys</code> to each element of the Array; if you have a Hash, you want to fix the keys with <code>underscore_key</code> and apply <code>convert_hash_keys</code> to each of the values; if you have something else then you want to pass it through untouched:</p>
<pre><code>def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
# or `value.map(&method(:convert_hash_keys))`
when Hash
Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
else
value
end
end
</code></pre> |
27,038,253 | Mock AsNoTracking Entity Framework | <p>How do I mock AsNoTracking method? <br>In below example, DbContext has injected to the service class.It works fine if I remove AsNoTracking extension method from GetOrderedProducts method, but with AsNoTracking test fails because it returns null.
I've also tried to mock AsNoTracking to return proper value but it didn't work.</p>
<pre><code>public interface IUnitOfWork
{
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveAllChanges();
}
public class Entites : DbContext, IUnitOfWork
{
public virtual DbSet<Product> Products { get; set; } // This is virtual because Moq needs to override the behaviour
public new virtual IDbSet<TEntity> Set<TEntity>() where TEntity : class // This is virtual because Moq needs to override the behaviour
{
return base.Set<TEntity>();
}
public int SaveAllChanges()
{
return base.SaveChanges();
}
}
public class ProductService
{
private readonly IDbSet<Product> _products;
private readonly IUnitOfWork _uow;
public ProductService(IUnitOfWork uow)
{
_uow = uow;
_products = _uow.Set<Product>();
}
public IEnumerable<Product> GetOrderedProducts()
{
return _products.AsNoTracking().OrderBy(x => x.Name).ToList();
}
}
[TestFixture]
public class ProductServiceTest
{
private readonly ProductService _productService;
public ProductServiceTest()
{
IQueryable<Product> data = GetRoadNetworks().AsQueryable();
var mockSet = new Mock<DbSet<Product>>();
mockSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var context = new Mock<Entites>();
context.Setup(c => c.Products).Returns(mockSet.Object);
context.Setup(m => m.Set<Product>()).Returns(mockSet.Object);
context.Setup(c => c.Products.AsNoTracking()).Returns(mockSet.Object);
_productService = new ProductService(context.Object);
}
private IEnumerable<Product> GetRoadNetworks()
{
return new List<Product>
{
new Product
{
Id = 1,
Name = "A"
},
new Product
{
Id = 2,
Name = "B"
},
new Product
{
Id = 1,
Name = "C"
}
};
}
[Test]
public void GetOrderedProductTest()
{
IEnumerable<Product> products = _productService.GetOrderedProducts();
List<string> names = products.Select(x => x.Name).ToList();
var expected = new List<string> {"A", "B", "C"};
CollectionAssert.AreEqual(names, expected);
}
}
</code></pre>
<p>The problem is AsNoTracking returns null in unit test
<img src="https://i.stack.imgur.com/4PEQn.png" alt="enter image description here"></p> | 27,087,604 | 3 | 3 | null | 2014-11-20 11:17:53.56 UTC | 9 | 2019-04-26 10:15:36.877 UTC | 2014-11-23 09:03:13.787 UTC | null | 369,161 | null | 369,161 | null | 1 | 33 | c#|entity-framework|unit-testing|mocking|moq | 9,180 | <p>Looking at the <a href="https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/QueryableExtensions.cs#L623" rel="noreferrer">source code</a> of the <code>AsNoTracking()</code> extension method:</p>
<pre><code>public static IQueryable AsNoTracking(this IQueryable source)
{
var asDbQuery = source as DbQuery;
return asDbQuery != null ? asDbQuery.AsNoTracking() : CommonAsNoTracking(source);
}
</code></pre>
<p>Since <code>source</code> (your <code>DbSet<Product></code> you're trying to mock) is indeed a <code>DbQuery</code> (because <code>DbSet</code> is deriving from <code>DbQuery</code>), it tries to invoke the 'real' (non-mocked) <code>AsNoTracking()</code> method which rightfully returns null.</p>
<p>Try to mock the <code>AsNoTracking()</code> method as well:</p>
<pre><code>mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);
</code></pre> |
271,907 | How to detect using c# if a pendrive is plugged into a USB port? | <p>Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port?
Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server. </p>
<p>a.) Can I get the details of the file(s) being copied?
b.) Is there a way to do this without a client application? </p>
<p>EDIT</p>
<p>I dont want to disable the USB port entirely. its to be on a need to have basis. Basically just want the users on the LAN to share data responsibly and know that whatever data is tranfered is monitored and logged and can be questioned later.</p> | 272,005 | 4 | 0 | null | 2008-11-07 12:21:24.923 UTC | 15 | 2011-01-27 20:02:38.047 UTC | 2011-01-27 20:02:38.047 UTC | null | 28,491 | null | 20,358 | null | 1 | 13 | c#|windows|usb|monitoring|usb-flash-drive | 22,176 | <p>[Assuming Windows, given the C# remark. Please tag accordingly]</p>
<p>Yes, this is possible. And it is possible to get the details of the file. It will require programming, though. Watch for <a href="http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx" rel="noreferrer">WM_DEVICECHANGE</a> and re-enumerate drives afterwards. It will get you USB pendrives, but also SD cards. I expect that's a bonus for you.</p>
<p>To get more details once you know a drive has arrived, use <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="noreferrer">System.IO.FileSystemWatcher</a></p>
<p><strong>Update</strong>
I found a better solution - if you register for volume interface notifications, you'll get the volume path for the new drive.
First, create a <code>DEV_BROADCAST_DEVICEINTERFACE</code> with <code>dbcc_classguid=GUID_DEVINTERFACE_VOLUME</code>. Then pass this to <code>RegisterDeviceNotification()</code>. You will again get a WM_DEVICECHANGE but you can now cast the lParam from the message to <code>DEV_BROADCAST_DEVICEINTERFACE*</code>.</p>
<p>You can pass the <code>dbcc_name</code> you receive to <code>GetVolumeNameForVolumeMountPoint()</code>. You can also pass all drive letters from <code>GetLogicalDriveStrings()</code> to <code>GetVolumeNameForVolumeMountPoint()</code>. You'll have one matching volume name; this is the new drive.</p> |
878,330 | How to pass in ID with Html.BeginForm()? | <p>In <a href="http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework" rel="noreferrer">ASP.NET MVC</a> I'm using the HTML helper </p>
<pre><code>Html.BeginForm("ActionName", "Controller", FormMethod.Post);
</code></pre>
<p>But I need to post to: /controller/action/23434</p>
<p>How do I pass in the ID?</p> | 878,408 | 4 | 0 | null | 2009-05-18 15:33:19.113 UTC | 7 | 2021-11-09 07:48:11.683 UTC | 2014-03-27 15:35:22.223 UTC | null | 444,991 | null | 68,183 | null | 1 | 41 | asp.net-mvc | 76,626 | <p>Matt's should work fine. If you are still passing in <code>FormMethod.Post</code>, though, you need to do it like this:</p>
<pre><code>Html.BeginForm("action","controller", new { Id = 12345 }, FormMethod.Post);
</code></pre>
<p>Reversing the third and fourth parameters will result in the <code>Id</code> being treated as an attribute instead of a route value.</p> |
1,003,358 | SQLite problem selecting two columns as one | <p>Basic table with empname and empdpt.<br>
In a Sql Server table, I can do <code>Select empname + ' ' + empdpt as expr1</code> no problem.<br>
Can't do the same using Sqlite!!<br>
When I try to combine two columns [with data], I get back a 0.<br>
I've tried in sqliteman and sqliteadmin as well as Server Explorer in VS.</p> | 1,003,385 | 4 | 0 | null | 2009-06-16 19:00:55.493 UTC | 10 | 2020-02-20 13:35:18.783 UTC | null | null | null | name | null | null | 1 | 42 | sqlite | 31,040 | <p>Try using the following:</p>
<pre><code>SELECT ("test" || " " || "test2") AS expr1 ;
</code></pre>
<p><strong>Update</strong></p>
<p>If these are columns you can do something similar: SELECT (column1 || " " || column2) AS expr1 FROM your_table;</p> |
998,979 | Difference between -%> and %> in rails | <p>I have started some rails tutorials and noticed that some of the view code blocks are like </p>
<pre><code><h1><%= @subject.name -%></h1>
</code></pre>
<p>and other code blocks are like</p>
<pre><code><h1><%= @subject.name %></h1>
</code></pre>
<p>What is the difference between -%> and %></p>
<p>If you know of some good syntax references you can point me to, that would also be helpful.</p> | 999,003 | 4 | 1 | null | 2009-06-15 23:37:44.92 UTC | 13 | 2014-11-13 13:41:25.95 UTC | 2009-08-27 14:12:28.153 UTC | null | 5,836 | null | 5,836 | null | 1 | 57 | ruby-on-rails | 7,108 | <p>The extra dash makes ERB not output the newline after the closing tag. There's no difference in your example, but if you have something like this:</p>
<pre><code><div>
<% if true -%>
Hi
<% end -%>
</div>
</code></pre>
<p>It'll produce:</p>
<pre><code><div>
Hi
</div>
</code></pre>
<p>and not this:</p>
<pre><code><div>
Hi
</div>
</code></pre> |
878,943 | Why return NotImplemented instead of raising NotImplementedError | <p>Python has a singleton called <a href="https://docs.python.org/2/library/constants.html#NotImplemented" rel="noreferrer"><code>NotImplemented</code></a>. </p>
<p>Why would someone want to ever return <code>NotImplemented</code> instead of raising the <a href="https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError" rel="noreferrer"><code>NotImplementedError</code></a> exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?</p> | 879,005 | 4 | 0 | null | 2009-05-18 17:43:40.817 UTC | 67 | 2020-08-27 06:08:12.783 UTC | 2017-06-15 20:23:24.127 UTC | null | 515,189 | null | 573 | null | 1 | 383 | python|exception | 82,427 | <p>It's because <code>__lt__()</code> and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas <code>NotImplemented</code> doesn't get raised and can be used in further tests.</p>
<p><a href="http://jcalderone.livejournal.com/32837.html" rel="noreferrer">http://jcalderone.livejournal.com/32837.html</a></p>
<p>To summarise that link:</p>
<blockquote>
<p>"<code>NotImplemented</code> signals to the runtime that it should ask someone else to satisfy the operation. In the expression <code>a == b</code>, if <code>a.__eq__(b)</code> returns <code>NotImplemented</code>, then Python tries <code>b.__eq__(a)</code>. If <code>b</code> knows enough to return <code>True</code> or <code>False</code>, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for <code>==</code> and <code>!=</code>)."</p>
</blockquote> |
710,275 | How to add/update an attribute to an HTML element using JavaScript? | <p>I'm trying to find a way that will add / update attribute using JavaScript. I know I can do it with <code>setAttribute()</code> function but that doesn't work in IE.</p> | 710,347 | 4 | 0 | null | 2009-04-02 15:39:08.127 UTC | 21 | 2017-07-07 09:26:39.967 UTC | 2015-02-01 16:43:30.083 UTC | null | 3,204,551 | dev.e.loper | 37,759 | null | 1 | 131 | javascript|html|cross-browser | 327,946 | <p>You can read <a href="http://www.quirksmode.org/dom/w3c_core.html#attributes" rel="noreferrer">here</a> about the behaviour of attributes in many different browsers, including IE.</p>
<p><code>element.setAttribute()</code> should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
<code>element.attributeName = 'value'</code> might work.</p> |
40,025,450 | Express JS: No 'Access-Control-Allow-Origin' header is present on the requested resource | <p>I have an API running on a server and a front-end client connecting to it to retrieve data. I did some research on the cross domain problem and has it working. However I've not sure what has changed. I am now getting this error in the console:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="https://api.mydomain/api/status" rel="noreferrer">https://api.mydomain/api/status</a>. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://beta.mydomain.com" rel="noreferrer">http://beta.mydomain.com</a>' is therefore not allowed
access. The response had HTTP status code 502.</p>
</blockquote>
<p>I have the following route file:</p>
<pre><code>var express = require('express');
var router = express.Router();
var Assessment = require('../app/models/assessment');
router.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
router.post('/api/status', function (req, res, next) {
getStatus.getStatus(req, res, Assessment);
});
module.exports = router;
</code></pre>
<p>And the following JavaScript making an Ajax call to that route:</p>
<pre><code>var user = {
'uid' : '12345'
};
$.ajax({
data: user,
method: 'POST',
url: 'https://api.mydomain/api/status',
crossDomain: true,
done: function () {
},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (xhr, status) {
}
});
</code></pre>
<p>I have tried:
Putting the requesting domain in the 'Access-Control-Allow-Origin' header
Using the cors module for express
Putting my router.all function inside middleware</p>
<p>The requesting domain is HTTP and the api domain is on HTTPS. However, I have had it working while the HTTP was enabled. </p>
<p>Does anyone have any insight into why the 'Access-Control-Allow-Origin' header is not being send?</p>
<p>Thank you</p> | 40,026,625 | 3 | 1 | null | 2016-10-13 15:42:16.48 UTC | 10 | 2018-06-19 10:56:09.967 UTC | null | null | null | null | 2,865,923 | null | 1 | 22 | javascript|ajax|node.js|express|cors | 52,880 | <p>Instead of setting the request headers to your express route, Can you try setting it to express instance itself like this,</p>
<pre><code>var express = require('express');
var app = express();
var Assessment = require('../app/models/assessment');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/api/status', function (req, res, next) {
// your code goes here
});
module.exports = app;
</code></pre>
<p>Hope this helps!</p> |
23,642,950 | How to reload/refresh model from database in Laravel? | <p>In some of my tests, I have a user model I have created and I run some methods that need to save certain attributes. In rails, I would typically call something like <code>user.reload</code> which would repopulate the attributes from the database.</p>
<p>Is there a way in laravel to do that? I read through the api and couldn't find a method for it: <a href="http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Model.html">http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Model.html</a> Any ideas on the "right" way to do this?</p> | 23,643,081 | 5 | 1 | null | 2014-05-13 22:55:24.753 UTC | 12 | 2021-02-22 17:50:30.257 UTC | 2019-09-01 01:28:40.283 UTC | null | 4,233,593 | null | 1,672,400 | null | 1 | 69 | php|laravel|unit-testing|laravel-4|eloquent | 93,213 | <p>I can't see it either. Looks like you'll have to:</p>
<pre><code>$model = $model->find($model->id);
</code></pre>
<p>You can also create one yourself:</p>
<pre><code>public function reload()
{
$instance = new static;
$instance = $instance->newQuery()->find($this->{$this->primaryKey});
$this->attributes = $instance->attributes;
$this->original = $instance->original;
}
</code></pre>
<p>Just tested it here and it looks it works, not sure how far this goes, though, Eloquen is a pretty big class.</p> |
23,648,458 | Call angularjs function using jquery/javascript | <p>I am trying to call angular function using javascript/jQuery, following are the link I found</p>
<ul>
<li><a href="https://stackoverflow.com/questions/18758997/call-angular-function-with-jquery">Call Angular Function with Jquery</a></li>
<li><a href="https://stackoverflow.com/questions/16709373/angularjs-how-to-call-controller-function-from-outside-of-controller-component">Call controller function from outside of controller component</a></li>
</ul>
<p>I have taken the same steps but getting error in browser console</p>
<pre><code>Uncaught TypeError: Cannot call method 'myfunction' of undefined
</code></pre>
<p>I have created the <a href="http://jsfiddle.net/mkbharti/8G8xH/3/" rel="noreferrer">fiddle</a>. How to call myfunction function and alert is displayed? Any Idea?</p> | 23,648,641 | 7 | 1 | null | 2014-05-14 07:41:39.553 UTC | 18 | 2020-12-09 20:43:35.67 UTC | 2017-05-23 12:18:01.347 UTC | null | -1 | null | 1,690,588 | null | 1 | 47 | javascript|jquery|angularjs | 112,071 | <p><em>Solution provide in the questions which you linked is correct.</em> Problem with your implementation is that You have not specified the <strong>ID</strong> of element correctly. </p>
<p>Secondly you need to use <code>load</code> event to execute your code. Currently DOM is not loaded hence element is not found thus you are getting error.</p>
<p><em>HTML</em></p>
<pre><code><div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
Hi
</div>
</code></pre>
<p><em>JS Code</em></p>
<pre><code>angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.myfunction = function (data) {
alert("---" + data);
};
});
window.onload = function () {
angular.element(document.getElementById('YourElementId')).scope().myfunction('test');
}
</code></pre>
<p><a href="http://jsfiddle.net/satpalsingh/VTbNf/" rel="noreferrer"><strong>DEMO</strong></a></p> |
23,605,967 | Photo capture on Windows Store App for Windows Phone | <p>Well, my question is simple:<br>
How do I capture pictures with a <code>Windows Store App</code> for <code>Windows Phone 8.1</code>, using the camera?<br>
The samples on MSDN use <code>Windows.Media.Capture.CameraCaptureUI</code>, which is not usable on Windows Phone, or are for <code>Silverlight</code>.<br>
I can't find any doc or sample specifically for Windows Phone app using Windows Runtime.<br>
If someone knows, or even have the doc for this, I would be glad.</p> | 23,606,620 | 3 | 2 | null | 2014-05-12 09:55:25.55 UTC | 18 | 2016-04-26 18:29:09.133 UTC | 2014-05-12 10:51:31.42 UTC | null | 2,681,948 | null | 3,627,550 | null | 1 | 18 | c#|windows|xaml|windows-phone-8.1|win-universal-app | 13,367 | <p>In WP8.1 Runtime (also in Silverlight) you can use <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.media.capture.mediacapture.aspx" rel="noreferrer">MediaCapture</a>. In short:</p>
<pre><code>// First you will need to initialize MediaCapture
Windows.Media.Capture.MediaCapture takePhotoManager = new Windows.Media.Capture.MediaCapture();
await takePhotoManager.InitializeAsync();
</code></pre>
<p>If you need a preview you can use a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.controls.captureelement" rel="noreferrer">CaptureElement</a>: </p>
<pre><code>// In XAML:
<CaptureElement x:Name="PhotoPreview"/>
</code></pre>
<p>Then in the code behind you can start/stop previewing like this:</p>
<pre><code>// start previewing
PhotoPreview.Source = takePhotoManager;
await takePhotoManager.StartPreviewAsync();
// to stop it
await takePhotoManager.StopPreviewAsync();
</code></pre>
<p>Finally to take a Photo you can for example take it directly to a file <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700836.aspx" rel="noreferrer">CapturePhotoToStorageFileAsync</a> or to a Stream <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700840.aspx" rel="noreferrer">CapturePhotoToStreamAsync</a>:</p>
<pre><code>ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
// a file to save a photo
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"Photo.jpg", CreationCollisionOption.ReplaceExisting);
await takePhotoManager.CapturePhotoToStorageFileAsync(imgFormat, file);
</code></pre>
<p>If you want to capture video then <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh452791.aspx" rel="noreferrer">here is more information</a>.</p>
<p>Also don't forget to add <code>Webcam</code> in <code>Capabilities</code> of your manifest file, and <code>Front/Rear Camera</code> in <code>Requirements</code>.</p>
<hr>
<p>In case you need to choose a Camera (fornt/back), you will need to get the Camera Id and then initialize <code>MediaCapture</code> with desired settings:</p>
<pre><code>private static async Task<DeviceInformation> GetCameraID(Windows.Devices.Enumeration.Panel desired)
{
DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desired);
if (deviceID != null) return deviceID;
else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desired));
}
async private void InitCamera_Click(object sender, RoutedEventArgs e)
{
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.Photo,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
}
</code></pre> |
38,251,763 | Moment.js - How to convert date string into date? | <p>Following up from my previous post: <a href="https://stackoverflow.com/questions/38154441/javascript-safari-new-date-with-strings-returns-invalid-date-when-typed">Javascript Safari: new Date() with strings returns invalid date when typed</a></p>
<p>I am using <strong>Moment.js</strong> to convert a date string into a date field based on user input in the text box. </p>
<p>This is to prevent the problem I described in the linked post for Safari and Firefox not able to render the date when Chrome is fine.</p>
<p>Here is the code snipper:</p>
<pre class="lang-js prettyprint-override"><code>var tempDate = moment(userInputFieldDate).format('DD-MM-YYYY');
alert(tempDate);
</code></pre>
<p>In Chrome, it does work fine (it use to work with the Javascript Date object too) but gives me the moment.js deprecation warning</p>
<blockquote>
<p>Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to <a href="https://github.com/moment/moment/issues/1407" rel="noreferrer">https://github.com/moment/moment/issues/1407</a> for more info.
Arguments: [object Object]
Error</p>
</blockquote>
<p>On Firefox and Safari is just gives an <code>UNDEFINED DATE</code> in the alert window. So not entirely sure what should I be doing to convert the date string to a Date object. </p>
<p>Any suggestions on this issue?</p> | 38,251,825 | 3 | 0 | null | 2016-07-07 17:29:57.98 UTC | 11 | 2020-12-08 11:30:05.103 UTC | 2020-06-06 19:38:57.447 UTC | null | 13,176,517 | null | 1,832,405 | null | 1 | 38 | javascript|date|momentjs | 159,135 | <p>If you are getting a JS based date <code>String</code> then first use the <code>new Date(String)</code> constructor and then pass the <code>Date</code> object to the <code>moment</code> method. Like:</p>
<pre><code>var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
</code></pre>
<p>In case <code>dateString</code> is <code>15-07-2016</code>, then you should use the <a href="http://momentjs.com/docs/#/parsing/string-format/" rel="noreferrer"><code>moment(date:String, format:String)</code></a> method</p>
<pre><code>var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
</code></pre> |
47,392,758 | Improving the performance of pandas groupby | <p>I have a machine learning application written in Python which includes a data processing step. When I wrote it, I initially did the data processing on Pandas DataFrames, but when this lead to abysmal performance I eventually rewrote it using vanilla Python, with for loops instead of vectorized operations and lists and dicts instead of DataFrames and Series. To my surprise, the performance of the code written in vanilla Python ended up being <em>far</em> higher than that of the code written using Pandas.</p>
<p>As my handcoded data processing code is substantially bigger and messier than the original Pandas code, I haven't quite given up on using Pandas, and I'm currently trying to optimize the Pandas code without much success.</p>
<p>The core of the data processing step consists of the following: I first divide the rows into several groups, as the data consists of several thousand time series (one for each "individual"), and I then do the same data processing on each group: a lot of summarization, combining different columns into new ones, etc.</p>
<p>I profiled my code using Jupyter Notebook's <code>lprun</code>, and the bulk of the time is spent on the following and other similar lines:</p>
<pre><code>grouped_data = data.groupby('pk')
data[[v + 'Diff' for v in val_cols]] = grouped_data[val_cols].transform(lambda x: x - x.shift(1)).fillna(0)
data[[v + 'Mean' for v in val_cols]] = grouped_data[val_cols].rolling(4).mean().shift(1).reset_index()[val_cols]
(...)
</code></pre>
<p>...a mix of vectorized and non-vectorized processing. I understand that the non-vectorized operations won't be faster than my handwritten for loops, since that's basically what they are under the hood, but how can they be <em>so much slower</em>? We're talking about a performance degradation of 10-20x between my handwritten code and the Pandas code.</p>
<p>Am I doing something very, very wrong?</p> | 47,482,207 | 1 | 0 | null | 2017-11-20 13:05:26.23 UTC | 15 | 2019-07-30 04:02:15.963 UTC | 2018-12-18 15:05:08.49 UTC | null | 4,909,087 | null | 1,004,065 | null | 1 | 37 | python|pandas | 17,797 | <p>No, I don't think you should give up on pandas. There's definitely better ways to do what you're trying to. The trick is to avoid <code>apply</code>/<code>transform</code> in any form as much as possible. Avoid them like the plague. They're basically implemented as for loops, so you might as well directly use python <code>for</code> loops which operate at C speed and give you better performance.</p>
<p>The real speed gain is where you get rid of the loops and use pandas' functions that implicitly vectorise their operations. For example, your first line of code can be simplified greatly, as I show you soon.</p>
<p>In this post I outline the setup process, and then, for each line in your question, offer an improvement, along with a side-by-side comparison of the timings and correctness.</p>
<h3>Setup</h3>
<pre><code>data = {'pk' : np.random.choice(10, 1000)}
data.update({'Val{}'.format(i) : np.random.randn(1000) for i in range(100)})
df = pd.DataFrame(data)
</code></pre>
<pre><code>g = df.groupby('pk')
c = ['Val{}'.format(i) for i in range(100)]
</code></pre>
<hr />
<h3><code>transform</code> + <code>sub</code> + <code>shift</code> → <code>diff</code></h3>
<p>Your first line of code can be replaced with a simple <code>diff</code> statement:</p>
<pre><code>v1 = df.groupby('pk')[c].diff().fillna(0)
</code></pre>
<p><strong>Sanity Check</strong></p>
<pre><code>v2 = df.groupby('pk')[c].transform(lambda x: x - x.shift(1)).fillna(0)
np.allclose(v1, v2)
True
</code></pre>
<p><strong>Performance</strong></p>
<pre><code>%timeit df.groupby('pk')[c].transform(lambda x: x - x.shift(1)).fillna(0)
10 loops, best of 3: 44.3 ms per loop
%timeit df.groupby('pk')[c].diff(-1).fillna(0)
100 loops, best of 3: 9.63 ms per loop
</code></pre>
<hr />
<h3>Removing redundant indexing operations</h3>
<p>As far as your second line of code is concerned, I don't see too much room for improvement, although you can get rid of the <code>reset_index()</code> + <code>[val_cols]</code> call if your groupby statement is not considering <code>pk</code> as the index:</p>
<pre><code>g = df.groupby('pk', as_index=False)
</code></pre>
<p>Your second line of code then reduces to:</p>
<pre><code>v3 = g[c].rolling(4).mean().shift(1)
</code></pre>
<p><strong>Sanity Check</strong></p>
<pre><code>g2 = df.groupby('pk')
v4 = g2[c].rolling(4).mean().shift(1).reset_index()[c]
np.allclose(v3.fillna(0), v4.fillna(0))
True
</code></pre>
<p><strong>Performance</strong></p>
<pre><code>%timeit df.groupby('pk')[c].rolling(4).mean().shift(1).reset_index()[c]
10 loops, best of 3: 46.5 ms per loop
%timeit df.groupby('pk', as_index=False)[c].rolling(4).mean().shift(1)
10 loops, best of 3: 41.7 ms per loop
</code></pre>
<p>Note that timings vary on different machines, so make sure you test your code thoroughly to make sure there is indeed an improvement on your data.</p>
<p>While the difference this time isn't as much, you can appreciate the fact that there are improvements that you can make! This could possibly make a much larger impact for larger data.</p>
<hr />
<h3>Afterword</h3>
<p>In conclusion, most operations are slow because they can be sped up. The key is to get rid of any approach that does not use vectorization.</p>
<p>To this end, it is sometimes beneficial to step out of pandas space and step into numpy space. Operations on numpy arrays or using numpy tend to be much faster than pandas equivalents (for example, <code>np.sum</code> is faster than <code>pd.DataFrame.sum</code>, and <code>np.where</code> is faster than <code>pd.DataFrame.where</code>, and so on).</p>
<p>Sometimes, loops cannot be avoided. In which case, you can create a basic looping function which you can then vectorise using numba or cython. Examples of that are here at <a href="https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html#enhancing-performance" rel="noreferrer">Enhancing Performance</a>, straight from the horses mouth.</p>
<p>In still other cases, your data is just too big to reasonably fit into numpy arrays. In this case, it would be time to give up and switch to <a href="http://dask.pydata.org/en/latest/dataframe.html" rel="noreferrer"><code>dask</code></a> or <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html" rel="noreferrer"><code>spark</code></a>, both of which offer high performance distributed computational frameworks for working with big data.</p> |
55,329,996 | How to create color shades using CSS variables similar to darken() of Sass? | <p>I'm looking a way of modifying a CSS variable as you would in SCSS</p>
<p>Define a color like primary - and automatically I would get shades for focus and actives states.
Basically, would like to change one variable in css variables and get 3 shades of the same color.</p>
<p>What Id like to achieve in CSS </p>
<pre><code>$color-primary: #f00;
.button {
background: $color-primary;
&:hover,
&:focus {
background: darken($color-primary, 5%);
}
&:active {
background: darken($color-primary, 10%);
}
}
</code></pre>
<p><strong>trying to achieve:</strong> </p>
<pre><code>:root {
--color-primary: #f00;
--color-primary-darker: #f20000 // var(--color-primary) * 5% darker
--color-primary-darkest: #e50000 // var(--color-primary) * 10% darker
}
.button {
background: var(--color-primary);
}
.button:hover,
.button:focus {
background: var(--color-primary-darker);
}
.button:active {
background: var(--color-primary-darkest);
}
</code></pre> | 55,330,103 | 4 | 0 | null | 2019-03-25 00:44:50.213 UTC | 5 | 2022-09-09 10:05:30.087 UTC | 2022-04-20 13:41:37.74 UTC | null | 8,620,333 | null | 4,634,990 | null | 1 | 37 | css|sass|css-variables | 39,062 | <p>The new <a href="https://www.w3.org/TR/css-color-5/#relative-colors" rel="noreferrer">Specification</a> introduces "relative color syntax" where you can do the following</p>
<pre><code>:root {
--color-primary: #f00; /* any format you want here */
--color-primary-darker: hsl(from var(--color-primary) h s calc(l - 5%));
--color-primary-darkest: hsl(from var(--color-primary) h s calc(l - 10%));
}
</code></pre>
<p>The idea is to convert the main color to <code>hsl</code> format and using <code>calc()</code> you adjust the lightness.</p>
<p>There is still <strong>no support</strong> for this to date so consider the below solution.</p>
<hr />
<p>You can consider <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#HSL_colors" rel="noreferrer"><code>hsl()</code></a> colors and simply control the lightness:</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-css lang-css prettyprint-override"><code>:root {
--color:0, 100%; /*the base color*/
--l:50%; /*the initial lightness*/
--color-primary: hsl(var(--color),var(--l));
--color-primary-darker: hsl(var(--color),calc(var(--l) - 5%));
--color-primary-darkest: hsl(var(--color),calc(var(--l) - 10%));
}
.button {
background: var(--color-primary);
display:inline-block;
padding:10px 20px;
color:#fff;
cursor:pointer;
}
.button:hover,
.button:focus {
background: var(--color-primary-darker);
}
.button:active {
background: var(--color-primary-darkest);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="button">some text</span></code></pre>
</div>
</div>
</p>
<p>As a side note, <a href="https://sass-lang.com/documentation/Sass/Script/Functions.html#darken-instance_method" rel="noreferrer"><code>darken()</code></a> is also doing the same thing:</p>
<blockquote>
<p>Makes a color darker. Takes a color and a number between 0% and 100%, and returns a color with the <strong>lightness decreased</strong> by that amount.</p>
</blockquote> |
25,697,780 | SQL CASE WHEN or IF ELSE IF | <p>I have multiple conditions to meet in a case
I would like to Know if I can use > < instead of defining every case</p>
<p>In this case when the credit rating is smaller then 3 then, the word "NO TRADE" will be inserted
and larger then 3, smaller then 5 would be "POOR", and so on and so on</p>
<pre><code>SELECT ClientId,
FirstName,
LastName,
Gender,
DateOfBirth,
CreditRating,
CASE CreditRating
WHEN 0 THEN 'NO TRADE'
WHEN 1 THEN 'NO TRADE'
WHEN 2 THEN 'NO TRADE'
WHEN 3 THEN 'POOR'
WHEN 4 THEN 'POOR'
WHEN 5 THEN 'AVARAGE'
WHEN 6 THEN 'AVARAGE'
WHEN 7 THEN 'GOOD'
ELSE 'PERFECT'
END AS RATING
FROM dbo.client
</code></pre> | 25,697,806 | 1 | 1 | null | 2014-09-06 07:04:55.8 UTC | null | 2019-10-07 15:03:20.943 UTC | null | null | null | null | 4,013,983 | null | 1 | 9 | sql | 38,107 | <p>Sure it is possible.</p>
<pre><code>CASE
WHEN CreditRating <= 2 THEN 'NO TRADE'
WHEN CreditRating <= 4 THEN 'POOR'
WHEN CreditRating <= 6 THEN 'AVARAGE'
WHEN CreditRating = 7 THEN 'GOOD'
ELSE 'PERFECT'
END AS RATING
</code></pre> |
20,753,550 | ENOENT, no such file or directory | <p>I'm getting this error from my node app:</p>
<pre><code>ENOENT, no such file or directory '~/Desktop/MyApp/newversion/partials/navigation.jade'
</code></pre>
<p>I know the file is there because when I try to open the file using the exact copied and pasted path, it works.
I also know the application is using the right directory because, well, it outputs it in the error.</p> | 20,753,566 | 16 | 1 | null | 2013-12-24 01:16:04.25 UTC | 20 | 2022-08-23 13:35:41.463 UTC | null | null | null | null | 1,236,793 | null | 1 | 78 | node.js|express | 326,618 | <p>Tilde expansion is a shell thing. Write the proper pathname (probably <code>/home/</code>yourusername<code>/Desktop/etcetcetc</code>) or use<br>
<code>process.env.HOME + '/Desktop/blahblahblah'</code></p> |
4,532,955 | What is the advantages of using binding attribute in JSF? | <p>See the following code:</p>
<pre><code><h:inputText id="name" value="#{jsfBean.name}" binding="#{jsfBean.htmlInputText}"/>
</code></pre>
<p>In the above example we are using the binding attribute to link with the server side bean property. I want to know what is the difference in using this attribute and not using this attribute.</p> | 4,532,971 | 1 | 0 | null | 2010-12-26 06:16:28.78 UTC | 10 | 2010-12-26 06:26:54.637 UTC | null | null | null | null | 421,753 | null | 1 | 15 | jsf | 32,252 | <p>With binding attribute you are mapping the <strong>actual component and NOT the component's value</strong>. For e.g the property in backing bean for your sample looks like below</p>
<pre><code>UIInput htmlInputText= null;
...
public void setHtmlInputText(UIInput userNoComponent) {
this.userNoComponent = userNoComponent;
}
public UIInput getHtmlInputText() {
return userNoComponent;
}
</code></pre>
<p><strong>Binding a component instance</strong> to a bean property has these advantages:</p>
<ul>
<li>The backing bean can programmatically
modify component attributes. </li>
<li>The backing bean can instantiate<br>
components rather than let the page<br>
author do so.</li>
</ul>
<p>Find more details <a href="http://download.oracle.com/javaee/5/tutorial/doc/bnatg.html" rel="noreferrer">in this tutorial</a></p> |
4,113,299 | Ruby on Rails Server options | <p>The whole issue of setting up a development server for my Ruby on Rails application confuses me. There are WEBrick, Mongrel, Passenger, Apache, Nginx and many more I am sure, and I don't really understand the different roles they play.</p>
<p>I started off using WEBrick, and now I use Mongrel for development. Are these servers stand-alone, or do they sit in front of Apache?</p>
<p>I have read about Passenger and I don't really understand what it is, the site says "makes deployment of Ruby web applications a breeze", does it replace Mongrel? Is it like Capistrano, which also deploys web applications?</p>
<p>Bearing in mind I would like to test SSL, and I believe that's not supported by mongrel, what is the best development server setup?</p>
<p>Thanks</p> | 4,113,570 | 1 | 3 | null | 2010-11-06 13:37:52.453 UTC | 540 | 2016-09-19 10:39:38.873 UTC | 2016-09-19 10:39:38.873 UTC | null | 1,524,624 | null | 341,878 | null | 1 | 594 | ruby-on-rails|apache|passenger|mongrel | 94,950 | <p>The word "deployment" can have two meanings depending on the context. You are also confusing the roles of Apache/Nginx with the roles of other components.</p>
<p>Historic note: This article was originally written on November 6, 2010, when the Ruby app server ecosystem was limited. I've updated this article on March 15 2013 with all the latest updates in the ecosystem.</p>
<p><strong>Disclaimer</strong>: I am one of the authors of Phusion Passenger, one of the app servers.</p>
<h2>Apache vs Nginx</h2>
<p>They're both web servers. They can serve static files but - with the right modules - can also serve dynamic web apps e.g. those written in PHP. Apache is more popular and has more features, Nginx is smaller and faster and has less features.</p>
<p>Neither Apache nor Nginx can serve Ruby web apps out-of-the-box, to do that you need to use Apache/Nginx in combination with some kind of add-on, described later.</p>
<p>Apache and Nginx can also act as reverse proxies, meaning that they can take an incoming HTTP request and forward it to another server, which also speaks HTTP. When that server responds with an HTTP response, Apache/Nginx will forward the response back to the client; You will learn later why this is relevant.</p>
<h2>Mongrel and other production app servers vs WEBrick</h2>
<p>Mongrel is a Ruby "application server": In concrete terms this means that Mongrel is an application which:</p>
<ol>
<li>Loads your Ruby app inside its own process space.</li>
<li>Sets up a TCP socket, allowing it to communicate with the outside world (e.g. the Internet).
Mongrel listens for HTTP requests on this socket and passes the request data to the Ruby web app. </li>
<li>The Ruby web app then returns an object, which describes what the HTTP response should look like, and Mongrel takes care of converting it to an actual HTTP response (the actual bytes) and sends it back over the socket.</li>
</ol>
<p>However Mongrel is quite dated, nowadays it is no longer maintained. Newer alternative application servers are:</p>
<ul>
<li>Phusion Passenger</li>
<li>Unicorn</li>
<li>Thin</li>
<li>Puma</li>
<li>Trinidad (JRuby only)</li>
<li>TorqueBox (JRuby only)</li>
</ul>
<p>I'll cover them later and describe how they differ from each other and from Mongrel.</p>
<p>WEBrick does the same thing as Mongrel, but the differences are:</p>
<ul>
<li>WEBrick is not fit for production, unlike everything else that I mentioned before. WEBrick is written entirely in Ruby. Mongrel (and most other Ruby app servers) is part Ruby and part C (Mostly Ruby), but its HTTP parser is written in C for performance.</li>
<li>WEBrick is slower and less robust. It has some known memory leaks and some known HTTP parsing problems.</li>
<li>WEBrick is usually only used as the default server during development because WEBrick is included in Ruby by default. Mongrel and other app servers needs to be installed separately. It's not recommended to use WEBrick in production environments, though for some reason Heroku chose WEBrick as its default server. They were using Thin before, so I have no idea why they switched to WEBrick.</li>
</ul>
<h2>The app server and the world</h2>
<p>All current Ruby app servers speak HTTP, however some app servers may be directly exposed to the Internet on port 80, while others may not.</p>
<ul>
<li>App servers that can be directly exposed to the Internet: Phusion Passenger, Rainbows</li>
<li>App servers that may not be directly exposed to the Internet: Mongrel, Unicorn, Thin, Puma. These app servers must be put behind a <em>reverse proxy web server</em> like Apache and Nginx.</li>
<li>I don't know enough about Trinidad and TorqueBox, so I've omitted them.</li>
</ul>
<p>Why must some app servers be put behind a reverse proxy?</p>
<ul>
<li>Some app servers can only handle 1 request concurrently, per process. If you want to handle 2 requests concurrently you need to run multiple app server instances, each serving the same Ruby app. This set of app server processes is called an <em>app server cluster</em> (hence the name Mongrel Cluster, Thin Cluster, etc). You must then setup Apache or Nginx to reverse proxy to this cluster. Apache/Nginx will take care of distributing requests between the instances in the cluster (More on this in section "I/O concurrency models").</li>
<li>The web server can buffer requests and responses, protecting the app server from "slow clients" - HTTP clients that don't send or accept data very quickly. You don't want your app server to do nothing while waiting for the client to send the full request or to receive the full response, because during that time the app server may not be able to do anything else. Apache and Nginx are very good at doing many things at the same time because they're either multithreaded or evented.</li>
<li>Most app servers can serve static files, but are not particularly good at it. Apache and Nginx can do it faster. </li>
<li>People typically set up Apache/Nginx to serve static files directly, but forward requests that don't correspond with static files to the app server, it's good security practice. Apache and Nginx are very mature and can shield the app server from (perhaps maliciously) corrupted requests.</li>
</ul>
<p>Why can some app servers be directly exposed to the Internet?</p>
<ul>
<li>Phusion Passenger is a very different beast from all the other app servers. One of its unique features is that it integrates into the web server.</li>
<li>The Rainbows author publicly stated that it's safe to directly expose it to the Internet. The author is fairly sure that there are no vulnerabilities in the HTTP parser (and similar). Still, the author provides no warranty and says that usage is at own risk.</li>
</ul>
<h2>Application servers compared</h2>
<p>In this section I'll compare most application servers I've mentioned, but not Phusion Passenger. Phusion Passenger is such a different beast from the rest that I've given it a dedicated section. I've also omitted Trinidad and TorqueBox because I do not know them well enough, but they're only relevant anyway if you use JRuby.</p>
<ul>
<li><strong>Mongrel</strong> was pretty bare bones. As mentioned earlier, Mongrel is purely single-threaded multi-process, so it is only useful in a cluster. There is no process monitoring: if a process in the cluster crashes (e.g. because of a bug in the app) then it needs to be manually restarted. People tend to use external process monitoring tools such as Monit and God.</li>
<li><strong>Unicorn</strong> is a fork of Mongrel. It supports limited process monitoring: if a process crashes it is automatically restarted by the master process. It can make all processes listen on a single shared socket, instead of a separate socket for each process. This simplifies reverse proxy configuration. Like Mongrel, it is purely single-threaded multi-process.</li>
<li><strong>Thin</strong> uses the evented I/O model by utilizing the EventMachine library. Other than using the Mongrel HTTP parser, it is not based on Mongrel in any way. Its cluster mode has no process monitoring so you need to monitor crashes etc. There is no Unicorn-like shared socket, so each process listens on its own socket. In theory, Thin's I/O model allows high concurrency, but in most practical situations that Thin is used for, one Thin process can only handle 1 concurrent request, so you still need a cluster. More about this peculiar property in section "I/O concurrency models".</li>
<li><strong>Puma</strong> was also forked from Mongrel, but unlike Unicorn, Puma is designed to be purely multi-threaded. There is therefore currently no builtin cluster support. You need to take special care to ensure that you can utilize multiple cores (More about this in section "I/O concurrency models").</li>
<li><strong>Rainbows</strong> supports multiple concurrency models through the use of different libraries.</li>
</ul>
<h2>Phusion Passenger</h2>
<p><a href="https://www.phusionpassenger.com" rel="noreferrer">Phusion Passenger</a> works very differently from all the other ones. Phusion Passenger integrates directly into Apache or Nginx, and so can be compared to mod_php for Apache. Just like mod_php allows Apache to serve PHP apps, almost magically, Phusion Passenger allows Apache (and also Nginx!) to serve Ruby apps, almost magically. Phusion Passenger's goal is to make everything Just Work(tm) with as little hassle as possible.</p>
<p>Instead of starting a process or cluster for your app, and configuring Apache/Nginx to serve static files and/or reverse proxying requests to the process/cluster with Phusion Passenger you only need to:</p>
<ol>
<li>You edit the web server config file and specify the location of your Ruby app's 'public' directory.</li>
<li>There is no step 2.</li>
</ol>
<p>All configuration is done within the web server config file. Phusion Passenger automates pretty much everything. There is no need to start a cluster and manage processes. Starting/stopping processes, restarting them when they crash, etc. - all automated. Compared to other app servers, Phusion Passenger has far fewer moving parts. This ease of use is one of the primary reasons why people use Phusion Passenger.</p>
<p>Also unlike other app servers, Phusion Passenger is primarily written in C++, making it very fast.</p>
<p>There's also an <a href="https://www.phusionpassenger.com/enterprise" rel="noreferrer">Enterprise variant</a> of Phusion Passenger with even more features, such as automated rolling restarts, multithreading support, deployment error resistance, etc.</p>
<p>For the above reasons, Phusion Passenger is currently the most popular Ruby app server, powering over 150,000 websites, including large ones such as New York Times, Pixar, Airbnb, etc.</p>
<h2>Phusion Passenger vs other app servers</h2>
<p>Phusion Passenger provides a lot more features and provides many advantages over other app servers, such as:</p>
<ul>
<li>Dynamically adjusting the number of processes based on traffic. We run a ton of Rails apps on our resource-constrainted server that are not public-facing, and that people in our organization only use at most a few times a day. Things like Gitlab, Redmine, etc. Phusion Passenger can spin down those processes when they're not used, and spinning them up when they're used, allowing more resources to be available for more important apps. With other app servers, all your processes are turned on all the time.</li>
<li>Some app servers are not good at certain workloads, by design. For example Unicorn is designed for fast-running requests only: See <a href="http://unicorn.bogomips.org/PHILOSOPHY.html" rel="noreferrer">the Unicorn website</a> section "Just Worse in Some Cases". </li>
</ul>
<p>Workloads that Unicorn is not good at are:</p>
<ul>
<li>Streaming workloads (e.g. Rails 4 live streaming or Rails 4 template streaming).</li>
<li>Workloads in which the app performs HTTP API calls.</li>
</ul>
<p>The hybrid I/O model in <a href="https://www.phusionpassenger.com/enterprise" rel="noreferrer">Phusion Passenger Enterprise 4</a> or later makes it an excellent choice for these kinds of workloads.</p>
<ul>
<li>Other app servers require the user to run at least one instance per application. By contrast, Phusion Passenger supports multiple applications in a single instance. This greatly reduces administration overhead.</li>
<li>Automatic user switching, a convenient security feature.</li>
<li>Phusion Passenger supports many MRI Ruby, JRuby and Rubinius. Mongrel, Unicorn and Thin only support MRI. Puma also supports all 3.</li>
<li>Phusion Passenger actually supports more than just Ruby! It also supports Python WSGI, so it can for example also run Django and Flask apps. In fact Phusion Passenger is moving into the direction of becoming a polyglot server. Node.js support on the todo list.</li>
<li>Out-of-band garbage collection. Phusion Passenger can run the Ruby garbage collector outside the normal request/response cycle, potentially reducing request times by hundreds of milliseconds. Unicorn also has a similar feature, but Phusion Passenger's version is more flexible because
1) it's not limited to GC and can be used for arbitrary work.
2) Phusion Passenger's version works well with multithreaded apps, while Unicorn's does not.</li>
<li>Automated rolling restarts. Rolling restarts on Unicorn and other servers require some scripting work. Phusion Passenger Enterprise completely automates this way for you.</li>
</ul>
<p>There are more features and advantages, but the list is really long. You should refer to the comprehensive Phusion Passenger manual (<a href="http://www.modrails.com/documentation/Users%20guide%20Apache.html" rel="noreferrer">Apache version</a>, <a href="http://www.modrails.com/documentation/Users%20guide%20Nginx.html" rel="noreferrer">Nginx version</a>) or <a href="https://www.phusionpassenger.com" rel="noreferrer">the Phusion Passenger website</a> for information.</p>
<h2>I/O concurrency models</h2>
<ul>
<li><strong>Single-threaded multi-process.</strong> This is traditionally the most popular I/O model for Ruby app servers, partially because multithreading support in the Ruby ecosystem was very bad. Each process can handle exactly 1 request at a time. The web server load balances between processes. This model is very robust and there is little chance for the programmer to introduce concurrency bugs. However, its I/O concurrency is extremely limited (limited by the number of processes). This model is very suitable for fast, short-running workloads. It is very unsuitable for slow, long-running blocking I/O workloads, e.g. workloads involving the calling of HTTP APIs.</li>
<li><strong>Purely multi-threaded.</strong> Nowadays the Ruby ecosystem has excellent multithreading support, so this I/O model has become very viable. Multithreading allows high I/O concurrency, making it suitable for both short-running and long-running blocking I/O workloads. The programmer is more likely to introduce concurrency bugs, but luckily most web frameworks are designed in such a way that this is still very unlikely. One thing to note however is that the MRI Ruby interpreter cannot leverage multiple CPU cores even when there are multiple threads, due to the use of the Global Interpreter Lock (GIL). You can work around this by using multiple multi-threaded processes, because each process can leverage a CPU core. JRuby and Rubinius have no GIL, so they can fully leverage multiple cores in a single process.</li>
<li><strong>Hybrid multi-threaded multi-process.</strong> Primarily implemented by Phusion Passenger Enterprise 4 and later. You can easily switch between single-threaded multi-process, purely multithreaded, or perhaps even multiple processes each with multiple threads. This model gives the best of both worlds.</li>
<li><strong>Evented.</strong> This model is completely different from the previously mentioned model. It allows very high I/O concurrency and is therefore excellent for long-running blocking I/O workloads. To utilize it, explicit support from the application and the framework is required. However all the major frameworks like Rails and Sinatra do not support evented code. This is why in practice a Thin process still cannot handle more than 1 request at a time, making it effectively behave the same as the single-threaded multi-process model. There are specialized frameworks that can take advantage of evented I/O, such as Cramp.</li>
</ul>
<p>An article was recently posted on the Phusion blog about optimally tuning the number of processes and threads given your workload. See <a href="http://blog.phusion.nl/2013/03/12/tuning-phusion-passengers-concurrency-settings/" rel="noreferrer">Tuning Phusion Passenger's concurrency settings</a>.</p>
<h2>Capistrano</h2>
<p>Capistrano is something completely different. In all the previous sections, "deployment" refers to the act of starting your Ruby app in an application server, so that it becomes accessible to visitors, but before that can happen one typically needs to do some preparation work, such as:</p>
<ul>
<li>Uploading the Ruby app's code and files to the server machine.</li>
<li>Installing libraries that your app depends on.</li>
<li>Setting up or migrating the database.</li>
<li>Starting and stopping any daemons that your app might rely on, such as Sidekiq/Resque workers or whatever.</li>
<li>Any other things that need to be done when you're setting up your application.</li>
</ul>
<p>In the context of Capistrano, "deployment" refers to doing all this preparation work. Capistrano is not an application server. Instead, it is a tool for automating all that preparation work. You tell Capistrano where your server is and which commands need to be run every time you deploy a new version of your app, and Capistrano will take care of uploading the Rails app to the server for you and running the commands you specified.</p>
<p>Capistrano is always used in combination with an application server. It does not replace application servers. Vice-versa, application servers do not replace Capistrano, they can be used in combination with Capistrano.</p>
<p>Of course you don't <em>have</em> to use Capistrano. If you prefer to upload your Ruby app with FTP and manually running the same steps of commands every time, then you can do that. Other people got tired of it, so they automate those steps in Capistrano.</p> |
4,170,978 | (![]+[])[+[]]... Explain why this works | <pre class="lang-js prettyprint-override"><code>alert((![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]);
</code></pre>
<p>The output of this code is: <code>fail</code>. Why?</p> | 4,171,028 | 1 | 14 | null | 2010-11-13 04:29:53.717 UTC | 66 | 2021-07-31 22:50:06.247 UTC | 2021-07-31 22:50:06.247 UTC | user16442705 | null | null | 385,335 | null | 1 | 123 | javascript | 14,904 | <p>As @Mauricio commented <code>(![]+[])[+[]]</code> is "f" (the first char of "false"), <code>(![]+[])[+!+[]])</code> is "a", etc...</p>
<p>How does it work?</p>
<p>Let's examine the first character, 'f':</p>
<pre><code>(![]+[])[+[]]; // 'f'
</code></pre>
<p>The first part of the expression—between parentheses—is composed by <code>![]+[]</code>, the first operand of the Addition operator is <code>![]</code> and it will produce <code>false</code>, because an array object—as any other Object instance—is <em>truthy</em>, and applying the Logical (!) NOT unary operator, it produces the value <code>false</code>, for example.</p>
<pre><code>![]; // false, it was truthy
!{}; // false, it was truthy
!0; // true, it was falsey
!NaN; // true, it was falsey
</code></pre>
<p>After it, we have the second operand of the addition, an empty Array, <code>[]</code>, this is made just to convert the <code>false</code> value to String, because the string representation of an empty array is just an empty string, is equivalent to:</p>
<pre><code>false+[]; // "false"
false+''; // "false"
</code></pre>
<p>The last part, the pair of square brackets after the parentheses, they are the property accessor, and they receive an expression, which is formed by the Unary Plus Operator applied to an empty array again.</p>
<p>What the Unary Plus Operator does is type conversion, to <code>Number</code>, for example:</p>
<pre><code>typeof +"20"; // "number"
</code></pre>
<p>One more time, this is applied to an empty Array, and as I said before, the String representation of an Array is an empty string, and when you convert an empty string to Number, it is converted to zero:</p>
<pre><code>+[]; // 0, because
+[].toString(); // 0, because
+""; // 0
</code></pre>
<p>Therefore we can "decode" the expression to in some steps:</p>
<pre><code>(![]+[])[+[]];
(false+[])[+[]];
(false+'')[+[]];
(false+'')[0];
('false')[0]; // "f"
</code></pre>
<p>Note that accessing characters by using the bracket notation on String values was not part of the ECMAScript 3rd. Edition Specification, (that's why the <code>charAt</code> method existed).</p>
<p>However this kind of "index properties" that represent the characters of a string were standardized on ECMAScript 5, and even before the standardization the feature was available in a good number of browsers (even in IE8 (standards mode)).</p> |
31,350,957 | FBSOpenApplicationErrorDomain error 1 | <p>I'm trying to run my iOS app that was migrated from <code>Swift 1.2</code> to <code>Swift 2.0</code> in Xcode 7 using iPhone Simulator (any), I'm getting the following error:</p>
<blockquote>
<p>The operation couldn’t be completed. (FBSOpenApplicationErrorDomain
error 1.)</p>
</blockquote>
<p>I already tried to reset simulator settings and content, quit Xcode, clean project, etc.</p> | 32,896,457 | 16 | 8 | null | 2015-07-10 21:58:24.313 UTC | 13 | 2021-11-08 18:52:39.567 UTC | 2015-07-10 22:21:05.577 UTC | null | 1,109,795 | null | 1,109,795 | null | 1 | 53 | ios|xcode|ios-simulator|swift2|xcode7 | 23,514 | <p>I had the same error after updating Xcode to v7.0. After few hours struggling, I found that there was some empty environment variable setup to be passed for Run action in my active scheme (have no idea why it was there). Removing this empty environment variable resolved the issue immediately.</p> |
6,652,547 | How to make a double gradient with XML (iphone like) | <p>How can I make this kind of drawable gradient with XML? </p>
<p><img src="https://i.stack.imgur.com/FrgFC.png" alt="Double gradient image"></p>
<p>I can do a simple gradient from color A to color B but i don't know how to combine two gradients in the same drawable.</p> | 14,018,579 | 2 | 2 | null | 2011-07-11 15:27:36.083 UTC | 12 | 2015-06-29 11:55:34.097 UTC | 2015-06-29 11:55:34.097 UTC | null | 165,071 | null | 393,984 | null | 1 | 14 | android|gradient | 15,032 | <p>I finally found a solution with a layer-list which is good enough for me : </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- First part is a gradient -->
<item android:left="0dp" android:right="0dp">
<shape android:shape="rectangle">
<gradient android:angle="-90" android:startColor="#9dcbf6"
android:endColor="#177ee6" />
</shape>
</item>
<!-- Second part is plain color. Slightly transparent -->
<item android:top="1sp" android:bottom="20sp" >
<shape android:shape="rectangle">
<solid android:color="#10ffffff"/>
</shape>
</item>
</layer-list>
</code></pre>
<p>The middle is set to 20 sp because the container has a 40sp height , but you can adjust to your will by editing : <code>android:bottom="20sp"</code></p> |
6,515,333 | How do I execute a single test using Ruby test/unit? | <p>Instead of running all the test cases automatically, is there any way to execute a single test under ruby test/unit framework. I know I can achieve that by using Rake but I am not ready to switch to rake at this moment. </p>
<pre><code>ruby unit_test.rb #this will run all the test case
ruby unit_test.rb test1 #this will only run test1
</code></pre> | 6,515,354 | 2 | 0 | null | 2011-06-29 03:04:47.4 UTC | 4 | 2011-10-11 21:16:15.773 UTC | 2011-06-29 12:33:03.233 UTC | null | 38,765 | null | 115,722 | null | 1 | 35 | ruby|unit-testing|testing|testunit | 20,507 | <p>you can pass the -n option on the command line to run a single test:</p>
<pre><code>ruby my_test.rb -n test_my_method
</code></pre>
<p>where 'test_my_method' is the name of the test method you would like to run.</p> |
7,593,231 | How to select default button in wpf dialog? | <p>I am creating a WPF dialog. It is like our normal <code>messagebox</code> with <code>ok</code> and <code>cancel</code> button. How to create such a dialog so that the <code>Ok</code> button is selected when the dialog is opened?</p> | 7,593,246 | 3 | 2 | null | 2011-09-29 06:16:02.447 UTC | null | 2021-03-23 14:32:59.38 UTC | 2013-02-21 22:00:51.853 UTC | null | 723,693 | null | 952,518 | null | 1 | 42 | c#|wpf|dialog | 36,417 | <p><strong>To set a Window's Default button</strong></p>
<p>Set your default button's <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.button.isdefault.aspx" rel="noreferrer">IsDefault property</a> to true.</p>
<p>Note that you can also set a Window's Cancel button by setting a button's <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.button.iscancel.aspx" rel="noreferrer">IsCancel property</a> to true.</p>
<hr>
<p><strong>To set the Selected (focused) button in a Window</strong></p>
<p>If you want to select a particular button then use the Focus method like this:</p>
<pre><code>yourButton.Focus();
</code></pre>
<p>You might do this when a Window loads (in the Window_Loaded event).</p>
<p>To select a particular button when your Window opens make sure its <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.istabstop.aspx" rel="noreferrer">IsTabStop property</a> is set to true and ensure its <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.tabindex.aspx" rel="noreferrer">TabIndex property</a> is lower than any other control on the Window.</p> |
7,237,271 | Large scale data processing Hbase vs Cassandra | <p>I am nearly landed at Cassandra after my research on large scale data storage solutions. But its generally said that Hbase is better solution for large scale data processing and analysis. </p>
<p>While both are same key/value storage and both are/can run (Cassandra recently) Hadoop layer then what makes Hadoop a better candidate when processing/analysis is required on large data.</p>
<p>I also found good details about both at
<a href="http://ria101.wordpress.com/2010/02/24/hbase-vs-cassandra-why-we-moved/">http://ria101.wordpress.com/2010/02/24/hbase-vs-cassandra-why-we-moved/</a> </p>
<p>but I'm still looking for concrete advantages of Hbase.</p>
<p>While I am more convinced about Cassandra because its simplicity for adding nodes and seamless replication and no point of failure features. And it also keeps secondary index feature so its a good plus.</p> | 7,251,868 | 3 | 0 | null | 2011-08-29 23:46:12.31 UTC | 53 | 2011-09-06 06:46:58.187 UTC | 2011-09-01 15:28:20.853 UTC | null | 130,168 | null | 848,927 | null | 1 | 85 | nosql|hadoop|cassandra|hbase|data-processing | 37,042 | <p>Trying to determine which is best for you really depends on what you are going to use it for, they each have their advantages and without any more details it becomes more of a religious war. That post you referenced is also more than a year old and both have gone through many changes since then. Please also keep in mind I am not familiar with the more recent Cassandra developments.</p>
<p>Having said that, I'll paraphrase HBase committer Andrew Purtell and add some of my own experiences:</p>
<ul>
<li><p>HBase is in larger production environments (1000 nodes) although that is still in the ballpark of Cassandra's ~400 node installs so its really a marginal difference.</p></li>
<li><p>HBase and Cassandra both supports replication between clusters/datacenters. I believe HBase's exposes more to the user so it appears more complicated but then you also get more flexibility.</p></li>
<li><p>If strong consistency is what your application needs then HBase is likely a better fit. It is designed from the ground up to be consistent. For example it allows for simpler implementation of atomic counters (I think Cassandra just got them) as well as Check and Put operations.</p></li>
<li><p>Write performance is great, from what I understand that was one of the reasons Facebook went with HBase for their messenger.</p></li>
<li><p>I'm not sure of the current state of Cassandra's ordered partitioner, but in the past it required manual rebalancing. HBase handles that for you if you want. The ordered partitioner is important for Hadoop style processing.</p></li>
<li><p>Cassandra and HBase are both complex, Cassandra just hides it better. HBase exposes it more via using HDFS for its storage, if you look at the codebase Cassandra is just as layered. If you compare the Dynamo and Bigtable papers you can see that Cassandra's theory of operation is actually more complex.</p></li>
<li><p>HBase has more unit tests FWIW.</p></li>
<li><p>All Cassandra RPC is Thrift, HBase has a Thrift, REST and native Java. The Thrift and REST do only offer a subset of the total client API but if you want pure speed the native Java client is there.</p></li>
<li><p>There are advantages to both peer to peer and master to slave. The master - slave setup generally makes it easier to debug and reduces quite a bit of complexity.</p></li>
<li><p>HBase is not tied to only traditional HDFS, you can change out your underlying storage depending on your needs. <a href="http://www.mapr.com/" rel="noreferrer">MapR</a> looks quite interesting and I have heard good things although I have not used it myself.</p></li>
</ul> |
7,451,524 | Why aren't ◎ܫ◎ and ☺ valid JavaScript variable names? | <p>I noticed that in Internet Explorer (but, unfortunately, not in the other browsers I tested), you can use some Unicode variable names. This made my day, and I was absolutely delighted that I could write fun Unicode-laden code like this:</p>
<pre><code>var ктоείναι草泥马 = "You dirty horse.",
happy☺n☺mat☺p☺eia = ":)Yay!",
ಠ_ಠ = "emoticon";
alert(ктоείναι草泥马 + happy☺n☺mat☺p☺eia + ಠ_ಠ);
</code></pre>
<p>For some reason, though, <code>◎ܫ◎</code>, <code>♨_♨</code> and <code>☺</code> are not valid variable names.</p>
<p>Why do <code>ಠ_ಠ</code> and <code>草泥马</code> work, but <code>◎ܫ◎</code>, <code>♨_♨</code> and <code>☺</code> don't?</p>
<p>EDIT: Test it out in your browser on <a href="http://jsfiddle.net/h5Gsf/1/" rel="noreferrer">JSFiddle</a>. I've tested it in Internet Explorer 9, Chrome, Firefox, and Opera. So far, it seems to only work in Internet Explorer 9. (I don't know about Internet Explorer 8 and below.) Let me know if it works in another browser.</p> | 7,451,569 | 4 | 7 | null | 2011-09-17 00:05:07.273 UTC | 151 | 2020-04-09 19:14:02.087 UTC | 2018-03-21 02:01:54.077 UTC | null | 546,661 | null | 546,661 | null | 1 | 743 | javascript|naming-conventions|invalid-characters | 50,734 | <p>ಠ_ಠ
and 草泥马 only contain "letters" used in actual alphabets; that is, ಠ
is a symbol from the <a href="http://en.wikipedia.org/wiki/Kannada_alphabet">Kannada alphabet</a>, and 草泥马 consists of Chinese characters.</p>
<p>◎ and ☺, however, are purely symbols; they are not associated with any alphabet.</p>
<p>The <a href="http://es5.github.com/#x7.6">ECMAScript standard, chapter 7.6</a> (which all the browsers except Internet Explorer are following), states that an identifier must start with one of the following.</p>
<ul>
<li>a Unicode letter</li>
<li><code>$</code> or <code>_</code></li>
<li><code>\</code> followed by a unicode escape sequence.</li>
</ul>
<p>The following characters of an identifier must be one of the following.</p>
<ul>
<li>any of the characters permitted at the start</li>
<li>a Unicode combining mark</li>
<li>a Unicode digit</li>
<li>a Unicode connector punctuation</li>
<li>a zero-width-non-joiner</li>
<li>a zero-width joiner</li>
</ul>
<p>IE goes beyond the standard and is permissive enough to allow some symbols, such as ☺.</p>
<p>There’s <a href="http://mothereff.in/js-variables">a tool</a> that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1.</p> |
1,947,290 | Excel formula - auto sum for the same types | <p>I need a quick an simple excel formula to get the sum of values for different types of objects as listed below:</p>
<pre><code>Type1 10
Type1 10
Type1 10
Type2 10
Type2 10
Type2 10
Type2 10
Type3 10
Type3 10
</code></pre>
<p>Number of items and number of types are unknown (long list), in a different worksheet I would like to get sum of types like:</p>
<pre><code>Sumof Type1: 30
Sumof Type2: 40
Sumof Type3: 20
</code></pre>
<p>I need no VBA, just simple excel formula please..</p>
<p>BR</p> | 1,947,391 | 4 | 1 | null | 2009-12-22 15:59:54.333 UTC | 2 | 2017-02-08 21:10:04.62 UTC | null | null | null | null | 154,522 | null | 1 | 11 | excel | 43,683 | <p>I think <a href="http://www.techonthenet.com/excel/formulas/sumif.php" rel="noreferrer">sumif</a> is what you are looking for</p> |
10,784,132 | Django - No module named _sqlite3 | <p>I have django 1.4 installed on my rhel 5. By default rhel 5 has python 2.4 in it but to use django 1.4 I manually installed python 2.7.3
The development server is running fine but when I create a new project and after changing the settings.py file as :</p>
<p>'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/oracle/Desktop/test1/my.db'</p>
<p>Now when I give python2.7 manage.py syncdb command, I get the error as:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 443, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 69, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py",
line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py",
line 8, in <module>
from django.core.management.sql import custom_sql_for_model,
emit_post_sync_signal
File "/usr/local/lib/python2.7/site-packages/django/core/management/sql.py",
line 6, in <module>
from django.db import models
File "/usr/local/lib/python2.7/site-packages/django/db/__init__.py",
line 40, in <module>
backend = load_backend(connection.settings_dict['ENGINE'])
File "/usr/local/lib/python2.7/site-packages/django/db/__init__.py",
line 34, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/usr/local/lib/python2.7/site-packages/django/db/utils.py",
line 92, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/local/lib/python2.7/site-packages/django/db/utils.py",
line 24, in load_backend
return import_module('.base', backend_name)
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py",
line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py",
line 31, in <module>
raise ImproperlyConfigured("Error loading either pysqlite2 or
sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either
pysqlite2 or sqlite3 modules (tried in that order): No module named
_sqlite3
</code></pre>
<p>Please suggest the way out?</p> | 10,796,995 | 9 | 2 | null | 2012-05-28 11:43:41.907 UTC | 3 | 2020-03-11 08:11:29.01 UTC | 2020-03-11 08:11:29.01 UTC | null | 6,573,902 | null | 1,421,567 | null | 1 | 21 | django|python-2.7|sqlite|django-models|django-admin | 38,004 | <p>At the <a href="https://github.com/django/django/blob/1.5/django/db/backends/sqlite3/base.py#L27" rel="nofollow">django.db.backends.sqlite3</a>, it tries to</p>
<pre><code>try:
try:
from pysqlite2 import dbapi2 as Database
except ImportError:
from sqlite3 import dbapi2 as Database
except ImportError as exc:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
</code></pre>
<p>So one of the modules named <strong><a href="http://www.sqlite.org/" rel="nofollow">sqlite3</a></strong> or <strong><a href="http://pypi.python.org/pypi/pysqlite/" rel="nofollow">pysqlite2</a></strong> is not installed.
Try to install them</p>
<pre><code>$ pip install sqlite3 # or pysqlite2
</code></pre>
<p><strong>Update</strong></p>
<p><code>sqlite3</code> and <code>pysqlite2</code> are part of Python, therefore these two packages are not in <a href="https://pypi.python.org" rel="nofollow">PyPi</a> anymore.</p> |
26,033,239 | List of objects to JSON with Python | <p>I have a problem converting <code>Object</code> instances to JSON:</p>
<pre><code>ob = Object()
list_name = scaping_myObj(base_url, u, number_page)
for ob in list_name:
json_string = json.dumps(ob.__dict__)
print json_string
</code></pre>
<p>In <code>list_name</code> I have a list of <code>Object</code> instances.</p>
<p><code>json_string</code> return, for example:</p>
<pre><code>{"city": "rouen", "name": "1, 2, 3 Soleil"}
{"city": "rouen", "name": "Maman, les p'tits bateaux"}
</code></pre>
<p>But I would like just 1 JSON string with all the info in a list:</p>
<pre><code>[{"city": "rouen", "name": "1, 2, 3 Soleil"}, {"city": "rouen", "name": "Maman, les p'tits bateaux"}]
</code></pre> | 26,033,300 | 3 | 2 | null | 2014-09-25 07:46:20.473 UTC | 12 | 2019-09-19 15:25:00.28 UTC | 2014-09-25 07:53:58.153 UTC | null | 100,297 | null | 4,046,638 | null | 1 | 54 | python|json|object|serialization | 116,289 | <p>You can use a list comprehension to produce a list of dictionaries, then convert that:</p>
<pre><code>json_string = json.dumps([ob.__dict__ for ob in list_name])
</code></pre>
<p>or use a <code>default</code> function; <code>json.dumps()</code> will call it for anything it cannot serialise:</p>
<pre><code>def obj_dict(obj):
return obj.__dict__
json_string = json.dumps(list_name, default=obj_dict)
</code></pre>
<p>The latter works for objects inserted at any level of the structure, not just in lists.</p>
<p>Personally, I'd use a project like <a href="https://marshmallow.readthedocs.io/" rel="noreferrer">marshmallow</a> to handle anything more complex; e.g. handling your example data could be done with</p>
<pre><code>from marshmallow import Schema, fields
class ObjectSchema(Schema):
city = fields.Str()
name = fields.Str()
object_schema = ObjectSchema()
json_string = object_schema.dumps(list_name, many=True)
</code></pre> |
49,019,022 | How to check a projects vue.js version? | <p>I use <strong>Ubuntu 16.04</strong> and I'd like to know how I check the <code>vue.js</code> <strong>version</strong> used by my project.</p>
<p>How do I do that?</p> | 49,020,316 | 9 | 6 | null | 2018-02-27 22:30:15.663 UTC | 9 | 2022-07-15 19:39:32.157 UTC | 2020-01-18 08:08:01.293 UTC | null | 2,512,022 | null | 8,824,387 | null | 1 | 84 | vue.js | 156,546 | <p>Let's summarize the solutions from @jonrsharpe, @JamesAMohler and @MartinCalvert for friends looking for a quick answer.</p>
<ol>
<li><p>Run <code>npm list vue</code> (or <code>npm list --depth=0 | grep vue</code> to exclude packages' dependencies). It is <a href="https://docs.npmjs.com/cli/ls" rel="noreferrer">a common way</a> to check npm package's version in the terminal.</p>
</li>
<li><p>Of course, you can also check vuejs's version by browsing package.json (or use command like <code>less package.json | grep vue</code>).</p>
</li>
<li><p>Use <code>Vue.version</code> during the runtime. It is a <a href="https://v2.vuejs.org/v2/api/#Vue-version" rel="noreferrer">global API</a> provided in vue.js.</p>
</li>
</ol> |
7,100,243 | Finding in elements in a tuple and filtering them | <p>Assuming I have a tuple like:</p>
<pre><code>[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
</code></pre>
<p>I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:</p>
<pre><code>[('img-1','iii'), ('img-2','jjj')]
</code></pre>
<p>Thanks!</p> | 7,100,256 | 5 | 0 | null | 2011-08-17 22:20:36.79 UTC | 4 | 2021-02-02 13:30:42.22 UTC | 2015-06-16 16:24:53.267 UTC | null | 4,852,410 | null | 614,954 | null | 1 | 21 | python | 51,223 | <p>One way:</p>
<pre><code>>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> [t for t in l if t[0].startswith('img')]
[('img-1', 'iii'), ('img-2', 'jjj')]
</code></pre>
<p>Another way:</p>
<pre><code>>>> filter(lambda x: x[0].startswith('img'), l)
[('img-1', 'iii'), ('img-2', 'jjj')]
</code></pre>
<p>The first is called a list comprehension. See <a href="https://stackoverflow.com/questions/7100243/finding-in-elements-in-a-tuple-and-filtering-them/7100289#7100289">F.C.'s answer</a> for a related technique. The basic syntax is <code>[{expression} for {item_var_or_vars} in {iterable} if {boolean_expression}]</code>. It's semantically equivalent to something like this:</p>
<pre><code>new_list = []
for {item_var_or_vars} in {iterable}:
if {boolean_expression}:
new_list.append({expression})
</code></pre>
<p>The <code>if {boolean_expression}</code> bit is optional, just as it is in the for loop. </p>
<p>The second is simply the built-in function <code>filter</code>, which accepts a test function and an iterable, and returns a list containing every element that "passes" the test function. <code>lambda</code>, if you haven't seen it before, is just a quick way of defining a function. You could do this instead:</p>
<pre><code>def keep_this_element(element):
return element[0].startswith('img') # returns True for ('img...', '...')
new_list = filter(keep_this_element, l) # keeps only elements that return True
</code></pre> |
7,206,442 | Printing all possible subsets of a list | <p>I have a List of elements (1, 2, 3), and I need to get the superset (powerset) of that list (without repeating elements). So basically I need to create a List of Lists that looks like:</p>
<pre><code>{1}
{2}
{3}
{1, 2}
{1, 3}
{2, 3}
{1, 2, 3}
</code></pre>
<p>What is the best (simplicity > efficiency in this case, the list won't be huge) way to implement this? Preferably in Java, but a solution in any language would be useful.</p> | 7,206,478 | 7 | 4 | null | 2011-08-26 14:44:04.793 UTC | 9 | 2020-12-21 16:00:34.73 UTC | 2011-08-27 01:26:02.533 UTC | null | 312,172 | null | 835,523 | null | 1 | 9 | java|algorithm|powerset|superset | 12,887 | <p>Use bitmasks:</p>
<pre><code>int allMasks = (1 << N);
for (int i = 1; i < allMasks; i++)
{
for (int j = 0; j < N; j++)
if ((i & (1 << j)) > 0) //The j-th element is used
System.out.print((j + 1) + " ");
System.out.println();
}
</code></pre>
<p>Here are all bitmasks:</p>
<pre><code>1 = 001 = {1}
2 = 010 = {2}
3 = 011 = {1, 2}
4 = 100 = {3}
5 = 101 = {1, 3}
6 = 110 = {2, 3}
7 = 111 = {1, 2, 3}
</code></pre>
<p>You know in binary the first bit is the rightmost.</p> |
7,068,919 | Devise limit one session per user at a time | <p>My app is using Rails 3.0.4 and Devise 1.1.7.</p>
<p>I'm looking for a way to prevent users from sharing accounts as the app is a subscription based service. I've been searching for over a week, and I still don't know how to implement a solution. I'm hoping someone has implemented a solution and can point me in the right direction. </p>
<p><strong>Solution</strong> (Thank you everyone for your answers and insight!)</p>
<p>In application controller.rb</p>
<pre><code>before_filter :check_concurrent_session
def check_concurrent_session
if is_already_logged_in?
sign_out_and_redirect(current_user)
end
end
def is_already_logged_in?
current_user && !(session[:token] == current_user.login_token)
end
</code></pre>
<p>In session_controller that overrides Devise Sessions controller:</p>
<pre><code>skip_before_filter :check_concurrent_session
def create
super
set_login_token
end
private
def set_login_token
token = Devise.friendly_token
session[:token] = token
current_user.login_token = token
current_user.save
end
</code></pre>
<p>In migration AddLoginTokenToUsers</p>
<pre><code>def self.up
change_table "users" do |t|
t.string "login_token"
end
end
def self.down
change_table "users" do |t|
t.remove "login_token"
end
end
</code></pre> | 7,069,053 | 7 | 1 | null | 2011-08-15 18:23:17.117 UTC | 33 | 2019-01-15 08:54:14.553 UTC | 2011-08-16 21:26:19.06 UTC | null | 564,761 | null | 564,761 | null | 1 | 54 | ruby-on-rails|ruby-on-rails-3|session|devise | 24,000 | <p>You can't do it.</p>
<ul>
<li>You can control IP addresses of user, so you can prevent presence of user from two IP at a time. ANd you can bind login and IP. You can try to check cities and other geolocation data through IP to block user.</li>
<li>You can set cookies to control something else.</li>
</ul>
<p>But none of this will guarantee that only one user uses this login, and that those 105 IP from all over the world doesn't belong to only one unique user, which uses Proxy or whatever.</p>
<p>And the last: you never need this in the Internet.</p>
<p><strong>UPD</strong></p>
<blockquote>
<p>However, what I'm asking is about limiting multiple users from using the same account simultaneously which I feel should be possible</p>
</blockquote>
<p>So you can store some token, that will contain some encrypted data: IP + secret string + user agent + user browser version + user OS + any other personal info: <code>encrypt(IP + "some secret string" + request.user_agent + ...)</code>. And then you can set a session or cookie with that token. And with each request you can fetch it: if user is the same? Is he using the same browser and the same browser version from the same OS etc.</p>
<p>Also you can use dynamic tokens: you change token each request, so only one user could use system per session, because each request token will be changed, another user will be logged out as far as his token will be expired.</p> |
7,405,740 | How can I initialize base class member variables in derived class constructor? | <p>Why can't I do this?</p>
<pre><code>class A
{
public:
int a, b;
};
class B : public A
{
B() : A(), a(0), b(0)
{
}
};
</code></pre> | 7,405,776 | 7 | 3 | null | 2011-09-13 17:09:51.557 UTC | 37 | 2020-06-04 18:22:30.23 UTC | 2018-03-24 06:15:33.22 UTC | null | 3,980,929 | null | 170,120 | null | 1 | 160 | c++|inheritance | 186,437 | <p>You can't initialize <code>a</code> and <code>b</code> in <code>B</code> because they are not members of <code>B</code>. They are members of <code>A</code>, therefore only <code>A</code> can initialize them. You can make them public, then do assignment in <code>B</code>, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in <code>A</code> to allow <code>B</code> (or any subclass of <code>A</code>) to initialize them:</p>
<pre><code>class A
{
protected:
A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
// Change "protected" to "public" to allow others to instantiate A.
private:
int a, b; // Keep these variables private in A
};
class B : public A
{
public:
B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
{
}
};
</code></pre> |
7,692,161 | What is "pom" packaging in maven? | <p>I was given a maven project to compile and get deployed on a tomcat server. I have never used maven before today, but I have been googling quite a bit. It seems like the top level <code>pom.xml</code> files in this project have the packaging type set as <code>pom</code>.</p>
<p>What am I supposed to do after <code>mvn install</code> to get this application deployed? I was expecting to be able to find a <code>war</code> file somewhere or something, but I guess I am looking in the wrong place or missing a step.</p> | 7,692,214 | 10 | 1 | null | 2011-10-07 19:45:38.4 UTC | 49 | 2021-01-22 14:26:16.193 UTC | 2017-11-07 06:25:48.54 UTC | null | 5,105,305 | null | 229,072 | null | 1 | 203 | java|tomcat|maven | 166,085 | <p><code>pom</code> is basically a container of submodules, each submodule is represented by a subdirectory in the same directory as <code>pom.xml</code> with <code>pom</code> packaging.</p>
<p>Somewhere, nested within the project structure you will find artifacts (modules) with <code>war</code> packaging. Maven generally builds everything into <code>/target</code> subdirectories of each module. So after <code>mvn install</code> look into <code>target</code> subdirectory in a module with <code>war</code> packaging.</p>
<p>Of course:</p>
<pre><code>$ find . -iname "*.war"
</code></pre>
<p>works equally well ;-).</p> |
14,084,406 | TypeScript and Socket.io | <p>I would like to use socket.io in my Typescript project, but I've only found .d.ts files for server-side typescript.</p>
<p>This is a nice example: <a href="https://github.com/soywiz/typescript-node-definitions/blob/master/socket.io.d.ts" rel="noreferrer">https://github.com/soywiz/typescript-node-definitions/blob/master/socket.io.d.ts</a></p>
<p>It shows how to use TypeScript in combination with Socket.io. However on the client side it uses JavaScript.</p>
<p>What I need is a .d.ts file for client-side TypeScript, that resolves the error message from this line:</p>
<pre><code>var socket=io.connect("localhost");
</code></pre>
<blockquote>
<p>The name "io" does not exist in the current scope</p>
</blockquote>
<p>Where can I find the appropriate definition file?</p> | 42,222,758 | 4 | 0 | null | 2012-12-29 17:55:42.263 UTC | 6 | 2020-07-15 16:36:14.137 UTC | 2014-03-30 19:23:02.227 UTC | null | 24,874 | null | 497,600 | null | 1 | 11 | javascript|node.js|web|socket.io|typescript | 42,859 | <p>There is @types/socket.io now, just install it by running:</p>
<p><code>npm i --save @types/socket.io</code></p> |
13,949,422 | jquery html 5 dragstart .on('dragstart',function(e){}) e.dataTransfer.setData() doesn't work | <p>chrome throw err: Cannot call method 'setData' of undefined,
I find the e is not equal to window.event(it havn't propert dataTransfer);both has very big different</p>
<p>I find both almost equal in the click event.</p>
<p>I used <a href="http://code.jquery.com/jquery-latest.js" rel="noreferrer">http://code.jquery.com/jquery-latest.js</a>.</p>
<p>I don't use drag feature,I just want know why.
it is new feature in html 5,jquery still behind of it ?.
or jquery team don't want support it?? or some other reason</p> | 13,950,239 | 2 | 1 | null | 2012-12-19 09:41:00.343 UTC | 4 | 2013-04-22 18:28:14.743 UTC | 2012-12-19 09:53:47.883 UTC | null | 1,621,519 | null | 1,621,519 | null | 1 | 30 | javascript|jquery|html|drag | 40,498 | <p>In the callback function you get a jQuery wrapper over a native event. Use the <code>originalEvent</code> property of passed argument:</p>
<pre><code>$('...').on('dragstart', function (event) {
event.originalEvent.dataTransfer.setData('...', '...');
});
</code></pre>
<p>P.S. dont' forget to set the <code>draggable="true"</code> attribute for the element to be dragged.</p> |
13,911,468 | How do I open the Bluetooth Settings Activity programmatically? | <p>I want to open bluetooth settings on button click
like this see image<img src="https://i.stack.imgur.com/PHlob.png" alt="bluetooth image"></p>
<p><strong>HomeActivity.java</strong></p>
<pre><code>button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.bluetoothSettings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( intent);
}
});
</code></pre> | 13,911,556 | 6 | 1 | null | 2012-12-17 09:31:17.963 UTC | 3 | 2022-07-01 07:04:55.823 UTC | 2015-06-09 07:50:20.393 UTC | null | 304,151 | null | 1,391,158 | null | 1 | 37 | android|android-intent|settings | 42,975 | <p>use</p>
<pre><code>ComponentName cn = new ComponentName("com.android.settings",
"com.android.settings.bluetooth.BluetoothSettings");
</code></pre>
<p>instead of</p>
<pre><code>final ComponentName cn = new ComponentName("com.android.settings",
"com.android.settings.bluetoothSettings");
</code></pre>
<p>to launch BluetoothSettings settings </p> |
9,229,849 | Sencha Touch 2.0 MVC tutorial | <p>I am very new to Sencha Touch framework, want to start with Sencha Touch 2.0 but not able to find any tutorial showing an application built using MVC Pattern and specifically in Sencha Touch version 2.0.</p> | 9,230,004 | 3 | 1 | null | 2012-02-10 15:08:37 UTC | 16 | 2017-10-22 09:53:05.323 UTC | 2017-10-22 09:53:05.323 UTC | null | 472,495 | null | 277,696 | null | 1 | 13 | sencha-touch|sencha-touch-2 | 25,503 | <p>Here are two videos from the sencha 2011 conference:</p>
<p>SenchaCon 2011: MVC in Depth Part 1
<a href="https://vimeo.com/33311074" rel="noreferrer">https://vimeo.com/33311074</a></p>
<p>and</p>
<p>SenchaCon 2011: MVC in Depth Part 2
<a href="https://vimeo.com/33430731" rel="noreferrer">https://vimeo.com/33430731</a></p>
<p>Also you can check their blog for other short tutorials. </p>
<p>Another video to better understand Sencha Touch 2 </p>
<p>SenchaCon 2011: The Sencha Class System <a href="https://vimeo.com/33437222" rel="noreferrer">https://vimeo.com/33437222</a></p> |
9,232,132 | Use of JMX and How to use for existing applications | <p>We have distributed web application developed few years back on JDK 5.</p>
<blockquote>
<p>How JMX will help this application?</p>
</blockquote>
<p>1) Will it help me to monitor performance (Memory, CPU and Network & Disk IO)? </p>
<p>2) If so then application is deployed in multiple servers,how can I monitor in one single dashboard?</p>
<p>3) Do I have to make any new code changes to the existing application or can I monitor without code changes? </p>
<p>4) What else can we do apart from performance monitoring? Because name is Management Extensions (MX) what can we manage and how? It seems primary objective is not monitoring, it is management?</p>
<p>I couldn’t get much about JMX from the tutorial provided in Oracle website <a href="http://docs.oracle.com/javase/tutorial/jmx/overview/why.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/jmx/overview/why.html</a>. It seems some business representative prepared this tutorial not a techie.</p>
<p>Can anyone help me in understanding this JMX stuff, your efforts are sincerely appreciated.</p>
<p>Thanks,
Your Friend.</p> | 9,235,042 | 1 | 1 | null | 2012-02-10 17:32:33.48 UTC | 9 | 2016-10-20 17:55:16.033 UTC | 2012-02-10 18:49:20.633 UTC | null | 327,813 | null | 327,813 | null | 1 | 16 | java|jmx|jconsole|performance | 11,258 | <p>JMX is a standardized way of getting information out of a running system and to invoke operations on it. The JVM gives you a set of MBeans through which you can access runtime data like memory consumption, GC stats and some more data. You can also invoke a number of operations. Your app server will also give you a number of MBeans which you can use to control the server and installed applications.</p>
<ol>
<li>Yes, it will give you some performance data. See <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/management/overview.html" rel="noreferrer">http://docs.oracle.com/javase/1.5.0/docs/guide/management/overview.html</a> for a list of resources.</li>
<li>This depends on your application server. If it support clustered environments, it will probably give you a dashboard.</li>
<li>If you are fine with the standard JVM and app server MBeans, you won't need do any changes. But you may want to write your own MBean to give specific application status and statistics or ways to control your application. See <a href="http://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html</a></li>
<li>Well, you can do anything you like in a standardized way.</li>
</ol>
<p>Take a look at jconsole (included in the JDK) to see what JMX offers for you!</p> |
9,211,208 | How to draw border on just one side of a linear layout? | <p>I'm able to draw border to a linear layout, but it is getting drawn on all sides. I want to restrict it to right side only, like you do in CSS (border-right:1px solid red;).</p>
<p>I've tried this, but it still draws on all sides:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<stroke
android:height="2dp"
android:width="2dp"
android:color="#FF0000" />
<solid android:color="#000000" />
<padding
android:bottom="0dp"
android:left="0dp"
android:right="1dp"
android:top="0dp" />
<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="5dp"
android:radius="1dp"
android:topLeftRadius="5dp"
android:topRightRadius="0dp" />
</shape>
</item>
</code></pre>
<p></p>
<p>Any suggestions on how to accomplish this?</p>
<p>BTW, I do not want to use the hack of putting a view of width 1dp on the required side.</p> | 9,212,584 | 11 | 1 | null | 2012-02-09 12:54:58.34 UTC | 76 | 2022-01-31 13:16:16.663 UTC | 2013-10-22 06:41:55.827 UTC | null | 918,472 | null | 967,062 | null | 1 | 213 | android | 207,436 | <p>You can use this to get border on one side</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
</code></pre>
<p><strong>EDITED</strong></p>
<p>As many including me wanted to have a one side border with transparent background, I have implemented a <code>BorderDrawable</code> which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a <code>BorderFrameLayout</code> in which your layout can be wrapped.</p>
<p>See my <a href="https://github.com/vivekkhandelwal/kLib-android">github</a> for the complete source.</p> |
44,667,242 | Python Asyncio in Django View | <p>I would like to make two POST requests from an API on a Django view at the same time.</p>
<p>This is how I would do it outside of django.</p>
<pre><code>import asyncio
import speech_recognition as sr
async def main(language1, language2):
loop = asyncio.get_event_loop()
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=lang, show_all=True))
future1 = loop.run_in_executor(None, reco_ibm, str(language1))
future2 = loop.run_in_executor(None, reco_ibm, str(language2))
response1 = await future1
response2 = await future2
loop = asyncio.get_even_loop()
loop.run_until_complete(main("en-US", "es-ES"))
</code></pre>
<p>I'm confused about the event loop. How can I do this inside my Django view? Do I need to use nested functions for this?</p>
<pre><code>def ibmaudio_ibm(request, language1, language2):
#Asyncio code here
</code></pre>
<p>Edit: How is this even considered a duplicate? Parallel calls and schedulling with crontab are completely different things...</p> | 44,683,173 | 4 | 3 | null | 2017-06-21 05:08:23.39 UTC | 10 | 2021-12-13 15:35:18.803 UTC | 2017-06-21 18:03:10.083 UTC | null | 4,135,058 | null | 4,135,058 | null | 1 | 19 | python|django | 19,264 | <p>Solution was to nest the function inside another one.</p>
<pre><code>def djangoview(request, language1, language2):
async def main(language1, language2):
loop = asyncio.get_event_loop()
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=lang, show_all=True))
future1 = loop.run_in_executor(None, reco_ibm, str(language1))
future2 = loop.run_in_executor(None, reco_ibm, str(language2))
response1 = await future1
response2 = await future2
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(language1, language2))
loop.close()
return(HttpResponse)
</code></pre> |
32,695,991 | How to get Last digit of number | <p>How to extract last(end) digit of the Number value using jquery.
because i have to check the last digit of number is 0 or 5. so how to get last digit after decimal point</p>
<p>For Ex.
<code>var test = 2354.55</code> Now how to get 5 from this numeric value using jquery.
i tried <strong>substr</strong> but that is only work for string not for Number format</p>
<p>Like if i am use <code>var test = "2354.55";</code></p>
<p>then it will work but if i use <code>var test = 2354.55</code> then it will not.</p> | 32,696,112 | 8 | 3 | null | 2015-09-21 13:04:10.89 UTC | 6 | 2021-03-14 12:59:44.793 UTC | null | null | null | null | 4,349,267 | null | 1 | 37 | javascript|jquery | 104,624 | <p>Try this one:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var test = 2354.55;
var lastone = +test.toString().split('').pop();
console.log("lastone-->", lastone, "<--typeof", typeof lastone);
// with es6 tagged template and es6 spread
let getLastDigit = (str, num)=>{
return num.toString();
};
let test2 = 2354.55;
let lastone2 = +[...getLastDigit`${test2}`].pop();
console.log("lastone2-->", lastone2, "<--typeof", typeof lastone2);</code></pre>
</div>
</div>
</p>
<hr>
<p>Updates with ES6/ES2015: </p>
<p>We can use tagged template in such case as numbers are not iterable. So, we need to convert the number to a string representation of it. Then just spread it and get the last number popped.</p> |
32,665,958 | Xcode updating is extremely slow | <p>After updating my gadgets with iOS 9 I've tried to update Xcode to Xcode 7 on my Mac through the App Store, but updating is too slow while speedtest.net shows that my download speed is about 30 mbps. What to do?</p> | 32,666,283 | 6 | 4 | null | 2015-09-19 08:19:43.95 UTC | 6 | 2019-08-23 01:51:39.86 UTC | 2019-05-12 09:46:33.48 UTC | null | 1,033,581 | null | 4,697,508 | null | 1 | 39 | xcode|app-store|xcode7 | 44,537 | <p>You can always download the <code>dmg</code> for new or earlier versions of <code>Xcode</code> (or any other developer tool for that matter) from <a href="https://developer.apple.com/downloads/">this link</a> provided by Apple for iOS and Mac developers.</p> |
32,717,251 | How to set project.version by passing version property on gradle command line? | <p>I want to build JAR with self-defined version passed via command line, such as:</p>
<p>When I execute gradle build task like this:</p>
<pre><code>gradle build -Pversion=1.0
</code></pre>
<p>myproject-1.0.jar should be generated. </p>
<p>I have tried adding the line below to the <strong><em>build.gradle</em></strong>, but it did not work:</p>
<pre><code>version = project.hasProperty('version') ? project['version'] : '10.0.0'
</code></pre> | 32,718,189 | 7 | 5 | null | 2015-09-22 12:44:57.873 UTC | 20 | 2021-07-18 02:15:32.75 UTC | null | null | null | null | 317,429 | null | 1 | 62 | java|groovy|gradle | 96,549 | <p>You are not able to override existing project properties from command line, take a look <a href="https://discuss.gradle.org/t/project-property-command-line-overrides-broken/2330">here</a>. So try to rename a version variable to something differing from version and set it with <code>-P</code> flag before command, like:</p>
<pre><code>gradle -PprojVersion=10.2.10 build
</code></pre>
<p>And then in your build.gradle</p>
<pre><code>if (project.hasProperty('projVersion')) {
project.version = project.projVersion
} else {
project.version = '10.0.0'
}
</code></pre>
<p>Or as you did with ?: operator</p> |
45,789,325 | Update some specific field of an entity in android Room | <p>I am using android room persistence library for my new project.
I want to update some field of table.
I have tried like in my <code>Dao</code> -</p>
<pre><code>// Method 1:
@Dao
public interface TourDao {
@Update
int updateTour(Tour tour);
}
</code></pre>
<p>But when I try to update using this method then it updates every field of the entity where it matches primary key value of tour object.
I have used <code>@Query</code></p>
<pre><code>// Method 2:
@Query("UPDATE Tour SET endAddress = :end_address WHERE id = :tid")
int updateTour(long tid, String end_address);
</code></pre>
<p>It is working but there will be many queries in my case because I have many fields in my entity. I want to know how can I update some field (not all) like <code>Method 1</code> where id = 1; (id is the auto generate primary key).</p>
<pre><code>// Entity:
@Entity
public class Tour {
@PrimaryKey(autoGenerate = true)
public long id;
private String startAddress;
private String endAddress;
//constructor, getter and setter
}
</code></pre> | 45,796,463 | 9 | 4 | null | 2017-08-21 04:29:01.613 UTC | 43 | 2022-02-04 23:59:44.13 UTC | 2018-10-24 18:20:18.74 UTC | null | 1,687,469 | null | 3,926,727 | null | 1 | 191 | android|sql-update|android-room | 187,898 | <blockquote>
<p>I want to know how can I update some field(not all) like method 1 where id = 1</p>
</blockquote>
<p>Use <code>@Query</code>, as you did in Method 2.</p>
<blockquote>
<p>is too long query in my case because I have many field in my entity</p>
</blockquote>
<p>Then have smaller entities. Or, do not update fields individually, but instead have more coarse-grained interactions with the database.</p>
<p><strike>IOW, there is nothing in Room itself that will do what you seek.</strike></p>
<p><strong>UPDATE 2020-09-15</strong>: Room now has partial entity support, which can help with this scenario. See <a href="https://stackoverflow.com/a/59834309/115145">this answer</a> for more.</p> |
19,495,610 | Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova | <p>Today I tried PhoneGap/Cordova with <strong>Mac OS X Mavericks</strong>. Building for iOS went just fine, but building for Android wasn't without some guesswork.</p>
<p>I installed Android 4.2.2 via the Android SDK Manager (I had to use the older <strong>API v17</strong> since it wasn't compatible with a newer one), added the <strong><code>PATH environment variables</code></strong> for the SDK's <code>platform-tools</code> and <code>tools</code> and thought I was ready to take off by running the command: </p>
<pre><code>phonegap run android
</code></pre>
<p>Nevertheless, I got the following error:</p>
<pre><code>[phonegap] detecting Android SDK environment...
[phonegap] using the local environment
[phonegap] adding the Android platform...
<b>[error] An error occured during creation of android sub-project. ERROR : executing command 'ant', make sure you have ant installed and added to your path.</b></code></pre> | 19,495,611 | 7 | 2 | null | 2013-10-21 13:16:38.463 UTC | 32 | 2014-11-04 11:19:03.673 UTC | 2014-11-04 11:19:03.673 UTC | null | 3,622,940 | null | 1,265,240 | null | 1 | 139 | android|cordova|ant|osx-mavericks | 101,519 | <p>The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.</p>
<p>Bulletproof solution:</p>
<ol>
<li><p>Download and install Homebrew by executing following command in terminal:</p>
<blockquote>
<p>ruby -e "$(curl -fsSL <a href="https://raw.githubusercontent.com/Homebrew/install/master/install">https://raw.githubusercontent.com/Homebrew/install/master/install</a>)"</p>
</blockquote></li>
<li><p>Install Apache Ant via Homebrew by executing </p>
<blockquote>
<p>brew install ant</p>
</blockquote></li>
</ol>
<p>Run the PhoneGap build again and it should successfully compile and install your Android app.</p> |
19,616,629 | CSS Inherit for unknown Background Color is Actually Transparent | <p>I am creating a tab-like functionality with <code><ul></code> and <code><li></code> elements, and I noticed this kind-of unexpected behavior with CSS <code>background-color: inherit</code>.<br>
One would expect that <code>inherit</code> wouldn't actually mean <code>transparent</code>, but rather <code>child.background-color == parent.background-color</code> (forgive the pseudo-code).</p>
<p>My code is quite simple, but I have a problem: <strong>I'm developing for variable conditions</strong>. That means I could never know what background-color will be used with my code, and I don't want to introduce my own.</p>
<p>I have prepared a <a href="http://jsfiddle.net/NEbxR/">JSFiddle</a>, in which the background is randomly set on page load, to imitate the randomness of my code's destination. The obvious problem is that the active tab looks awful with its background-color pre-set. So, I changed it to <code>background-color: inherit</code>. (see <a href="http://jsfiddle.net/NEbxR/1/">JSFiddle 2</a>)</p>
<p>While this obviously solved the background issue, the border of the element below (<code>cg_content</code>) started showing again, because the <code>inherit</code> property, acts like <code>transparent</code>, instead of what it does when there is a set background-color.</p>
<p>Question is: <strong>Is there a way to make it inherit the actual background-color without Javascript?</strong><br>
<strong>If not, could you suggest a better way to make these tabs look good without pre-set colors?</strong></p>
<p>P.S.: The content <code><div></code> should not be a child element of the <code><li></code> elements, as these tabs share some contents.<br>
P.S.2: I can't make it any more clear, that I obviously know how to do this with JS. I just don't want to.</p> | 19,616,684 | 2 | 2 | null | 2013-10-27 09:40:37.373 UTC | 4 | 2020-12-19 03:19:12.237 UTC | null | null | null | null | 1,554,215 | null | 1 | 29 | html|css|tabs|background-color | 61,944 | <p>Setting <code>background-color: inherit</code> <strong>does</strong> cause it to take the background colour of the parent element. </p>
<p>The reason it is taking <code>transparent</code> is because the background colour of the parent (the <code>li</code>) <strong>is</strong> <code>transparent</code> (the default value).</p>
<p>The only other element in your second JSFiddle which has a background colour set is <code>#unknown_background</code>, which is the anchor's great-great-grandparent.</p>
<p>Add <code>div, ul, li { background-color: inherit; }</code> to the end of your stylesheet and the background will be inherited all the way down and the border will not show up.</p> |
34,312,252 | "exclude" property of tsconfig.json is not being respected | <p>I am working with the excellent Express/Node/Typescript example code found <a href="https://github.com/czechboy0/Express-4x-Typescript-Sample" rel="noreferrer" title="here">here</a>. It transpiles the .ts code with the following command from run.sh:</p>
<p><code>./node_modules/.bin/tsc --sourcemap --module commonjs ./bin/www.ts</code></p>
<p>This works as advertised, but I would prefer to use a tsconfig.json file and <code>tsc -p .</code> However, when I run that command I get a raft of <code>TS2300: Duplicate identifier 'foo' errors</code>when <code>tsc</code>(erroneously?) tries to walk the <code>./node_modules</code> and <code>./typings</code> directories. Below is the tsconfig.json I am using:</p>
<pre><code>{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings"
]
}
</code></pre>
<p>Any ideas? I am using tsc 1.7.3 FWIW.</p> | 34,312,696 | 9 | 3 | null | 2015-12-16 12:36:14.917 UTC | 4 | 2022-03-01 10:02:22.303 UTC | 2015-12-16 12:47:30.927 UTC | null | 2,760,795 | null | 2,760,795 | null | 1 | 41 | node.js|typescript|tsd | 40,303 | <p>I did:</p>
<pre><code>git clone https://github.com/czechboy0/Express-4x-Typescript-Sample.git
cd Express-4x-Typescript-Sample/
./run.sh
tsd install # I don't know why, but this helped me.
./run.sh
</code></pre>
<p>I created <code>Express-4x-Typescript-Sample/tsconfig.json</code> file with content</p>
<pre><code>{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings"
]
}
</code></pre>
<p>I ran</p>
<pre><code>[...]/Express-4x-Typescript-Sample$ tsc -p .
</code></pre>
<p>and it works work me - i.e. there are no errors.</p> |
34,092,346 | Remove key from a Json inside a JsonObject | <p>I have JsonObject like below</p>
<pre><code>{"status":"ACTIVE","accounts":{"email":"[email protected]","name":"Test"}}
</code></pre>
<p>How can I remove Json key "email" and its value from the JsonObject by using something like <code>jsonObj.remove("email")</code> in java</p>
<p>JsonObj.removev working for me if I need to remove status key <code>jsonObj.remove("status")</code></p>
<p>Update </p>
<p>Some more background,
This is for mainly testing a rest end point. In my test I created java object matching to payload with Builder pattern and then covert to Json using GsonBuilder like</p>
<pre><code>import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
public class JsonConvertor() {
public static JsonObject convertToJsonObject(Object payload) {
GsonBuilder builder = new GsonBuilder();
return (JsonObject) builder.setFieldNamingPolicy(FieldNamingPolicy.Policy).
create().toJsonTree(payload);
}}
</code></pre>
<p>If I need to remove a required field I use, JsonObj.remove("key") on Json Object created by above function. </p> | 34,093,558 | 4 | 4 | null | 2015-12-04 15:59:26.41 UTC | 9 | 2022-09-07 12:05:25.73 UTC | 2015-12-04 16:49:44.183 UTC | null | 2,604,853 | null | 2,604,853 | null | 1 | 30 | java|json | 115,608 | <p>If Gson is like Jackson (I assume so) you'll have to first get the <code>JsonObject</code> "accounts" from the root object and then remove the member "email", e.g. like this:</p>
<pre><code>jsonObj.getAsJsonObject("accounts").remove("email");
</code></pre>
<p>Alternatively - and probably the preferred way - you would map the json object to a POJO (one that has the fields "status", "accounts" and "accounts" would point to another POJO), navigate to the accounts-POJO and set "email" to null there. Then you reformat the root POJO to JSON and apply a setting that omits fields with null values.</p>
<p><strong>Edit</strong> (answer to the question in the comment):</p>
<p>To make it short, I don't know whether there is a built-in functionality or not but it should be doable.</p>
<p>The problem is that if you just provide keys like <code>email</code> etc. you might get situations where there are multiple keys so identifying the correct one could be hard. Thus it might be better to provide the key as <code>accounts.email</code> and split the "key" into sub-expressions and then traverse the Json tree using the parts or convert the Json to a POJO and use some expression language (e.g. Java EL or OGNL) to traverse the POJO.</p>
<p>If you want to remove all properties named <code>email</code> you could just travers the entire json tree, check whether there is a property with that name and if so remove it.</p> |
24,792,638 | How can I import data from ASCII (ISO/IEC 8859-1) to my Rails/PGSQL database? | <p>I am trying to use data from the USDA found here: <a href="http://www.ars.usda.gov/Services/docs.htm?docid=23634" rel="noreferrer">http://www.ars.usda.gov/Services/docs.htm?docid=23634</a></p>
<blockquote>
<p>ASCII (8.6Mb) - This file contains the SR26 data in ASCII (ISO/IEC 8859-1), delimited files. These tables are organized in a relational format, and are best used with a relational database management system (RDBMS), which will allow you to form your own queries of the database and generate custom reports.</p>
</blockquote>
<p>I am new to manipulating data like this and think I would like to get it in CSV, maybe? But, then I might lose the relationships so maybe I should go right to PGSQL. Not sure how to approach this. </p>
<p>Looking for guidance, thanks.</p> | 24,793,469 | 3 | 2 | null | 2014-07-16 23:41:37.29 UTC | 9 | 2018-04-08 15:23:14.303 UTC | 2014-07-17 01:24:32.27 UTC | null | 398,670 | null | 2,842,709 | null | 1 | 14 | mysql|ruby-on-rails|postgresql|ruby-on-rails-4|import | 2,754 | <p>The zip contains a number of files:</p>
<pre><code> inflating: DATA_SRC.txt
inflating: DATSRCLN.txt
inflating: DERIV_CD.txt
inflating: FD_GROUP.txt
inflating: FOOD_DES.txt
inflating: FOOTNOTE.txt
inflating: LANGDESC.txt
inflating: LANGUAL.txt
inflating: NUT_DATA.txt
inflating: NUTR_DEF.txt
inflating: sr26_doc.pdf
inflating: SRC_CD.txt
inflating: WEIGHT.txt
</code></pre>
<p>each of which appears to be in a bizarre almost-CSV-like format, e.g. <code>NUTR_DEF.txt</code>:</p>
<pre><code>~287~^~g~^~GALS~^~Galactose~^~2~^~2100~
~291~^~g~^~FIBTG~^~Fiber, total dietary~^~1~^~1200~
</code></pre>
<p>plus <code>sr26_doc.pdf</code>, the documentation.</p>
<h2>Creating table definitions</h2>
<p>So what you need to do here is create SQL table definitions for the database - with one table for each input file. You need the <code>CREATE TABLE</code> command for this; see the PostgreSQL documentation.</p>
<p>Page 35 of the PDF should help you - "Figure 1. Relationships among files in the USDA National Nutrient Database for Standard Reference". The following pages describe the file formats, telling you what each column means. You can write <code>CREATE TABLE</code> statements based on this description.</p>
<p>Here's an example, for <code>FOOD_DES.txt</code> (food description), the first entry.</p>
<pre><code>CREATE TABLE food_des (
"NDB_No" varchar(5) NOT NULL PRIMARY KEY,
"FdGrp_Cd" varchar(4) NOT NULL,
"Long_Desc" varchar(200) NOT NULL,
"Shrt_Desc" varchar(60) NOT NULL,
"ComName" varchar(100),
"ManufacName" varchar(65),
"Survey" varchar(1),
"Ref_desc" varchar(135),
"Refuse" smallint,
"SciName" varchar(65),
"N_Factor" NUMERIC(4,2),
"Pro_Factor" NUMERIC(4,2),
"Fat_Factor" NUMERIC(4,2),
"CHO_Factor" NUMERIC(4,2)
);
</code></pre>
<p>That's a pretty literal copy of the description. It's not how I'd design the table</p>
<p>I've used <code>NUMERIC</code> arbitrary-precision decimal floating point types for accuracy in non-integer numeric types. If performance is more important than accuracy, you can use <code>float4</code> instead.</p>
<p>For relationships, you use <code>FOREIGN KEY</code> constraints - just <code>colname coltype REFERENCES othertable(othercol)</code> is sufficient to create one.</p>
<p><strong>Important</strong>: I double quoted the column names to preserve the same name as in the definitions. That means you have to always double quote them when you refer to them, e.g. <code>SELECT "NDB_No" FROM food_des;</code> . If you don't want that, just leave off the double quotes - or pick different names. You don't have to stick to the clumsy abbreviated column names they used, and it's quite reasonable to write:</p>
<pre><code>CREATE TABLE food_description (
ndb_no varchar(5) NOT NULL PRIMARY KEY,
foodgroup_code varchar(4) NOT NULL,
long_description varchar(200) NOT NULL,
short_description varchar(60) NOT NULL,
common_name varchar(100),
manufacturer_name varchar(65),
</code></pre>
<p>etc. Similarly, if you're working with Rails, you can convert the table definitions to follow Rails's conventions, especially if you then intend to do the data loading via Rails.</p>
<h2>Loading data</h2>
<p>If these were sane, sensible delimited files you could then just load each table using the <code>psql</code> command <code>\copy</code>, or PgAdmin-III's "import" option. </p>
<p>It is actually CSV, they've just decided to use totally bizarre delimiter and quote chars. Import via <code>psql</code> with:</p>
<pre><code>\copy food_des FROM 'FOOD_DES.txt' (FORMAT CSV, DELIMITER '^', QUOTE '~');
</code></pre>
<p>or the equivalent in whatever tool you use to talk to PostgreSQL.</p>
<p>The results are a sensible looking table:</p>
<pre><code>craig=> select * from food_des limit 2;
NDB_No | FdGrp_Cd | Long_Desc | Shrt_Desc | ComName | ManufacName | Survey | Ref_desc | Refuse | SciName | N_Factor | Pro_Factor | Fat_Factor | CHO_Factor
--------+----------+----------------------------+--------------------------+---------+-------------+--------+----------+--------+---------+----------+------------+------------+------------
01001 | 0100 | Butter, salted | BUTTER,WITH SALT | | | Y | | 0 | | 6.38 | 4.27 | 8.79 | 3.87
01002 | 0100 | Butter, whipped, with salt | BUTTER,WHIPPED,WITH SALT | | | Y | | 0 | | 6.38 | 4.27 | 8.79 | 3.87
(2 rows)
</code></pre>
<p>Similarly, if using Rails you can use whatever Rails CSV library you want and bulk-load into models.</p> |
201,476 | Simple java client code for Web Service - something to do with QName? | <p>I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.</p>
<pre><code>Element or attribute do not match QName production: QName::=(NCName':')?NCName
</code></pre>
<p>Have I got something wrong with QName?- I can't even find any useful information about it.</p>
<p>My client code is below:</p>
<pre><code>import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class TestClient {
public static void main(String [] args)
{
try{
String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( new QName("http://testPackage.fc.com/, doBasicStuff") );
String ret = (String) call.invoke( new Object[] {"some kind of message"} );
System.out.println(ret);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
</code></pre>
<p>My web serivce code is really basic - just a simple class that returns your input string with a bit of concat text:</p>
<pre><code>public String doBasicStuff(String message)
{
return "This is your message: " + message;
}
</code></pre> | 201,508 | 5 | 1 | null | 2008-10-14 14:50:10.103 UTC | 1 | 2012-12-15 00:29:32.98 UTC | 2009-03-18 09:56:28.01 UTC | Dreas Grech | 44,084 | Simon E | 5,175 | null | 1 | 2 | java|web-services|client|rpc | 56,470 | <p>As the exception says, you call the QName constructor incorrectly:</p>
<pre><code>new QName("http://testPackage.fc.com/, doBasicStuff")
</code></pre>
<p>is incorrect. I think you have to pass two strings, one containing the namespace, one the localname. The documentation will typically contain a description on how to use that class.</p> |
459,677 | C#, a String's Split() method | <p>C#, a String's Split() method, how can I put the resulting string[] into an ArrayList or Stack? </p> | 459,680 | 5 | 0 | null | 2009-01-19 23:58:35.003 UTC | 7 | 2015-08-17 06:30:29.87 UTC | 2009-01-20 08:39:43.143 UTC | Ed Swangren | 1,053 | Steve | 56,898 | null | 1 | 19 | c#|arrays|collections|split|arraylist | 66,574 | <p>You can initialize a <code>List<T></code> with an array (or any other object that implements <code>IEnumerable</code>). You should prefer the strongly typed <code>List<T></code> over <code>ArrayList</code>.</p>
<pre><code>var myList = new List<string>(myString.Split(','));
</code></pre> |
993,124 | Does Haskell have variables? | <p>I've frequently heard claims that Haskell doesn't have variables; in particular, <a href="https://stackoverflow.com/questions/333185/what-type-of-scope-does-haskell-use/333219#333219">this answer</a> claims that it doesn't, and it was upvoted at least nine times and accepted.</p>
<p>So does it have variables or not, and why?</p>
<p>This question also appears to apply ML, F#, OCaml, Erlang, Oz, Lava, and all <a href="http://en.wikipedia.org/wiki/Static_single_assignment_form" rel="noreferrer">SSA</a> intermediate languages.</p> | 993,779 | 5 | 2 | null | 2009-06-14 16:15:30.873 UTC | 9 | 2019-05-08 22:05:03.897 UTC | 2017-05-23 12:34:30.953 UTC | null | -1 | null | 107,294 | null | 1 | 35 | variables|haskell|immutability|monads|referential-transparency | 40,548 | <p>Haskell has immutable variables (variables in the math sense) by default:</p>
<pre><code> foo x y = x + y * 2
</code></pre>
<p>By default variables are not <em>mutable cells</em>.</p>
<p>Haskell also has mutable cells though, but you enable them explicitly:</p>
<pre><code> > import Data.IORef (newIORef, readIORef, writeIORef)
> v <- newIORef 0
> readIORef v
0
> writeIORef v 7
> readIORef v
7
</code></pre>
<p>So, <em>YES</em> Haskell has true variables. But it does not use mutable variables by default.</p> |
352,612 | How to get Maven to run war:exploded but not war:war | <p>I have a Maven pom that uses <code><packaging>war</packaging></code>. But actually, I don't want build the war-file, I just want all the dependent jars collected and a full deployment directory created.</p>
<p>So I'm running the <code>war:exploded</code> goal to generate the deploy directory:</p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<configuration>
<webappDirectory>target/${env}/deploy</webappDirectory>
<archiveClasses>true</archiveClasses>
</configuration>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
</plugin>
</code></pre>
<p>The trouble is, the war file still gets built. Is there a simple way of having <code><packaging>war</packaging></code> execute the <code>war:exploded</code> goal instead of the war:war goal?</p>
<p>Or is there another simple way to do this?</p> | 1,530,489 | 5 | 2 | null | 2008-12-09 12:49:58.933 UTC | 15 | 2016-08-24 05:27:22.293 UTC | 2013-12-27 08:08:06.833 UTC | null | 451,518 | Adrian Pronk | 41,861 | null | 1 | 60 | maven-2 | 37,895 | <p>According <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Built-in_Lifecycle_Bindings" rel="noreferrer">builtin lifecycle bindings</a> for war packaging in package phase war:war mojo is called.</p>
<p>You can call previous 'prepare-package' phase - all actions will be performed and after that call mojo war:exploded</p>
<pre><code>mvn prepare-package war:exploded
</code></pre>
<p>The results will be the same as yours but no war created.</p> |
461,901 | ASP.NET Control to HTML tag equivalent | <p>I'm looking for a cheat sheet that will allow me to show an HTML designer the equivalent asp.net controls for standard HTML tags. As an example the <asp:Panel> will render as an HTML <div> and an <asp:Label> will render as an HTML <span>. I've been googling this to no avail. Can someone post a link to a good cheat sheet so that the designers on this project can understand the markup on the aspx pages more clearly. </p>
<p>To be clear, I would like a link to a list of major ASP.NET controls, with descriptions as to how they would relate to standard HTML. It would be great if this were in PDF format or on an easy to read and print web page. The reason, in my case, would be that we have a PHP developer who is very familiar with HTML coming to work on our project, and I feel it would be useful to have a better understanding of standard ASP.NET server controls if I could hand him such a "cheat sheet". </p>
<p>I'm referring mainly to the .NET 2.0 framework, but we are also doing work with 3.0/3.5.</p> | 462,013 | 5 | 1 | null | 2009-01-20 15:59:58.917 UTC | 33 | 2017-06-20 12:36:58.703 UTC | 2009-01-20 19:05:16.25 UTC | stephenbayer | 18,893 | stephenbayer | 18,893 | null | 1 | 63 | asp.net|html|tags|servercontrols | 62,314 | <p>This isn't a simple question, as it depends on which version of .NEt you're talking about and states of controls sometimes. For example, the PANEL, in 1 & 1.1 render to a TABLE while in later versions it's a DIV.</p>
<p>But overall (for 2/3), here goes:</p>
<ul>
<li><p>Panel - Div</p>
</li>
<li><p>Panel -- GroupingText="###" is Fieldset, Legend</p>
</li>
<li><p>Label - Span</p>
</li>
<li><p>Button - Input, Type Button</p>
</li>
<li><p>Link Button - Href with JS Postback Script</p>
</li>
<li><p>Hyperlink - Standard HREF</p>
</li>
<li><p>Image Button - Input, Type Image</p>
</li>
<li><p>Textbox -- Default is Input, Type Text</p>
</li>
<li><p>Textbox -- Mode = Password is Input, type Password</p>
</li>
<li><p>Textbox -- Mode= Multiline is Textarea</p>
</li>
<li><p>DropDownList - Select</p>
</li>
<li><p>Listbox - Select</p>
</li>
<li><p>RadioButton - Input, Radio with GroupName</p>
</li>
<li><p>Checkbox - Input, Checkbox</p>
</li>
<li><p>Repeater/Listview --Complex.</p>
</li>
<li><p>Gridview - Table</p>
</li>
<li><p>Table - Table</p>
</li>
<li><p>File - Input, Type=File</p>
<p>That's the basics. The more esoteric controls such as the LOGIN control is a table with a bunch of odds an ends within it.</p>
</li>
</ul> |
814,474 | JPA not saving foreign key to @OneToMany relation | <p>I'm using Spring with Hibernate as a JPA provider and are trying to get a @OneToMany (a contact having many phonenumbers) to save the foreign key in the phone numbers table. From my form i get a Contact object that have a list of Phone(numbers) in it. The Contact get persisted properly (Hibernate fetches an PK from the specified sequence). The list of Phone(numbers) also gets persisted with a correct PK, but there's no FK to the Contacts table. </p>
<pre><code>public class Contact implements Serializable {
@OneToMany(mappedBy = "contactId", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<Phone> phoneList;
}
public class Phone implements Serializable {
@JoinColumn(name = "contact_id", referencedColumnName = "contact_id")
@ManyToOne
private Contact contactId;
}
@Repository("contactDao")
@Transactional(readOnly = true)
public class ContactDaoImpl implements ContactDao {
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void save(Contact c) {
em.persist(c);
em.flush();
}
}
@Controller
public class ContactController {
@RequestMapping(value = "/contact/new", method = RequestMethod.POST)
public ModelAndView newContact(Contact c) {
ModelAndView mv = new ModelAndView("contactForm");
contactDao.save(c);
mv.addObject("contact", c);
return mv;
}
}
</code></pre>
<p>Hopefully I got all of the relevant bits above, otherwise please let me know.</p> | 814,495 | 6 | 0 | null | 2009-05-02 09:09:51.763 UTC | 9 | 2020-04-06 19:59:19.347 UTC | 2018-05-04 01:58:26.197 UTC | null | 771,217 | null | 149,374 | null | 1 | 22 | java|spring|jpa | 48,303 | <p>You have to manage the Java relationships yourself. For this kind of thing you need something like:</p>
<pre><code>@Entity
public class Contact {
@Id
private Long id;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "contact")
private List<Phone> phoneNumbers;
public void addPhone(PhoneNumber phone) {
if (phone != null) {
if (phoneNumbers == null) {
phoneNumbers = new ArrayList<Phone>();
}
phoneNumbers.add(phone);
phone.setContact(this);
}
}
...
}
@Entity
public class Phone {
@Id
private Long id;
@ManyToOne
private Contact contact;
...
}
</code></pre> |
554,522 | Something like inheritance in database design | <p>Suppose you were setting up a database to store crash test data of various vehicles. You want to store data of crash tests for speedboats, cars, and go-karts.</p>
<p>You could create three separate tables: SpeedboatTests, CarTests, and GokartTests. But a lot of your columns are going to be the same in each table (for example, the employee id of the person who performed the test, the direction of the collision (front, side, rear), etc.). However, plenty of columns will be different, so you don't want to just put all of the test data in a single table because you'll have quite a few columns that will always be null for speedboats, quite a few that will always be null for cars, and quite a few that will always be null for go-karts. </p>
<p>Let's say you also want to store some information that isn't directly related to the tests (such as the employee id of the designer of the thing being tested). These columns don't seem right to put in a "Tests" table at all, especially because they'll be repeated for all tests on the same vehicle.</p>
<p>Let me illustrate one possible arrangement of tables, so you can see the questions involved.</p>
<pre>
Speedboats
id | col_about_speedboats_but_not_tests1 | col_about_speedboats_but_not_tests2
Cars
id | col_about_cars_but_not_tests1 | col_about_cars_but_not_tests2
Gokarts
id | col_about_gokarts_but_not_tests1 | col_about_gokarts_but_not_tests2
Tests
id | type | id_in_type | col_about_all_tests1 | col_about_all_tests2
(id_in_type will refer to the id column of one of the next three tables,
depending on the value of type)
SpeedboatTests
id | speedboat_id | col_about_speedboat_tests1 | col_about_speedboat_tests2
CarTests
id | car_id | col_about_car_tests1 | col_about_car_tests2
GokartTests
id | gokart_id | col_about_gokart_tests1 | col_about_gokart_tests2
</pre>
<p>What is good/bad about this structure and what would be the preferred way of implementing something like this?</p>
<p>What if there's also some information that applies to all vehicles that you'd prefer to have in a Vehicles table? Would the CarTests table then look something like...</p>
<pre>
id | vehicle_id | ...
With a Vehicles table like this:
id | type | id_in_type
(with id_in_type pointing to the id of either a speedboat, car, or go-kart)
</pre>
<p>This is just getting to be a royal mess it seems. How SHOULD something like this be set up?</p> | 554,681 | 6 | 1 | null | 2009-02-16 20:55:44.813 UTC | 26 | 2014-06-18 14:46:20.653 UTC | 2014-06-18 14:46:20.653 UTC | null | 1,478,085 | Daniel Straight | 65,393 | null | 1 | 24 | database-design|polymorphic-associations|class-table-inheritance | 12,897 | <p>The <code>type</code> and <code>id_in_type</code> design is called <a href="http://en.wikipedia.org/wiki/Polymorphic_association" rel="noreferrer">Polymorphic Associations</a>. This design breaks rules of normalization in multiple ways. If nothing else, it should be a red flag that you <em>can't</em> declare a real foreign key constraint, because the <code>id_in_type</code> may reference any of several tables.</p>
<p>Here's a better way of defining your tables:</p>
<ul>
<li>Make an abstract table <code>Vehicles</code> to provide an abstract reference point for all vehicle sub-types and vehicle tests.</li>
<li>Each vehicle sub-type has a primary key that does not auto-increment, but instead references <code>Vehicles</code>.</li>
<li>Each test sub-type has a primary key that does not auto-increment, but instead references <code>Tests</code>.</li>
<li>Each test sub-type also has a foreign key to the corresponding vehicle sub-type.</li>
</ul>
<p>Here's sample DDL:</p>
<pre><code>CREATE TABLE Vehicles (
vehicle_id INT AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE Speedboats (
vehicle_id INT PRIMARY KEY,
col_about_speedboats_but_not_tests1 INT,
col_about_speedboats_but_not_tests2 INT,
FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id)
);
CREATE TABLE Cars (
vehicle_id INT PRIMARY KEY,
col_about_cars_but_not_tests1 INT,
col_about_cars_but_not_tests2 INT,
FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id)
);
CREATE TABLE Gokarts (
vehicle_id INT PRIMARY KEY,
col_about_gokarts_but_not_tests1 INT,
col_about_gokarts_but_not_tests2 INT,
FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id)
);
CREATE TABLE Tests (
test_id INT AUTO_INCREMENT PRIMARY KEY,
col_about_all_tests1 INT,
col_about_all_tests2 INT
);
CREATE TABLE SpeedboatTests (
test_id INT PRIMARY KEY,
vehicle_id INT NOT NULL,
col_about_speedboat_tests1 INT,
col_about_speedboat_tests2 INT,
FOREIGN KEY(test_id) REFERENCES Tests(test_id),
FOREIGN KEY(vehicle_id) REFERENCES Speedboats(vehicle_id)
);
CREATE TABLE CarTests (
test_id INT PRIMARY KEY,
vehicle_id INT NOT NULL,
col_about_car_tests1 INT,
col_about_car_tests2 INT,
FOREIGN KEY(test_id) REFERENCES Tests(test_id),
FOREIGN KEY(vehicle_id) REFERENCES Cars(vehicle_id)
);
CREATE TABLE GokartTests (
test_id INT PRIMARY KEY,
vehicle_id INT NOT NULL,
col_about_gokart_tests1 INT,
col_about_gokart_tests2 INT,
FOREIGN KEY(test_id) REFERENCES Tests(test_id),
FOREIGN KEY(vehicle_id) REFERENCES Gokarts(vehicle_id)
);
</code></pre>
<p>You could alternatively declare <code>Tests.vehicle_id</code> which references <code>Vehicles.vehicle_id</code> and get rid of the vehicle_id foreign keys in each test sub-type table, but that would permit anomalies, such as a speedboat test that references a gokart's id.</p> |
395,256 | Transparent images with C# WinForms | <p>I am working on a Windows Forms application in VS 2008, and I want to display one image over the top of another, with the top image being a gif or something with transparent parts.</p>
<p>Basically I have a big image and I want to put a little image on top if it, so that they kinda appear as one image to the user.</p>
<p>I've been trying to use a picturebox, but this doesn't seem to have worked, any suggestions?</p> | 434,706 | 6 | 2 | null | 2008-12-27 18:30:58.093 UTC | 10 | 2020-02-06 05:58:55.86 UTC | null | null | null | null | 30,025 | null | 1 | 25 | c#|.net|image|transparency|picturebox | 55,686 | <p>I was in a similar situation a couple of days ago. You can create a transparent control to host your image.</p>
<pre><code>using System;
using System.Windows.Forms;
using System.Drawing;
public class TransparentControl : Control
{
private readonly Timer refresher;
private Image _image;
public TransparentControl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
refresher = new Timer();
refresher.Tick += TimerOnTick;
refresher.Interval = 50;
refresher.Enabled = true;
refresher.Start();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20;
return cp;
}
}
protected override void OnMove(EventArgs e)
{
RecreateHandle();
}
protected override void OnPaint(PaintEventArgs e)
{
if (_image != null)
{
e.Graphics.DrawImage(_image, (Width / 2) - (_image.Width / 2), (Height / 2) - (_image.Height / 2));
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//Do not paint background
}
//Hack
public void Redraw()
{
RecreateHandle();
}
private void TimerOnTick(object source, EventArgs e)
{
RecreateHandle();
refresher.Stop();
}
public Image Image
{
get
{
return _image;
}
set
{
_image = value;
RecreateHandle();
}
}
}
</code></pre> |
545,667 | How to use Windows login for single-sign-on and for Active Directory entries for Desktop Java application? | <p>I'd like to have my desktop Java application to have single sign on related to
Active Directory users. In two steps, I'd like to:</p>
<ol>
<li>Be sure that the particular user has logged in to Windows with some user entry.</li>
<li>Check out some setup information for that user from the Active Directory</li>
</ol>
<p>With <a href="https://stackoverflow.com/questions/31394/java-programatic-way-to-determine-current-windows-user">Java: Programatic Way to Determine Current Windows User</a> I can get the name of the current Windows user but can I rely to that? I think the</p>
<pre><code>System.getProperty("user.name")
</code></pre>
<p>won't be secure enough? ("user.name" seems to be got from environment variables, so I can't rely on that, I think?)</p>
<p>Question <a href="https://stackoverflow.com/questions/390150/authenticating-against-active-directory-with-java-on-linux">Authenticating against Active Directory with Java on Linux</a>
provides me the authentication for given name+pass but I'd like to authenticate based on the Windows logon?</p>
<p>For the Active Directory access, LDAP would probably be the choice?</p> | 1,523,296 | 6 | 0 | null | 2009-02-13 11:52:08.54 UTC | 11 | 2019-07-17 19:38:58.743 UTC | 2019-07-17 19:38:58.743 UTC | Rich B | 2,756,409 | Touko | 28,482 | null | 1 | 30 | java|active-directory|single-sign-on|windows-authentication | 42,595 | <p>It is not supported. Java 6 has improvements, but not enough yet. </p>
<p>Java has its own GSS stack. The problem is for single sign-on, you need to get the Kerberos ticket from the OS (not the Java stack). Otherwise the user has to authenticate a second time (defeating the purpose of single sign-on).</p>
<p>Look at <a href="http://java.sun.com/developer/technicalArticles/J2SE/security/" rel="noreferrer">http://java.sun.com/developer/technicalArticles/J2SE/security/</a>. Look down for "Access Native GSS-API" and it talks about a new system property sun.security.jgss.native which when set to true causes Java to use the underlying OS GSS implementation, giving access to the OS level authentication. Perfect!.... except its only supported for Solaris and Linux, not Microsoft Windows.</p>
<p>Java 6 however does appear to have enough support for acting as a <em>server</em> receiving SPNEGO authentication requests from IE and then authenticating that user against Active Directory. Its just the desktop client support that is still incomplete.</p> |
1,019,740 | Speed of calculating powers (in python) | <p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p>
<pre><code>x*x
</code></pre>
<p>than</p>
<pre><code>x**2
</code></pre>
<p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication?
<br/></p>
<p><strong>Edit:</strong> Here's some example code I tried...</p>
<pre><code>def pow1(r, n):
for i in range(r):
p = i**n
def pow2(r, n):
for i in range(r):
p = 1
for j in range(n):
p *= i
</code></pre>
<p>Now, pow2 is just a quick example and is clearly not optimised!<br/>
But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/>
I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p> | 1,019,932 | 6 | 5 | null | 2009-06-19 19:46:44.33 UTC | 3 | 2014-07-25 08:25:08.353 UTC | 2009-06-19 20:20:02.157 UTC | null | 124,780 | null | 124,780 | null | 1 | 41 | python|algorithm|performance | 40,514 | <p>Basically naive multiplication is O(n) with a very low constant factor. Taking the power is O(log n) with a higher constant factor (There are special cases that need to be tested... fractional exponents, negative exponents, etc) . Edit: just to be clear, that's O(n) where n is the exponent.</p>
<p>Of course the naive approach will be faster for small n, you're only really implementing a small subset of exponential math so your constant factor is negligible. </p> |
31,081,644 | How to redirect back to form with input - Laravel 5 | <p>How do I redirect back to my form page, with the given <code>POST</code> params, if my form action throws an exception?</p> | 31,081,645 | 10 | 3 | null | 2015-06-26 20:29:18.747 UTC | 18 | 2022-02-20 19:47:10.037 UTC | null | null | null | null | 385,265 | null | 1 | 79 | php|forms|laravel|redirect|laravel-5 | 159,457 | <p>You can use the following:</p>
<pre class="lang-php prettyprint-override"><code>return Redirect::back()->withInput(Input::all());
</code></pre>
<p>If you're using <a href="http://laravel.com/docs/5.1/validation#form-request-validation" rel="noreferrer">Form Request Validation</a>, this is exactly how Laravel will redirect you back with errors and the given input.</p>
<p>Excerpt from <a href="https://github.com/laravel/framework/blob/ebd86d7d2ff4e34b24a0dd84d10bb77c13130222/src/Illuminate/Foundation/Validation/ValidatesRequests.php#L123-L125" rel="noreferrer"><code>\Illuminate\Foundation\Validation\ValidatesRequests</code></a>:</p>
<blockquote>
<pre><code>return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
</code></pre>
</blockquote> |
35,636,739 | Kafka Consumer Marking the coordinator 2147483647 dead | <p>I am using Kafka Server 0.9 with consumer kafka-client version 0.9 and kafka-producer 0.8.2.</p>
<p>Every thing is working great except i am getting lot of info that the coordinator is dead on the consumer</p>
<pre><code>2016-02-25 19:30:45.046 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.048 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.049 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.050 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.051 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.052 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.053 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.054 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.055 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.056 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.057 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.058 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.059 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.060 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.061 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.062 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.062 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.063 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.064 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.065 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.066 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.067 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.068 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.068 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.069 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.070 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.071 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.072 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.072 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.073 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.074 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.075 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.075 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.076 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.077 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.078 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.079 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.079 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.080 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.081 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.082 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.083 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.083 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.084 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.085 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.086 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.086 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.087 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.088 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.089 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.089 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.090 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.091 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.093 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.094 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-02-25 19:30:45.094 INFO 10263 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
</code></pre>
<p>I also noticed that the producer is having disconnect connect every 10 minute as the below </p>
<pre><code>2016-03-12 15:55:36 INFO [pool-1-thread-1] - Fetching metadata from broker id:0,host:192.168.72.30,port:9092 with correlation id 41675 for 1 topic(s) Set(act)
2016-03-12 15:55:36 INFO [pool-1-thread-1] - Connected to 192.168.72.30:9092 for producing
2016-03-12 15:55:36 INFO [pool-1-thread-1] - Disconnecting from 192.168.72.30:9092
2016-03-12 15:55:36 INFO [pool-1-thread-1] - Disconnecting from kafkauk.XXXXXXXXXX.co:9092
2016-03-12 15:55:36 INFO [pool-1-thread-1] - Connected to kafkauk.XXXXXXXXXX.co:9092 for producing
</code></pre>
<p>this is my producer configuration</p>
<pre><code>metadata.broker.list=192.168.72.30:9092
serializer.class=kafka.serializer.StringEncoder
request.required.acks=1
linger.ms=2000
batch.size=500
</code></pre>
<p>and consumer config</p>
<pre><code>bootstrap.servers: kafkauk.xxxxxxxx.co:9092
group.id: cdrServer
client.id: cdrServer
enable.auto.commit: true
auto.commit.interval.ms: 1000
session.timeout.ms: 30000
key.deserializer: org.apache.kafka.common.serialization.StringDeserializer
value.deserializer: org.apache.kafka.common.serialization.StringDeserializer
</code></pre>
<p>I could not figure out what does these mean and should i neglect them or i am missing something in the configuration </p>
<hr>
<p>After i change kafka to debug level on the consumer i found the below </p>
<pre><code>2016-03-13 18:21:55.586 DEBUG 5469 --- [ cdrServer] org.apache.kafka.clients.NetworkClient : Node 2147483647 disconnected.
2016-03-13 18:21:55.586 INFO 5469 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Marking the coordinator 2147483647 dead.
2016-03-13 18:21:55.586 DEBUG 5469 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Issuing group metadata request to broker 0
2016-03-13 18:21:55.586 DEBUG 5469 --- [ cdrServer] org.apache.kafka.clients.NetworkClient : Sending metadata request ClientRequest(expectResponse=true
, callback=null, request=RequestSend(header={api_key=3,api_version=0,correlation_id=183025,client_id=cdrServer}, body={topics=[act]}), isInitiatedByNetworkCli
ent, createdTimeMs=1457893315586, sendTimeMs=0) to node 0
2016-03-13 18:21:55.591 DEBUG 5469 --- [ cdrServer] org.apache.kafka.clients.Metadata : Updated cluster metadata version 296 to Cluster(nodes = [N
ode(0, kafkauk.xxxxxxxxx.co, 9092)], partitions = [Partition(topic = act, partition = 0, leader = 0, replicas = [0,], isr = [0,]])
2016-03-13 18:21:55.592 DEBUG 5469 --- [ cdrServer] o.a.k.c.c.internals.AbstractCoordinator : Group metadata response ClientResponse(receivedTimeMs=1457
893315592, disconnected=false, request=ClientRequest(expectResponse=true, callback=org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient$RequestFu
tureCompletionHandler@1e2de777, request=RequestSend(header={api_key=10,api_version=0,correlation_id=183024,client_id=cdrServer}, body={group_id=cdrServer}), c
reatedTimeMs=1457893315586, sendTimeMs=1457893315586), responseBody={error_code=0,coordinator={node_id=0,host=kafkauk.xxxxxxxx.co,port=9092}})
</code></pre>
<p>I am not sure it is a network problem because it happen every 9 minute exactly</p>
<hr>
<p>Update</p>
<p>I found that is directly related to </p>
<pre><code>connections.max.idle.ms: 300000
</code></pre>
<p>What ever i put then i will get disconnected at this value</p> | 37,912,724 | 7 | 2 | null | 2016-02-25 19:39:15.607 UTC | 6 | 2022-04-05 21:17:44.623 UTC | 2016-03-20 20:53:45.803 UTC | null | 3,224,122 | null | 3,224,122 | null | 1 | 23 | apache-kafka|kafka-consumer-api | 41,198 | <p>In my case the message was in logs when I try to assign partitions manually. After I've read in api docs of the new consumer follow notice: </p>
<blockquote>
<p>It is also possible for the consumer to manually assign specific partitions (similar to the older "simple" consumer) using assign(Collection). In this case, dynamic partition assignment and consumer group coordination will be disabled. </p>
</blockquote>
<p>That is, if you have code like this:</p>
<pre><code> KafkaConsumer<String, String> consumer = new KafkaConsumer(props);
consumer.assign( Arrays.asList(
new TopicPartition("topic", 0),
new TopicPartition("topic", 1)
));
</code></pre>
<p>then the message "Marking the coordinator 2147483647 dead" puts in our logs always.</p> |
21,111,534 | Why "long value" equals to null is allowed? | <p>When I was debugging a few lines of code and asking me why on earth it wasn't working I have stumbled on this situation ...</p>
<pre><code>if(answer.AnswerID == null)
{
// do something
}
</code></pre>
<p>When in fact it should be this way:</p>
<pre><code>if(answer == null)
{
// do something
}
</code></pre>
<ul>
<li><code>answer</code> is an object of the type <code>Answer - a class</code>.</li>
<li><code>AnswerID</code> is a property of type <code>long</code>.</li>
</ul>
<p>The weird thing is that if you try something like this:</p>
<pre><code>long myLongValue = null;
</code></pre>
<p>The compiler will show you an error: </p>
<pre><code>Connot convert null to long ...
</code></pre>
<p>So my question is: Why did I not get a <b>compile error</b> when I was trying to compare a <code>long type</code> with <code>null</code>?</p>
<p><b>EDITED</b></p>
<p>This question <b>IS NOT</b> about <code>nullable</code> types.</p>
<p>I'm asking WHY .NET allows me to compare a long variable with null. I'm talking about <code>long type</code> and not about <code>long<b>?</b> type</code>.</p> | 21,111,655 | 3 | 6 | null | 2014-01-14 10:43:50.387 UTC | 3 | 2014-05-16 14:53:55.48 UTC | 2014-05-16 14:53:55.48 UTC | null | 437,246 | null | 437,246 | null | 1 | 32 | c#|.net | 49,711 | <p>As <a href="https://stackoverflow.com/questions/21111534/why-long-value-equals-to-null-is-allowed/21111655#comment31762641_21111534">@Tim</a> pointed out, you won't get an error for the following code:</p>
<pre><code>long foo = 42;
if (foo == null) { }
</code></pre>
<p>You'll get a warning instead:</p>
<blockquote>
<p>The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?'.</p>
</blockquote>
<p>This gives a warning instead of an error because of <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/06/27/what-exactly-does-lifted-mean.aspx" rel="noreferrer">lifted operators</a>, defined in the C# language specification as such:</p>
<blockquote>
<p><em><strong>Lifted operators</strong></em> permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. [...] For the equality operators</p>
<pre><code>== !=
</code></pre>
<p>a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. <strong>The lifted form is constructed by adding a single ? modifier to each operand type.</strong> The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.</p>
</blockquote>
<p>The "underlying operator" in this case is <a href="http://msdn.microsoft.com/en-us/library/53k8ybth(v=vs.120).aspx" rel="noreferrer">the predefined value type <code>long</code>'s <code>==</code> operator</a>:</p>
<blockquote>
<p>For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise.</p>
</blockquote>
<p>Because <code>foo</code> is implicitly converted (<em>"Predefined implicit conversions that operate on non-nullable value types can also be used with nullable forms of those types.")</em> and the <code>null</code> literal is also implicitly converted (<em>"An implicit conversion exists from the null literal to any nullable type."</em>), the expression:</p>
<pre><code>(long)foo == null
</code></pre>
<p>Becomes:</p>
<pre><code>(long?)foo == (long?)null
</code></pre>
<p>Which, given <code>foo</code> is of type <code>long</code> and thus always has a value, always returns false and won't even apply <code>long</code>'s <code>==</code> operator.</p>
<p>I'm not entirely sure, but I suspect this to exist to enable comparison between nullable and non-nullable values without explicit casting:</p>
<pre><code>long? foo = 42;
long bar = 42;
Console.WriteLine(foo == bar); // true
foo = null;
Console.WriteLine(bar == foo); // false
</code></pre>
<p>If this wasn't handled by the language as specified above, you'd get <em>"Operator <code>==</code> cannot be applied to operands of type <code>long?</code> and <code>long</code>"</em>, because <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx" rel="noreferrer"><code>Nullable<T></code></a> doesn't have an <code>==</code> operator, and <code>long</code> doesn't have an <code>==</code> operator accepting a <code>long?</code>.</p> |
68,312,799 | Android Studio: "The emulator process for AVD Pixel_2_API_30 has terminated." on MacBook Pro M1 (Apple Silicon) | <p>I have a problem to start an Android Emulator on my MacBook Pro M1 (Apple Silicon). When I try to start an emulator (API 30, CPU/ABI arm64), I get this error: "The emulator process for AVD Pixel_2_API_30 has terminiated."</p>
<p>I'm using 2020.3.1 Beta 5 of Android Studio.</p>
<p>Does anyone know how to solve this problem?</p>
<p><a href="https://i.stack.imgur.com/B8Xmk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B8Xmk.png" alt="Error Message when starting an Android Emulator" /></a></p> | 68,313,121 | 13 | 2 | null | 2021-07-09 07:23:58.053 UTC | 4 | 2022-08-30 13:30:06.51 UTC | null | null | null | null | 8,358,501 | null | 1 | 38 | android|android-studio|android-emulator|apple-silicon | 56,371 | <p>It would seem due to the fact you are using a beta version of android studio the message "The emulator process for AVD Pixel_2_API_30 was killed." has been changed to "The emulator process for AVD Pixel_2_API_30 has terminated." but fundamentally they should still have the same solutions the most common solution being:</p>
<blockquote>
<p>"All of the answers are too confusing to follow. Replace SDK or
upgrade OS. The quickest way I found is to:</p>
<p>Tools > SDK Manager > SDK Tools</p>
<p>De-select Android Emulator, then click Apply. - The Android Emulator
will be deleted.</p>
<p>Now, by default the Emulator version shown will be 30.6.5. Select the
checkbox and click apply. This version of emulator will be installed.</p>
<p>That is it, just 2 minutes of you time.</p>
<p>Update: 1 Jul 2021 Issue solved with latest Emulator version 30.7.5"</p>
</blockquote>
<p>Credits to: <a href="https://stackoverflow.com/users/1505493/karan-sharma">Karan Sharma</a> in the post <a href="https://stackoverflow.com/a/68141022/10411757">found here</a></p>
<p>If this does not fix the error then there are a multitude of different solutions that can be found by googling "Android studio MacBook emulator process for AVD was killed." or simply downgrading/upgrading your emulator works too, because it is a common issue with the v30.6.x emulator versions.</p> |
2,330,157 | iPhone : making UIBarButtonItem that is arrow shaped | <p>I have a UIBarButtonItem on a navigation bar. I'd like to make it arrow shaped. By that I mean I want it to be square except for a pointy side. Does anyone know how to do this?</p>
<p>Thanks!</p> | 2,433,896 | 6 | 0 | null | 2010-02-24 22:33:32.257 UTC | 14 | 2014-03-26 19:53:53.503 UTC | null | null | null | null | 2,684,342 | null | 1 | 11 | iphone|xcode|uinavigationcontroller|uibarbuttonitem | 33,786 | <p>I wrestled with several approaches on this one and finally figured it out using all the answers from several sources. There are a couple of tricks; this snippet will show it all (I was creating a custom <code>rightNavButton</code>, but you can adapt this easily for any <code>UIBarButtonItem</code>):</p>
<pre><code>// Produces a nice "right arrow" style button that mirrors the back arrow
// automatically added by the navController
//
UIImage *buttonImage = [UIImage imageNamed:@"forwardButton.png"];
UIButton *forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
[forwardButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[forwardButton setTitle:@"Meter" forState:UIControlStateNormal];
forwardButton.font = [UIFont boldSystemFontOfSize:12];
forwardButton.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[forwardButton addTarget:self action:@selector(showMeter)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithCustomView:forwardButton];
</code></pre>
<p>Note: it turns out that if you try to set the target and action directly on the button item after assigning a custom view using a <code>UIButton</code> that it won't take - you have to set the target and action on the button itself - apparently the <code>navBar</code> uses the button provided verbatim.</p>
<p><strike>This is the image I was using on the opaque black <code>navBar</code> (you can use anything, obviously): <a href="http://raretiger.com/images/forwardbutton.png" rel="nofollow noreferrer">http://raretiger.com/images/forwardbutton.png</a></strike></p> |
1,457,842 | Is this good code? (copy constructor and assignment operator ) | <p>For one reason or another, I'm forced to provide both a copy constructor and an operator= for my class. I thought I didn't need <code>operator=</code> if I defined a copy ctor, but <code>QList</code> wants one. Putting that aside, I hate code duplication, so is there anything wrong with doing it this way?</p>
<pre><code>Fixture::Fixture(const Fixture& f) {
*this = f;
}
Fixture& Fixture::operator=(const Fixture& f) {
m_shape = f.m_shape;
m_friction = f.m_friction;
m_restitution = f.m_restitution;
m_density = f.m_density;
m_isSensor = f.m_isSensor;
return *this;
}
</code></pre>
<p>And just out of curiosity, there's no way to switch it so that the bulk of the code is in the copy ctor and <code>operator=</code> somehow utilizes it? I tried <code>return Fixture(f);</code> but it didn't like that.</p>
<hr>
<p>It appears I need to make it more clear that the copy constructor and assignment operator have been implicitly disabled by the class I am inheriting from. Why? Because it's an abstract base class that shouldn't be instantiated on its own. This class, however, <em>is</em> meant to stand alone.</p> | 1,457,873 | 6 | 8 | null | 2009-09-22 02:20:33.43 UTC | 9 | 2015-07-01 08:49:37.85 UTC | 2015-07-01 08:49:37.85 UTC | null | 1,122,645 | null | 65,387 | null | 1 | 13 | c++|operator-overloading|copy-constructor | 3,987 | <p>This is bad, because the <code>operator=</code> can't rely on a set-up object anymore. You should do it the other way around, and can use the copy-swap idiom. </p>
<p>In the case where you just have to copy over all elements, you can use the implicitly generated assignment operator. </p>
<p>In other cases, you will have to do something in addition, mostly freeing and copying memory. This is where the copy-swap idiom is good for. Not only is it elegant, but it also provide so an assignment doesn't throw exceptions if it only swaps primitives. Let's a class pointing to a buffer that you need to copy:</p>
<pre><code>Fixture::Fixture():m_data(), m_size() { }
Fixture::Fixture(const Fixture& f) {
m_data = new item[f.size()];
m_size = f.size();
std::copy(f.data(), f.data() + f.size(), m_data);
}
Fixture::~Fixture() { delete[] m_data; }
// note: the parameter is already the copy we would
// need to create anyway.
Fixture& Fixture::operator=(Fixture f) {
this->swap(f);
return *this;
}
// efficient swap - exchanging pointers.
void Fixture::swap(Fixture &f) {
using std::swap;
swap(m_data, f.m_data);
swap(m_size, f.m_size);
}
// keep this in Fixture's namespace. Code doing swap(a, b)
// on two Fixtures will end up calling it.
void swap(Fixture &a, Fixture &b) {
a.swap(b);
}
</code></pre>
<p>That's how i write the assignment operator usually. Read <a href="http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">Want speed? Pass by value</a> about the unusual assignment operator signature (pass by value). </p> |
2,001,755 | Using int as a type parameter for java.util.Dictionary | <p>When I try to declare a Dictionary as such:</p>
<pre><code>private Dictionary<String, int> map;
</code></pre>
<p>The compiler gives me the following error:</p>
<blockquote>
<p>Syntax error on token "int", Dimensions expected after this token</p>
</blockquote>
<p>But it works fine with <code>Integer</code>. I'm vaguely aware that Java treats <code>int</code> / <code>Integer</code> differently (I come from a .NET background), but I was hoping someone could give me a full explanation on why I can't use primitives in a Dictionary<></p> | 2,001,777 | 6 | 3 | null | 2010-01-04 19:51:56.373 UTC | 4 | 2011-08-31 20:20:34.117 UTC | 2011-08-31 20:20:34.117 UTC | null | 561,690 | null | 3,603 | null | 1 | 34 | java|dictionary|primitive | 41,724 | <p>In Java primitives aren't objects, so you can't use them in place of objects. However Java will automatically box/unbox primitives (aka <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html" rel="noreferrer">autoboxing</a>) into objects so you can do things like:</p>
<pre><code>List<Integer> intList = new LinkedList<Integer>();
intList.add(1);
intList.add(new Integer(2));
...
Integer first = intList.get(0);
int second = intList.get(1);
</code></pre>
<p>But this is really just the compiler automatically converting types for you. </p> |
2,231,500 | Error connecting to all of my SQL servers | <p>I suddenly started getting this error when trying to connect to any of my sql servers (25+) from SSMS on Windows XP. When I left work yesterday everything was working fine, came in this morning, and I started getting this. Tried rebooting my pc but that obviously didn't fix it. My co-workers can all connect just fine. Searched for a solution but everything I found was regarding encryption in regards to .NET applications. Not sure how to apply that to SSMS.
<a href="http://picasaweb.google.com/lh/photo/-l9VrFuYXk-A80NzZ1kzng?feat=directlink">alt text http://picasaweb.google.com/lh/photo/-l9VrFuYXk-A80NzZ1kzng?feat=directlink</a></p>
<p>For some reason the image won't work so the error is this:</p>
<p><strong>A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.) (Microsoft SQL Server)</strong></p> | 2,231,739 | 7 | 1 | null | 2010-02-09 18:35:03.347 UTC | 1 | 2022-01-24 18:50:12.393 UTC | null | null | null | null | 193,284 | null | 1 | 14 | sql-server-2005|security|windows-xp|ssms | 45,443 | <p>Try this...</p>
<p>Its gotta be a client issue if you lost connection to all your remote servers and your coworkers are fine. You probably got "clicky" and changed some settings inadvertantly.</p>
<p>Open your client network utility (mine is here: C:\WINDOWS\system32\cliconfg.exe).
Under the General Tab, check out the disabled protocols. They should all have "force protocol encryption" <strong>unchecked</strong>. If this is checked for any of those values, your local SSMS is probably trying to force an encrypted connection and failing.</p>
<p>Report back if this doesn't work, and I'll poke around a bit more.</p> |
1,804,991 | Remove dom element without knowing its parent? | <p>Is it possible to remove a dom element that has no parent other than the body tag? I know this would be easy with a framework like jquery, but I'm trying to stick to straight javascript.</p>
<p>Here's the code I've found to do it otherwise:</p>
<pre><code>function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
</code></pre>
<p>Thanks!</p> | 1,805,001 | 7 | 5 | null | 2009-11-26 18:00:34.657 UTC | 4 | 2017-08-14 11:18:59.717 UTC | null | null | null | null | 174,621 | null | 1 | 45 | javascript|removechild | 41,317 | <p>You should be able to get the parent of the element, then remove the element from that</p>
<pre><code>function removeElement(el) {
el.parentNode.removeChild(el);
}
</code></pre>
<p><strong>Update</strong></p>
<p>You can set this as a new method on the HTMLElement:</p>
<pre><code>HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }
</code></pre>
<p>And then do <code>el.remove()</code> (which will also return the element)</p> |
1,638,834 | How to check if a file exists in Documents folder? | <p>I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.</p>
<p>Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.</p>
<p>How I can do that? With <code>NSFileManager</code> I can't get outside of <code>mainBundle</code>..</p> | 1,638,853 | 7 | 1 | null | 2009-10-28 17:33:26.82 UTC | 60 | 2020-05-20 11:39:12.897 UTC | 2017-05-15 15:04:27.507 UTC | null | 2,990,682 | null | 196,894 | null | 1 | 219 | ios|iphone|xcode|webview|nsfilemanager | 151,926 | <h3>Swift 3:</h3>
<pre><code>let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
</code></pre>
<p>... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:</p>
<pre><code>let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
</code></pre>
<h3>Objective-C:</h3>
<pre><code>NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
</code></pre> |
1,503,959 | How to count occurrences of a column value efficiently in SQL? | <p>I have a table of students:</p>
<pre><code>id | age
--------
0 | 25
1 | 25
2 | 23
</code></pre>
<p>I want to query for all students, and an additional column that counts how many students are of the same age:</p>
<pre><code>id | age | count
----------------
0 | 25 | 2
1 | 25 | 2
2 | 23 | 1
</code></pre>
<p>What's the most efficient way of doing this? <strong>I fear that a sub-query will be slow, and I'm wondering if there's a better way</strong>. Is there?</p> | 1,503,980 | 7 | 0 | null | 2009-10-01 13:27:26.927 UTC | 55 | 2022-01-30 18:41:13.293 UTC | 2009-10-01 13:41:07.443 UTC | null | 11,208 | null | 11,208 | null | 1 | 224 | sql|performance | 548,540 | <p>This should work:</p>
<pre><code>SELECT age, count(age)
FROM Students
GROUP by age
</code></pre>
<p>If you need the id as well you could include the above as a sub query like so:</p>
<pre><code>SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
</code></pre> |
2,259,544 | Is wchar_t needed for unicode support? | <p>Is the <code>wchar_t</code> type required for unicode support? If not then what's the point of this multibyte type? Why would you use wchar_t when you could accomplish the same thing with <code>char</code>?</p> | 2,259,615 | 8 | 1 | null | 2010-02-13 23:32:01.653 UTC | 14 | 2015-10-21 17:11:03.157 UTC | null | null | null | null | 440,093 | null | 1 | 38 | c++|c|unicode | 20,207 | <h3>No.</h3>
<p>Technically, no. Unicode is a standard that defines code points and it does not require a particular encoding.</p>
<p>So, you could use unicode with the UTF-8 encoding and then everything would fit in a one or a short sequence of <code>char</code> objects and it would even still be null-terminated.</p>
<p>The problem with UTF-8 and UTF-16 is that <code>s[i]</code> is not necessarily a character any more, it might be just a piece of one, whereas with sufficiently wide characters you can preserve the abstraction that <code>s[i]</code> is a single character, tho it does not make <em>strings</em> fixed-length under various transformations.</p>
<p>32-bit integers are at least wide enough to solve the code point problem but they still don't handle corner cases, e.g., upcasing something can change the number of characters.</p>
<p>So it turns out that the <code>x[i]</code> problem is not completely solved even by char32_t, and those other encodings make poor file formats.</p>
<p>Your implied point, then, is quite valid: <code>wchar_t</code> is a failure, partly because Windows made it only 16 bits, and partly because it didn't solve every problem and was horribly incompatible with the byte stream abstraction.</p> |
2,203,525 | Are the x,y and row, col attributes of a two-dimensional array backwards? | <p>If I think of the x,y coordinate plane, x,y is the common notation for an ordered pair, but if I use a two-dime array I have myArray[row][col] and row is the y and col is the x. Is that backwards or am I just thinking about it wrong? I was thinking it would look like myArray[x][y] but that's wrong if I want real rows and columns (like in a gameboard.) Wouldn't it be myArray[y][x] to truly mimic a row column board?</p> | 2,203,610 | 8 | 1 | null | 2010-02-04 21:54:11.947 UTC | 19 | 2022-09-05 22:33:46.85 UTC | 2022-09-05 22:29:50.25 UTC | null | 1,459,996 | null | 28,045 | null | 1 | 58 | multidimensional-array|coordinate-systems|mathematical-notation | 46,630 | <p>You have it right, and it does feel a bit backwards. The row number is a y coordinate, and the column number is an x coordinate, and yet we usually write row,col but we also usually write x,y.</p>
<p>Whether you want to write your array as [y][x] or [x][y] depends mostly on how much you actually care about the layout of your array in memory (and if you do, what language you use). And whether you want to write functions/methods that can operate on rows or columns in isolation.</p>
<p>If you are writing C/C++ code, arrays are stored in <a href="http://en.wikipedia.org/wiki/Row-major_order" rel="nofollow noreferrer">Row Major Order</a> which means that a single row of data can be treated as 1 dimensional array. But a single column of data cannot. If I remember correctly, VB uses column major order, so languages vary. I'd be surprised of C# isn't also row major order, but I don't know.</p> |
1,784,132 | Intellij Community can't use http proxy for Maven | <p>I have Intellij IDEA Community installed on a Linux box that needs to use an authenticated proxy to get to the Internet. I have a system-wide proxy on the box that works, and I have the proxy configured in ~/.m2/settings.xml. Maven correctly uses the proxy when I run try it from the command-line. </p>
<p>I have the same proxy configured within Intellij and it gives me the plugins listing correctly. But when I try to sync with the Maven repository withing Intellij I keep getting this:</p>
<pre><code>[WARNING] Unable to get resource 'org.codehaus.mojo:hibernate3-maven-plugin:pom:2.2'
from repository restlet (http://maven.restlet.org): Authorization failed: Not
authorized by proxy.
</code></pre>
<p>I went to Settings->Maven and put in the proxy info as properties and that didn't work. I can see by looking at those settings that Intellij is reading my ~./m2/settings.xml fine because it knows where my local repo is (it's in a non-standard place).</p>
<p>Anyone know how I can get this working?</p> | 1,784,459 | 9 | 0 | null | 2009-11-23 16:07:36.083 UTC | 17 | 2022-01-04 09:14:20.157 UTC | 2009-11-29 21:45:38.61 UTC | null | 112,671 | null | 39,188 | null | 1 | 40 | java|maven-2|intellij-idea | 82,121 | <p>I commented out the proxy config in my ~/.m2/settings.xml file, let the Intellij Proxy info alone, and then supplied the properties in Setting->Maven. Not sure why that worked (nor why the settings.xml wasn't working right) but it's working now.</p> |
1,582,383 | How can i tell if an object has a key value observer attached | <p>if you tell an objective c object to removeObservers: for a key path and that key path has not been registered, it cracks the sads. like -</p>
<p>'Cannot remove an observer for the key path "theKeyPath" from because it is not registered as an observer.'</p>
<p>is there a way to determine if an object has a registered observer, so i can do this</p>
<pre><code>if (object has observer){
remove observer
}
else{
go on my merry way
}
</code></pre> | 6,714,561 | 10 | 3 | null | 2009-10-17 15:00:12.677 UTC | 35 | 2017-11-02 14:17:48.253 UTC | 2009-10-17 15:10:06.097 UTC | null | 12,178 | null | 100,652 | null | 1 | 142 | objective-c|cocoa|key|key-value-observing | 59,287 | <p>Put a try catch around your removeObserver call</p>
<pre><code>@try{
[someObject removeObserver:someObserver forKeyPath:somePath];
}@catch(id anException){
//do nothing, obviously it wasn't attached because an exception was thrown
}
</code></pre> |
1,378,133 | Why are Oracle table/column/index names limited to 30 characters? | <p>I can understand that many years ago there would be this kind of limitation, but nowadays surely this limit could easily be increased. We have naming conventions for objects, but there is always a case that turns up where we hit this limit - especially in naming foreign keys.</p>
<p>Does anybody actually know why this isn't a bigger size - or is it bigger in 11g?</p>
<hr>
<p>Apparently the answer is that it will break currently scripts that aren't defensively coded. I say that is a very worrying thing, Oracle is trying to be <strong>the</strong> database, surely this is the kind of thing that you must constantly improve, otherwise your product will die the death of a thousand cuts.</p>
<p>Whenever I see this kind of objection in-house, I think it is time to bite the bullet and sort it out. If people are running scripts that they do not check or maintain when they upgrade Oracle versions, then let them suffer the consequences of that choice. Provide them a compatibility flag, up the size to 4000, then save me the wasted time when I'm creating objects of having to constantly count to 30 to check the name is 'OK'. </p> | 1,378,160 | 10 | 5 | null | 2009-09-04 09:20:06.347 UTC | 29 | 2016-12-30 21:14:13.16 UTC | 2009-09-07 08:41:34.143 UTC | null | 159,226 | null | 159,226 | null | 1 | 160 | oracle|oracle10g|size | 91,186 | <p>I believe it's the ANSI standard.</p>
<p><strong>EDIT:</strong></p>
<p>Actually, I think it's the SQL-92 standard.</p>
<p>A later version of the standard appears to optionally allow for 128 character names, but Oracle doesn't yet support this (or has partial support for it, insofar as it allows 30 characters. Hmmm.)</p>
<p>Search for "F391, Long identifiers" on this page... <a href="http://stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/ap_standard_sql001.htm" rel="noreferrer">http://stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/ap_standard_sql001.htm</a></p>
<p>(Looking for a ref)</p> |
2,053,245 | How can I detect if the user is on localhost in PHP? | <p>In other words, how can I tell if the person using my web application is on the server it resides on? If I remember correctly, PHPMyAdmin does something like this for security reasons.</p> | 2,053,295 | 11 | 0 | null | 2010-01-12 23:28:15.18 UTC | 27 | 2022-03-02 18:40:45.407 UTC | null | null | null | null | 66,812 | null | 1 | 113 | php|localhost|detection | 103,264 | <p>You can also use <code>$_SERVER['REMOTE_ADDR']</code> for which IP address of the client requesting is given by the web server. </p>
<pre><code>$whitelist = array(
'127.0.0.1',
'::1'
);
if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
// not valid
}
</code></pre> |
1,854,890 | Comparing two NSDates and ignoring the time component | <p>What is the most efficient/recommended way of comparing two NSDates? I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day. This seems long winded and I feel like I am missing something obvious.</p>
<p>The code I am trying to fix is:</p>
<pre><code>if (!([key compare:todaysDate] == NSOrderedDescending))
{
todaysDateSection = [eventSectionsArray count] - 1;
}
</code></pre>
<p>where key and todaysDate are NSDate objects and todaysDate is creating using:</p>
<pre><code>NSDate *todaysDate = [[NSDate alloc] init];
</code></pre>
<p>Regards</p>
<p>Dave </p> | 1,854,919 | 16 | 1 | null | 2009-12-06 09:36:35.273 UTC | 32 | 2018-04-24 11:59:54.367 UTC | 2010-09-20 13:56:21.13 UTC | null | 218,394 | null | 218,394 | null | 1 | 72 | iphone|objective-c|nsdate | 38,882 | <p>You set the time in the date to 00:00:00 before doing the comparison:</p>
<pre><code>unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
// ... necessary cleanup
</code></pre>
<p>Then you can compare the date values. See the <a href="http://developer.apple.com/iphone/library/documentation/cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html" rel="noreferrer">overview in reference documentation</a>.</p> |
1,778,088 | How do I clone a single branch in Git? | <p>I have a local Git repository in <code>~/local_repo</code>. It has a few branches:</p>
<pre><code>$ git branch
* master
rails
c
c++
</code></pre>
<p>To clone the local repository, I do:</p>
<pre><code>$ git clone ~/local_repo new_repo
Initialized empty Git repository in /home/username/new_repo/.git/
</code></pre>
<p>The <code>new_repo</code> master branch points to the <code>local_repo</code> master branch, and I can push / pull.</p>
<p>But I am unable to clone another branch. I want to only pull the branch I want (e.g. <code>rails</code>), so that the new repository has a <code>master</code> branch that pushes to and pulls from <code>local_repo</code>'s <code>rails</code> branch, by default. How do I accomplish this, or perhaps something similar with <code>local_repo</code> tracking the master <code>local_repo</code>?</p> | 9,920,956 | 26 | 8 | null | 2009-11-22 07:21:19.42 UTC | 344 | 2022-07-08 05:40:26.53 UTC | 2022-07-08 05:40:26.53 UTC | null | 365,102 | null | 66,450 | null | 1 | 962 | git|branch|git-clone | 884,286 | <p>Note: the <strong><a href="https://lkml.org/lkml/2012/3/28/418" rel="noreferrer">git1.7.10</a> (April 2012)</strong> actually allows you to <strong>clone only one branch</strong>:</p>
<pre class="lang-bash prettyprint-override"><code># clone only the remote primary HEAD (default: origin/master)
git clone <url> --single-branch
# as in:
git clone <url> --branch <branch> --single-branch [<folder>]
</code></pre>
<p>(<code><url></code> is the URL if the remote repository, and does not reference itself the branch cloned)</p>
<p>You can see it in <a href="https://github.com/git/git/blob/master/t/t5500-fetch-pack.sh" rel="noreferrer"><code>t5500-fetch-pack.sh</code></a>:</p>
<pre class="lang-bash prettyprint-override"><code>test_expect_success 'single branch clone' '
git clone --single-branch "file://$(pwd)/." singlebranch
'
</code></pre>
<p><a href="https://stackoverflow.com/users/229753/tobu">Tobu</a> <a href="https://stackoverflow.com/questions/1778088/how-to-clone-a-single-branch-in-git/9920956?noredirect=1#comment27508922_9920956">comments</a> that:</p>
<blockquote>
<p><strong>This is implicit when doing a shallow clone.<br />
This makes <code>git clone --depth 1</code> the easiest way to save bandwidth.</strong></p>
</blockquote>
<p>And since Git 1.9.0 (February 2014), shallow clones support data transfer (push/pull), so that option is even more useful now.<br />
See more at "<a href="https://stackoverflow.com/a/21217267/6309">Is <code>git clone --depth 1</code> (shallow clone) more useful than it makes out?</a>".</p>
<hr />
<p>"Undoing" a shallow clone is detailed at "<a href="https://stackoverflow.com/a/17937889/6309">Convert shallow clone to full clone</a>" (git 1.8.3+)</p>
<pre class="lang-bash prettyprint-override"><code># unshallow the current branch
git fetch --unshallow
# for getting back all the branches (see Peter Cordes' comment)
git config remote.origin.fetch refs/heads/*:refs/remotes/origin/*
git fetch --unshallow
</code></pre>
<p>As <a href="https://stackoverflow.com/users/1308967/chris">Chris</a> comments:</p>
<blockquote>
<p>the magic line for getting missing branches to reverse <code>--single-branch</code> is (git v2.1.4):</p>
</blockquote>
<pre class="lang-bash prettyprint-override"><code>git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/*
git fetch --unshallow
</code></pre>
<hr />
<p>With Git 2.26 (Q1 2020), "<code>git clone --recurse-submodules --single-branch</code>" <strong>now uses the same single-branch option when cloning the submodules</strong>.</p>
<p>See <a href="https://github.com/git/git/commit/132f600b060c2db7fd3d450dfadb6779a61c648a" rel="noreferrer">commit 132f600</a>, <a href="https://github.com/git/git/commit/47319576f112b60ecd85930d162cd7656132fd0d" rel="noreferrer">commit 4731957</a> (21 Feb 2020) by <a href="https://github.com/nasamuffin" rel="noreferrer">Emily Shaffer (<code>nasamuffin</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/b22db265d6bde72391c8d47700dc781a3ea2ae41" rel="noreferrer">commit b22db26</a>, 05 Mar 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/132f600b060c2db7fd3d450dfadb6779a61c648a" rel="noreferrer"><code>clone</code></a>: pass --single-branch during --recurse-submodules</h2>
<p><sup>Signed-off-by: Emily Shaffer</sup><br />
<sup>Acked-by: Jeff King</sup></p>
<p>Previously, performing "<code>git clone --recurse-submodules --single-branch</code>" resulted in submodules cloning all branches even though the superproject cloned only one branch.</p>
<p>Pipe <code>--single-branch</code> through the submodule helper framework to make it to '<code>clone</code>' later on.</p>
</blockquote> |
1,409,649 | How to change the height of a <br>? | <p>I have a big paragraph of text that is divided into subparagraphs with <code><br></code>'s:</p>
<pre><code><p>
Blah blah blah.
<br/>
Blah blah blah. Blah blah blah. Blah blah blah.
<br/>
Blah blah blah.
</p>
</code></pre>
<p>I want to widen the gap between these subparagraphs, like there is two <code><br></code>'s or something like that. I know that the right way to do this is to use <code><p></p></code>, but right now I cannot change this layout, so I am looking for CSS-only solution.</p>
<p>I've tried setting <code><br></code>'s <code>line-height</code> and <code>height</code> with <code>display: block</code>, I also Googled and Stack Overflow-ed briefly, but did not find any solution. Is this even possible without changing the layout?</p> | 1,409,742 | 34 | 6 | null | 2009-09-11 08:14:53.877 UTC | 48 | 2021-06-12 20:24:05.973 UTC | 2013-04-30 05:22:22.183 UTC | null | 1,563,422 | null | 155,336 | null | 1 | 322 | html|css | 716,481 | <p>Css:</p>
<pre><code>br {
display: block;
margin: 10px 0;
}
</code></pre>
<p>The solution is probably not cross-browser compatible, but it's something at least. Also consider setting <code>line-height</code>:</p>
<pre><code>line-height:22px;
</code></pre>
<p>For Google Chrome, <a href="https://stackoverflow.com/questions/967776/br-line-height-in-safari-and-chrome-leaving-gap">consider</a> setting <code>content</code>:</p>
<pre><code>content: " ";
</code></pre>
<p>Other than that, I think you're stuck with a JavaScript solution.</p> |
33,704,714 | Can't require() default export value in Babel 6.x | <p>In Babel 5.x, I can write the following code:</p>
<p><strong>app.js</strong></p>
<pre><code>export default function (){}
</code></pre>
<p><strong>index.js</strong></p>
<pre><code>require('babel/register');
require('./app')();
</code></pre>
<p>Then, I can run <code>node index.js</code> with no errors. However, using Babel 6.x, running the following code</p>
<p><strong>index.es6.js</strong></p>
<pre><code>require('babel-core/register');
require('./app')();
</code></pre>
<p>results in an error</p>
<blockquote>
<p>require(...) is not a function</p>
</blockquote>
<p>I want to know why?</p> | 33,705,077 | 3 | 5 | null | 2015-11-14 03:09:56.373 UTC | 24 | 2021-08-19 14:06:53.563 UTC | 2016-03-08 23:44:19.11 UTC | null | 1,391,671 | null | 4,485,565 | null | 1 | 98 | javascript|ecmascript-6|babeljs | 54,160 | <p><strong>TL;DR</strong></p>
<p>You have to use</p>
<pre><code>const app = require('./app').default;
app();
</code></pre>
<p><strong>Explanation</strong></p>
<p>Babel 5 used to have a compatibility hack for <code>export default</code>: if a module contained only one export, and it was a default export, it was assigned to <code>module.exports</code>. So, for example, your module <strong>app.js</strong></p>
<pre><code>export default function () {}
</code></pre>
<p>would be transpiled to this</p>
<pre><code>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function () {};
module.exports = exports["default"];
</code></pre>
<p>This was done <em>purely</em> for compatibility with <code>require</code>-ing Babel-transpiled modules (like you are doing). It was also inconsistent; if a module contained both named and default exports, it could not be <code>require</code>-d.</p>
<p>In reality, according to the ES6 module spec, a default export is <em>no different</em> than a named export with the name <code>default</code>. It is just syntactic sugar which can be statically resolved at compile time, so this</p>
<pre><code>import something from './app';
</code></pre>
<p>is the same as this</p>
<pre><code>import { default as something } from './app';
</code></pre>
<p>That being said, it appears that Babel 6 decided to drop the interoperability hack when transpiling modules. Now, your module <strong>app.js</strong> is transpiled as</p>
<pre><code>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {};
</code></pre>
<p>As you see, no more assignment to <code>module.exports</code>. To <code>require</code> this module, you need to do</p>
<pre><code>const app = require('./app').default;
app();
</code></pre>
<p>Or, more concisely, and closer to your original code:</p>
<pre><code>require('./app').default();
</code></pre> |
8,796,747 | How to scroll to bottom of ListBox? | <p>I am using a Winforms ListBox as a small list of events, and want to populate it so that the last event (bottom) is visible. The <code>SelectionMode</code> is set to none. The user can scroll the list but I would prefer it start out scrolled to the end.</p>
<p>Looking at the lack of support for things like <code>ScrollIntoView</code>, <code>EnsureVisible</code>, I am assuming I will need to create a custom control that inherits from ListBox; however I'm not sure what to do from there.</p>
<p>Some pointers?</p> | 8,796,820 | 4 | 2 | null | 2012-01-09 23:40:03.457 UTC | 3 | 2021-03-04 19:02:52.667 UTC | null | null | null | null | 161,052 | null | 1 | 74 | c#|winforms|listbox | 83,223 | <p>I believe you can do that easily by setting the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.topindex.aspx" rel="noreferrer"><code>TopIndex</code></a> property appropriately.</p>
<p>For example:</p>
<pre><code>int visibleItems = listBox.ClientSize.Height / listBox.ItemHeight;
listBox.TopIndex = Math.Max(listBox.Items.Count - visibleItems + 1, 0);
</code></pre> |
17,821,532 | How to open Navigation Drawer with no actionbar, open with just a button | <p>I have a navigation bar without any actionbar (I don't want an actionbar). I'm trying to make it so that I have a button that can open the navigation drawer. </p>
<p>I know there's a method called openDrawer for the DrawerLayout
<a href="http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)">http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)</a></p>
<p>I didn't know how to use it, but i have tried making a button when click, runs this method:</p>
<pre><code>DrawerLayout mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout);
mDrawerLayout.openDrawer(mDrawerLayout);
</code></pre>
<p>When i click it on it, it gives me a Java NullPointerException. Anybody has any idea?</p>
<p>EDIT:
This code is inside a fragment, and I'm trying to refer those drawer layout outside the fragment. I used debugger, and it is showing that mDrawlerLayout is NULL. </p>
<p>Any advice?</p>
<p>Thanks!</p> | 17,822,591 | 7 | 0 | null | 2013-07-23 21:39:23.51 UTC | 20 | 2020-01-27 15:46:16.813 UTC | 2013-07-23 22:06:42.967 UTC | null | 2,511,100 | null | 2,511,100 | null | 1 | 42 | android|button|navigation-drawer|drawerlayout | 83,244 | <p>It's giving you a null pointer because you are trying to find the drawer layout in the fragment's view, when it is actually in the activities view.</p>
<p>A quick hack to do what you want is to find the view like:</p>
<pre><code>getActivity().findViewById(R.id.drawer_layout)
</code></pre>
<p>That should work. A better way is to have a method on the activity for opening the drawer</p>
<pre><code>public void openDrawer(){
mDrawerLayout.openDrawer(mDrawerLayout);
}
</code></pre>
<p>In the activity onCreate run your findViewById:</p>
<pre><code>mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout);
</code></pre>
<p>mDrawerLayout should be a member variable of your activity.</p>
<p>Then in your fragment you can call:</p>
<pre><code>//cast activity to MyActivity so compiler doesn't complain
((MyActivity)getActivity()).openDrawer();
</code></pre>
<p>An even better way to do it is to create a listener in the fragment and set the activity as a listener to the fragment. Then you can call a method on the activity, similar to above. I'll let you do some research on how to do that.</p> |
17,698,434 | The requested PHP extension intl is missing from your system (SonataAdminBundle) in Symfony2 | <p>I try to install the sandbox but I get the following error from composer:</p>
<blockquote>
<p>Loading composer repositories with package information Installing
dependencies from lock file Your requirements could not be resolved to
an installable set of packages.</p>
</blockquote>
<p>Problem 1</p>
<pre><code>- Installation request for sonata-project/intl-bundle 2.1.0 -> satisfiable by sonata-project/intl-bundle 2.1.0.`
- sonata-project/intl-bundle 2.1.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.`
</code></pre>
<p>Problem 2</p>
<pre><code>- sonata-project/intl-bundle 2.1.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.`
- sonata-project/news-bundle 2.1.x-dev requires sonata-project/intl-bundle 2.1.* -> satisfiable by sonata-project/intl-bundle 2.1.0.
- Installation request for sonata-project/news-bundle 2.1.
</code></pre> | 33,857,986 | 8 | 3 | null | 2013-07-17 11:19:45.9 UTC | 2 | 2020-06-30 16:11:10.253 UTC | 2013-07-17 13:51:05.837 UTC | null | 1,443,490 | null | 2,361,831 | null | 1 | 16 | php|symfony|intl | 67,215 | <p>I had the same problem while I was installing new Magento 2.0, after different hit and trials, I manged to solve it by following these steps:</p>
<p>I copied all <strong>icu*</strong> files from php directory to Appache directory, and it worked.</p>
<p>Php direcotry: </p>
<blockquote>
<p>WAMP\bin\php\php5.5.12</p>
</blockquote>
<p>Appache Directory: </p>
<blockquote>
<p>WAMP\bin\apache\apache2.4.9</p>
</blockquote>
<p>Make sure to un-comment following line in php.ini file:</p>
<blockquote>
<p>extension=ext/php_intl.dll</p>
</blockquote> |
18,149,601 | Go install fails with error: no install location for directory xxx outside GOPATH | <pre><code>~/src/go-statsd-client> echo $GOPATH
/Users/me/gopath
~/src/go-statsd-client> echo $GOROOT
/usr/local/Cellar/go/1.1.1\
~/src/go-statsd-client> go install
go install: no install location for directory /Users/me/src/go-statsd-client outside GOPATH
</code></pre>
<p>No matter what structure the project is in this always fails with the same message. Go build works perfectly.</p>
<p>Here is my <code>go env</code></p>
<pre><code>GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/me/gopath"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.1.1"
GOTOOLDIR="/usr/local/Cellar/go/1.1.1/pkg/tool/darwin_amd64"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread -fno-common"
CGO_ENABLED="1"
</code></pre>
<p>This is on Mac OSX Mountain Lion and go was installed with homebrew.</p> | 18,164,310 | 12 | 0 | null | 2013-08-09 14:52:32.463 UTC | 33 | 2019-07-01 00:12:09.783 UTC | 2019-03-03 16:47:28.683 UTC | null | 1,103,953 | null | 41,709 | null | 1 | 164 | macos|go | 130,346 | <p>When you provide no arguments to <code>go install</code>, it defaults to attempting to install the package in the current directory. The error message is telling you that it cannot do that, because the current directory isn't part of your <code>$GOPATH</code>.</p>
<p>You can either:</p>
<ul>
<li>Define <code>$GOPATH</code> to your $HOME (<code>export GOPATH=$HOME</code>).</li>
<li>Move your source to within the current <code>$GOPATH</code> (<code>mv ~/src/go-statsd-client /User/me/gopath</code>).</li>
</ul>
<p>After either, going into the <code>go-statsd-client</code> directory and typing <code>go install</code> will work, and so will typing <code>go install go-statsd-client</code> from anywhere in the filesystem. The built binaries will go into <code>$GOPATH/bin</code>.</p>
<p>As an unrelated suggestion, you probably want to namespace your package with a domain name, to avoid name clashing (e.g. <code>github.com/you/go-statsd-client</code>, if that's where you hold your source code).</p> |
6,911,894 | Ninject InRequestScope missing | <p>Have a couple of questions regarding the latest version (2.2.1.4) of ninject.</p>
<p>Was trying to Bind a Linq2sql <code>DataContext</code> to a concrete implementation <code>InRequestScope</code> (in a class library project)</p>
<pre><code>Bind<DataContext>().To<MoneywatchDataContext>()
</code></pre>
<p>but could not find <code>InRequestScope</code> method </p>
<p><img src="https://i.stack.imgur.com/Tlrbx.png" alt="enter image description here"></p>
<p>ended up doing this, </p>
<pre><code>Bind<DataContext>().To<MoneywatchDataContext>().InScope(ctx => HttpContext.Current)
</code></pre>
<p>Just wanted to find out if:</p>
<ol>
<li>If this will behave exactly like the <code>InRequestScope</code> Method.</li>
<li>That it will gurantee that when my <code>HTTContext.Current</code> is GC'ed the underlying <code>DataCotext</code> will be disposed as well. </li>
</ol> | 6,912,529 | 3 | 0 | null | 2011-08-02 12:13:42.463 UTC | 1 | 2015-12-01 19:04:28.967 UTC | 2013-04-03 12:59:09.237 UTC | null | 11,635 | null | 186,061 | null | 1 | 34 | c#|binding|ninject|ninject-2 | 7,952 | <p>Most likely you reference a no web version of Ninject. Replace it with the normal version and you will have the InRequestScope extension method.</p> |
6,837,543 | Show virtual keyboard on mobile phones in javascript | <p>I'm creating a mobile version of my site. There's a part of the site where a dialog pops up with a text input. Normally I would just use jQuery to bring focus to the text input, but that's not working. Here's what I'm trying:</p>
<pre><code>$("#textinput").focus();
$("#textinput").click();
$("#textinput").trigger("tap"); //jQuery Mobile
</code></pre>
<p>None of them seem to work. Any ideas? I've been testing it on my DroidX. I'm using jQuery Mobile but I'm open to other libraries if they help.</p> | 6,837,575 | 3 | 0 | null | 2011-07-26 22:49:24.917 UTC | 16 | 2021-03-05 16:57:31.893 UTC | null | null | null | null | 212,188 | null | 1 | 42 | javascript|jquery|jquery-mobile | 80,978 | <p>You can't, at least not in iOS (iPhone), and I believe Android as well. It's a usability issue that the keyboard should not be allowed to be triggered except by user input (it's just annoying if it's automatic).</p>
<p>There are a couple of ways I know of to get around this:</p>
<ul>
<li><code>prompt()</code> opens the keyboard</li>
<li>If you trigger the <code>.focus()</code> from within a <code>.click()</code> event (e.g. from opening your dialog), the keyboard shows up</li>
</ul> |
6,412,896 | Giving application elevated UAC | <p>I have an application which needs the UAC elevation.</p>
<p>I have the code which lets me give that but the application opens twice and that's an issue.</p>
<p>Here's the code of Form1:</p>
<pre><code>public Form1()
{
InitializeComponent();
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
if (!hasAdministrativeRight)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process p = Process.Start(startInfo);
}
catch (System.ComponentModel.Win32Exception ex)
{
return;
}
}
}
</code></pre>
<p>Here's the code of programs.cs:</p>
<pre><code>static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
</code></pre>
<p>By debugging I found out that first it executes</p>
<blockquote>
<p>Process p = Process.Start(startInfo);</p>
</blockquote>
<p>which opens the application UAC elevation dialog and then opens the application</p>
<p>but then it goes to the</p>
<blockquote>
<p>Application.Run(new Form1());</p>
</blockquote>
<p>in main() and opens the application again.</p>
<p>I don't want it to open the app again.</p>
<p>I am new to this so I am asking is there anything I am doing wrong and do I need to close the UAC once its open?</p> | 6,413,024 | 4 | 1 | null | 2011-06-20 14:35:36.897 UTC | 4 | 2022-08-17 05:42:31.053 UTC | 2022-08-17 05:42:31.053 UTC | null | 1,879,699 | null | 175,084 | null | 1 | 13 | c#|asp.net|winforms|uac | 45,972 | <p>You don't need to meddle with all that to make sure that your application always runs with elevated privileges. You can simply <a href="http://msdn.microsoft.com/en-us/library/bb756929.aspx" rel="noreferrer">add an application manifest</a> which instructs Windows to run your app elevated, and the UAC prompt will appear without you needing to write a single line of code.</p>
<p>There's a related question with an answer that also describes how to add a manifest here: <a href="https://stackoverflow.com/q/4383288/50079">How can I embed an application manifest into an application using VS2008?</a></p> |
35,844,279 | Why does m[1] - m[0] return 3 where m is a 3x3 matrix? | <p>This is my code:</p>
<pre><code>int m[][3] = {
{ 0 , 1 , 2 },
{ 10, 11, 12 },
{ 20, 21, 22 }
};
printf("%d %d\n", m[1] - m[0], m[1][0] - m[0][0]);
</code></pre>
<p>And why does</p>
<pre><code>m[1] - m[0]
</code></pre>
<p>return <code>3</code>? I know why the second expression would return <code>10</code> but the 1<sup>st</sup> one doesn't seem logical to me.</p> | 35,844,334 | 2 | 3 | null | 2016-03-07 12:53:46.723 UTC | 4 | 2016-05-12 11:03:58.193 UTC | 2016-04-13 17:45:51.063 UTC | null | 1,009,479 | null | 3,680,672 | null | 1 | 36 | c|arrays|matrix | 1,937 | <p>In your code:</p>
<pre><code> m[1] - m[0]
</code></pre>
<p>denotes a pointer subtraction which gives you the difference of the two pointers based on the <em>type</em>. In this case, both the pointers are differentiated by 3 elements, so the result is 3.</p>
<p>To quote <code>C11</code> standard, chapter §6.5.6</p>
<blockquote>
<p>When two pointers are subtracted, both shall point to elements of the same array object,
or one past the last element of the array object; the result is the difference of the
subscripts of the two array elements. [...]</p>
</blockquote>
<p>and</p>
<blockquote>
<p>[...] In other words, if the expressions <code>P</code> and <code>Q</code> point to, respectively, the <code>i</code>-th and <code>j</code>-th elements of
an array object, the expression <code>(P)-(Q)</code> has the value <code>i−j</code> provided the value fits in an object of type <code>ptrdiff_t</code>. [....]</p>
</blockquote>
<p>To help visualize better, please see the following image</p>
<p><a href="https://i.stack.imgur.com/lYYoo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/lYYoo.jpg" alt="enter image description here"></a></p>
<p>Here, <code>s</code> is a two dimensional array, defined as <code>s[4][2]</code>. Considering the data type of the array consumers 2 byte each, please follow the elements (index) and corresponding memory location (<em>arbitrary</em>). This will give a better understating how actually in memory, the array elements are contiguous.</p>
<p>So, as per the representation, <code>s[0]</code> and <code>s[1]</code> are differentiated by two elements, <code>s[0][0]</code> and <code>s[0][1]</code>. Hence, <code>s[1] - s[0]</code> will produce a result of 2.</p> |
18,959,691 | IOS7 (only) stdlibc++ linking issue | <p>I need help.
I had a framwork which was using stdc++ like std:string.
Now when i have created new app for IOS7 only there is problem with linking this framework because of problems with stdc++ lib:</p>
<p>Undefined symbols for architecture armv7
"std::basic_string, std::allocator >::_Rep::_S_empty_rep_storage", referenced from ...</p>
<p>I have find out something strange that when i change the Deplyment target to ios6 in this app all is working fine.
With ios7 i see errors.</p>
<p>I already have flag set in other linker flags: -lstdc++ </p>
<p>Any idea what ami doing wrong?</p> | 21,206,163 | 4 | 3 | null | 2013-09-23 12:49:26.627 UTC | 13 | 2014-10-08 18:35:35.68 UTC | null | null | null | null | 790,873 | null | 1 | 28 | xcode|ios7|libstdc++ | 29,060 | <p>Just an update on this answer: </p>
<p>This step is very important!</p>
<p>Ensure that <strong>C++ Standard Library</strong> is set to <strong>libstdc++ (GNU c++ standard library)</strong> in the Apple LLVM 5.0 Compiler Build Settings</p>
<p>Background:</p>
<p>I have an iOS app that abruptly stopped building for iOS 7 with standard library link errors. I had been testing the app successfully on the simulator and on an iPad mini, and archived it as well, but when I added an iPhone 5S for testing, I started getting link errors (possibly because of a new architecture in the mix?).</p>
<p>Searching the link errors on Google, I found advice to explicitly add libstdc++.dylib to the linked libraries. This did not work.</p>
<p>I experimented by adding libstdc++.6.dylib to the linked libraries instead; this eliminated the link errors, but the app crashed in the standard C++ library code very early.</p>
<p>Removing the explicit additions of the library and changing the compiler setting in Build Settings, as noted above, corrected the link errors and runtime problem. </p>
<p>Thanks to rimestad for the pointer!</p> |
34,372,618 | npm - "Can't find Python executable "python", you can set the PYTHON env variable." | <p>I'm trying to run the following command: <code>npm install -g bower gulp cordova ionic tsd@next karma-cli protractor node-gyp coffee-script js-beautify typescript npm-check</code></p>
<p>I have installed Python, Visual Studio Express and node-gyp so thought I'd be good to go, however I get the following errors:</p>
<p><a href="https://i.stack.imgur.com/1JN7A.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1JN7A.png" alt="enter image description here"></a></p>
<p>Regarding the <code>"Can't find Python executable "python", you can set the PYTHON env variable."</code> error, I'm a little confused because I have set the PYTHON environmental variable like so:</p>
<p><a href="https://i.stack.imgur.com/iTJkM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iTJkM.png" alt="enter image description here"></a></p>
<p>Any ideas please?</p> | 34,372,675 | 15 | 7 | null | 2015-12-19 16:01:07.927 UTC | 23 | 2022-09-12 12:23:08.6 UTC | 2015-12-19 16:29:03.747 UTC | null | 3,330,348 | null | 124,201 | null | 1 | 111 | python|node.js|npm|npm-install | 384,943 | <p>You got to add python to your PATH variable. One thing you can do is Edit your Path variable now and add</p>
<p><code>;%PYTHON%;</code></p>
<p>Your variable PYTHON should point to the root directory of your python installation.</p> |
27,812,098 | Graphics driver "hello world" example? | <p>What are the steps necessary to create a GPU driver that render pixels on a display? Basically just the simplest "hello world" example of creating a GPU driver, such as turning the screen red or just showing a single pixel. Where do you start?</p>
<p>I would like to hack on the GPU directly, without any C or OpenGL abstraction or any of that. I am using Mac OSX, and I think I have the Intel HD i7 graphics card, so <a href="http://renderingpipeline.com/graphics-literature/low-level-gpu-documentation/">these docs</a> seemed like a good fit:</p>
<ul>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol1_Part1r2.pdf">Volume 1 Part 1: Graphics Core</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol1_Part2r2.pdf">Volume 1 Part 2: Graphics Core – MMIO, Media Registers & Programming Environment</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol1_Part3r2.pdf">Volume 1 Part 3: Graphics Core – Memory Interface and Commands Render Engine</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol1_Part4r2.pdf">Volume 1 Part 4: Graphics Core – Video Codec Engine</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol1_Part5r2.pdf">Volume 1 Part 5: Graphics Core – Blitter Engine</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol2_Part1r2.pdf">Volume 2 Part 1: 3D/Media – 3D Pipeline</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol2_Part2r2.pdf">Volume 2 Part 2: 3D/Media – Media</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol3_Part1r2.pdf">Volume 3 Part 1: Display Registers – VGA Registers</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol3_Part2r2.pdf">Volume 3 Part 2: Display Registers – CPU Registers</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol3_Part3r2.pdf">Volume 3 Part 3: PCH Display Registers</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol4_Part1r2.pdf">Volume 4 Part 1: Subsystem and Cores – Shared Functions</a></li>
<li><a href="http://files.renderingpipeline.com/gpudocs/intel/hd/IHD_OS_Vol4_Part2_July_28_10.pdf">Volume 4 Part 2: Subsystem and Cores – Message Gateway, URB, Video Motion, and IS</a></li>
</ul>
<p>The Mesa3D project says that there are a number of open source graphics drivers, and Wikipedia says that Intel produces these docs so that you can write an open source driver if you want, but don't explain how.</p>
<p>I also came across <a href="https://github.com/jagregory/abrash-black-book">Michael Abrash's Graphics Programming Black Book</a>, which explains a lot.</p>
<p>However that is a bit much to bite off all at once. And there doesn't seem to be any information on how to get started hacking on a GPU driver, a "hello world" project.</p>
<p>For example:</p>
<ul>
<li>To learn assembly, you can just <code>brew install nasm</code>, write some assembly, compile, and run it to print "hello world".</li>
<li>To learn Arduino, you can plug in an Arduino board into your computer via a USB cable, install their software, and upload some C code directly to the board and run it, to show a blinking LED light.</li>
</ul>
<p>How do you do that same sort of thing for the graphics card?</p>
<p><em>The hello world example doesn't necessarily have to work (though that would be cool if it did!); even just outlining what it would take in a higher-level/practical sense would be helpful. If it's not possible on a Mac, or even on Linux, that would be good to know. But even then the question remains, where do you start in writing a graphics driver?</em></p> | 27,812,800 | 1 | 3 | null | 2015-01-07 03:44:52.953 UTC | 24 | 2015-01-07 06:05:34.013 UTC | 2015-01-07 05:05:24.473 UTC | null | 169,992 | null | 169,992 | null | 1 | 29 | c|opengl|assembly|graphics | 13,309 | <ul>
<li><strong>Step 1</strong>: Understand the particular GPU you are targetting (Architecture, register and stream details). I am afraid for many of
the GPUs these details may be proprietary and you may not get it. (But as you mentioned, in your case specs are available)</li>
<li><strong>Step 2</strong>: Add some calls in your driver that are able to query registers / details from the driver.</li>
<li><strong>Step 3</strong>: Add some calls in your driver to modify registers. (Change mode etc)</li>
<li><strong>Step 4</strong>: You can check how to draw a triangle / quad on your GPU with a constant color. Try to implement screen clear (functionality
similar to <em>glClear</em>) by drawing a big quad or 2 triangles or 1
triangle of dimension double of the screen or sending some clear
command. (whichever method is supported by the GPU) If you are
drawing a triangle or quad, use NDC (normalized device coordinate)
system and prefer to work in Raw windowing system or NWS (Null
windowing system). Windowing system is responsible for displaying
your output framebuffer after compositing or some post processing. By
Raw or NWS, I mean display the framebuffer directly to screen.</li>
<li><strong>Step 5 (most of the things are optional)</strong>: Implement some complex drawing. This may involve support of other drawing modes like pixel,
line, triangular strip, triangular fan etc and support of texture,
lighting, transformation, interaction with other windowing system.
For this step you will need to learn assembly. But do notice, this is
not x86 or arm (CPU) assembly, rather it is GPU assembly which is
specialized in handling <a href="http://en.wikipedia.org/wiki/SIMD" rel="noreferrer">SIMD</a>.</li>
<li><strong>Step 6</strong>: Implement stencil functionality. Prepare a stencil of hello world in your program. Clear the screen with color 1. Apply the
stencil and clear the screen again with color 2. Now you have hello
world written in color 2 with color 1 as background.</li>
</ul>
<p>Mottivation to do this all is: You want to do this. And this will be cool.</p>
<p>Demotivation to do this is: Possible unavailability of GPU specifications, learning curve for GPU assembly, complexity of graphics.</p>
<p>My Recommendation: If GPU specs (along with assembly) is available to you, I would suggest implement subset of any available API set (open vg and open GLES 1.1) for example. To read more about these API set, please visit <a href="https://www.khronos.org/" rel="noreferrer">khronos</a> website.</p> |
5,215,048 | javascript checkbox enable/disable | <p>Ok this is very anoying, and it is probably very simple. I want to start my web page with disabled checkboxes, and after particlar line in listbox is selected to enable those boxes. So I put this in onload method</p>
<pre><code>onload = function () {
for (i = 0; i < document.frmMain.checkgroup.length; i++){
document.frmMain.checkgroup[i].disabled = true ;
}
}
</code></pre>
<p>it start my page with disabled boxes, now i want do enable them</p>
<pre><code>function enableCheckboxes(){
if (document.frmMain.Vrste[document.frmMain.Vrste.selectedIndex].value == "Sendvici i Rostilj"){
for(i=0;i<document.frmMain.checkgroup.length;i++){
document.frmMain.checkgroup[i].enabled = true;
}
}
}
</code></pre>
<p>it goes in to the for loop, but it never enable those checkboxes. I cannot figure it why.</p>
<p>and this is html part, where i call enablecheckbox function:</p>
<pre><code><select name="Vrste" onChange="PopulatePodvrste(); enableCheckboxes();" size="8">
<option value="Pica">Pica</option>
<option value="Barbarina domaca trpeza">Barbarina domaca trpeza</option>
<option value="Slana Palacinka">Slana Palacinka</option>
<option value="Slatka Palacinka">Slatka Palacinka</option>
<option value="Sendvici i Rostilj">Rostilj i sendvici</option>
<option value="Dobro jutro sa Barbarom">Dobro jutro sa Barbarom</option>
<option value="Chicken Meni">Chicken Meni</option>
<option value="Posebna Ponuda">Posebna Ponuda</option>
<option value="Salate">Salate</option>
</select>
</code></pre>
<p>And finally actual checkboxes:</p>
<pre><code><input type="checkbox" name="checkgroup" >Susam</input><br>
<input type="checkbox" name="checkgroup" >Cili</input><br>
<input type="checkbox" name="checkgroup" >Tartar</input><br>
<input type="checkbox" name="checkgroup" >Urnebes</input><br>
<input type="checkbox" name="checkgroup" >Krastavac</input>
</code></pre> | 5,215,074 | 2 | 0 | null | 2011-03-07 01:59:31.29 UTC | 4 | 2011-03-07 02:03:39.543 UTC | null | null | null | null | 521,683 | null | 1 | 5 | javascript|html|listbox|checkbox | 63,276 | <p>Try instead:</p>
<pre><code> document.frmMain.checkgroup[i].disabled = false ;
</code></pre> |
16,332,283 | Set permission for getting User's email ID from Facebook Login | <p>I'm using <code>Facebook 3.0 SDK</code> for android. I have to implement <code>Facebook</code> log in. I'm accessing user's basic info like name, userID. But I want to have access to email also of the user. I have gone through many blogs and forum but cannot figure out how to do that.</p>
<p>I'm using my own android button for log in not <code>com.facebook.widget.LoginButton</code>. If I use <code>Facebook</code> log in button it was easy just have to use these lines:</p>
<pre><code>authButton.setReadPermissions(Arrays.asList("basic_info","email"));
</code></pre>
<p>But, I have my own requirement, will have to go with default android buttons. Here is what I have done so far:</p>
<pre><code>Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, Arrays.asList("email"));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLogin = (Button) findViewById(R.id.logIn);
mLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
@Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
System.out
.println("Facebook Response: "
+ response.toString());
access_token = session.getAccessToken();
firstName = user.getFirstName();
fb_user_id = user.getId();
System.out
.println("Facebook Access token: "
+ access_token);
System.out.println("First Name:"
+ firstName);
System.out.println("FB USER ID: "
+ fb_user_id);
}
}
});
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
</code></pre>
<p>I'm able to get all those things which I'm printing in log, but was unable to retrieve email from the user profile.</p>
<p>What can I do for this?</p>
<p>Any kind of help will be appreciated.</p> | 16,356,911 | 2 | 3 | null | 2013-05-02 07:07:56.747 UTC | 10 | 2017-02-07 15:09:33.047 UTC | 2013-05-02 17:21:23.457 UTC | null | 1,677,125 | null | 1,321,290 | null | 1 | 11 | android|facebook|facebook-login|facebook-android-sdk | 41,124 | <p>Solved it: Here is what I have done...</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLogin = (Button) findViewById(R.id.logIn);
mLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
// Do whatever u want. User has logged in
} else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) context);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(null);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
Session session = new Builder(MainActivity.this).build();
Session.setActiveSession(session);
session.openForPublish(op);
}
}
public void call(Session session, SessionState state, Exception exception) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
@Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello "
+ user.getName() + "!");
access_token = session
.getAccessToken();
firstName = user.getFirstName();
fb_user_id = user.getId();
System.out
.println("Facebook Access token: "
+ access_token);
System.out.println("First Name:"
+ firstName);
System.out.println("FB USER ID: "
+ fb_user_id);
}
}
});
}
}
});
}
}
</code></pre>
<p>Now I'm able to get email permission with rest of the publish permission.</p>
<p>Marking this as accepted answer so that it can help others.</p> |
158,703 | Is it OK to use HttpRuntime.Cache outside ASP.NET applications? | <p>Scott Hanselman <a href="http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx" rel="noreferrer">says yes</a>.</p>
<blockquote>
<p>Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.</p>
</blockquote>
<p>MSDN <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx" rel="noreferrer">says no</a>.</p>
<blockquote>
<p>The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.</p>
</blockquote>
<p>So what should I think?</p> | 2,771,486 | 8 | 2 | null | 2008-10-01 17:17:54.937 UTC | 11 | 2016-12-15 16:56:00.973 UTC | null | null | null | Jakub Šturc | 2,361 | null | 1 | 39 | .net|caching | 12,176 | <p>I realize this question is old, but in the interest of helping anyone who finds this via search, its worth noting that .net v4 includes a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace:</p>
<p><a href="https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx</a></p>
<p>The static reference to the default cache instance is: MemoryCache.Default</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.