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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24,847,361 | No signature of method: is applicable for argument types error in Groovy | <p>I am quite new to groovy and getting following error when running the below method. I am trying to pass xml file name and Map</p>
<h2>RD.groovy</h2>
<pre><code> Given(~'^input currency "([^"]*)"$') { String baseCurr ->
fromCurr = baseCurr
}
When(~'^insert end Currency "([^"]*)"$') { String tragetCurr ->
toCurr = tragetCurr
}
Then(~'^get the expected end currency value "([^"]*)"$') { String result ->
assert result == currCon(fromCurr, toCurr)
}
private currCon(fromCurr, toCurr)
{
def binding = ["fromCurr": fromCurr, "toCurr": toCurr]
response = Consumer.currConvert("request/CurrencyConvert.xml",binding) --> This is line 119
assert 200 == response.status
return response.data.ConversionRateResult.toString()
}
</code></pre>
<h2>ClassA.groovy</h2>
<pre><code> package abc.api.member
import abc.util.Log
import abc.util.TemplateUtil
import groovyx.net.http.ContentType
import abc.api.RestClient
class ClassA extends ClassB{
ClassA(RestClient restClient) {
super(restClient)
}
def currConvert(String xmlFilename, Map binding) {
return currencyConvertRequest(TemplateUtil.xmlFromTemplate(xmlFilename, binding))
}
def currencyConvertRequest(xmlString) {
def params = [path : 'CurrencyConvertor.asmx',
headers: globeHeaders(),
body: xmlString]
return restClient.post(params)
}
</code></pre>
<h2>Consumer.Groovy</h2>
<pre><code>package abc.api.member
import geb.Browser
import org.apache.http.client.utils.URIBuilder
import abc.api.RestClient
import abc.browser.member.Admin
class Consumer {
Browser browser
String token
String userId
@Delegate
private ClassA classA
Consumer(url) {
browser = new Browser()
browser.baseUrl = baseUrl(url)
restClient = new RestClient(url)
classA = new ClassA(restClient)
}
private baseUrl(url) {
URI uri = URI.create(url)
URIBuilder builder = new URIBuilder()
URI result =builder.setHost(uri.host). //
setPath(uri.path). //
setPort(uri.port). //
setScheme(uri.scheme).
setUserInfo("Cons", "pbiCons").build()
return result.toURL().toString()
}
</code></pre>
<p>Error:</p>
<pre><code>groovy.lang.MissingMethodException: No signature of method: abc.api.consumer.Consumer.currConvert() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, java.util.LinkedHashMap) values: [request/globe/CurrencyConvert.xml, [fromCurr:AUD, ...]]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:51)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at RD.currCon(RD.groovy:119)
</code></pre>
<p>After searching the issue it turned out its a common issue. Couldn't figure out though. Because all solutions are subjective.</p>
<p>Just curious where I am doing wrong</p>
<p>Thanks</p> | 24,847,525 | 2 | 2 | null | 2014-07-20 04:26:20.473 UTC | 2 | 2021-09-11 10:33:27.24 UTC | 2014-07-21 00:38:46.607 UTC | null | 2,303,693 | null | 2,303,693 | null | 1 | 16 | groovy|gradle|cucumber | 136,211 | <p><code>currConvert</code> is an instance method, but it's being called as if it was a static method.</p> |
24,732,320 | does not have a corresponding column in the data reader with the same name | <p>I have <code>Table</code> named <code>tbl_search</code> with columns : <code>id(int), title(nvarchar100), result(ntext)</code>
and i want using <code>SQL query</code>, like this :</p>
<pre><code> using (var db = new GoogleEntities())
{
const string selectCmd =
@"Select top 1 title From tbl_search Where title=@title and id=@id ";
var data = db.Database.SqlQuery<tbl_search>(
selectCmd,
new SqlParameter("@title", "wcf"),
new SqlParameter("@id", 1)
).FirstOrDefault();
if (data != null)
{
var serviceMember = data.ToString();
label1.Text = serviceMember == "" ? "" : (serviceMember == "True" ? "On" : "Off");
}
}
</code></pre>
<p>but it give me an error :</p>
<blockquote>
<p>The data reader is incompatible with the specified 'GoogleModel.tbl_search'. A member of the type, 'id', does not have a corresponding column in the data reader with the same name.</p>
</blockquote>
<p>NOTE: this is my <code>tbl_search</code> class :</p>
<pre><code> public partial class tbl_search
{
public int id { get; set; }
public string title { get; set; }
public string result { get; set; }
}
</code></pre>
<p>i have <code>id</code> in my table.. What is the problem!!</p> | 24,733,731 | 4 | 2 | null | 2014-07-14 08:24:41.363 UTC | 2 | 2020-03-17 19:27:21.24 UTC | null | null | null | null | 3,214,054 | null | 1 | 19 | entity-framework | 46,668 | <p>Your SQL Statement only returns the title not the full entity.</p>
<p>Change:</p>
<pre><code>Select top 1 title From tbl_search Where title=@title and id=@id
</code></pre>
<p>to:</p>
<pre><code>Select top 1 * From tbl_search Where title=@title and id=@id
</code></pre> |
27,738,903 | Provider 'xx' must return a value from $get factory method in AngularJs | <p>I have written an <code>angularjs</code> factory as below</p>
<pre><code>module.factory('LogService', function () {
function log(msg) {
console.log("Rahkaran:" + new Date() + "::" + msg);
}
return
{
log: log
};
});
</code></pre>
<p>But I kept getting this error</p>
<blockquote>
<p><code>Provider 'LogService' must return a value from $get factory method</code></p>
</blockquote>
<p>I googled about the error and I couldn't find any solution.</p>
<p>Coincidentally I changed the <code>return</code> statement to this</p>
<pre><code>return{
log: log
};
</code></pre>
<p>And error is gone!!</p>
<p>Is there any differences between having <code>{</code> in front of <code>return</code> or at the next line?</p> | 27,738,985 | 2 | 1 | null | 2015-01-02 07:30:30.477 UTC | 5 | 2015-12-28 05:56:51.437 UTC | 2015-02-10 14:43:18.487 UTC | null | 3,556,874 | null | 2,279,488 | null | 1 | 32 | javascript|angularjs | 25,064 | <p>This is called <strong>Automatic semicolon insertion</strong></p>
<p>The return statement is affected by automatic semicolon insertion (ASI). There is no line terminator <code>;</code> between the return keyword and the expression allowed.</p>
<pre><code>return
a + b;
// is transformed by ASI into
return;
a + b;
</code></pre>
<p>So you must insert <code>{</code> in front of return and <strong>Not at the next line.</strong></p>
<p><em>Reference:</em>
<em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return</a></em></p> |
44,706,196 | MySQL multiple columns in IN clause | <p>I have a database with four columns corresponding to the geographical coordinates x,y for the start and end position. The columns are: </p>
<ul>
<li>x0</li>
<li>y0</li>
<li>x1</li>
<li>y1</li>
</ul>
<p>I have an index for these four columns with the sequence x0, y0, x1, y1.</p>
<p>I have a list of about a hundred combination of geographical pairs. How would I go about querying this data efficiently?</p>
<p>I would like to do something like this as suggested on <a href="https://stackoverflow.com/questions/13027708/sql-multiple-columns-in-in-clause">this SO answer</a> but it only works for Oracle database, not MySQL:</p>
<pre><code>SELECT * FROM my_table WHERE (x0, y0, x1, y1) IN ((4, 3, 5, 6), ... ,(9, 3, 2, 1));
</code></pre>
<p>I was thinking it might be possible to do something with the index? What would be the best approach (ie: fastest query)? Thanks for your help!</p>
<p>Notes:</p>
<ul>
<li>I cannot change the schema of the database</li>
<li>I have about 100'000'000 rows</li>
</ul>
<p><strong>EDIT:</strong>
The code as-is was actually working, however it was extremely slow and did not take advantage of the index (as we have an older version of MySQL <code>v5.6.27</code>). </p> | 44,706,402 | 5 | 2 | null | 2017-06-22 17:46:07.063 UTC | 6 | 2017-06-22 19:48:47.79 UTC | 2017-06-22 19:48:47.79 UTC | null | 1,855,919 | null | 1,855,919 | null | 1 | 36 | mysql|sql|where-in | 47,064 | <p>To make effective use of the index, you could rewrite the IN predicate</p>
<pre><code>(x0, y0, x1, y1) IN ((4, 3, 5, 6),(9, 3, 2, 1))
</code></pre>
<p>Like this: </p>
<pre><code>( ( x0 = 4 AND y0 = 3 AND x1 = 5 AND y1 = 6 )
OR ( x0 = 9 AND y0 = 3 AND x1 = 2 AND y1 = 1 )
)
</code></pre> |
21,532,113 | Golang converting string to int64 | <p>I want to convert a string to an int64. What I find from the <code>strconv</code> package is the <code>Atoi</code> function. It seems to cast a string to an int and return it:</p>
<pre><code>// Atoi is shorthand for ParseInt(s, 10, 0).
func Atoi(s string) (i int, err error) {
i64, err := ParseInt(s, 10, 0)
return int(i64), err
}
</code></pre>
<p>The ParseInt actually returns an int64:</p>
<pre><code>func ParseInt(s string, base int, bitSize int) (i int64, err error){
//...
}
</code></pre>
<p>So if I want to get an int64 from a string, should I avoid using Atoi, instead use ParseInt? Or is there an Atio64 hidden somewhere?</p> | 21,532,180 | 3 | 1 | null | 2014-02-03 16:08:00.637 UTC | 9 | 2021-03-26 19:09:34.13 UTC | 2017-09-27 08:04:40.54 UTC | null | 1,663,023 | null | 1,663,023 | null | 1 | 117 | string|go|int64 | 144,471 | <p>No, there's no Atoi64. You should also pass in the 64 as the last parameter to ParseInt, or it might not produce the expected value on a 32-bit system.</p>
<p>Adding abbreviated example:</p>
<pre><code>var s string = "9223372036854775807"
i, _ := strconv.ParseInt(s, 10, 64)
fmt.Printf("val: %v ; type: %[1]T\n", i)
</code></pre>
<p><a href="https://play.golang.org/p/FUC8QO0-lYn" rel="noreferrer">https://play.golang.org/p/FUC8QO0-lYn</a></p> |
21,850,995 | Association for polymorphic belongs_to of a particular type | <p>I'm relatively new to Rails. I would like to add an association to a model that uses the polymorphic association, but returns only models of a particular type, e.g.:</p>
<pre><code>class Note < ActiveRecord::Base
# The true polymorphic association
belongs_to :subject, polymorphic: true
# Same as subject but where subject_type is 'Volunteer'
belongs_to :volunteer, source_association: :subject
# Same as subject but where subject_type is 'Participation'
belongs_to :participation, source_association: :subject
end
</code></pre>
<p>I've tried a vast array of combinations from reading about the associations on ApiDock but nothing seems to do exactly what I want. Here's the best I have so far:</p>
<pre><code>class Note < ActiveRecord::Base
belongs_to :subject, polymorphic: true
belongs_to :volunteer, class_name: "Volunteer", foreign_key: :subject_id, conditions: {notes: {subject_type: "Volunteer"}}
belongs_to :participation, class_name: "Participation", foreign_key: :subject_id, conditions: {notes: {subject_type: "Participation"}}
end
</code></pre>
<p>And I want it to pass this test:</p>
<pre><code>describe Note do
context 'on volunteer' do
let!(:volunteer) { create(:volunteer) }
let!(:note) { create(:note, subject: volunteer) }
let!(:unrelated_note) { create(:note) }
it 'narrows note scope to volunteer' do
scoped = Note.scoped
scoped = scoped.joins(:volunteer).where(volunteers: {id: volunteer.id})
expect(scoped.count).to be 1
expect(scoped.first.id).to eq note.id
end
it 'allows access to the volunteer' do
expect(note.volunteer).to eq volunteer
end
it 'does not return participation' do
expect(note.participation).to be_nil
end
end
end
</code></pre>
<p>The first test passes, but you can't call the relation directly:</p>
<pre><code> 1) Note on volunteer allows access to the volunteer
Failure/Error: expect(note.reload.volunteer).to eq volunteer
ActiveRecord::StatementInvalid:
PG::Error: ERROR: missing FROM-clause entry for table "notes"
LINE 1: ...."deleted" = 'f' AND "volunteers"."id" = 7798 AND "notes"."s...
^
: SELECT "volunteers".* FROM "volunteers" WHERE "volunteers"."deleted" = 'f' AND "volunteers"."id" = 7798 AND "notes"."subject_type" = 'Volunteer' LIMIT 1
# ./spec/models/note_spec.rb:10:in `block (3 levels) in <top (required)>'
</code></pre>
<hr>
<h3>Why?</h3>
<p>The reason I want to do it this way is because I'm constructing a scope based on parsing a query string including joining to various models/etc; the code used to construct the scope is considerably more complex than that above - it uses <code>collection.reflections</code>, etc. My current solution works for this, but it offends me I can't call the relations directly from an instance of Note.</p>
<p>I could solve it by splitting it into two issues: using scopes directly</p>
<pre><code> scope :scoped_by_volunteer_id, lambda { |volunteer_id| where({subject_type: 'Volunteer', subject_id: volunteer_id}) }
scope :scoped_by_participation_id, lambda { |participation_id| where({subject_type: 'Participation', subject_id: participation_id}) }
</code></pre>
<p>and then just using a getter for <code>note.volunteer</code>/<code>note.participation</code> that just returns <code>note.subject</code> if it has the right <code>subject_type</code> (nil otherwise) but I figured in Rails there must be a better way?</p> | 25,966,630 | 5 | 1 | null | 2014-02-18 10:31:57.467 UTC | 9 | 2020-09-25 21:11:35.397 UTC | null | null | null | null | 141,284 | null | 1 | 28 | ruby-on-rails|ruby-on-rails-3|polymorphic-associations | 14,321 | <p>I had bump into the similar problem. and I finally ironed out the best and most robust solution by using a self reference association like below.</p>
<pre><code>class Note < ActiveRecord::Base
# The true polymorphic association
belongs_to :subject, polymorphic: true
# The trick to solve this problem
has_one :self_ref, :class_name => self, :foreign_key => :id
has_one :volunteer, :through => :self_ref, :source => :subject, :source_type => Volunteer
has_one :participation, :through => :self_ref, :source => :subject, :source_type => Participation
end
</code></pre>
<p>Clean & simple, only tested on Rails 4.1, but I guess it should work for previous versions.</p> |
9,558,549 | Validate decimal value to 2 decimal places with data annotations? | <p>I have this in my view model:</p>
<pre><code>[Required(ErrorMessage = "Price is required")]
[Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")]
[DisplayName("Price ($)")]
public decimal Price { get; set; }
</code></pre>
<p>I'd like to validate that the user doesn't enter more than 2 decimal places. So I'd like to have</p>
<p><strong>Valid values</strong>: 12, 12.3, 12.34</p>
<p><strong>Invalid values</strong>: 12., 12.345</p>
<p>Is there a way to validate this with a data annotation?</p> | 9,558,668 | 8 | 0 | null | 2012-03-04 20:33:38.48 UTC | 5 | 2020-06-15 18:08:50.123 UTC | null | null | null | null | 295,302 | null | 1 | 22 | c#|asp.net|asp.net-mvc|asp.net-mvc-3 | 100,890 | <p>You could use the RegularExpression attribute, with a regex that matches your criteria. There are a whole bunch of expressions here that involve numbers, I'm sure one will fit the bill. Here is the <a href="http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3" rel="noreferrer">link</a>.</p>
<p>This will get you started, though it may not be as inclusive as you want (requires at least one digit leading the decimal point):</p>
<pre><code>[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price")]
</code></pre>
<p>Note that it is difficult to emit a precise error message because you don't know which part of the regex failed to match (the string "z.22" has the correct number of decimal places, for example, but is not a valid price).</p> |
22,444,799 | How to uninstall .vsix Visual Studio Extensions? | <p>I am currently trying to install the XNA Game Studio for Visual Studio Express 2013. And I accidentally ran the .vsix program BEFORE actually installing the XNA framework.</p>
<p>After installing it and re-running the .vsix, I get a message error saying that the extension has already been installed. Which is not false.</p>
<p>I have tried a lot of things to "delete" the empty extension : going in %LocalAppData%\Microsoft\VisualStudio and trying to find the extension, but finding myself with nothing, for example.</p>
<p>I would like to know how I can properly uninstall and reinstall the framework.</p> | 22,445,013 | 10 | 1 | null | 2014-03-17 00:01:11.473 UTC | 15 | 2022-08-04 03:22:01.437 UTC | 2017-11-15 19:01:11.153 UTC | null | 3,063,884 | user3147186 | null | null | 1 | 86 | visual-studio-2013|xna|uninstallation|vsix | 80,025 | <p>In the menu, go to:</p>
<ul>
<li>Visual Studio 2017: <strong>Tools > Extensions And Updates</strong> </li>
<li>Visual Studio 2019: <strong>Extensions > Manage Extensions</strong></li>
</ul>
<p>A new window will pop up, then in the panel to the left, click the arrow besides <strong>Installed</strong> to bring it down and select the menu item <strong>All</strong>.</p>
<p>All you have to do now is to navigate in the middle panel to your installed exstension, select it and click <strong>Uninstall</strong>.</p> |
22,709,882 | How to suppress application logging messages from a node.js application when running unit tests? | <p>While unit-testing my node.js application (which is basically a REST backend) using mocha and supertest, I need only the test-specific message on the screen, but the stdout is also cluttered with application log messages.</p>
<p>I start the unit test with:</p>
<pre><code>mocha -R spec .
</code></pre>
<p>... and get this output (this is what it <em>should not</em> be):</p>
<pre><code>[App] Listening on port 3000 ...
[App] Starting app, hooray!
Project API
GET /projects
[App] entering "projects" module ...
√ should return an array of projects (317ms)
</code></pre>
<p>I marked the application log message with [App]. What I <em>really want</em> would be this output from the unit test:</p>
<pre><code> Project API
GET /projects
√ should return an array of projects (317ms)
</code></pre>
<p>How can I suppress console.log/warn/error output by the application interspersed with Mocha's reporter output?</p>
<p><strong>SOLUTION:</strong></p>
<p>Following dankohn's approach, I ended up like this, which solves my issue (using <a href="http://github.com/flatiron/winston">winston</a> for logging):</p>
<p>(in node's "main" server file, server.js:)</p>
<pre><code>if (process.env.NODE_ENV !== 'test') {
logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'foo.log' })
]
});
} else {
// while testing, log only to file, leaving stdout free for unit test status messages
logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({ filename: 'foo.log' })
]
});
}
</code></pre>
<p>... and to set the env variable, each unit test file starts with:</p>
<pre><code>process.env.NODE_ENV = 'test';
</code></pre> | 22,710,649 | 5 | 1 | null | 2014-03-28 10:15:20 UTC | 12 | 2022-02-19 12:13:29.43 UTC | 2014-04-09 11:06:48.407 UTC | null | 3,472,081 | null | 3,472,081 | null | 1 | 64 | node.js|unit-testing|mocha.js | 37,101 | <p>In your app.js:</p>
<pre><code>if (process.env.NODE_ENV !== 'test') {
app.use(express.logger());
}
</code></pre>
<p>At the top of each of your mocha files:</p>
<pre><code>process.env.NODE_ENV = 'test';
</code></pre>
<p><strong>Update:</strong></p>
<p>We use this function in our import code:</p>
<pre><code>function logExceptOnTest(string) {
if (process.env.NODE_ENV !== 'test') {
console.log(string);
}
}
</code></pre>
<p>Then, replace all your <code>console.log('it worked')</code> with <code>logExceptOnTest('it worked')</code>. The basic trick is to use environment variables as a global flag as to the level of logging you want.</p> |
31,741,405 | Error: SetSite failed for package [ApacheCordovaToolsPackage] | <p>I just installed both Visual studio 2015 and visual studio cordova tools.
It wrked fine and i was able to create a project with it.</p>
<p>I then installed ionic cli, and suddenly i am getting the error </p>
<pre><code>SetSite failed for package [ApacheCordovaToolsPackage]
</code></pre>
<p>I have tried repairing Visual studio and cordova tools to no avail.
Any help?</p> | 31,834,181 | 2 | 2 | null | 2015-07-31 08:19:05.343 UTC | 9 | 2016-02-13 09:11:41.037 UTC | null | null | null | null | 1,431,191 | null | 1 | 13 | visual-studio|cordova|visual-studio-cordova | 10,599 | <p>The steps in <a href="https://social.msdn.microsoft.com/Forums/en-US/0e5115ca-83a7-4294-8740-289b3f453fca/rtm-known-issue-package-load-failure-when-creating-a-windows-app-project-with-javascript-or-hang">this MSDN forum post</a> worked for me. Reproducing for Googleability:</p>
<blockquote>
<p>Find the installer for Visual Studio 2015 in your installer cache.</p>
</blockquote>
<pre><code>cd /d "%ProgramData%\Package Cache"
dir vs*exe /s /b
</code></pre>
<blockquote>
<p>Find the path to vs_community.exe, vs_professional.exe, or vs_enterprise.exe, and copy that path. </p>
</blockquote>
<p>(I found my <code>vs_enterprise.exe</code> at <code>C:\ProgramData\Package Cache\{a60a492e-b5eb-4218-a9e6-f38d18a7dbaf}\vs_enterprise.exe</code>)</p>
<p>CD into that path, e.g.,</p>
<pre><code>cd {a60a492e-b5eb-4218-a9e6-f38d18a7dbaf}
</code></pre>
<p>Execute the installer with the options <code>/modify /installselectableitems Javascript</code>, e.g.,</p>
<pre><code>vs_enterprise.exe /modify /installselectableitems Javascript
</code></pre>
<blockquote>
<p>In Visual Studio setup, select Modify then Update, without changing any feature selections. </p>
</blockquote>
<p>Then:</p>
<pre><code>cd C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
devenv /updateconfiguration
devenv /clearcache
</code></pre> |
3,960,050 | How to develop plugins for the native Android browser | <p>I searched the web but no luck: how can plugins for the native Android browser be developed?! Neither Google nor the Android SDK give information about this topic.</p> | 4,007,934 | 1 | 3 | null | 2010-10-18 14:12:38.28 UTC | 9 | 2015-08-21 21:33:26.343 UTC | 2012-02-10 14:09:04.54 UTC | null | 894,284 | null | 419,501 | null | 1 | 11 | android|plugins|browser | 10,821 | <p>I found a sample of a plugin in the Android source code under <code>development/samples/BrowserPlugin</code>. </p>
<p>So I guess <code>development/samples/BrowserPlugin/README</code> should be a good start.</p> |
3,697,252 | Problem understanding C# type inference as described in the language specification | <p>The <strong><a href="http://www.microsoft.com/downloads/en/details.aspx?familyid=DFBF523C-F98C-4804-AFBD-459E846B268E&displaylang=en" rel="noreferrer">C# language specification</a></strong> describes type inference in Section §7.5.2. There is a detail in it that I don’t understand. Consider the following case:</p>
<pre><code>// declaration
void Method<T>(T obj, Func<string, T> func);
// call
Method("obj", s => (object) s);
</code></pre>
<p>Both the Microsoft and Mono C# compilers correctly infer <code>T</code> = <code>object</code>, but my understanding of the algorithm in the specification would yield <code>T</code> = <code>string</code> and then fail. Here is how I understand it:</p>
<p><strong>The first phase</strong></p>
<ul>
<li><p>If Ei is an anonymous function, an <em>explicit parameter type inference</em> (§7.5.2.7) is made from Ei to Ti</p>
<p>⇒ has no effect, because the lambda expression has no explicit parameter types. Right?</p></li>
<li><p>Otherwise, if Ei has a type U and xi is a value parameter then a <em>lower-bound inference</em> is made from U to Ti.</p>
<p>⇒ the first parameter is of static type <code>string</code>, so this adds <code>string</code> to the lower bounds for <code>T</code>, right?</p></li>
</ul>
<p><strong>The second phase</strong></p>
<ul>
<li><p>All <em>unfixed</em> type variables Xi which do not <em>depend on</em> (§7.5.2.5) any Xj are fixed (§7.5.2.10).</p>
<p>⇒ <code>T</code> is unfixed; <code>T</code> doesn’t depend on anything... so <code>T</code> should be fixed, right?</p></li>
</ul>
<p><strong>§7.5.2.11 Fixing</strong></p>
<ul>
<li><p>The set of candidate types Uj starts out as the set of all types in the set of bounds for Xi.</p>
<p>⇒ { <code>string</code> (lower bound) }</p></li>
<li><p>We then examine each bound for Xi in turn: [...] For each lower bound U of Xi all types Uj to which there is not an implicit conversion from U are removed from the candidate set. [...]</p>
<p>⇒ doesn’t remove anything from the candidate set, right?</p></li>
<li><p>If among the remaining candidate types Uj there is a unique type V from which there is an implicit conversion to all the other candidate types, then Xi is fixed to V.</p>
<p>⇒ Since there is only one candidate type, this is vacuously true, so Xi is fixed to <code>string</code>. Right?</p></li>
</ul>
<hr>
<p><strong>So where am I going wrong?</strong></p> | 3,701,299 | 1 | 6 | null | 2010-09-13 00:24:47.747 UTC | 26 | 2010-09-13 17:22:28.083 UTC | 2010-09-13 01:46:22.293 UTC | null | 33,225 | null | 33,225 | null | 1 | 62 | c#|language-features|type-inference|language-specifications | 1,242 | <p>UPDATE: My initial investigation on the bus this morning was incomplete and wrong. The text of the first phase specification is correct. The implementation is correct.</p>
<p>The spec is wrong in that it gets the order of events wrong in the second phase. We should be specifying that we make output type inferences <em>before</em> we fix the non-dependent parameters.</p>
<p>Man, this stuff is complicated. I have rewritten this section of the spec more times than I can remember.</p>
<p>I have seen this problem before, and I distinctly recall making revisions such that the incorrect term "type variable" was replaced everywhere with "type parameter". (Type parameters are not storage locations whose contents can vary, so it makes no sense to call them variables.) I think at the same time I noted that the ordering was wrong. Probably what happened was we accidentally shipped an older version of the spec on the web. Many apologies.</p>
<p>I will work with Mads to get the spec updated to match the implementation. I think the correct wording of the second phase should go something like this:</p>
<blockquote>
<ul>
<li>If no unfixed type parameters exist then type inference succeeds.</li>
<li>Otherwise, if there exists one or more arguments Ei with
corresponding parameter type Ti such that
the output type of Ei with type Ti contains at least one unfixed
type parameter Xj, and
none of the input types of Ei with type Ti contains any unfixed
type parameter Xj,
then an output type inference is made from all such Ei to Ti.</li>
</ul>
<p>Whether or not the previous step actually made an inference, we
must now fix at least one type parameter, as follows:</p>
<ul>
<li>If there exists one or more type parameters Xi such that
Xi is unfixed, and
Xi has a non-empty set of bounds, and
Xi does not depend on any Xj
then each such Xi is fixed. If any fixing operation fails then
type inference fails.</li>
<li>Otherwise, if there exists one or more type parameters Xi such that
Xi is unfixed, and
Xi has a non-empty set of bounds, and
there is at least one type parameter Xj that depends on Xi
then each such Xi is fixed. If any fixing operation fails then
type inference fails.</li>
<li>Otherwise, we are unable to make progress and there are
unfixed parameters. Type inference fails.</li>
</ul>
<p>If type inference neither fails nor succeeds then the second phase is repeated.</p>
</blockquote>
<p>The idea here is that we want to ensure that the algorithm never goes into an infinite loop. At every repetition of the second phase it either succeeds, fails, or makes progress. It cannot possibly loop more times than there are type parameters to fix to types.</p>
<p>Thanks for bringing this to my attention.</p> |
20,928,727 | Adding commits to another person's pull request on GitHub | <p>My project on GitHub has received a <a href="https://github.com/johnbillion/query-monitor/pull/45">pull request</a>. The pull request only partly fixes the issue that it's addressing. I've pulled in the changes to a local branch and added some commits of my own.</p>
<p>I'd now like to push those commits back to my remote repo and have them show up on the pull request, but without merging them into the target branch. I'd like to keep the pull request open for further review and discussion, and potentially further commits.</p>
<p>Is there a way I can add commits to the pull request without merging them into the target branch and therefore closing the pull request?</p> | 46,063,271 | 4 | 3 | null | 2014-01-05 00:56:18.09 UTC | 19 | 2021-09-15 17:19:08.917 UTC | 2014-01-05 01:05:31.543 UTC | null | 129,655 | null | 337,059 | null | 1 | 45 | git|github|pull-request | 12,741 | <p>As long as the original author has clicked the checkbox in the bottom right:</p>
<p><a href="https://i.stack.imgur.com/wu4Wd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wu4Wd.png" alt="Allow Maintainers" /></a></p>
<p>If that box is checked, then you can push back to the original branch without needing to add a remote by using:</p>
<pre><code>git push [email protected]:user/repo local_branch_name:remote_branch_name
</code></pre>
<p>This is particularly useful if you're using a tool like <a href="http://hub.github.com" rel="nofollow noreferrer">hub</a> where you can check out a pull request without needing to add a remote.</p>
<p><strong>Edit:</strong> You also need to have write access to the repository where the PR has been opened.</p>
<p><strong>Further Edit:</strong> The <a href="https://cli.github.com" rel="nofollow noreferrer">new command line tool</a> from GitHub does a good job of checking out PRs so that you can just use <code>git push</code> as is to push updates to remotes (assuming you have permission).</p> |
18,348,612 | What is the definition / difference of "backend" and a "frontend" in a software development / project? | <p>How a newbie differentiate between this? How one can know he/she is working is back-end system or front-end system?</p> | 18,348,643 | 1 | 0 | null | 2013-08-21 03:56:51.35 UTC | 5 | 2015-10-30 12:28:13.427 UTC | 2015-10-30 12:28:13.427 UTC | null | 1,936,186 | null | 1,936,186 | null | 1 | 12 | frontend|backend|agile | 43,213 | <p>"Front-end" typically means the parts of the project a user interacts with--such as the graphical user interface or command line. It's a vague term, there isn't an exact definition.</p>
<p>"Back-end" means the parts that do the work, but the user is unaware of or cannot see. Databases, services, etc.</p>
<p>Think of it like a restaurant where you can't see the kitchen. As a customer you see the front-end--the decorations, menus, wait-staff. Meanwhile the kitchen and stockroom are out of view, but preparing food.</p> |
2,033,242 | Concatenation Operator + or , | <pre><code>var1 = 'abc'
var2 = 'xyz'
print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz
</code></pre>
<p>... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?</p>
<p>Thanks</p> | 2,033,272 | 3 | 0 | null | 2010-01-09 11:57:34.49 UTC | 6 | 2016-04-03 11:11:33.53 UTC | 2010-01-18 17:33:55.147 UTC | null | 87,699 | null | 172,637 | null | 1 | 12 | python|python-3.x|concatenation | 41,257 | <p>(You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.)</p>
<p>The first, <code>print('literal' + var1 + var2)</code>, evaluates an expression and passes <em>a single argument</em> to print. The second, <code>print('literal', var1, var2)</code>, just passes <em>three arguments</em> to print. This is almost the same output purely by chance: that's how print works. The second is not doing any concatenation, and is simply outputting each value separated by a space (which is print's default behavior).</p>
<p>To be explicit: the plus in the expression <strong>is</strong> doing concatenation, but the comma <strong>is not</strong> doing concatenation.</p>
<hr>
<p><strong>Timing:</strong> I got the results below; however, I believe this is biased because the strings are so short (e.g. longer strings could reverse the result), and in any case, printing as presenting in the question won't take long (you'll get better performance worrying about <em>many</em> other things instead).</p>
<p><em>Note:</em> Use <code>python -m timeit --help</code> for instructions on how to use timeit.</p>
<pre><code>$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a, b'
100000 loops, best of 3: 7.68 usec per loop
$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a + " " + b'
100000 loops, best of 3: 4.67 usec per loop
$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, " ".join([a, b])'
100000 loops, best of 3: 5.37 usec per loop
</code></pre>
<p>In particular, notice each code will give the exact same output (it's meaningless to compare if one method <em>gives the wrong results</em>). The StringIO is an easy way to <em>not</em> print to the screen in these tests, but it could be affecting the results too.</p> |
1,998,328 | throwing/returning a 404 actionresult or exception in Asp.net MVC and letting IIS handle it | <p>how do I throw a 404 or FileNotFound exception/result from my action and let IIS use my customErrors config section to show the 404 page?</p>
<p>I've defined my customErrors like so</p>
<pre><code><customErrors mode="On" defaultRedirect="/trouble">
<error statusCode="404" redirect="/notfound" />
</customErrors>
</code></pre>
<p>My first attempt at an actionResult that tries to add this doesnt work.</p>
<pre><code>public class NotFoundResult : ActionResult {
public NotFoundResult() {
}
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.TrySkipIisCustomErrors = false;
context.HttpContext.Response.StatusCode = 404;
}
}
</code></pre>
<p>But this just shows a blank page and not my /not-found page</p>
<p>:(</p>
<p>What should I do?</p> | 1,998,500 | 3 | 0 | null | 2010-01-04 08:58:17.197 UTC | 6 | 2014-06-18 15:17:35.727 UTC | null | null | null | null | 209 | null | 1 | 51 | asp.net-mvc|http|iis-7 | 57,784 | <p>ASP.NET MVC 3 introduced the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.httpnotfoundresult%28v=vs.98%29.aspx" rel="noreferrer">HttpNotFoundResult</a> action result which should be used in preference to manually throwing the exception with the http status code.
This can also be returned via the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpnotfound%28v=vs.98%29.aspx" rel="noreferrer">Controller.HttpNotFound</a> method on the controller:</p>
<pre><code>public ActionResult MyControllerAction()
{
...
if (someNotFoundCondition)
{
return HttpNotFound();
}
}
</code></pre>
<p>Prior to MVC 3 you had to do the following:</p>
<pre><code>throw new HttpException(404, "HTTP/1.1 404 Not Found");
</code></pre> |
8,491,958 | Use CSS to make background-image above background-color in a list | <p>This is the code</p>
<pre><code><ul>
<li class="test">
<a href="#">
<h2>Blah</h2>
<p>Blah Blah Blah</p>
</a>
</li>
</ul>
</code></pre>
<p>Basically, my list already has some styling, for example, I set the background-color for it.</p>
<p>Now in the class "test", I also set a background-image.</p>
<p>My question is I want to make the background-image stays above the background-color and I dont know how to achieve this. I tried with z-index but I think it is not applicable for background-image.</p>
<p>Please take a look at the image</p>
<p><img src="https://i179.photobucket.com/albums/w293/blackstorm_9x/Background.jpg" alt="Output"></p>
<p>Edit: This is the CSS Code</p>
<p>For example, this is the styling for my list</p>
<pre><code>#sidebar ul li{
background:#ccf;
}
</code></pre>
<p>And this is the styling for the class test</p>
<pre><code>.test{
background-image: url('img/big_tick.png');
background-repeat:no-repeat;
background-position: bottom right;
-moz-background-size: 30%;
-webkit-background-size: 30%;
background-size: 30%;
margin-right: 30px;
}
</code></pre> | 8,492,335 | 2 | 1 | null | 2011-12-13 15:43:54.52 UTC | null | 2015-05-03 04:20:07.077 UTC | 2017-02-08 14:33:57.067 UTC | null | -1 | null | 826,224 | null | 1 | 6 | css|z-index|background-image|background-color | 55,017 | <p>Add the <code>!important</code> attribute to your <code>background-image</code>. Like this:</p>
<pre><code>.test a{
background-image: url('img/big_tick.png') !important;
background-repeat:no-repeat;
background-position: bottom right;
-moz-background-size: 30%;
-webkit-background-size: 30%;
background-size: 30%;
margin-right: 30px;
</code></pre>
<p>}</p>
<p>I have an example fiddle <a href="http://jsfiddle.net/LHmfT/11/">here</a></p>
<p>EDIT: I changed the class to <code>.test a</code> to reflect the actual styling scheme</p> |
27,274,705 | TypeError: coercing to Unicode: need string or buffer, int found | <p>I have 2 APIs. I am fetching data from them. I want to assign particular code parts to string so that life became easier while coding. Here is the code:</p>
<pre><code>import urllib2
import json
urlIncomeStatement = 'http://dev.c0l.in:8888'
apiIncomeStatement = urllib2.urlopen(urlIncomeStatement)
dataIncomeStatement = json.load(apiIncomeStatement)
urlFinancialPosition = 'http://dev.c0l.in:9999'
apiFinancialPosition = urllib2.urlopen(urlFinancialPosition)
dataFinancialPositiont = json.load(apiFinancialPosition)
for item in dataIncomeStatement:
name = item['company']['name']
interestPayable = int(item['company']['interest_payable'])
interestReceivable = int(item['company']['interest_receivable'])
sales = int(item['company']['interest_receivable'])
expenses = int(item['company']['expenses'])
openingStock = int(item['company']['opening_stock'])
closingStock = int(item['company']['closing_stock'])
sum1 = sales + expenses
if item['sector'] == 'technology':
name + "'s interest payable - " + interestPayable
name + "'s interest receivable - " + interestReceivable
name + "'s interest receivable - " + sales
name + "'s interest receivable - " + expenses
name + "'s interest receivable - " + openingStock
name + "'s interest receivable - " + closingStock
print sum1
</code></pre>
<p>In result I get:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/gnite_000/Desktop/test.py", line 25, in <module>
name + "'s interest payable - " + interestPayable
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre> | 27,274,835 | 2 | 3 | null | 2014-12-03 14:52:25.617 UTC | 2 | 2016-11-07 15:12:54.707 UTC | 2016-11-07 15:12:54.707 UTC | null | 1,503 | null | 4,145,406 | null | 1 | 29 | python|api|unicode|buffer|typeerror | 92,484 | <p>The problem might have to do with the fact that you are adding ints to strings here</p>
<pre><code> if item['sector'] == 'technology':
name + "'s interest payable - " + interestPayable
name + "'s interest receivable - " + interestReceivable
name + "'s interest receivable - " + sales
name + "'s interest receivable - " + expenses
name + "'s interest receivable - " + openingStock
name + "'s interest receivable - " + closingStock
</code></pre>
<p>As far as I'm aware, the interpretor cannot implicitly convert an int to a string.
This might work, though,</p>
<pre><code> str(name) + "'s interest receivable - " + str(closingStock)
</code></pre>
<p>On which I'm assuming Python > 3.0</p> |
19,407,985 | Leaflet.js fitBounds with padding? | <p>I'm trying to set the fitBounds option in a leaflet map like this:</p>
<pre class="lang-js prettyprint-override"><code>var bounds = new L.LatLngBounds([[Math.max(lat, borneLat), Math.max(lng, borneLng)], [Math.min(lat, borneLat), Math.min(lng, borneLng)]]);
map.fitBounds(bounds, { padding: [20, 20] });
</code></pre>
<p>However this doesn't seem to add any padding ? at least the map "zoom level" doesn't change, and it's always showing the two points in the edges (i.e. one is top far right and the other is bottom far left). For some marker sets, it works ok, the zoom is at a decent level away and you can see everything nicely. However when the items are quite close to each other, it seems it zooms in a bit too much unless I can fit it with some "padding."</p>
<p>Also I'm unsure if the bounds would be correct like that? Should I use instead just:</p>
<pre class="lang-js prettyprint-override"><code>var bounds = [[Math.max(lat, borneLat), Math.max(lng, borneLng)], [Math.min(lat, borneLat), Math.min(lng, borneLng)]];
</code></pre> | 19,410,457 | 4 | 0 | null | 2013-10-16 15:50:05.05 UTC | 2 | 2022-09-01 19:57:59.42 UTC | 2022-09-01 19:57:59.42 UTC | null | 1,243,247 | null | 187,505 | null | 1 | 50 | leaflet | 61,942 | <p><code>map.fitBounds(bounds, {padding: []})</code> should work. I suggest you to change padding to eg. <code>[50, 50]</code>, maybe your padding values are too small.</p>
<p>Check out this <a href="http://jsfiddle.net/BC7q4/444/" rel="noreferrer">JSFiddle example</a>.</p> |
19,333,648 | Start a Task without waiting | <p>I am using asp.net mvc and I want to cache some data about user from database when he reaches the home page of the site.
So when user requests the Home page, I want to call an async method, which makes database calls and caches data.</p>
<p>Any examples of doing this would be great.</p> | 19,333,720 | 5 | 1 | null | 2013-10-12 11:28:09.14 UTC | 2 | 2022-09-01 07:57:24.053 UTC | null | null | null | null | 2,873,833 | null | 1 | 22 | c#|asp.net-mvc|parallel-processing|task | 44,422 | <pre><code>ThreadPool.QueueUserWorkItem((Action<object>)state =>
{
//do your async work
}, null);
</code></pre>
<p>or <code>Task.StartNew(...)</code></p>
<p>(sorry for the brief answer, this may take you on the right track or someone can edit this to show a full example, please?)</p> |
1,033,460 | Simple jQuery ajax example not finding elements in returned HTML | <p>I'm trying to learn jQuery's ajax functions. I've got it working, but jQuery doesn't find elements in the returned HTML DOM. In the same folder as jquery, run this page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.min.js"></script>
<script tyle="text/javascript">
$(document).ready(function(){
$('input').click(function(){
$.ajax({
type : "GET",
url : 'ajaxtest-load.html',
dataType : "html",
success: function(data) {
alert( data ); // shows whole dom
alert( $(data).find('#wrapper').html() ); // returns null
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});
});
});
</script
</head>
<body>
<input type="button" value="load" />
</body>
</html>
</code></pre>
<p>Which loads this page "ajaxtest-load.html":</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>load this</title>
</head>
<body>
<div id="wrapper">
test
</div>
</body>
</html>
</code></pre>
<p>It gives two alerts. One showing the DOM was loaded, but the second shows NULL instead of the #wrapper. What am I doing wrong? </p>
<p>EDIT: I'm loading "ajaxtest-load.html" which includes the whole header, including jquery again. Is that the issue?</p> | 1,033,928 | 4 | 2 | null | 2009-06-23 15:50:28.117 UTC | 9 | 2015-02-15 08:42:05.02 UTC | 2015-02-15 08:42:05.02 UTC | null | 4,323,648 | null | 110,218 | null | 1 | 11 | jquery|ajax|dom|parsing | 36,924 | <p>I've managed to load snippets off of full html-documents just fine by using <code>.load()</code>.</p>
<p>To create a new block with extracted html into the DOM I do this:</p>
<pre><code>$('<div></div>').appendTo('body').load('some-other-document.html div#contents');
</code></pre>
<p>If it's not working for you, make sure you're using the most recent version (or post 1.2) of jQuery. See the <a href="http://docs.jquery.com/Ajax/load" rel="noreferrer">documentation for .load</a> for more examples.</p>
<p>Edit:</p>
<p>Note, though, that with the above example the result will be:</p>
<pre><code><div><div id="contents">...</div></div>
</code></pre>
<p>To get just the contents of the #contents div in the other document, use a callback-function in the load-function call.</p>
<pre><code>$('<div></div>').load('some-other-document.html div#contents', null,
function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == success) {
$('<div></div>').appendTo('body').html($(this).html());
}
}
);
</code></pre> |
429,200 | WPF: Best way to raise a popup window that is modal to the page? | <p>I am building a WPF app using navigation style pages and not windows.
I want to show a window inside a page, this window must be modal to the page, but allow the user to go to other page, and go back to the same page with the modal window in the same state.</p>
<p>I have tried with the WPF popup control but the problem is that the control hides everytime you navigate away from the page. I guess that I can write the code to show it again, but does not seams the right way.</p>
<p>What is the best way to do this in WPF?</p> | 584,332 | 4 | 1 | null | 2009-01-09 18:41:26.05 UTC | 6 | 2016-10-19 15:35:28.03 UTC | null | null | null | Eduardo Molteni | 2,385 | null | 1 | 16 | wpf|popup | 56,693 | <p>This <a href="https://stackoverflow.com/questions/173652/how-do-i-make-modal-dialog-for-a-page-in-my-wpf-application/173769#173769">StackOverflow answer</a> may help you on your way.
I created some sample code that some other users have asked for. I have added this to a blog post <a href="http://bradleach.wordpress.com/2009/02/25/control-level-modal-dialog/" rel="nofollow noreferrer">here</a>.</p>
<p>Hope this helps!</p> |
189,621 | When does CSS's !important declaration not work? | <p>I am wondering if someone can put a bit of an authoritative reference summary of when the !important declaration in CSS does <strong>not</strong> work to override inline styles.</p> | 189,634 | 4 | 0 | null | 2008-10-09 23:47:33.84 UTC | 3 | 2022-02-17 17:55:54.877 UTC | null | null | null | Graphain | 364 | null | 1 | 25 | css | 40,115 | <p>There are many factors involved in determining which styles override one another. The lower a style declaration appears in the <strong>cascade</strong>, and the <strong>more specific</strong> it is in targeting the element, the more it will weigh against other styles.</p>
<p>This is the <a href="http://www.w3.org/TR/CSS2/cascade.html" rel="noreferrer">CSS2 standard</a> for style inheritance:</p>
<blockquote>
<ol>
<li>If the cascade results in a value, use it.</li>
<li>Otherwise, if the property is inherited, use the value of the parent
element, generally the computed value.</li>
<li>Otherwise use the property's initial value. The initial value of
each property is indicated in the
property's definition.</li>
</ol>
</blockquote>
<p>Internally, the browser will <a href="http://www.w3.org/TR/CSS2/cascade.html#specificity" rel="noreferrer">calculate the specificity of a rule</a>, according to the standard. The !important declaration will add weight to the rule, but dynamically assigning a style attribute will often take precedence, because it is usually more-highly specified..</p> |
249,062 | Easy to use SNMP client library for c++? | <p>What's an easy to use SNMP client library for c++?</p> | 249,131 | 4 | 0 | null | 2008-10-30 01:59:06.65 UTC | 11 | 2016-08-13 20:26:01.83 UTC | null | null | null | Brian R. Bondy | 3,153 | null | 1 | 34 | c++|snmp | 45,450 | <p>Probably the best choice is <a href="http://www.net-snmp.org/" rel="noreferrer">net-snmp</a>. Note that the library has "C" linkage but will work just fine with C++.</p> |
68,021,770 | setOnNavigationItemSelectedListener deprecated | <p>Currently I am working on an app which has a bottom navbar with three menu items. I had used <code>setOnNavigationItemSelectedListener()</code> for items being clicked. but now iam facing issue that the method has been depreciated.</p>
<ul>
<li>App Language: <code>Java</code></li>
<li>Issue: <code>'setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemSelectedListener)' is deprecated </code></li>
</ul>
<p>Is there any way to resolve it? is is there any better alternative than <code>setOnNavigationItemSelectedListener()</code> method.</p> | 68,024,338 | 6 | 1 | null | 2021-06-17 14:54:52.733 UTC | 8 | 2022-08-28 20:30:41.073 UTC | 2021-07-09 09:31:20.667 UTC | null | 1,426,539 | null | 15,129,080 | null | 1 | 47 | java|android|bottombar | 33,128 | <p>Its deprecated according to github sources: <a href="https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/bottomnavigation/BottomNavigationView.java#L223" rel="noreferrer">BottomNavigationView.setOnNavigationItemSelectedListener</a></p>
<p>In its comment you can read:</p>
<pre><code>@deprecated Use {@link NavigationBarView#setOnItemSelectedListener(OnItemSelectedListener)}
* instead.
</code></pre>
<p>so use <a href="https://github.com/material-components/material-components-android/blob/cd5c2cc03ff30eb3f6c6959ffbc0c173ec63c089/lib/java/com/google/android/material/navigation/NavigationBarView.java#L371" rel="noreferrer">NavigationBarView.setOnItemSelectedListener</a> from its base class:</p>
<pre><code> /**
* Set a listener that will be notified when a navigation item is selected. This listener will
* also be notified when the currently selected item is reselected, unless an {@link
* OnItemReselectedListener} has also been set.
*
* @param listener The listener to notify
* @see #setOnItemReselectedListener(OnItemReselectedListener)
*/
public void setOnItemSelectedListener(@Nullable OnItemSelectedListener listener) {
selectedListener = listener;
}
</code></pre>
<p>Also see this <a href="https://github.com/material-components/material-components-android/commit/720088c5c2462dbaaa90490bca04bb3bbdc708b1" rel="noreferrer">commit</a></p>
<p>as it explains confusion about this change:</p>
<blockquote>
<p>The listeners were deprecated in favor of
<code>NavigationBarView#OnItemSelectedListener</code> and
<code>NavigationBarView#OnItemReselectedListener</code>, but deprecation
documentation was never added, so it's unclear what developers should
use instead.</p>
</blockquote> |
40,079,214 | How to enable cross origin requests in ASP.NET MVC | <p>I am trying to create a web application which works with cross-origin requests (CORS) in MVC 5. I have tried everything without any result.</p>
<p><strong>With an attribute</strong> </p>
<pre><code>public class AllowCrossSiteJsonAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
</code></pre>
<p><strong>With EnableCors attribute</strong> </p>
<pre><code> [EnableCors("*")]
</code></pre>
<p>Nothing works I'm starting to think that it is impossible</p> | 40,080,162 | 7 | 2 | null | 2016-10-17 05:42:43.7 UTC | 6 | 2019-09-07 21:02:16.34 UTC | null | null | null | null | 5,740,390 | null | 1 | 40 | c#|asp.net|asp.net-mvc|cors | 125,939 | <p>To enable cross-origin requests, add the <code>[EnableCors]</code> attribute to your Web API controller or controller method:</p>
<pre><code>[EnableCors(origins: "http://systematixindia.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller method`enter code here`s not shown...
}
</code></pre>
<p><a href="http://enable-cors.org/server_aspnet.html" rel="nofollow noreferrer" title="Read more">Read More</a></p> |
37,245,679 | ECMAScript template literals like 'some ${string}' are not working | <p>I wanted to try using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="noreferrer">template literals</a> and it’s not working: it’s displaying the literal variable names, instead of the values. I am using Chrome v50.0.2 (and jQuery).</p>
<h2>Example</h2>
<pre class="lang-js prettyprint-override"><code>console.log('categoryName: ${this.categoryName}\ncategoryElements: ${this.categoryElements} ');
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code>${this.categoryName}
categoryElements: ${this.categoryElements}
</code></pre> | 37,245,773 | 8 | 1 | null | 2016-05-16 02:00:45.263 UTC | 18 | 2022-08-29 09:03:14.657 UTC | 2021-06-19 14:14:12.71 UTC | null | 4,642,212 | null | 1,342,684 | null | 1 | 80 | javascript|template-literals | 59,444 | <h3>JavaScript <em>template literals</em> require backticks, not straight quotation marks.</h3>
<p>You need to use backticks (otherwise known as "grave accents" - which you'll find next to the 1 key <a href="https://superuser.com/questions/254076/how-do-i-type-the-tick-and-backtick-characters-on-windows">if you're using a QWERTY keyboard</a>) - rather than single quotes - to create a template literal.</p>
<p>Backticks are common in many programming languages but may be new to JavaScript developers.</p>
Example:
<pre><code>categoryName="name";
categoryElements="element";
console.log(`categoryName: ${this.categoryName}\ncategoryElements: ${categoryElements} `)
</code></pre>
Output:
<pre><code>VM626:1 categoryName: name
categoryElements: element
</code></pre>
See:
<p><a href="https://stackoverflow.com/questions/27678052/what-is-the-usage-of-the-backtick-symbol-in-javascript">Usage of the backtick character (`) in JavaScript</a></p> |
25,044,936 | chrome.identity User Authentication in a Chrome Extension | <p>I'm trying to write a chrome extension that requires user authentication.<br>
<a href="https://developer.chrome.com/extensions/app_identity#update_manifest">Google's tutorial</a> suggests that I need to upload to the web store first to get a key:</p>
<blockquote>
<ol>
<li>Login to the Google APIs Console using the same Google account used to
upload your app to the Chrome Web Store.</li>
</ol>
</blockquote>
<p>I uploaded a non-functioning version to just get the key, but it's hanging there pending for over a week now. How could I get that key or somehow inspire Google to approve this app that I don't want on the Web Store? Am I doing this all wrong?</p> | 25,046,173 | 2 | 0 | null | 2014-07-30 19:06:13.26 UTC | 32 | 2016-09-10 07:19:15.06 UTC | 2016-02-02 10:03:48.23 UTC | null | 934,239 | null | 1,247,016 | null | 1 | 28 | google-chrome|google-chrome-extension|oauth | 17,535 | <p>You don't have to upload an extension to the Chrome Web Store in order to use the <a href="https://developer.chrome.com/extensions/identity"><code>chrome.identity</code></a> API. It suffices to have a valid extension ID. The easiest way to get started is to copy the 32-character extension ID from <code>chrome://extensions/</code> to your project's credentials section at the <a href="https://console.developers.google.com/project">API console</a> <sup>see screenshot below</sup>.<br>
Though if you ever want to publish the extension or use it in a different profile or computer, then you'd better choose an extension ID that you control. This can be done by setting the <a href="https://developer.chrome.com/extensions/manifest/key"><code>"key"</code></a> key in the manifest file. See <a href="https://stackoverflow.com/questions/23873623/obtaining-chrome-extension-id-for-development">Obtaining Chrome Extension ID for development</a> for a detailed answer on generating these keys.</p>
<p>For example, try out the following extension, using a key that I just generated. It will print your user info in a dialog.</p>
<p>manifest.json</p>
<pre class="lang-js prettyprint-override"><code>{
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0W0/YVPvLrj2cWBOXfPBBYwPp56R+OJb9QLudyMpigF+V4DFV0NEUnbo9iA6m+7cVPiD6YbhbIaiAoHSdtqEKwaYvrEJRGuGsLjDq+RMwG2x+FcGIsO4ny0BuZaZ/Q2+DaL33NBUl2h9dIi1xa0Suq6qpoJ4yykTu9y7Q6rB9ulJze6DiZL7LWU5NzHCEWt21zAhpLZOqvYY8wzY69pMf+P0+uOLuy87x84rvCRNegbSmEYLC5f4y6ikjVnFUxJBxMlpMg3bByxbrLVBFPuHj4khkr6adUXgks2vBBHFcrRh5EYXopI+PLwUJPfFtzyN8+L7swen9kcK8gXMwX28KwIDAQAB",
"name": "Identity test",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"permissions": [
"identity"
],
"oauth2": {
"client_id": "1014705257182-52dddl9dbiec2ln22stokphlaq0v7gor.apps.googleusercontent.com",
"scopes": ["profile"]
}
}
</code></pre>
<p>background.js</p>
<pre class="lang-js prettyprint-override"><code>chrome.identity.getAuthToken({
interactive: true
}, function(token) {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
var x = new XMLHttpRequest();
x.open('GET', 'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token);
x.onload = function() {
alert(x.response);
};
x.send();
});
</code></pre>
<p><a href="https://i.stack.imgur.com/olY8B.png"><img src="https://i.stack.imgur.com/olY8B.png" alt=""></a></p> |
35,409,127 | How to create a csr file for azure web app | <p>I need to create a csr file to give it to someone.</p>
<p>The csr file is for a SSL certificate for a azure web app.</p>
<p>When I google I find inconsistent information about <strong>where</strong> to generate the csr file.</p>
<p>Some sources say: I have to create the csr file on the server the web app is running.</p>
<p>In my case the server on azure is unknown. I can not run anything there...</p>
<p>Or is it ok to create the csr on my local pc with all company data + the subject filled out with the custom domain?</p> | 35,409,941 | 5 | 0 | null | 2016-02-15 12:14:36.63 UTC | 3 | 2020-11-10 21:14:30.273 UTC | null | null | null | null | 1,230,266 | null | 1 | 32 | azure|ssl|csr|azure-web-app-service | 30,640 | <p>You're able to create a cer-file with the help of the Certreq.exe or OpenSSL tool.</p>
<p>For more details, please have a look at the official documentation how to <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure-ssl-certificate/" rel="noreferrer">enable HTTPS for an app in Azure App Service</a>.</p> |
25,809,168 | AnyObject and Any in Swift | <p>I don't understand when to use <code>AnyObject</code> and when to use <code>Any</code> in Swift.</p>
<p>In my case, I've a <code>Dictionary</code></p>
<blockquote>
<p>[String: ???]</p>
</blockquote>
<p>??? : Can be <code>Int</code>, <code>Double</code>, <code>Float</code>, <code>String</code>, <code>Array</code>, <code>Dictionary</code></p>
<p>Can someone explain me the difference between <code>Any</code> and <code>AnyObject</code>
and which one to use in my case.</p> | 25,809,478 | 5 | 0 | null | 2014-09-12 13:13:22.147 UTC | 21 | 2021-07-20 14:09:06.577 UTC | 2021-07-20 14:09:06.577 UTC | null | 3,701,102 | null | 693,396 | null | 1 | 104 | swift|value-type|reference-type | 37,267 | <p><code>AnyObject</code> is only for reference types (classes), <code>Any</code> is for both value and reference types.</p>
<p>So you should go for <code>[String: Any]</code>.</p>
<blockquote>
<p><strong>Type Casting for Any and AnyObject</strong></p>
<p>Swift provides two special types for working with nonspecific types:</p>
<ul>
<li><code>Any</code> can represent an instance of any type at all, including function
types. </li>
<li><code>AnyObject</code> can represent an instance of any class type. </li>
</ul>
<p><strong>NOTE:</strong></p>
<p>Use <code>Any</code> and <code>AnyObject</code> only when you explicitly need the behavior and
capabilities they provide. It is always better to be specific about
the types you expect to work with in your code.</p>
</blockquote>
<p>From <strong>The Swift Programming Language</strong>:
<a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-ID342">https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-ID342</a></p>
<p>-</p>
<p>Also note that when you work with Cocoa API, it's common to receive an Array of AnyObject, this is because Objective-C arrays are NOT typified.
So you need to cast them to the array type you expect.</p>
<p>-</p>
<p><strong>EDIT:</strong> (december 22, 2015)<br>
On the last statement, note that this is changing with Swift 2.0 and Xcode 7.<br>
Apple has introduced <a href="http://www.thomashanning.com/objective-c-lightweight-generics/">‘Lightweight’ generics</a> in Objective-C so lots of Cocoa APIs now already returns the correct type.</p>
<p><strong>EDIT:</strong> (october 18, 2016)<br>
Note that, as of Swift 3.0, Objective-C <code>id</code>s are now imported as <code>Any</code>, not anymore as <code>AnyObject</code>.</p> |
68,155,090 | Extra padding above table view headers in iOS 15 | <p>How to change the extra padding above <code>UITableView</code> section headers that has started to appear in iOS 15?</p> | 68,155,091 | 9 | 0 | null | 2021-06-27 20:39:40.52 UTC | 13 | 2022-04-21 18:46:35.857 UTC | 2021-07-05 09:48:40.947 UTC | null | 4,153,728 | null | 4,153,728 | null | 1 | 75 | ios|uitableview|ios15 | 19,333 | <p>Since iOS 15, <code>UITableView</code> contains a new property called <a href="https://developer.apple.com/documentation/uikit/uitableview/3750914-sectionheadertoppadding" rel="noreferrer"><code>sectionHeaderTopPadding</code></a> which specifies the amount of padding above each section header.</p>
<pre><code>tableView.sectionHeaderTopPadding = 0.0
</code></pre>
<blockquote>
<p><strong>Note:</strong> This applies only to the <code>UITableView.Style.plain</code>.</p>
</blockquote> |
25,538,579 | Use Cocoapods with an App Extension | <p>I'm trying to build a photo App Extension in Xcode 6 Beta-6 that uses cocoapods libraries.
The bridging header that Xcode creates for the photo extension can't see anything from cocoapods.</p>
<p>For example: <code>#import <GPUImage/GPUImage.h></code> results in the error <code>"GPUImage/GPUImage.h" file not found</code>.</p>
<p>I've tried every conceivable path for the import (with brackets and quotes) and have had almost no success. The exception is that for simple pods like <code>SVProgressHUD</code>, the following ugly terrible hack works:
<code>#import "../Pods/SVProgressHUD/SVProgressHUD/SVProgressHUD.h"</code>.</p>
<p>But for GPUImage, it walks into the <code>GPUImage.h</code> header and decides it suddenly can't see <code>GPUImageContext.h</code> despite having no issue when this is imported with the bridging header for the normal swift code that is not part of the app extension.</p>
<p>What is different about the compilation of app extensions that is preventing the bridging header from behaving sanely?</p>
<p>Note:
I've read every possible permutation of <a href="https://medium.com/@stigi/swift-cocoapods-da09d8ba6dd2" rel="noreferrer">this tutorial</a> and it is not immediately applicable, just in case anyone thinks they have found the answer there.</p>
<p>Also, the problem described in <a href="https://stackoverflow.com/q/25495225/579405">this SO question</a> may be related, but I asked this question anyway in case my issue is specific to app extensions. </p> | 28,917,143 | 4 | 1 | null | 2014-08-27 23:38:14.51 UTC | 40 | 2018-03-04 03:12:27.16 UTC | 2018-03-04 03:12:27.16 UTC | null | 1,033,581 | null | 579,405 | null | 1 | 84 | swift|ios8|cocoapods|ios-app-extension|xcode6-beta6 | 28,886 | <p>The proper way to do this is to update your podfile to add just 1 line :</p>
<pre><code>link_with 'yourApp', 'yourAppExtension'
</code></pre>
<p>and a pod update should resolve the issue.</p> |
36,532,307 | rem px in Javascript | <p>I use this code in JS:</p>
<p><code>bigPhoto.setAttribute("width", "200rem");</code></p>
<p>The result is in pixel in html source, </p>
<p><a href="https://i.stack.imgur.com/eoG7J.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eoG7J.jpg" alt="enter image description here"></a></p>
<p>But:</p>
<p><a href="https://i.stack.imgur.com/CkknS.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CkknS.jpg" alt="enter image description here"></a></p>
<p>When I change it to <strong>20rem</strong> the photo become really small.</p>
<p>I couldn't solve the problem which is mentioned in the photos.</p> | 36,532,398 | 2 | 3 | null | 2016-04-10 16:22:26.147 UTC | 8 | 2018-09-09 20:28:40.373 UTC | 2018-09-09 20:28:40.373 UTC | user2705585 | 9,299,174 | null | 4,162,391 | null | 1 | 41 | javascript|html|css|measurement | 49,631 | <p>The HTML width attribute only takes an integer number of pixels or a percentage (followed by a % sign).</p>
<p>If you wish to use CSS length units you have to use CSS (and set <code>bigPhoto.style.width = "200rem"</code>.</p> |
4,081,811 | Correct way to use _viewstart.cshtml and partial Razor views? | <p>I'm using <a href="http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx" rel="noreferrer"><strong>_viewstart.cshtml</strong> to automagically assign the same Razor Layout</a> to my views.</p>
<p>It's a dead simple file in the root of my Views folder that looks like this:</p>
<pre><code>@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
</code></pre>
<p>This is more DRY than adding the @Layout directive to every single view.</p>
<p>However, this poses a problem for Razor <strong>partial</strong> views, because they run the contents of _viewstart.cshtml and therefore incorrectly assign themselves a layout, which makes them, um, no longer partial. </p>
<p>Here's a hypothetical project, showing the _viewstart.cshtml file, the shared _layout.shtml file, and a partial view ("AnonBar.cshtml").</p>
<p><img src="https://dl.dropbox.com/u/58785/RazorPartialViewstart.PNG" alt="Example project structure"></p>
<p>Currently, the way that I'm getting around this is by adding the following line to every partial view:</p>
<pre><code>@{
Layout = "";
}
</code></pre>
<p>This seems like the wrong way to denote a view as a partial in Razor. (Note that unlike the web forms view engine, the file extension is the same for partial views.)</p>
<p>Other options I considered but that are even worse:</p>
<ul>
<li>Putting all partial views into a common folder, so they could share a common _viewstart.cshtml. This breaks the convention of views being in the same folder as their controller.</li>
<li>Not using partial views. </li>
</ul>
<p>Is this something that is still being fleshed out by the Razor view engine team, or am I missing a fundamental concept?</p> | 4,082,220 | 1 | 2 | null | 2010-11-02 20:29:01.76 UTC | 30 | 2010-11-02 23:01:15.323 UTC | 2017-02-08 14:30:48.337 UTC | null | -1 | null | 1,690 | null | 1 | 158 | razor|asp.net-mvc-3 | 59,149 | <p>If you <code>return PartialView()</code> from your controllers (instead of <code>return View()</code>), then <code>_viewstart.cshtml</code> will not be executed.</p> |
25,378,624 | Should a RESTful API return 400 or 404 when passed an invalid id | <p>When building a RESTful API and a user provides an <strong>id</strong> of resource that does not exist, should you return <code>404 Not Found</code> or <code>400 Bad Request</code>.</p>
<p>For example:</p>
<pre><code>https://api.domain.com/v1/resource/foobar
</code></pre>
<p>Where <strong>foobar</strong> does not exist.</p> | 25,378,892 | 6 | 2 | null | 2014-08-19 08:16:35.227 UTC | 13 | 2021-03-27 07:48:54.81 UTC | 2021-03-27 07:48:54.81 UTC | null | 9,213,345 | null | 425,964 | null | 1 | 70 | rest | 61,535 | <p>I would return 404 in case of resource does not exist(means the url path is wrong) and i will return 400 only if the rest call is made with some invalid data (@PathParam) for example<br>
<a href="https://api.domain.com/v1/profile/test@email">https://api.domain.com/v1/profile/test@email</a> : here i am trying to get profile of email id, but the email itself is wrong, so I will return 400.<br>
<a href="https://api.domain.com/v1/profile1111/[email protected]">https://api.domain.com/v1/profile1111/[email protected]</a> will return 404 because the url path is invalid. </p> |
55,358,811 | Error: Unable to resolve module `react-native-gesture-handler` | <p><em>I try to use navigate in react-native..
I added :</em> <code>npm install --save react-navigation</code></p>
<p>but it gives me an error like this : </p>
<p><em>error: bundling failed: Error: Unable to resolve module <code>react-native-gesture-handler</code> from <code>C:\reactnative\proejectName\node_modules\@react-navigation\native\src\Scrollables.js</code>: Module <code>react-native-gesture-handler</code> does not exist in the Haste module map</em></p>
<p><strong>this is index :</strong></p>
<pre><code>import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);
</code></pre>
<p><strong>This is app.js</strong></p>
<pre><code>import React from 'react';
import { createStackNavigator, createAppContainer, } from 'react-navigation';
import First from './src/Components/First';
import DescriptionPage from './src/Components/DescriptionPage';
const Navigation = createStackNavigator({
First: {
screen: First,
},
DescriptionPage: {
screen: DescriptionPage,
},
});
const App = createAppContainer(Navigation);
export default App;
</code></pre>
<p><strong>this is package.json :</strong></p>
<pre><code>{
"name": "ProjectName",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.1",
"react-native-sqlite-storage": "^3.3.10",
"react-navigation": "^3.5.1"
},
"devDependencies": {
"@babel/core": "7.4.0",
"@babel/runtime": "7.4.2",
"babel-jest": "24.5.0",
"eslint-config-rallycoding": "^3.2.0",
"jest": "24.5.0",
"metro-react-native-babel-preset": "0.53.1",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native"
}
}
</code></pre> | 55,358,957 | 23 | 2 | null | 2019-03-26 13:51:12.483 UTC | 7 | 2022-09-19 13:04:35.567 UTC | 2019-03-26 13:54:47.543 UTC | null | 11,028,464 | null | 11,028,464 | null | 1 | 104 | react-native | 167,284 | <p>You need to install <code>react-native-gesture-handler</code> as well separately in the project dependency list and link it too with native as well. Please refer to this <a href="https://reactnavigation.org/docs/en/getting-started.html#installation" rel="noreferrer">doc</a>.</p> |
7,293,978 | repeat an iteration of for loop | <p>if for some reason i want to repeat the same iteration how i can do it in python?</p>
<pre><code>for eachId in listOfIds:
#assume here that eachId conatins 10
response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
if response == 'market is closed':
time.sleep(24*60*60) #sleep for one day
</code></pre>
<p>now when the function wake up from sleep after one day (market (currency trade market) is open) i want to resume my for loop from <code>eachId = 10</code> <code>not</code> from <code>eachId = 11</code>, because <code>eachId = 10</code> is not yet been processed as <code>market was closed</code>, any help is highly appreciated thanks.</p> | 7,293,992 | 4 | 2 | null | 2011-09-03 15:22:12.937 UTC | 4 | 2011-09-03 15:29:05.99 UTC | null | null | null | null | 860,103 | null | 1 | 25 | python|for-loop | 63,205 | <p>Do it like this:</p>
<pre><code>for eachId in listOfIds:
successful = False
while not successful:
response = makeRequest(eachId)
if response == 'market is closed':
time.sleep(24*60*60) #sleep for one day
else:
successful = True
</code></pre>
<p>The title of your question is the clue. <em>Repeating</em> is achieved by iteration, and in this case you can do it simply with a nested <code>while</code>.</p> |
21,663,256 | How to initialize a vector of vectors on a struct? | <p>If I have a NxN matrix</p>
<pre><code>vector< vector<int> > A;
</code></pre>
<p>How should I initialize it?</p>
<p>I've tried with no success:</p>
<pre><code> A = new vector(dimension);
</code></pre>
<p>neither:</p>
<pre><code> A = new vector(dimension,vector<int>(dimension));
</code></pre> | 21,663,317 | 2 | 3 | null | 2014-02-09 18:41:57.653 UTC | 20 | 2017-06-12 08:40:46.7 UTC | 2017-06-12 08:40:46.7 UTC | null | 2,968,729 | null | 2,968,729 | null | 1 | 54 | c++|vector | 122,695 | <p>You use <code>new</code> to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.</p>
<p>You have no reason to use <code>new</code>, since <code>A</code> is an automatic variable. You can simply initialise <code>A</code> using its constructor:</p>
<pre><code>vector<vector<int> > A(dimension, vector<int>(dimension));
</code></pre> |
1,652,904 | "UnicodeEncodeError: 'ascii' codec can't encode character" | <p>I'm trying to pass big strings of random html through regular expressions and my Python 2.6 script is choking on this: </p>
<p>UnicodeEncodeError: 'ascii' codec can't encode character</p>
<p>I traced it back to a trademark superscript on the end of this word: Protection™ -- and I expect to encounter others like it in the future.</p>
<p>Is there a module to process non-ascii characters? or, what is the best way to handle/escape non-ascii stuff in python?</p>
<p>Thanks!
Full error:</p>
<pre><code>E
======================================================================
ERROR: test_untitled (__main__.Untitled)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\Test2.py", line 26, in test_untitled
ofile.write(Whois + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 1005: ordinal not in range(128)
</code></pre>
<p>Full Script:</p>
<pre><code>from selenium import selenium
import unittest, time, re, csv, logging
class Untitled(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*firefox", "http://www.BaseDomain.com/")
self.selenium.start()
self.selenium.set_timeout("90000")
def test_untitled(self):
sel = self.selenium
spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
for row in spamReader:
sel.open(row[0])
time.sleep(10)
Test = sel.get_text("//html/body/div/table/tbody/tr/td/form/div/table/tbody/tr[7]/td")
Test = Test.replace(",","")
Test = Test.replace("\n", "")
ofile = open('TestOut.csv', 'ab')
ofile.write(Test + '\n')
ofile.close()
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
</code></pre> | 1,653,052 | 4 | 3 | null | 2009-10-31 00:07:48.547 UTC | 12 | 2015-08-13 12:11:57.91 UTC | 2013-05-04 10:28:14.55 UTC | null | 635,608 | null | 175,285 | null | 1 | 27 | regex|unicode|python-2.6|non-ascii-characters | 43,972 | <p>You're trying to pass a bytestring to something, but it's impossible (from the scarcity of info you provide) to tell <strong>what</strong> you're trying to pass it to. You start with a Unicode string that cannot be encoded as ASCII (the default codec), so, you'll have to encode by some different codec (or transliterate it, as @R.Pate suggests) -- but it's impossible for use to say <em>what</em> codec you should use, because we don't know what you're passing the bytestring and therefore don't know what that unknown subsystem is going to be able to accept and process correctly in terms of codecs.</p>
<p>In such total darkness as you leave us in, <code>utf-8</code> is a reasonable blind guess (since it's a codec that can represent any Unicode string exactly as a bytestring, and it's the standard codec for many purposes, such as XML) -- but it can't be any more than a blind guess, until and unless you're going to tell us more about <strong>what</strong> you're trying to pass that bytestring to, and for what purposes.</p>
<p>Passing <code>thestring.encode('utf-8')</code> rather than bare <code>thestring</code> will definitely avoid the particular error you're seeing right now, but it may result in peculiar displays (or whatever it <strong>is</strong> you're trying to do with that bytestring!) unless the recipient is ready, willing and able to accept utf-8 encoding (and how could WE know, having absolutely zero idea about what the recipient could possibly be?!-)</p> |
10,796,650 | Why can't an interface implementation return a more specific type? | <p>If an interface specifies a property or method to return another interface, why is it not allowed for implementations of the first interface to "change" the return type into a more specific type?</p>
<p>Let's take an example to illustrate:</p>
<pre><code>interface IFoo
{
IBar GetBar();
}
interface IBar
{ }
class Foo : IFoo
{
// This is illegal, we are not implementing IFoo properly
public Bar GetBar()
{
return new Bar();
}
}
class Bar : IBar
{ }
</code></pre>
<p><em>I know</em> how to make it work, that's <em>not</em> my concern.</p>
<p>I can just either:</p>
<ul>
<li>Change return type of <code>GetFoo()</code> to <code>IBar</code>, or</li>
<li>Explicitly implement the interface and just call <code>GetBar</code> from the <code>IFoo.GetBar()</code> method</li>
</ul>
<p>What I am really asking is the reasoning for not just allowing the code above to compile. Is there any case where the above doesn't fulfill the contract specified by <code>IFoo</code>. </p> | 10,796,688 | 3 | 2 | null | 2012-05-29 09:44:40.64 UTC | 1 | 2020-08-17 11:28:25.147 UTC | null | null | null | null | 8,521 | null | 1 | 34 | c#|interface|language-design|overloading | 3,798 | <p>Usually, I'd say that it would be a case of balancing the benefit against the added complexity of supporting such a feature. (All features take effort to design, document, implement, test, and then developers need to be educated about them too.) Note that there could be some significant complexities if you wanted to support returning a value type which implemented an interface, for example (as that ends up in a different representation, rather than just a reference).</p>
<p>In this case, I don't <em>believe</em> the CLR even supports such a feature, which would make it very hard for C# to do so cleanly.</p>
<p>I agree it would be a useful feature, but I suspect it hasn't been deemed useful enough to warrant the extra work required.</p> |
28,404,971 | Finding the closest or exact key in a std::map | <p>I need to create a lookup table which links a length to a time interval (both are of data type double). The keys increment linearly as they are inserted, so it will already be sorted (perhaps an unordered_map would be better?). </p>
<p>What I am looking for is a way to find a key that best matches the current length provided to get the time value, or even better find the two keys that surround the length (the given key is between them) so I can find the interpolated value between the two time values. </p>
<p>I also need the best performance possible as it will be called in real time.</p>
<p>EDIT: I would have rather the following was a comment to the first answer below, but the format is hard to read. </p>
<p>I tried to do the following, but it seems to return the same iterator (5.6):</p>
<pre><code>std::map<double, double> map;
map.insert(std::pair<double, double>(0.123, 0.1));
map.insert(std::pair<double, double>(2.5, 0.4));
map.insert(std::pair<double, double>(5.6, 0.8));
std::map<double, double>::iterator low, high;
double pos = 3.0;
low = map.lower_bound(pos);
high = map.upper_bound(pos);
</code></pre>
<p>How would I get 'low' to point to the last element that is < than the key used to search?</p>
<p>EDIT 2:
Silly me, 'low--' will do it, providing it's not the first element. </p>
<p>Getting there :) </p> | 28,405,093 | 7 | 2 | null | 2015-02-09 07:43:24.833 UTC | 5 | 2020-01-16 13:41:48.227 UTC | 2015-02-09 08:43:06.26 UTC | null | 2,080,170 | null | 2,080,170 | null | 1 | 29 | c++ | 24,791 | <p>For this, you can use either <a href="http://en.cppreference.com/w/cpp/container/map/lower_bound" rel="noreferrer"><code>std::map::lower_bound</code></a></p>
<blockquote>
<p>Returns an iterator pointing to the first element that is not less than key.</p>
</blockquote>
<p>or <a href="http://en.cppreference.com/w/cpp/container/map/equal_range" rel="noreferrer"><code>std::map::equal_range</code></a></p>
<blockquote>
<p>Returns a range containing all elements with the given key in the container.</p>
</blockquote>
<hr>
<p>In your case, if you want the closest entry, you need to check both the returned entry and the one before and compare the differences. Something like this might work </p>
<pre><code>std::map<double, double>::iterator low, prev;
double pos = 3.0;
low = map.lower_bound(pos);
if (low == map.end()) {
// nothing found, maybe use rbegin()
} else if (low == map.begin()) {
std::cout << "low=" << low->first << '\n';
} else {
prev = std::prev(low);
if ((pos - prev->first) < (low->first - pos))
std::cout << "prev=" << prev->first << '\n';
else
std::cout << "low=" << low->first << '\n';
}
</code></pre> |
28,816,627 | How to find linearly independent rows from a matrix | <p>How to identify the linearly independent rows from a matrix? For instance,</p>
<p><img src="https://i.stack.imgur.com/Zb9f8.gif" alt="enter image description here"></p>
<p>The 4th rows is independent.</p> | 28,817,934 | 7 | 3 | null | 2015-03-02 18:12:37.24 UTC | 10 | 2022-06-27 09:58:00.397 UTC | 2016-10-04 11:13:25.323 UTC | null | 3,067,748 | null | 3,067,748 | null | 1 | 31 | python|numpy|matrix|linear-algebra | 48,219 | <p>First, your 3rd row is linearly dependent with 1t and 2nd row. However, your 1st and 4th column are linearly dependent.</p>
<p>Two methods you could use:</p>
<p><strong>Eigenvalue</strong></p>
<p>If one eigenvalue of the matrix is zero, its corresponding eigenvector is linearly dependent. The documentation <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html#numpy.linalg.eig" rel="noreferrer">eig</a> states the returned eigenvalues are repeated according to their multiplicity and not necessarily ordered. However, assuming the eigenvalues correspond to your row vectors, one method would be:</p>
<pre><code>import numpy as np
matrix = np.array(
[
[0, 1 ,0 ,0],
[0, 0, 1, 0],
[0, 1, 1, 0],
[1, 0, 0, 1]
])
lambdas, V = np.linalg.eig(matrix.T)
# The linearly dependent row vectors
print matrix[lambdas == 0,:]
</code></pre>
<p><strong>Cauchy-Schwarz inequality</strong></p>
<p>To test linear dependence of vectors and figure out which ones, you could use the <a href="http://en.wikipedia.org/wiki/Cauchy%E2%80%93Schwarz_inequality" rel="noreferrer">Cauchy-Schwarz inequality</a>. Basically, if the inner product of the vectors is equal to the product of the norm of the vectors, the vectors are linearly dependent. Here is an example for the columns:</p>
<pre><code>import numpy as np
matrix = np.array(
[
[0, 1 ,0 ,0],
[0, 0, 1, 0],
[0, 1, 1, 0],
[1, 0, 0, 1]
])
print np.linalg.det(matrix)
for i in range(matrix.shape[0]):
for j in range(matrix.shape[0]):
if i != j:
inner_product = np.inner(
matrix[:,i],
matrix[:,j]
)
norm_i = np.linalg.norm(matrix[:,i])
norm_j = np.linalg.norm(matrix[:,j])
print 'I: ', matrix[:,i]
print 'J: ', matrix[:,j]
print 'Prod: ', inner_product
print 'Norm i: ', norm_i
print 'Norm j: ', norm_j
if np.abs(inner_product - norm_j * norm_i) < 1E-5:
print 'Dependent'
else:
print 'Independent'
</code></pre>
<p>To test the rows is a similar approach.</p>
<p>Then you could extend this to test all combinations of vectors, but I imagine this solution scale badly with size.</p> |
7,594,337 | Learning Haskell with a view to learning Scala | <p>I've read a few questions such as Scala vs Haskell discussing the merits of both languages or which to learn, but I already know that I'd like to learn Scala. I was a Java programmer at uni and now mainly use PHP. </p>
<p>I want to learn Scala as it looks like an improvement on Java for personal projects and I'd also like to learn a functional language to improve my knowledge as a programmer.</p>
<p>I am wondering if it would be a good idea to learn Haskell as an introduction to functional programming as it is purely functional so I'd properly learn it rather than haphazard using bits of functional in Scala without knowing why? </p>
<p>I'd also like to use Haskell for personal projects etc as it looks great, but I don't really see many real world applications of it, seems more used for academic stuff hence wanting to learn it to get the functional understanding then move on to Scala.</p> | 7,594,599 | 6 | 0 | null | 2011-09-29 08:16:07.383 UTC | 11 | 2017-04-20 14:03:53.12 UTC | null | null | null | null | 513,546 | null | 1 | 45 | scala|haskell|functional-programming|purely-functional | 4,284 | <p>Speaking as someone who came from Java, and for whom Scala was a gateway drug to Haskell, I happen to think this is a great idea (learn Haskell first)! </p>
<p>Haskell is conceptually a much simpler language than Scala, and if your goal is to learn how to program functionally, you can't help but do so if you start with Haskell. By design, Scala supports a kind of "legacy mode" of coding in which you don't really have to change your Java (or PHP) habits too much if you don't want to. I think this is a strategic decision--and a good one!--meant to increase adoption amongst crusty Java stalwarts. </p>
<p>But that's not you! You're actually <em>interested</em> in learning something new... so why not go all-out? Learning functional programming in a pure setting, without the clutter and the temptation to regress into old habits, will crystallize the concepts in your brain.</p>
<p>Then by all means return to Scala and learn how it differs from Haskell; it is both weaker in some respects and stronger in others, but you will then be on a much better foundation to appreciate these differences.</p> |
7,582,336 | Force youtube embed to start in 720p | <p>There are a few methods suggested for doing this online, but none of them seem to work.</p>
<p>For example:</p>
<p><a href="http://blog.makezine.com/archive/2008/11/youtube-in-720p-hd-viewin.html">http://blog.makezine.com/archive/2008/11/youtube-in-720p-hd-viewin.html</a></p>
<p>That article is about making it start in 720p, but it doesn't even work on their own video.</p>
<p>Does anyone here know how to do it?</p> | 10,480,294 | 10 | 2 | null | 2011-09-28 11:13:11.563 UTC | 19 | 2021-06-03 08:32:58.197 UTC | null | null | null | null | 952,248 | null | 1 | 52 | html|youtube|embed | 194,363 | <p><em>(This answer was updated, as the previous method using <code>vq</code> isn't recognized anymore.)</em></p>
<p>Specifying the height of the video will change the quality accordingly.
example for html 5;</p>
<pre><code><iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>
</code></pre>
<p>If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.</p>
<p>Tested on a working server + passes the w3.org nuhtml validator.</p> |
7,085,644 | How to check if APK is signed or "debug build"? | <p>As far as I know, in android "release build" is signed APK. How to check it <strong>from code</strong> or does Eclipse has some kinda of secret defines?</p>
<p>I need this to debug populating ListView items from web service data (no, logcat not an option). </p>
<p>My thoughts: </p>
<ul>
<li>Application's <code>android:debuggable</code>, but for some reason that doesn't look reliable. </li>
<li>Hard-coding device ID isn't good idea, because I am using same device for testing signed APKs. </li>
<li>Using manual flag somewhere in code? Plausible, but gonna definitely forget to change at some time, plus all programmers are lazy.</li>
</ul> | 11,535,593 | 10 | 2 | null | 2011-08-16 22:07:01.797 UTC | 41 | 2019-07-15 15:37:32.287 UTC | 2012-05-27 16:09:41.5 UTC | null | 244,296 | null | 421,752 | null | 1 | 128 | android|debugging|certificate | 82,915 | <p>There are different way to check if the application is build using debug or release certificate, but the following way seems best to me.</p>
<p>According to the info in Android documentation <a href="http://developer.android.com/tools/publishing/app-signing.html" rel="noreferrer">Signing Your Application</a>, debug key contain following subject distinguished name: "<strong>CN=Android Debug,O=Android,C=US</strong>". We can use this information to test if package is signed with debug key without hardcoding debug key signature into our code.</p>
<p>Given:</p>
<pre><code>import android.content.pm.Signature;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
</code></pre>
<p>You can implement an isDebuggable method this way:</p>
<pre><code>private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
private boolean isDebuggable(Context ctx)
{
boolean debuggable = false;
try
{
PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),PackageManager.GET_SIGNATURES);
Signature signatures[] = pinfo.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for ( int i = 0; i < signatures.length;i++)
{
ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
if (debuggable)
break;
}
}
catch (NameNotFoundException e)
{
//debuggable variable will remain false
}
catch (CertificateException e)
{
//debuggable variable will remain false
}
return debuggable;
}
</code></pre> |
14,148,422 | What is the best way to pass information between threads? | <p>I want to be listening to a server while my program is doing other things, when a message is received from the server I want to interpret it. </p>
<p>I know about threading but not sure completely on how it works. If I have a thread listening for the server how can I pass that data to the main thread for interpretation? What is the best way for the main thread to send data to the server? What is the use of the synchronized modifier?</p> | 14,148,447 | 3 | 1 | null | 2013-01-03 22:39:51.81 UTC | 15 | 2020-02-15 15:51:50.82 UTC | null | null | null | null | 1,946,982 | null | 1 | 31 | java|multithreading|sockets | 51,400 | <blockquote>
<p>If I have a thread listening for the server how can I pass that data to the main thread for interpretation? What is the best way for the main thread to send data to the server? </p>
</blockquote>
<p>I'd use a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" rel="noreferrer"><code>BlockingQueue</code></a> for this. You define a single <code>BlockingQueue</code> such as the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html" rel="noreferrer"><code>LinkedBlockingQueue</code></a>. Your listener class then calls <code>queue.take()</code> which will wait for your server to call <code>queue.put()</code>. It leaves all of the synchronization, waits, notifies, etc. to the Java class instead of your own code.</p>
<blockquote>
<p>What is the use of the synchronized modifier?</p>
</blockquote>
<p>I'd do some reading to understand more about this. This is not the sort of thing that can be answered in a short-ish SO response. The <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/" rel="noreferrer">Java concurrency tutorial</a> is a good place to start.</p> |
13,826,149 | How have both local and remote variable inside an SSH command | <p>How can I have both local and remote variable in an ssh command? For example in the following sample code:</p>
<pre><code>A=3;
ssh host@name "B=3; echo $A; echo $B;"
</code></pre>
<p>I have access to A but B is not accessible.</p>
<p>But in the following example:</p>
<pre><code>A=3;
ssh host@name 'B=3; echo $A; echo $B;'
</code></pre>
<p>I don't have A and just B is accessible.</p>
<p>Is there any way that both A and B be accessible?</p> | 13,826,220 | 1 | 1 | null | 2012-12-11 18:22:03.11 UTC | 19 | 2015-07-07 22:39:32.353 UTC | 2012-12-11 18:24:37.377 UTC | null | 1,741,864 | null | 1,727,184 | null | 1 | 32 | linux|bash | 27,023 | <p>I think this is what you want:</p>
<pre><code>A=3;
ssh host@name "B=3; echo $A; echo \$B;"
</code></pre>
<hr>
<p><strong>When you use double-quotes</strong>:</p>
<p>Your shell does auto expansion on variables prefixed with <code>$</code>, so in your first example, when it sees </p>
<pre><code>ssh host@name "B=3; echo $A; echo $B;"
</code></pre>
<p>bash expands it to:</p>
<pre><code>ssh host@name "B=3; echo 3; echo ;"
</code></pre>
<p>and <strong>then</strong> passes <code>host@name "B=3; echo 3; echo ;"</code> as the argument to <code>ssh</code>. This is because you defined <code>A</code> with <code>A=3</code>, but you never defined <code>B</code>, so <code>$B</code> resolves to the empty string locally.</p>
<hr>
<p><strong>When you use single-quotes</strong>:</p>
<p>Everything enclosed by single-quotes are interpreted as string-literals, so when you do:</p>
<pre><code>ssh host@name 'B=3; echo $A; echo $B;'
</code></pre>
<p>the instructions <code>B=3; echo $A; echo $B;</code> will be run once you log in to the remote server. You've defined <code>B</code> in the remote shell, but you never told it what <code>A</code> is, so <code>$A</code> will resolve to the empty string.</p>
<hr>
<p><strong>So when you use <code>\$</code>, as in the solution:</strong></p>
<p><code>\$</code> means to interpret the <code>$</code> character literally, so we send literally <code>echo $B</code> as one of the instructions to execute remotely, instead of having bash expand <code>$B</code> locally first. What we end up telling <code>ssh</code> to do is equivalent to this:</p>
<pre><code>ssh host@name 'B=3; echo 3; echo $B;'
</code></pre> |
14,278,603 | PHP range() from A to ZZ? | <p>Is it possible to get a range with PHP from A to ZZ*?</p>
<p>a b c ... aa ... zx zy zz</p>
<p>For me this didn't work:</p>
<pre><code>range('A', 'ZZ');
</code></pre>
<p>It's for PHPExcel, when it gives <strong>BE</strong> as highest field i'd run through all colums. In this case i only get A, B:</p>
<pre><code>range ('A', 'BE')
</code></pre> | 14,278,719 | 16 | 1 | null | 2013-01-11 12:52:53.903 UTC | 8 | 2022-05-16 09:26:01.65 UTC | 2013-01-11 13:02:07.487 UTC | null | 414,340 | null | 414,340 | null | 1 | 33 | php|range | 42,595 | <p>Just Try this- (tested working fine)</p>
<pre><code>function createColumnsArray($end_column, $first_letters = '')
{
$columns = array();
$length = strlen($end_column);
$letters = range('A', 'Z');
// Iterate over 26 letters.
foreach ($letters as $letter) {
// Paste the $first_letters before the next.
$column = $first_letters . $letter;
// Add the column to the final array.
$columns[] = $column;
// If it was the end column that was added, return the columns.
if ($column == $end_column)
return $columns;
}
// Add the column children.
foreach ($columns as $column) {
// Don't itterate if the $end_column was already set in a previous itteration.
// Stop iterating if you've reached the maximum character length.
if (!in_array($end_column, $columns) && strlen($column) < $length) {
$new_columns = createColumnsArray($end_column, $column);
// Merge the new columns which were created with the final columns array.
$columns = array_merge($columns, $new_columns);
}
}
return $columns;
}
echo "<pre>";
print_r( createColumnsArray('BZ'));
</code></pre>
<p>copied from <a href="http://php.net/range">http://php.net/range</a></p> |
14,210,474 | Grouped UITableView has 20px of extra padding at the bottom | <p>Grouped table views seem to have extra padding on the bottom in iOS 6 (iOS 5 does not have it), but I can't find any documentation that suggests this is correct / expected behavior.</p>
<p>This affects the example projects as well, for instance the <code>SimpleTableView</code> project in the <code>TableViewSuite</code> example. I think I had to change the style in the <code>AppDelegate</code> to 'grouped', and updated the SDK to iOS 6, but no other changes have been made to the project.</p>
<p>Investigating revealed that there are <code>10px</code> reserved for header and footer views, plus some <code>20px</code> that can't be accounted for.
There are no actual header or footer views (<code>tableHeaderView</code> and <code>tableFooterView</code> are <code>nil</code>, and implementing and returning <code>nil</code> for e.g. <code>viewForFooterInSection</code> does nothing).
I cannot find any '20' value on the tableView itself, though I may have missed something of course.</p>
<p>Adding a zero-size view for the footer does nothing, but adding a <code>1px</code> square view causes the extra padding to vanish. e.g.:</p>
<pre><code>tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0,0,1,1)];
</code></pre>
<p>It does take up <code>1px</code> of height still, so the bottom padding is now <code>11px</code>, but this is far less noticeable than 20. And now setting the <code>sectionFooterHeight</code> to 0 will result in only <code>1px</code> of bottom-space.</p>
<p>My question is: what? And how can I completely remove it? This isn't anything mission-critical, but it is extremely weird, undesirable, and as far as I can tell it's undocumented. </p>
<p>Please note - its copy past question from apple dev forum. But I have exactly the same issue and I don't understand how to solve it too.</p> | 31,445,770 | 12 | 2 | null | 2013-01-08 07:52:40.06 UTC | 16 | 2021-01-29 08:23:56.113 UTC | 2016-08-31 20:22:39.127 UTC | null | 3,701,102 | null | 754,328 | null | 1 | 60 | objective-c|ios|uitableview | 30,082 | <p>@frankWhite' solution works great, but here is a better solution to avoid typing 0.1, 0.001 or others to make it less ambiguous.</p>
<pre><code>// Swift version
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// remove bottom extra 20px space.
return CGFloat.min
}
</code></pre>
<pre><code>// Objective-C version
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
// remove bottom extra 20px space.
return CGFLOAT_MIN;
}
</code></pre> |
14,223,628 | Why does a self-referencing iframe not infinitely loop and crash my machine? | <p>I created a simple HTML page with an <code>iframe</code> whose <code>src</code> attribute references the containing page -- in other words a self-referencing iframe.</p>
<p><strong>this.html</strong></p>
<pre><code><html>
<head></head>
<body>
<iframe src="this.html"></iframe>
</body>
</html>
</code></pre>
<p>Why does this not infinitely loop and crash my browser? Also, why doesn't even IE crash at this?</p>
<p>(Note: This spawned from a team discussion on the virtues and demerits of using iframes to solve problems. You know, the 'mirror of a mirror' sort.)</p> | 14,223,829 | 3 | 4 | null | 2013-01-08 20:41:15.097 UTC | 12 | 2022-01-06 16:31:53.123 UTC | 2018-04-11 04:34:12.65 UTC | null | -1 | null | 941,058 | null | 1 | 70 | html|internet-explorer|google-chrome|firefox|iframe | 16,099 | <p>W3C took care of that in 1997 explaining how frames should be implemented in "<a href="http://www.w3.org/TR/WD-frames-970331">Implementing HTML Frames</a>":</p>
<blockquote>
<p>Any frame that attempts to assign as its SRC a URL used by any of its ancestors is treated as if it has no SRC URL at all (basically a blank frame). </p>
</blockquote>
<hr>
<h2>Iframe recursion bug/attack history</h2>
<p>As kingdago found out and mentioned in the comment above, one browser that missed to implement a safeguard for this was <strong>Mozilla</strong> in <em>1999</em>. Quote from one of the developers:</p>
<blockquote>
<p>This is a parity bug (and a source of possible embarrasment) since MSIE5
doesn't have a problem with these kinds of pages.</p>
</blockquote>
<p>I decided to dig some more into this and it turns out that in <em>2004</em> this happened <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=228829">again</a>. However, this time <strong>JavaScript</strong> was involved:</p>
<blockquote>
<p>This is the code, what causes it: <iframe name="productcatalog"
id="productcatalog" src="page2.htm"></iframe> directly followed by
a script with this in it:
frames.productcatalog.location.replace(frames.productcatalog.location
+ location.hash);</p>
<p>...</p>
<p>Actual Results: The parent window gets recursively loaded into the
iframe, resulting sometimes in a crash.</p>
<p>Expected Results: Just show it like in Internet Explorer.</p>
</blockquote>
<p>Then <a href="http://www.securityfocus.com/bid/27812/info">again</a> in <em>2008</em> with <strong>Firefox 2</strong> (this also involved JavaScript).</p>
<p>And <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=530258">again</a> in <em>2009</em>. The interesting part here is that this bug is <strong>still open</strong> and this attachment: <code>https://bugzilla.mozilla.org/attachment.cgi?id=414035</code> (will you restrain your curiosity?) will still crash/freeze your Firefox (I just tested it and I almost crashed the whole Ubuntu). In Chrome it just loads indefinitely (probably because each tab lives in a separate process). </p>
<hr>
<p>As for the other browsers:</p>
<ul>
<li>In <em>2005</em> <a href="https://bugs.kde.org/show_bug.cgi?id=116406">Konqueror</a> had a bug in it's safeguard that allowed to render iframes <a href="http://bugsfiles.kde.org/attachment.cgi?id=18978">one inside another</a> (but it seems that somehow it wasn't freezing/crashing the whole app).</li>
<li>IE6, Opera 7.54 and Firefox 0.9.3 are also <a href="http://xforce.iss.net/xforce/xfdb/17089">reported</a> to be susceptible to attacks basing on iframe recursion.</li>
</ul> |
14,008,470 | Android invalidateOptionsMenu() for API < 11 | <p>I used <code>ActivityCompat.invalidateOptionsMenu(MainActivity.this);</code> so that my menu item "refresh" can automatically be enabled/disabled without the using have to touch the "Menu" option (imagine the user leaves the Menu open... I need the "Refresh" menu item to automatically disabled and enable itself). </p>
<p>The <code>ActivityCompat.invalidateOptionsMenu(MainActivity.this)</code> works fine in Android 11+. But what can I use for android API < 11 ? :S I've searched so much but I cannot find an answer. Can anyone please help me on this? </p>
<p>This works fine in Android API 11+, using the <code>onPrepareOptionsMenu</code> and <code>ActivityCompat.invalidateOptionsMenu(MainActivity.this)</code>.
The issue is trying to get it done in Android API < 11.</p>
<p>Here is my <code>onPrepareOptionsMenu</code> method: </p>
<pre><code>@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(menuRefreshEnable){
menu.getItem(0).setEnabled(true);
}
if(!menuRefreshEnable){
menu.getItem(0).setEnabled(false);
}
return true;
}
</code></pre> | 18,547,122 | 3 | 2 | null | 2012-12-23 03:51:33.863 UTC | 24 | 2014-08-22 23:58:08.437 UTC | 2013-02-05 16:58:57.94 UTC | null | 523,100 | null | 1,917,221 | null | 1 | 76 | android|menu | 20,504 | <p>On <code>API < 11</code> use <code>supportInvalidateOptionsMenu()</code> method</p> |
28,991,391 | Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat | <p>When trying to start Tomcat Server through cmd prompt using 'startup.bat' getting error as-"JRE_HOME variable is not defined correctly. The environment variable is needed to Run this program"
Defined Environment path as-</p>
<p>CATALINA_HOME-C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59<br>
JAVA_HOME-C:\Program Files\Java\jdk1.8.0_25;<br>
JRE_Home-C:\Program Files\Java\jre1.8.0_25\bin; </p> | 28,992,413 | 2 | 2 | null | 2015-03-11 15:54:27.337 UTC | 18 | 2019-01-08 17:27:51.783 UTC | 2015-03-11 16:25:30.523 UTC | null | 2,083,599 | null | 4,637,378 | null | 1 | 50 | java|apache|tomcat|batch-file | 161,700 | <p>Got the solution and it's working fine.
Set the environment variables as:</p>
<ul>
<li><code>CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59</code> <em>(path where your Apache Tomcat is)</em></li>
<li><code>JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25;</code> <em>(path where your JDK is)</em></li>
<li><code>JRE_Home=C:\Program Files\Java\jre1.8.0_25;</code> <em>(path where your JRE is)</em></li>
<li><code>CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib</code></li>
</ul> |
29,284,266 | MySQL - Base64 vs BLOB | <p>For the sake of simplicity, suppose I'm developing a mobile app like Instagram. Users can download images from the server, and upload images of their own. Currently the server stores all images (in reality, just small thumbnails) in a MySQL database as BLOBs. It seems that the most common way to transfer images is by using Base64 encoding, which leaves me with two options:</p>
<ol>
<li>Server stores all images as BLOBs. To upload an image, client encodes it into Base64 string, then sends it to the server. Server decodes image BACK into binary format and stores it as BLOB in the database. When client requests an image, server re-encodes the image as Base64 string and sends it to the client, who then decodes it back to binary for display.</li>
<li>Server stores all images as Base64 strings. To upload an image, client encodes it into Base64 string and sends it to the server. Server does no encoding or decoding, but simply stores the string in the database. When client requests an image, the Base64 string is returned to the client, who then decodes it for display.</li>
</ol>
<p>Clearly, option #1 requires significantly more processing on the server, as images must be encoded/decoded with every single request. This makes me lean toward option #2, but some research has suggested that storing Base64 string in MySQL is much less efficient than storing the image directly as BLOB, and is generally discouraged.</p>
<p>I'm certainly not the first person to encounter this situation, so does anybody have suggestions on the best way to make this work?</p> | 29,289,772 | 3 | 3 | null | 2015-03-26 16:47:43.827 UTC | 13 | 2018-09-04 09:23:22.107 UTC | 2016-03-03 09:45:48.597 UTC | null | 3,539,857 | null | 4,259,255 | null | 1 | 27 | mysql|json|encoding|base64|blob | 23,640 | <p>JSON assumes utf8, hence is incompatible with images unless they are encoded in some way.</p>
<p>Base64 is almost exactly 8/6 times as bulky as binary (BLOB). One could argue that it is easily affordable. 3000 <code>bytes</code> becomes about 4000 <code>bytes</code>.</p>
<p>Everyone <em>should</em> be able to accept arbitrary 8-bit codes, but not everybody does. Base-64 may be the simplest and overall best compromise for not having to deal with 8-bit data.</p>
<p>Since these are "small", I would store them in a table, not a file. I would, however, store them in a separate table and <code>JOIN</code> by an appropriate <code>id</code> when you need them. This allows queries that don't need the image to run faster because they are not stepping over the BLOBs.</p>
<p>Technically, <code>TEXT CHARACTER SET ascii COLLATE ascii_bin</code> would do, but <code>BLOB</code> makes it clearer that there is not really any usable text in the column.</p> |
29,978,695 | Remove all items from RecyclerView | <p>I am trying to remove all the elements from my <code>RecyclerView</code> in my <code>onRestart</code> method so the items don't get loaded twice:</p>
<pre><code>@Override
protected void onRestart() {
super.onRestart();
// first clear the recycler view so items are not populated twice
for (int i = 0; i < recyclerAdapter.getSize(); i++) {
recyclerAdapter.delete(i);
}
// then reload the data
PostCall doPostCall = new PostCall(); // my AsyncTask...
doPostCall.execute();
}
</code></pre>
<p>But for some reason the <code>delete</code> method I created in the <code>adapter</code> is not functioning properly:</p>
<p>in RecyclerAdapter.java: </p>
<pre><code>public void delete(int position){
myList.remove(position);
notifyItemRemoved(position);
}
public int getSize(){
return myList.size();
}
</code></pre>
<p>I think every other item in my list gets deleted instead of the entire list.</p>
<p>With a <code>listview</code> it was so easy and I simply called <code>adapter.clear()</code>.</p>
<p>Can someone please help me fix up the code?</p>
<p>I think I should be using <code>notifyItemRangeRemoved(...,...);</code> but I am not sure how. TIA</p> | 29,979,007 | 14 | 6 | null | 2015-04-30 22:10:54.397 UTC | 17 | 2021-05-20 10:34:08.95 UTC | 2018-12-18 05:30:08.95 UTC | null | 950,427 | null | 2,456,977 | null | 1 | 64 | android|adapter|android-recyclerview | 133,964 | <h2>This works great for me:</h2>
<pre><code>public void clear() {
int size = data.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
data.remove(0);
}
notifyItemRangeRemoved(0, size);
}
}
</code></pre>
<p><strong>Source:</strong> <a href="https://github.com/mikepenz/LollipopShowcase/blob/master/app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java" rel="noreferrer">https://github.com/mikepenz/LollipopShowcase/blob/master/app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java</a></p>
<h2>or:</h2>
<pre><code>public void clear() {
int size = data.size();
data.clear();
notifyItemRangeRemoved(0, size);
}
</code></pre>
<h2>For you:</h2>
<pre><code>@Override
protected void onRestart() {
super.onRestart();
// first clear the recycler view so items are not populated twice
recyclerAdapter.clear();
// then reload the data
PostCall doPostCall = new PostCall(); // my AsyncTask...
doPostCall.execute();
}
</code></pre> |
9,215,162 | HTML force URL hyperlink to be treated as non-relative (absolute) | <p>I have a list of URLs that our users have entered for websites of various clients... I am loading this list from the server into a grid for the users to see... I made the URLs clickable by wrapping them with a href HTML tag... the problem is, <strong>sometimes</strong> the user enters urls without the http:// or www. prefix and so the browser treats them as relative URLs which are never ever the case because all these websites are for our clients and they are all external. Is there a way to force these URLs to be treated as absolute instead of relative?</p>
<p>Here is an example:</p>
<pre><code><a target='_blank' href='google.com'>google.com</a>
</code></pre>
<p>If you try this, you'll see that the browser will assume it is a relative path which shouldn't be the case.</p>
<p>Thanks</p>
<hr>
<p>Solution:</p>
<p>I've chosen to check for '//' (because I don't know what the protocol is - could be http or https) and if not found, I assume it is an http website and I prefix the URL with that - so in short no way to force the browser to treat the hyperlinks as absolute</p> | 9,215,194 | 3 | 1 | null | 2012-02-09 16:54:26.417 UTC | 2 | 2021-06-08 03:43:59.283 UTC | 2012-02-09 17:33:22.687 UTC | null | 618,532 | null | 618,532 | null | 1 | 28 | html|url|href|relative-path|absolute-path | 15,876 | <p>Why don't you preprocess the input and append <code>http://</code> when necessary? </p> |
32,774,491 | Is providing a Promise as a module's export a valid pattern for asynch initialization in Node.js? | <p>I need to write some modules that load data one time and then provide an interface to that data. I'd like to load the data asynchronously. My application already uses promises. Is providing a promise as the result of requiring a module a valid pattern/idiom?</p>
<p>Example Module:</p>
<pre><code>var DB = require('promise-based-db-module');
module.exports =
DB.fetch('foo')
.then(function(foo){
return {
getId: function(){return foo.id;},
getName: function(){return foo.name;}
};
});
</code></pre>
<p>Example Usage:</p>
<pre><code>require('./myPromiseModule')
.then(function(dataInterface){
// Use the data
});
</code></pre>
<p>UPDATE:</p>
<p>I've used this for a while now and it works great. One thing I've learned, and it's hinted at in the accepted answer, is that it is good to cache the promise itself, and whenever you want to access the data use <code>then</code>. The first time the data is accessed, the code will wait until the promise is resolved. Subsequent usage of <code>then</code> will return the data immediately. e.g.</p>
<pre><code>var cachedPromise = require('./myPromiseModule');
cachedPromise.then(function(dataInterface){
// Use the data
});
...
cachedPromise.then(function(dataInterface){
// Use the data again somewhere else.
});
</code></pre> | 32,775,386 | 1 | 3 | null | 2015-09-25 03:50:29.36 UTC | 7 | 2018-04-04 20:59:26.85 UTC | 2018-04-04 20:59:26.85 UTC | null | 328,237 | null | 328,237 | null | 1 | 32 | javascript|node.js|promise|node-modules | 11,858 | <p>This seems like a perfectly good interface for a module who's job is to do a one-time fetch of some data. </p>
<p>The data is obtained async so a promise makes sense for that. The goal is to fetch the data just once and then let all places this module gets used just have access to that original data. A promise works great for that too because it's a one-shot device that remembers its state.</p>
<p>Personally, I'm not sure why you need the <code>getId()</code> and <code>getName()</code> methods when you could just offer direct access to the properties, but either can work.</p>
<p>A downside to this interface is that there is no means of requesting a fresh copy of the data (newly loaded from the DB).</p> |
32,699,721 | JavaScript: Extract video frames reliably | <p>I'm working on a client-side project which lets a user supply a video file and apply basic manipulations to it. I'm trying to extract the frames from the video reliably. At the moment I have a <code><video></code> which I'm loading selected video into, and then pulling out each frame as follows:</p>
<ol>
<li>Seek to the beginning</li>
<li>Pause the video</li>
<li>Draw <code><video></code> to a <code><canvas></code></li>
<li>Capture the frame from the canvas with <code>.toDataUrl()</code></li>
<li>Seek forward by 1 / 30 seconds (1 frame).</li>
<li>Rinse and repeat</li>
</ol>
<p>This is a rather inefficient process, and more specifically, is proving unreliable as I'm often getting stuck frames. This seems to be from it not updating the actual <code><video></code> element before it draws to the canvas.</p>
<p>I'd rather not have to upload the original video to the server just to split the frames, and then download them back to the client.</p>
<p>Any suggestions for a better way to do this are greatly appreciated. The only caveat is that I need it to work with any format the browser supports (decoding in JS isn't a great option).</p> | 32,708,998 | 2 | 3 | null | 2015-09-21 16:02:04.093 UTC | 40 | 2022-03-26 02:25:58.043 UTC | 2015-09-22 05:26:08.737 UTC | null | 1,677,573 | null | 1,677,573 | null | 1 | 56 | javascript|html|video|canvas | 67,997 | <p><strong>[2021 update]</strong>: Since this question (and answer) has first been posted, things have evolved in this area, and it is finally time to make an update; <a href="https://stackoverflow.com/revisions/32708998/5">the method that was exposed here</a> went out-of-date, but luckily a few new or incoming APIs can help us better in extracting video frames:</p>
<h3>The most promising and powerful one, but still under development, with a lot of restrictions: <a href="https://w3c.github.io/webcodecs/" rel="noreferrer">WebCodecs</a></h3>
<p>This new API unleashes access to the media decoders and encoders, enabling us to access raw data from video frames (YUV planes), which may be a lot more useful for many applications than rendered frames; and for the ones who need rendered frames, the <a href="https://w3c.github.io/webcodecs/#videoframe-interface" rel="noreferrer">VideoFrame</a> interface that this API exposes can be drawn directly to a <canvas> element or converted to an ImageBitmap, avoiding the slow route of the MediaElement.<br />
However there is a catch, apart from its current low support, this API needs that the input has been demuxed already.<br />
There are some demuxers online, for instance for MP4 videos <a href="https://github.com/gpac/mp4box.js/" rel="noreferrer">GPAC's mp4box.js</a> will help a lot.</p>
<p>A full example can be found <a href="https://github.com/w3c/webcodecs/tree/main/samples/mp4-decode" rel="noreferrer">on the proposal's repo</a>.</p>
<p>The key part consists of</p>
<pre><code>const decoder = new VideoDecoder({
output: onFrame, // the callback to handle all the VideoFrame objects
error: e => console.error(e),
});
decoder.configure(config); // depends on the input file, your demuxer should provide it
demuxer.start((chunk) => { // depends on the demuxer, but you need it to return chunks of video data
decoder.decode(chunk); // will trigger our onFrame callback
})
</code></pre>
<p>Note that we can even grab the frames of a MediaStream, thanks to <a href="https://github.com/w3c/mediacapture-transform" rel="noreferrer">MediaCapture Transform</a>'s <a href="https://w3c.github.io/mediacapture-transform/#track-processor" rel="noreferrer">MediaStreamTrackProcessor</a>.
This means that we should be able to combine <a href="https://wicg.github.io/video-rvfc/" rel="noreferrer">HTMLMediaElement.captureStream()</a> and this API in order to get our VideoFrames, without the need for a demuxer. However this is true only for a few codecs, and it means that we will extract frames at reading speed...<br />
Anyway, here is an example working on latest Chromium based browsers, with <code>chrome://flags/#enable-experimental-web-platform-features</code> switched on:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (window.MediaStreamTrackProcessor) {
let stopped = false;
const track = await getVideoTrack();
const processor = new MediaStreamTrackProcessor(track);
const reader = processor.readable.getReader();
readChunk();
function readChunk() {
reader.read().then(async({ done, value }) => {
if (value) {
const bitmap = await createImageBitmap(value);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
value.close();
}
if (!done && !stopped) {
readChunk();
} else {
select.disabled = false;
}
});
}
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoTrack() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
const [track] = video.captureStream().getVideoTracks();
video.onended = (evt) => track.stop();
return track;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>video,canvas {
max-width: 100%
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>start</button>
<select disabled>
</select>
<canvas></canvas></code></pre>
</div>
</div>
</p>
<h3>The easiest to use, but still with relatively poor browser support, and subject to the browser dropping frames: <a href="https://wicg.github.io/video-rvfc/" rel="noreferrer">HTMLVideoElement.requestVideoFrameCallback</a></h3>
<p>This method allows us to schedule a callback to whenever a new frame will be painted on the HTMLVideoElement.<br />
It is higher level than WebCodecs, and thus may have more latency, and moreover, with it we can only extract frames at reading speed.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (HTMLVideoElement.prototype.requestVideoFrameCallback) {
let stopped = false;
const video = await getVideoElement();
const drawingLoop = async(timestamp, frame) => {
const bitmap = await createImageBitmap(video);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
if (!video.ended && !stopped) {
video.requestVideoFrameCallback(drawingLoop);
} else {
select.disabled = false;
}
};
// the last call to rVFC may happen before .ended is set but never resolve
video.onended = (evt) => select.disabled = false;
video.requestVideoFrameCallback(drawingLoop);
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoElement() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
return video;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>video,canvas {
max-width: 100%
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>start</button>
<select disabled>
</select>
<canvas></canvas></code></pre>
</div>
</div>
</p>
<h3>For your Firefox users, Mozilla's non-standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seekToNextFrame" rel="noreferrer">HTMLMediaElement.seekToNextFrame()</a></h3>
<p>As its name implies, this will make your <video> element seek to the next frame.<br />
Combining this with the <em>seeked</em> event, we can build a loop that will grab every frame of our source, faster than reading speed (yeah!).<br />
But this method is proprietary, available only in Gecko based browsers, not on any standard tracks, and probably gonna be removed in the future when they'll implement the methods exposed above.<br />
But for the time being, it is the best option for Firefox users:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (HTMLMediaElement.prototype.seekToNextFrame) {
let stopped = false;
const video = await getVideoElement();
const requestNextFrame = (callback) => {
video.addEventListener("seeked", () => callback(video.currentTime), {
once: true
});
video.seekToNextFrame();
};
const drawingLoop = async(timestamp, frame) => {
if(video.ended) {
select.disabled = false;
return; // FF apparently doesn't like to create ImageBitmaps
// from ended videos...
}
const bitmap = await createImageBitmap(video);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
if (!video.ended && !stopped) {
requestNextFrame(drawingLoop);
} else {
select.disabled = false;
}
};
requestNextFrame(drawingLoop);
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoElement() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
return video;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>video,canvas {
max-width: 100%
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>start</button>
<select disabled>
</select>
<canvas></canvas></code></pre>
</div>
</div>
</p>
<h3>The least reliable, that did stop working over time: <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event" rel="noreferrer">HTMLVideoElement.ontimeupdate</a></h3>
<p>The strategy <em>pause - draw - play - wait for timeupdate</em> used to be (in 2015) a quite reliable way to know when a new frame got painted to the element, but since then, browsers have put serious limitations on this event which was firing at great rate and now there isn't much information we can grab from it...</p>
<p>I am not sure I can still advocate for its use, I didn't check how Safari (which is currently the only one without a solution) handles this event (their handling of medias is very weird for me), and there is a good chance that a simple <code>setTimeout(fn, 1000 / 30)</code> loop is actually more reliable in most of the cases.</p> |
19,704,996 | How to replace a value of a json file in java | <p>Hello members of stackoverflow,</p>
<p>I need some help with replacing a line in a json file. I have attempted using the same method i use to replace a line in a text file with no success.</p>
<p>Basically the json file contains the following string:</p>
<pre><code> "id": "TEXT",
</code></pre>
<p>And i want to replace the "TEXT" with "HELLO"</p>
<p>How would i do this, also i have the 'json_simple' library imported if that is of any use for this.</p>
<p>Any help with this would be greatly appreciated.</p>
<p>Thanks.</p> | 19,705,386 | 3 | 2 | null | 2013-10-31 11:15:26.65 UTC | 1 | 2016-01-23 21:20:02.9 UTC | null | null | null | null | 2,826,304 | null | 1 | 5 | java | 44,156 | <p>Without using a JSON parser as someone suggested, you can do it simply with a regex :</p>
<pre><code>str = str.replaceAll("(\\s*?\"id\"\\s*?:\\s*?)\"TEXT\",", "$1\"HELLO\"");
</code></pre>
<p>If the "TEXT" string is an unique placeholder for your replacement, you could simply use String <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29" rel="nofollow">replace</a> method, in this way : </p>
<pre><code>str.replace("\"TEXT\"", "\"HELLO\"");
</code></pre> |
19,484,948 | iOS Launch Screen Asset Catalog not working | <p>I believe I am making a silly mistake. But I cannot figure it out. </p>
<p>I have an image named Default.png that I have added to my project. Now when I go to General and then Launch Images I drag and drop this Default.png to the 2x window for my app. When I go to build the project and try it, I get this error:</p>
<p>"The launch image set named "LaunchImage" did not have any applicable content."</p>
<p>What's the problem here? I've also seen that simply dragging and dropping the Default.png should do it, but I think that's for older versions. </p>
<p>Any ideas? </p>
<p>Thanks</p> | 19,485,019 | 8 | 3 | null | 2013-10-21 01:29:27.09 UTC | 3 | 2016-07-13 20:28:22.573 UTC | null | null | null | null | 1,357,707 | null | 1 | 25 | iphone|ios|xcode | 50,243 | <p>Search for LaunchImage keyword in your .plist file and delete it. Then, try assigning the image again by dragging as you already did before...</p> |
19,627,284 | What is the difference between json and XML? | <p>What is the difference between json and XML?Which is better in performance aspect while working with android?Why json is described as lightweight?</p> | 19,627,363 | 3 | 3 | null | 2013-10-28 04:40:29.233 UTC | 3 | 2013-10-28 04:52:09.417 UTC | null | null | null | null | 2,901,768 | null | 1 | 8 | xml|json | 43,129 | <p>I suggest you to read the following link below first</p>
<p><a href="https://stackoverflow.com/questions/4862310/json-and-xml-comparison">JSON and XML comparison</a></p>
<p>The first comment clearly explains your first two questions.</p>
<p>and for the last question my suggestion would be <strong>JSON</strong>, The reason is that JSON is light weight and also its very easy to handle and parse when comparing to XML formats. also I believe that <strong>JSON started overtaking the technology over XML in many aspects</strong>. There are tons and tons of examples and discussions available in web to support the JSON format over XML.</p>
<p>And for Android, since it is a technology which is going to rule the world for next few decades you must decide whether you need to choose the <strong>older technology(XML)</strong> which is getting down or <strong>the newer technology (JSON)</strong> which is growing up. The choice is yours.</p> |
3,274,082 | Make 1 column from two column environment with LaTeX | <p>I make a document with <code>twocolumn</code>, but sometimes <code>twocolumn</code> is too narrow for source code listing.</p>
<p>I found the <code>multicols</code> environment and used it as follows:</p>
<pre>
% \documentclass[twocolumn]{article} % I don't use towcolumn, but multicolumn
\documentclass[]{article}
\usepackage{multicol}
...
\begin{multicols*}{2}
\section{In short}
...
\end{multicols*}
% Now I use one column
\begin{multicols*}{1}
...
\end{multicols*}
</pre>
<p>The result is not what I wanted.
<a href="http://img3.imageshack.us/img3/6239/screenshot20100717at920.png" rel="nofollow noreferrer">http://img3.imageshack.us/img3/6239/screenshot20100717at920.png</a></p>
<p>What's wrong with my LaTeX code? What do you do for this case? </p>
<p>I tried to use a <code>figure*</code> environment, but it just floats around, so I'd rather not use it.</p> | 3,274,173 | 2 | 0 | null | 2010-07-18 02:22:02.317 UTC | null | 2012-10-28 22:15:11.87 UTC | 2010-07-18 07:59:02.377 UTC | null | 31,615 | null | 260,127 | null | 1 | 4 | latex | 54,244 | <p>Does this give you what you want?</p>
<pre><code>\documentclass[]{article}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
\section{In short}
double column text here. .double column text here. . .
double column text here. . .
double column text here. . .
double column text here. . .
.
\end{multicols}
% Now I use one column
% don't put any multicol command here, you're in outer
% single column document already
put single column text here. put single column text here.
put single column text here. put single column text here.
put single column text here. put single column text here.
. . .
\begin{multicols}{2}
\section{In short}
double column text here. . .
double column text here. . .
double column text here. . .
double column text here. . .
double column text here. . .
\end{multicols}
\end{document}
</code></pre> |
52,059,339 | Difference between apk (.apk) and app bundle (.aab) | <p>Recently Google brought up a new feature <code>app bundle</code> which is a pretty similar concept to APK except its flexibility and architectural differences. </p>
<p>I have read out lots of blog/articles to understand how app bundle works in devices in comparison with APK file.</p>
<p>What is the actual internal working process of app bundle and how it works on Android devices starting from Google Play Store?</p> | 53,396,721 | 3 | 5 | null | 2018-08-28 13:40:03.667 UTC | 37 | 2022-05-09 16:23:01.053 UTC | 2019-01-09 03:34:13.303 UTC | null | 6,398,434 | null | 3,806,413 | null | 1 | 197 | android|apk|android-app-bundle | 169,917 | <p>App Bundles are a publishing format, whereas APK (Android application PacKage) is the packaging format which eventually will be installed on device.</p>
<p>App Bundles use <a href="https://github.com/google/bundletool" rel="noreferrer">bundletool</a> to create a set of APK. (.apks)
This can be extracted and the base and configuration splits as well as potential dynamic feature modules can be deployed to a device.</p>
<p>The dependencies can look something like this:
<img src="https://developer.android.com/images/app-bundle/apk_splits_tree-2x.png" alt="Bundletool modules"></p>
<p>The contents of an App Bundle look kind of like this:
<img src="https://developer.android.com/images/app-bundle/aab_format-2x.png" alt="Bundletool contents"></p>
<p>More information on App Bundles is <a href="https://developer.android.com/guide/app-bundle" rel="noreferrer">available here</a>.</p> |
703,669 | Easiest way to concatenate NSString and int | <p>Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating <code>NSString</code>s and <code>int</code>s?</p> | 704,513 | 5 | 0 | null | 2009-04-01 01:11:07.96 UTC | 6 | 2016-02-28 19:09:31.063 UTC | 2016-02-28 19:09:31.063 UTC | null | 603,977 | null | 60,006 | null | 1 | 27 | objective-c|string|cocoa|cocoa-touch|nsstring | 63,737 | <p>Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.</p>
<pre><code>NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:@"... now has another int: %d", myInt];
</code></pre> |
706,906 | Jquery: Filter dropdown list as you type | <p>I have used a prototype plugin which filters the contents of a dropdown as you type. So for example if you typed 'cat' into the text box, only items containing the substring 'cat' would be left as options in the drop down.</p>
<p>Does anyone know of a jquery plugin which can do this?</p> | 706,988 | 5 | 0 | null | 2009-04-01 18:55:29.497 UTC | 24 | 2018-01-13 09:43:48.717 UTC | 2011-12-28 22:16:54.37 UTC | null | 938,089 | null | 1,349,865 | null | 1 | 37 | javascript|jquery|jquery-plugins | 103,417 | <p>I wrote <a href="http://andrew.hedges.name/experiments/narrowing/" rel="noreferrer">a little script to do this</a> a few years ago. It could be packaged up as a jQuery plug-in quite easily, probably. You're welcome to it.</p>
<p>I also do this in my <a href="http://andrew.hedges.name/widgets/#phpfr" rel="noreferrer">PHP Function Reference</a> Dashboard widget if you want to look at the code there.</p> |
258,486 | Calculate the display width of a string in Java | <p>How to calculate the length (in pixels) of a string in Java?</p>
<p>Preferable without using Swing.</p>
<p>EDIT:
I would like to draw the string using the drawString() in Java2D
and use the length for word wrapping.</p> | 258,499 | 5 | 4 | null | 2008-11-03 12:30:04.75 UTC | 24 | 2020-07-18 21:19:01.95 UTC | 2008-11-03 12:40:04.387 UTC | eflles | 26,567 | eflles | 26,567 | null | 1 | 109 | java|string-length | 157,290 | <p>If you just want to use AWT, then use <a href="http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#getFontMetrics()" rel="noreferrer"><code>Graphics.getFontMetrics</code></a> (optionally specifying the font, for a non-default one) to get a <code>FontMetrics</code> and then <a href="http://docs.oracle.com/javase/6/docs/api/java/awt/FontMetrics.html#stringWidth(java.lang.String)" rel="noreferrer"><code>FontMetrics.stringWidth</code></a> to find the width for the specified string.</p>
<p>For example, if you have a <code>Graphics</code> variable called <code>g</code>, you'd use:</p>
<pre><code>int width = g.getFontMetrics().stringWidth(text);
</code></pre>
<p>For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.</p> |
1,283,085 | Padding doesn't affect <shape> in an XML Layout | <p>I am trying to set padding in a <code><shape></code> declared within an XML file/layout. But whatever I set, nothing changes related to padding. If I modify any other properties, I see the effects on the UI. But it doesn't work with padding. Could you please advise on the possible reasons for which this might occur?</p>
<p>Here is the XML Shape I am trying to style:</p>
<pre><code> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1dp"
android:color="#ffffff"
android:dashWidth="2dp"/>
<solid android:color="@color/button_white_cover"/>
<corners android:radius="11dp"/>
<padding android:left="1dp"
android:top="20dp"
android:right="20dp"
android:bottom="2dp"/>
</shape>
</code></pre> | 1,285,476 | 5 | 0 | null | 2009-08-15 23:07:09.953 UTC | 19 | 2021-04-28 10:23:32.72 UTC | 2018-11-06 11:13:39.42 UTC | null | 4,807,532 | null | 139,394 | null | 1 | 113 | android|user-interface | 93,747 | <p>I have finally resolved my problem with padding.</p>
<p>So padding here will have no effect on the shape. Instead of this, you will have to apply padding in other drawable that will use it. So, I have a drawable that uses the shape and there I do following:</p>
<pre><code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_below"/>
<item android:top="10px" android:right="10px" android:drawable="@drawable/shape_cover"/>
</layer-list>
</code></pre>
<p>So, as you can see in the second <code><item></code>-element I set padding (top and right). And after this everything works.</p>
<p>Thanks.</p> |
25,449 | How to create a pluginable Java program? | <p>I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?</p>
<p>I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.</p>
<hr>
<p>Although I do like Eclipse RCP, I think it's too much for my simple needs.</p>
<p>Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.</p>
<p>But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.</p> | 25,492 | 6 | 1 | null | 2008-08-24 23:28:38.987 UTC | 25 | 2021-01-12 13:18:19.77 UTC | 2011-11-19 01:16:59.083 UTC | null | 419 | pek | 2,644 | null | 1 | 40 | java|plugins|plugin-architecture | 32,773 | <p>I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html" rel="noreferrer">ClassLoader</a> to load those classes and create instances of them.</p>
<p>One way you can go about it is this:
</p>
<pre><code>File dir = new File("put path to classes you want to load here");
URL loadPath = dir.toURI().toURL();
URL[] classUrl = new URL[]{loadPath};
ClassLoader cl = new URLClassLoader(classUrl);
Class loadedClass = cl.loadClass("classname"); // must be in package.class name format
</code></pre>
<p>That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:
</p>
<pre><code>MyModule modInstance = (MyModule)loadedClass.newInstance();
</code></pre> |
334,519 | LDAP through Ruby or Rails | <p>I've been attempting to hook a Rails application up to ActiveDirectory. I'll be synchronizing data about users between AD and a database, currently MySQL (but may turn into SQL Server or PostgreSQL).</p>
<p>I've checked out activedirectory-ruby, and it looks really buggy (for a 1.0 release!?). It wraps Net::LDAP, so I tried using that instead, but it's really close to the actual syntax of LDAP, and I enjoyed the abstraction of ActiveDirectory-Ruby because of its ActiveRecord-like syntax.</p>
<p>Is there an elegant ORM-type tool for a directory server? Better yet, if there were some kind of scaffolding tool for LDAP (CRUD for users, groups, organizational units, and so on). Then I could quickly integrate that with my existing authentication code though Authlogic, and keep all of the data synchronized.</p> | 5,684,335 | 6 | 0 | null | 2008-12-02 16:17:00.313 UTC | 29 | 2012-09-18 17:19:22.997 UTC | 2009-03-09 23:18:34.123 UTC | Rich B | 5,640 | null | 42,486 | null | 1 | 45 | ruby-on-rails|ruby|active-directory|ldap | 36,094 | <p>Here is sample code I use with the <a href="http://net-ldap.rubyforge.org/">net-ldap</a> gem to verify user logins from the ActiveDirectory server at my work:</p>
<pre><code>require 'net/ldap' # gem install net-ldap
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "@mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end
</code></pre>
<p>The <code>first.displayName.first</code> code at the end looks a little goofy, and so might benefit from some explanation:</p>
<ul>
<li><p><a href="http://net-ldap.rubyforge.org/Net/LDAP.html#method-i-search"><code>Net::LDAP#search</code></a> always returns an array of results, even if you end up matching only one entry. The first call to <code>first</code> finds the first (and presumably only) entry that matched the email address.</p></li>
<li><p>The <a href="http://net-ldap.rubyforge.org/Net/LDAP/Entry.html"><code>Net::LDAP::Entry</code></a> returned by the search conveniently lets you access attributes via method name, so <code>some_entry.displayName</code> is the same as <code>some_entry['displayName']</code>.</p></li>
<li><p>Every attribute in a <code>Net::LDAP::Entry</code> is always an array of values, even when only one value is present. Although it might be silly to have a user with multiple "displayName" values, LDAP's generic nature means that it's possible. The final <code>first</code> invocation turns the array-of-one-string into just the string for the user's full name.</p></li>
</ul> |
159,006 | Max and min values in a C++ enum | <p>Is there a way to find the maximum and minimum defined values of an enum in c++?</p> | 159,018 | 6 | 2 | null | 2008-10-01 18:27:26.5 UTC | 7 | 2021-05-21 22:45:27.54 UTC | null | null | null | Matt | 17,693 | null | 1 | 87 | c++|enums | 59,161 | <p>No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,</p>
<pre><code>enum MyPretendEnum
{
Apples,
Oranges,
Pears,
Bananas,
First = Apples,
Last = Bananas
};
</code></pre>
<p>There do not need to be named values for every value between <code>First</code> and <code>Last</code>.</p> |
30,866,753 | Merging two List of objects in java 8 | <p>I have a Java class <code>Parent</code> with 20 attributes <code>(attrib1, attrib2 .. attrib20)</code> and its corresponding getters and setters. Also I have two lists of <code>Parent</code> objects: <code>list1</code> and <code>list2</code>.</p>
<p>Now I want to merge both lists and avoid duplicate objects based on <code>attrib1</code> and <code>attrib2</code>.</p>
<p>Using Java 8:</p>
<pre><code>List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
</code></pre>
<p>But in which place I have to specify the attributes? Should I override <code>hashCode</code> and <code>equals</code> method?</p> | 30,867,713 | 4 | 3 | null | 2015-06-16 11:51:31.217 UTC | 8 | 2015-06-26 08:58:31.37 UTC | 2015-06-26 07:48:25.453 UTC | null | 4,856,258 | null | 4,788,787 | null | 1 | 34 | java|java-8|java-stream | 56,035 | <p>If you want to implement <code>equals</code> and <code>hashCode</code>, the place to do it is <em>inside</em> the class <code>Parent</code>. Within that class add the methods like</p>
<pre><code> @Override
public int hashCode() {
return Objects.hash(getAttrib1(), getAttrib2(), getAttrib3(),
// …
getAttrib19(), getAttrib20());
}
@Override
public boolean equals(Object obj) {
if(this==obj) return true;
if(!(obj instanceof Parent)) return false;
Parent p=(Parent) obj;
return Objects.equals(getAttrib1(), p.getAttrib1())
&& Objects.equals(getAttrib2(), p.getAttrib2())
&& Objects.equals(getAttrib3(), p.getAttrib3())
// …
&& Objects.equals(getAttrib19(), p.getAttrib19())
&& Objects.equals(getAttrib20(), p.getAttrib20());
}
</code></pre>
<p>If you did this, <code>distinct()</code> invoked on a <code>Stream<Parent></code> will automatically do the right thing.</p>
<hr>
<p>If you don’t want (or can’t) change the class <code>Parent</code>, there is no delegation mechanism for equality, but you may resort to <em>ordering</em> as that has a delegation mechanism:</p>
<pre><code>Comparator<Parent> c=Comparator.comparing(Parent::getAttrib1)
.thenComparing(Parent::getAttrib2)
.thenComparing(Parent::getAttrib3)
// …
.thenComparing(Parent::getAttrib19)
.thenComparing(Parent::getAttrib20);
</code></pre>
<p>This defines an order based on the properties. It requires that the types of the attributes itself are comparable. If you have such a definition, you can use it to implement the equivalent of a <code>distinct()</code>, based on that <code>Comparator</code>:</p>
<pre><code>List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.filter(new TreeSet<>(c)::add)
.collect(Collectors.toList());
</code></pre>
<p>There is also a thread-safe variant, in case you want to use it with parallel streams:</p>
<pre><code>List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.filter(new ConcurrentSkipListSet<>(c)::add)
.collect(Collectors.toList());
</code></pre> |
39,139,087 | Why is derived class move constructible when base class isn't? | <p>Consider the following example:</p>
<pre><code>#include <iostream>
#include <string>
#include <utility>
template <typename Base> struct Foo : public Base {
using Base::Base;
};
struct Bar {
Bar(const Bar&) { }
Bar(Bar&&) = delete;
};
int main() {
std::cout << std::is_move_constructible<Bar>::value << std::endl; // NO
std::cout << std::is_move_constructible<Foo<Bar>>::value << std::endl; // YES. Why?!
}
</code></pre>
<p>Why does the compiler generate a move constructor despite the base class being non-move-constructible?</p>
<p>Is that in the standard or is it a compiler bug? Is it possible to "perfectly propagate" move construction from base to derived class? </p> | 39,139,214 | 2 | 7 | null | 2016-08-25 07:23:28.743 UTC | 5 | 2016-08-25 14:18:40.253 UTC | 2016-08-25 14:18:40.253 UTC | null | 3,309,790 | null | 2,163,127 | null | 1 | 57 | c++|c++11|language-lawyer|move-semantics|move-constructor | 2,476 | <p>Because:</p>
<blockquote>
<p>A defaulted move constructor that is defined as deleted is ignored by overload resolution.</p>
</blockquote>
<p>([class.copy]/11)</p>
<p><code>Bar</code>'s move constructor is <em>explicitly deleted</em>, so <code>Bar</code> cannot be moved. But <code>Foo<Bar></code>'s move constructor is <em>implicitly deleted</em> after being implicitly declared as defaulted, due to the fact that the <code>Bar</code> member cannot be moved. Therefore <code>Foo<Bar></code> can be moved using its copy constructor.</p>
<p>Edit: I also forgot to mention the important fact that an inheriting constructor declaration such as <code>using Base::Base</code> does not inherit default, copy, or move constructors, so that's why <code>Foo<Bar></code> doesn't have an explicitly deleted move constructor inherited from <code>Bar</code>.</p> |
33,335,338 | Inserting array values | <p>How do I write and execute a query which inserts array values using libpqxx?</p>
<pre><code>INSERT INTO exampleTable(exampleArray[3]) VALUES('{1, 2, 3}');
</code></pre>
<p>This example code gives me:</p>
<pre><code>ERROR: syntax error at or near "'"
</code></pre>
<p>What is wrong? In PostgreSQL documentation I found that:</p>
<pre><code>CREATE TABLE sal_emp (
name text,
pay_by_quarter integer[],
schedule text[][]
);
</code></pre>
<p>...</p>
<pre><code>INSERT INTO sal_emp
VALUES ('Bill',
'{10000, 10000, 10000, 10000}',
'{{"meeting", "lunch"}, {"training", "presentation"}}');
</code></pre> | 33,343,939 | 2 | 4 | null | 2015-10-25 21:34:30.077 UTC | 9 | 2022-07-16 07:32:15.947 UTC | 2018-07-27 11:44:32.063 UTC | null | 1,995,738 | null | 5,445,780 | null | 1 | 54 | arrays|postgresql | 106,936 | <p>You should use a column name without an index to insert an array:</p>
<pre><code>create table example(arr smallint[]);
insert into example(arr) values('{1, 2, 3}');
-- alternative syntax
-- insert into example(arr) values(array[1, 2, 3]);
select * from example;
arr
---------
{1,2,3}
(1 row)
</code></pre>
<p>Use the column name with an index to access a single element of the array:</p>
<pre><code>select arr[2] as "arr[2]"
from example;
arr[2]
--------
2
(1 row)
update example set arr[2] = 10;
select * from example;
arr
----------
{1,10,3}
(1 row)
</code></pre>
<p>You can use <code>arr[n]</code> in <code>INSERT</code> but this has special meaning. With this syntax you can create an array with one element indexed from the given number:</p>
<pre><code>delete from example;
insert into example(arr[3]) values (1);
select * from example;
arr
-----------
[3:3]={1}
(1 row)
</code></pre>
<p>As a result you have an array which lower bound is 3:</p>
<pre><code>select arr[3] from example;
arr
-----
1
(1 row)
</code></pre> |
1,622,834 | Confirm Password? | <p>New to all this so forgive my ignorance. I am trying to figure out how to add a "confirm your password" field to my form. Using PHP and mySQL. Is this entered in the html form code, and how can you set it to auto check that the password and confirm password fields match. </p> | 1,622,846 | 5 | 1 | null | 2009-10-26 02:25:18.243 UTC | 2 | 2018-12-28 12:30:50.147 UTC | 2012-10-09 15:58:06.243 UTC | null | 1,359,042 | null | 195,699 | null | 1 | 6 | php | 103,948 | <p>Just get both the password and confirm password fields in the form submit PHP and test for equality:</p>
<pre><code>if ($_POST["password"] === $_POST["confirm_password"]) {
// success!
}
else {
// failed :(
}
</code></pre>
<p>where <code>password</code> and <code>confirm_password</code> are the IDs of the HTML text inputs for the passwords.</p> |
1,391,692 | Encrypting with RSA private key in Java | <p>I'm trying to encrypt some content with an RSA private key. </p>
<p>I'm following this example:
<a href="http://www.junkheap.net/content/public_key_encryption_java" rel="nofollow noreferrer">http://www.junkheap.net/content/public_key_encryption_java</a><br>
<br>
but converting it to use private keys rather than public. Following that example, I think what I need to do is:</p>
<ul><li>Read in a DER-format private key</li>
<li>Generate a PCKS8EncodedKeySpec</li>
<li>call generatePrivate() from KeyFactory to get a private key object</li>
<li>Use that private key object with the Cipher object to do the encryption</li>
</ul>
<p>So, the steps:</p>
<p>The key was generated from openssl with:</p>
<p><code>openssl genrsa -aes256 -out private.pem 2048</code></p>
<p>and then was converted to DER format with:</p>
<p><code>openssl rsa -in private.pem -outform DER -out private.der</code></p>
<p>I generate the PKCS8EncodedKeySpec with:</p>
<pre><code>byte[] encodedKey = new byte[(int)inputKeyFile.length()];
try {
new FileInputStream(inputKeyFile).read(encodedKey);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
return privateKeySpec;
</code></pre>
<p>And then generate the private key object with:</p>
<pre><code>PrivateKey pk = null;
try {
KeyFactory kf = KeyFactory.getInstance(RSA_METHOD);
pk = kf.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pk;
</code></pre>
<p>However, on the call to:</p>
<pre><code>pk = kf.generatePrivate(privateKeySpec);
</code></pre>
<p>I get:</p>
<pre><code>java.security.spec.InvalidKeySpecException: Unknown key spec.
at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePrivate(DashoA12275)
at com.sun.net.ssl.internal.ssl.JSA_RSAKeyFactory.engineGeneratePrivate(DashoA12275)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:237)
</code></pre>
<p>Questions:</p>
<ul>
<li>Is the general approach right?</li>
<li>Is the PCKS8EncodedKeySpec the right keyspec to use?</li>
<li>Any thoughts on the invalid key spec error?</li>
</ul> | 1,391,786 | 5 | 1 | null | 2009-09-08 02:35:34.507 UTC | 8 | 2015-05-06 08:48:16.63 UTC | 2014-03-01 21:44:31.073 UTC | null | 642,148 | null | 136,451 | null | 1 | 10 | java|encryption|cryptography|rsa|private-key | 40,747 | <p>First of all, I'm confused why you are planning to use a <code>Cipher</code> to encrypt with a private key, rather than signing with a <code>Signature</code>. I'm not sure that all RSA <code>Cipher</code> providers will use the correct block type for setup, but it's worth a try.</p>
<p>Setting that aside, though, I think that you are trying to load a non-standard OpenSSL-format key. Converting it to DER with <code>rsa</code> is essentially just a base-64 decode; the structure of the key is not PKCS #8.</p>
<p>Instead, after <code>genrsa</code>, use the <code>openssl pkcs8</code> command to convert the generated key to unencrypted PKCS #8, DER format:</p>
<pre><code>openssl pkcs8 -topk8 -nocrypt -in private.pem -outform der -out private.der
</code></pre>
<p>This will produce an unencrypted private key that can be loaded with a <code>PKCS8EncodedKeySpec</code>.</p> |
1,414,968 | How do I configure the Linux kernel within Buildroot? | <p>I'm trying to build a rootfs for an x86 target, which is all simple enough. However I can't figure out how I configure the kernel that buildroot produces. The first run through came up with menuconfig, but it's cached the .config since then and I can't see where to change it.</p>
<p>~650MB of kernel modules don't do good things to an embedded target :P</p>
<p>Is there an easy way to configure the kernel within buildroot? Something like the <code>uclibc-menuconfig</code> target would be perfect.</p> | 1,415,300 | 5 | 1 | null | 2009-09-12 12:09:47.993 UTC | 7 | 2018-12-05 04:45:39.24 UTC | null | null | null | null | 48,234 | null | 1 | 17 | linux|embedded|kernel|buildroot | 47,485 | <p>And the answer is:</p>
<pre><code>make linux26-menuconfig
</code></pre> |
1,385,346 | What are differences between PECL and PEAR? | <p>I can see that GD library is for images. But I can't see differences between PECL and PEAR.
Both have authentication.
What are the main differences between two?
Why don't they combine them?</p> | 1,385,351 | 6 | 0 | null | 2009-09-06 10:19:20.107 UTC | 47 | 2022-05-09 17:20:15.49 UTC | null | null | null | null | 119,198 | null | 1 | 148 | php|pear|pecl | 36,624 | <p><strong>PECL</strong> stands for <strong>PHP Extension Community Library</strong>, it has extensions written in C, that can be loaded into PHP to provide additional functionality. You need to have administrator rights, a C compiler and associated toolchain to install those extensions.</p>
<p><strong>PEAR</strong> is <strong>PHP Extension and Application Repository</strong>, it has libraries and code written IN php. Those you can simply download, install and include in your code.</p>
<p>So, yes they are similar, but yet so different :)</p> |
1,932,449 | Beginners Assembly Language | <p>Where could one start learning assembly language from? Could you suggest some place that can get me kick-started with it?</p> | 1,932,462 | 10 | 4 | null | 2009-12-19 09:19:39.387 UTC | 23 | 2014-08-12 05:34:29.607 UTC | 2011-09-21 03:33:42.46 UTC | null | 436,641 | null | 235,055 | null | 1 | 12 | assembly | 21,867 | <p>Back in college I used to use the awesome <a href="http://www.emu8086.com/" rel="noreferrer">8086 Microprocessor Emulator</a> for Assembly programming on Windows. There are <a href="http://www.emu8086.com/assembly_language_tutorial_assembler_reference/asm_tutorial_01.html" rel="noreferrer">beginner tutorials</a> available on its website. </p>
<p>No matter what resource you use, it's important to be patient while learning Assembly. You might understand nothing while reading the first hundred pages, keep on & eventually you'll understand 'em all.</p> |
1,972,392 | Pick a random value from an enum? | <p>If I have an enum like this:</p>
<pre><code>public enum Letter {
A,
B,
C,
//...
}
</code></pre>
<p>What is the best way to pick one randomly? It doesn't need to be production quality bulletproof, but a fairly even distribution would be nice.</p>
<p>I could do something like this</p>
<pre><code>private Letter randomLetter() {
int pick = new Random().nextInt(Letter.values().length);
return Letter.values()[pick];
}
</code></pre>
<p>But is there a better way? I feel like this is something that's been solved before.</p> | 1,972,399 | 16 | 3 | null | 2009-12-29 00:54:29.203 UTC | 40 | 2022-03-24 15:03:34.78 UTC | 2018-08-14 16:42:06.333 UTC | null | 452,775 | null | 147,601 | null | 1 | 206 | java|random|enums | 211,307 | <p>The only thing I would suggest is caching the result of <code>values()</code> because each call copies an array. Also, don't create a <code>Random</code> every time. Keep one. Other than that what you're doing is fine. So:</p>
<pre><code>public enum Letter {
A,
B,
C,
//...
private static final List<Letter> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Letter randomLetter() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
</code></pre> |
1,603,109 | How to make a Python script run like a service or daemon in Linux | <p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p> | 1,603,138 | 17 | 4 | null | 2009-10-21 19:36:34.51 UTC | 102 | 2022-08-13 10:00:38.67 UTC | 2016-04-27 14:04:45.727 UTC | null | 562,769 | null | 191,474 | null | 1 | 216 | python|linux|scripting|daemons | 378,997 | <p>You have two options here.</p>
<ol>
<li><p>Make a proper <strong>cron job</strong> that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can <a href="http://en.wikipedia.org/wiki/Cron" rel="noreferrer">read more</a> at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.</p></li>
<li><p>Use some kind of <strong>python approach</strong> (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).</p></li>
</ol>
<p>I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.</p>
<p>Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by <a href="https://stackoverflow.com/users/93988/ivan-nevostruev">Ivan Nevostruev</a> in comments to <a href="https://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux/1603146#1603146">this</a> answer). While if the script is added as a cron job, it will just trigger again.</p> |
8,383,521 | How to configure maven local and remote repository in gradle build file? | <p>i want to use the maven local repository additionally to a maven remote one. I found the JIRA-Issue <a href="http://issues.gradle.org/browse/GRADLE-1173" rel="noreferrer">http://issues.gradle.org/browse/GRADLE-1173</a> for that, but adapting my gradle build file in that way some snapshot dependencies which are only available in the local maven repository are still not found. I get an error that the Snapshot-Dependency is not found.</p>
<p>Is it possible to have one local and one remote maven repository?</p>
<p>Here is the relevant part of my gradle build file:</p>
<pre><code>apply plugin: 'maven'
repositories {
mavenLocal()
maven {
credentials {
username "myusername"
password "mypassword"
}
url "http://myremoterepository"
}
}
</code></pre> | 20,962,300 | 2 | 2 | null | 2011-12-05 09:52:30.16 UTC | 9 | 2014-12-19 11:54:20.887 UTC | 2014-02-04 15:36:31.49 UTC | null | 745,827 | null | 745,827 | null | 1 | 23 | maven|gradle | 39,243 | <p>I also needed to do a similar setup with my project and I can verify your build.gradle setup works provided your Maven is setup correctly. </p>
<p><em>Gradle</em>'s <code>mavenLocal()</code> relies on the <code>localRepository</code> definition from the <em>maven</em> <a href="http://maven.apache.org/settings.html"><code>settings.xml</code></a> file:</p>
<pre><code> <localRepository>USER_HOME\.m2\repository</localRepository>
</code></pre>
<p>The settings.xml should be in either your <code>M2_HOME/conf</code> or your <code>USER_HOME/.m2 directory</code>. You should check:</p>
<ol>
<li><em>maven</em> is installed correctly</li>
<li><code>M2_HOME</code> environment variable exists </li>
<li><code>settings.xml</code> has the correct <code>localRepository</code> defined..</li>
</ol> |
46,446,143 | Can't import: android.support.v7.widget.RecyclerView in Android Studio | <p>I'm following my teachers tutorial and therefore writing exactly the same code that he has in his example. So I just created a new class to learn <code>RecyclerView</code> but I can't import <code>RecyclerView</code> On mouse-over, it just says "<strong>Cannot resolve symbol RecyclerView</strong>". I use <code>Android Studio 2.3.3.</code> Am I missing something obvious? </p>
<pre><code>import android.support.v7.widget.RecyclerView;
public class CustomAdapter extends RecyclerView.Adapter<ComposedAdapter.Holder> {
//stuff
}
</code></pre>
<p>Gradle: </p>
<pre><code>apply plugin: 'com.android.application'android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "sofialarsson.customrecyclerview"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
</code></pre> | 46,446,547 | 9 | 4 | null | 2017-09-27 10:56:54.5 UTC | 5 | 2020-08-09 08:22:06.507 UTC | 2017-09-27 11:14:08.34 UTC | null | 6,875,719 | null | 6,875,719 | null | 1 | 12 | java|android | 58,692 | <p>You need to add dependencies in <code>build.gradle</code></p>
<p>Use this update <code>gradle</code> file </p>
<pre><code>apply plugin: 'com.android.application'android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "sofialarsson.customrecyclerview"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile "com.android.support:appcompat-v7:25.0.0"
compile "com.android.support:recyclerview-v7:25.0.0"
testCompile 'junit:junit:4.12'
}
</code></pre> |
17,842,764 | Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell | <p>I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).</p>
<p>Lets say, there are folders mentioned below:</p>
<p>Main Folder: File aaa, File bbb</p>
<p>Sub Folder a: File 1, File 2, File 3</p>
<p>Sub Folder b: File 4, File 5, File 6</p>
<p>Script used:</p>
<pre><code>Get-ChildItem -Path \\Server1\Test -recurse | ForEach-Object {
Copy-Item -LiteralPath $_.FullName -Destination \\server2\test |
Get-Acl -Path $_.FullName | Set-Acl -Path "\\server2\test\$(Split-Path -Path $_.FullName -Leaf)"
}
</code></pre>
<p>Output:
File aaa, File bbb</p>
<p>Sub Folder a (Empty Folder)</p>
<p>Sub Folder b (Empty Folder)</p>
<p>File 1, File 2, File 3, File 4, File 5, File 6.</p>
<p>I want the files to get copied to their respective folders (Like the source folders). Any further help is highly appreciated.</p> | 17,843,127 | 5 | 2 | null | 2013-07-24 19:07:22.423 UTC | 6 | 2020-09-22 15:43:36.18 UTC | 2018-04-04 09:21:48.73 UTC | null | 271,200 | null | 1,926,332 | null | 1 | 40 | powershell|powershell-2.0|powershell-3.0 | 175,124 | <p>This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.</p>
<pre><code>Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force
</code></pre>
<p>I just tested it and it worked for me.</p>
<p><strong>edit:</strong> <em>included suggestion from the comments</em></p>
<pre><code># Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse
</code></pre> |
18,207,470 | Adding Table rows Dynamically in Android | <p>I am trying to create a layout where I need to add table rows dynamically. Below is the table layout xml</p>
<pre><code><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/displayLinear"
android:background="@color/background_df"
android:orientation="vertical" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/display_row"
android:layout_marginTop="280dip" >
</TableLayout>
</code></pre>
<p>The activity file where rows are being added dynamically is</p>
<pre><code>public void init(){
menuDB = new MenuDBAdapter(this);
ll = (TableLayout) findViewById(R.id.displayLinear);
TableRow row=(TableRow)findViewById(R.id.display_row);
for (int i = 0; i <2; i++) {
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
}
</code></pre>
<p>But when I run this, I am getting below error</p>
<pre><code>08-13 16:27:46.437: E/AndroidRuntime(23568): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roms/com.example.roms.DisplayActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
</code></pre>
<p>I understand that this is due to command <code>ll.addView(row,i);</code> but when I remove this its adding all stuff in a single row rather tan creating a new row for next item. I tried with giving index too as <code>row.addView(addBtn,i)</code> but still its not populating correctly. Please advise. Thanks.</p> | 18,207,894 | 8 | 1 | null | 2013-08-13 11:06:36.227 UTC | 32 | 2022-02-13 16:21:22.83 UTC | 2013-08-13 12:02:13.083 UTC | null | 98,497 | null | 2,416,087 | null | 1 | 39 | android|android-layout | 177,915 | <p>You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:</p>
<pre><code> public void init(){
TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);
for (int i = 0; i <2; i++) {
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
}
</code></pre> |
44,594,475 | Listener Binding; Cannot Find the Setter | <p>I am trying to implement <a href="https://developer.android.com/topic/libraries/data-binding/index.html#listener_bindings" rel="noreferrer">listener bindings</a>, but when I run my code I get the following error:</p>
<pre><code>Caused by: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'android:onClick' with parameter type lambda on android.widget.Button. file:~/GithubBrowser/app/src/main/res/layout/loading_state.xml loc:30:31 - 30:52 ****\ data binding error ****
</code></pre>
<p>This is the layout file in question:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="com.example.app.data.model.Resource"/>
<import type="com.example.app.data.model.Status"/>
<variable name="resource" type="Resource"/>
<variable name="callback" type="com.example.app.ui.common.RetryCallback"/>
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:padding="@dimen/default_margin">
<Button android:id="@+id/retry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/retry"
android:onClick="@{() -> callback.retry()}"/>
</LinearLayout>
</layout>
</code></pre>
<p>And this is the <code>RetryCallback</code> interface referenced in the layout:</p>
<pre><code>package com.example.app.ui.common
interface RetryCallback {
fun retry()
}
</code></pre>
<hr />
<h3>Edit</h3>
<p>The top-level <code>build.gradle</code>:</p>
<pre><code>buildscript {
ext.android_tools_version = '3.0.0-alpha3'
ext.kotlin_version = '1.1.2-5'
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$android_tools_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
ext {
architecture_version = '1.0.0-alpha2'
constraint_version = '1.0.2'
dagger_version = '2.11'
espresso_version = '2.2.2'
glide_version = '3.7.0'
junit_version = '4.12'
mockito_version = '2.7.19'
mock_server_version = '3.6.0'
moshi_version = '1.5.0'
retrofit_version = '2.2.0'
support_version = '25.4.0'
timber_version = '4.5.1'
}
allprojects {
repositories {
jcenter()
mavenCentral()
maven { url 'https://maven.google.com' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>And the app module <code>build.gradle</code>:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.app"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
testCoverageEnabled !project.hasProperty('android.injected.invoked.from.ide')
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
kapt {
generateStubs = true
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile "com.android.support:appcompat-v7:$support_version"
compile "com.android.support:cardview-v7:$support_version"
compile "com.android.support:design:$support_version"
compile "com.android.support:recyclerview-v7:$support_version"
compile "com.android.support.constraint:constraint-layout:$constraint_version"
compile "android.arch.lifecycle:extensions:$architecture_version"
compile "android.arch.lifecycle:runtime:$architecture_version"
compile "android.arch.persistence.room:runtime:$architecture_version"
compile "com.google.dagger:dagger:$dagger_version"
compile "com.google.dagger:dagger-android:$dagger_version"
compile "com.google.dagger:dagger-android-support:$dagger_version"
compile "com.squareup.moshi:moshi:$moshi_version"
compile "com.squareup.retrofit2:retrofit:$retrofit_version"
compile "com.squareup.retrofit2:converter-moshi:$retrofit_version"
compile "com.github.bumptech.glide:glide:$glide_version"
compile "com.jakewharton.timber:timber:$timber_version"
kapt "com.android.databinding:compiler:$android_tools_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
kapt "android.arch.persistence.room:compiler:$architecture_version"
kapt "android.arch.lifecycle:compiler:$architecture_version"
testCompile "junit:junit:$junit_version"
testCompile "com.squareup.okhttp3:mockwebserver:$mock_server_version"
testCompile ("android.arch.core:core-testing:$architecture_version", {
exclude group: 'com.android.support', module: 'support-compat'
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-ccore-utils'
})
androidTestCompile "com.android.support:appcompat-v7:$support_version"
androidTestCompile "com.android.support:cardview-v7:$support_version"
androidTestCompile "com.android.support:design:$support_version"
androidTestCompile "com.android.support:recyclerview-v7:$support_version"
androidTestCompile ("com.android.support.test.espresso:espresso-core:$espresso_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.google.code.findbugs', module: 'jsr305'
})
androidTestCompile ("com.android.support.test.espresso:espresso-contrib:$espresso_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.google.code.findbugs', module: 'jsr305'
})
androidTestCompile "org.mockito:mockito-android:$mockito_version"
}
</code></pre> | 44,989,266 | 9 | 7 | null | 2017-06-16 17:00:25.327 UTC | 3 | 2019-08-07 10:24:00.14 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 5,115,932 | null | 1 | 31 | android|kotlin|android-databinding | 28,488 | <p>I just had that issue and I have managed to solve it by deleting .idea, .gradle and gradle folders and let Android Studio recreate whole project from scratch from gradle files.</p> |
6,738,328 | shouldOverrideUrlLoading in WebView for Android not running | <p>-Edit: Solution Found-<br>
Figured it out after some heavy searching - one person (I literally mean one) said they instead used onPageLoad(); which worked perfectly for my purposes. The difference is that onPageLoad() runs later than shouldOverrideUrlLoading, but It doesn't make a difference in my code.</p>
<p>I'm trying to set up Twitter authorization with OAuth for an Android app, and thus far I can successfully send the user to the authorization URL, however, what I am trying to do now is intercept the redirect to the callback (which would just lead to a 404 error, our callback URL isn't going to have an associated page on our servers). What I'm attempting to do is check if the URL is our callback, then extract the OAuth Verifier from the URL. I setup my WebView with this code:</p>
<pre><code>view = (WebView)findViewById(R.id.twitterWbVw);
view.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView wView, String url)
{
String urlHolder;
String[] verifExtrctr;
urlHolder = url.substring(0, url.indexOf('?'));
System.out.println("url");
if(urlHolder.equalsIgnoreCase(CALLBACK_URL))
{
verifExtrctr = urlHolder.split("?");
verifExtrctr = verifExtrctr[2].split("=");
if(verifExtrctr[0].equalsIgnoreCase("oauth_verifier"))
{
params[5] = verifExtrctr[1];
return true;
}
else
{
System.out.println("Inocorrect callback URL format.");
}
}
else
{
wView.loadUrl(url);
}
return true;
}
});
view.loadUrl(urlAuthorize.toExternalForm());
</code></pre>
<p>Thing is <em>even System.out.println("url");</em>(which I'm using to debug)<em>doesn't run!</em> So I'm pretty much dry on ideas, and can't find anyone with a similar problem. The authorization URL goes through fine, and I can successfully authorize the app, however the redirect to the callback URL for some reason never get's intercepted. Any help would be appreciated, this is in my onResume() if that matters.</p> | 6,739,042 | 3 | 6 | null | 2011-07-18 19:31:03.25 UTC | 12 | 2019-05-17 07:38:22.01 UTC | 2013-11-26 15:49:16.35 UTC | null | 1,503,078 | null | 842,809 | null | 1 | 22 | android|https|android-webview|webviewclient | 66,366 | <p>After some research I conclude that despite what most of the tutorials out there say, <code>shouldOverrideUrlLoading()</code> does not get called when:</p>
<ol>
<li><p>You load a URL like </p>
<pre><code>loadUrl("http://www.google.com");
</code></pre></li>
<li><p>The browser redirects the user automatically via an HTTP Redirect. <strong>(See the comment from @hmac below regarding redirects)</strong></p></li>
</ol>
<p><em>It does however</em>, get called when you you click on a link inside a webpage inside the webview. IIRC the twitter authorization uses an HTTP Redirect.. Bummer, this would be helpful if it worked how all the tutorials say it does. I think this is from a very old version the Android API...</p>
<p>You might want to consider overriding the <code>onProgressChanged</code> method of a <code>WebChromeClient</code> like here: <a href="https://stackoverflow.com/questions/3149216/how-to-listen-for-a-webview-finishing-loading-a-url-in-android">How to listen for a WebView finishing loading a URL?</a> <strong>or</strong> the <code>onPageFinished()</code> method of the <code>WebViewClient</code>.</p> |
6,873,533 | Observable Collection replace item | <p>I have a <code>ObservableCollection</code>, I can add and remove item from the collection. But I can't replace an existing item in the collection. There is a way to replace an item and reflect that on my bound components. </p>
<pre><code>System.Collections.Specialized.NotifyCollectionChangedAction.Replace
</code></pre>
<p>Can anyone please show me how to accomplish this?</p> | 6,873,600 | 3 | 1 | null | 2011-07-29 13:03:33.88 UTC | 3 | 2022-02-25 10:10:56.323 UTC | 2014-07-20 05:18:57.267 UTC | null | 1,468,093 | null | 835,292 | null | 1 | 34 | wpf|binding|replace|observablecollection | 30,290 | <pre><code>collection[someIndex] = newItem;
</code></pre> |
7,004,728 | Is this "should not happen" crash an AMD Fusion CPU bug? | <p>My company has started having a number of customers call in because our program is crashing with an access violation on their systems.</p>
<p>The crash happens in SQLite 3.6.23.1, which we ship as part of our application. (We ship a custom build, in order to use the same VC++ libraries as the rest of the app, but it's the stock SQLite code.)</p>
<p>The crash happens when <code>pcache1Fetch</code> executes <code>call 00000000</code>, as shown by the WinDbg callstack:</p>
<pre><code>0b50e5c4 719f9fad 06fe35f0 00000000 000079ad 0x0
0b50e5d8 719f9216 058d1628 000079ad 00000001 SQLite_Interop!pcache1Fetch+0x2d [sqlite3.c @ 31530]
0b50e5f4 719fd581 000079ad 00000001 0b50e63c SQLite_Interop!sqlite3PcacheFetch+0x76 [sqlite3.c @ 30651]
0b50e61c 719fff0c 000079ad 0b50e63c 00000000 SQLite_Interop!sqlite3PagerAcquire+0x51 [sqlite3.c @ 36026]
0b50e644 71a029ba 0b50e65c 00000001 00000e00 SQLite_Interop!getAndInitPage+0x1c [sqlite3.c @ 40158]
0b50e65c 71a030f8 000079ad 0aecd680 071ce030 SQLite_Interop!moveToChild+0x2a [sqlite3.c @ 42555]
0b50e690 71a0c637 0aecd6f0 00000000 0001edbe SQLite_Interop!sqlite3BtreeMovetoUnpacked+0x378 [sqlite3.c @ 43016]
0b50e6b8 71a109ed 06fd53e0 00000000 071ce030 SQLite_Interop!sqlite3VdbeCursorMoveto+0x27 [sqlite3.c @ 50624]
0b50e824 71a0db76 071ce030 0b50e880 071ce030 SQLite_Interop!sqlite3VdbeExec+0x14fd [sqlite3.c @ 55409]
0b50e850 71a0dcb5 0b50e880 21f9b4c0 00402540 SQLite_Interop!sqlite3Step+0x116 [sqlite3.c @ 51744]
0b50e870 00629a30 071ce030 76897ff4 70f24970 SQLite_Interop!sqlite3_step+0x75 [sqlite3.c @ 51806]
</code></pre>
<p>The relevant line of C code is: </p>
<pre><code>if( createFlag==1 ) sqlite3BeginBenignMalloc();
</code></pre>
<p>The compiler inlines <code>sqlite3BeginBenignMalloc</code>, which is defined as:</p>
<pre><code>typedef struct BenignMallocHooks BenignMallocHooks;
static SQLITE_WSD struct BenignMallocHooks {
void (*xBenignBegin)(void);
void (*xBenignEnd)(void);
} sqlite3Hooks = { 0, 0 };
# define wsdHooksInit
# define wsdHooks sqlite3Hooks
SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
wsdHooksInit;
if( wsdHooks.xBenignBegin ){
wsdHooks.xBenignBegin();
}
}
</code></pre>
<p>And the assembly for this is:</p>
<pre><code>719f9f99 mov esi,dword ptr [esp+1Ch]
719f9f9d cmp esi,1
719f9fa0 jne SQLite_Interop!pcache1Fetch+0x2d (719f9fad)
719f9fa2 mov eax,dword ptr [SQLite_Interop!sqlite3Hooks (71a7813c)]
719f9fa7 test eax,eax
719f9fa9 je SQLite_Interop!pcache1Fetch+0x2d (719f9fad)
719f9fab call eax ; *** CRASH HERE ***
719f9fad mov ebx,dword ptr [esp+14h]
</code></pre>
<p>The registers are:</p>
<pre><code>eax=00000000 ebx=00000001 ecx=000013f0 edx=fffffffe esi=00000001 edi=00000000
eip=00000000 esp=0b50e5c8 ebp=000079ad iopl=0 nv up ei pl nz na po nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010202
</code></pre>
<p>If <code>eax</code> is 0 (which it is), the zero flag should be set by <code>test eax, eax</code>, but it's non-zero. Because the zero flag isn't set, <code>je</code> doesn't jump, and then the app crashes trying to execute <code>call eax (00000000)</code>.</p>
<p><em>Update</em>: <code>eax</code> should always be 0 here because <code>sqlite3Hooks.xBenignBegin</code> is not set in our build of the code. I could rebuild SQLite with <code>SQLITE_OMIT_BUILTIN_TEST</code> defined, which would turn on <code>#define sqlite3BeginBenignMalloc()</code> in the code and omit this code path entirely. That may solve the issue, but it doesn't feel like a "real" fix; what would stop it happening in some other code path?</p>
<p>So far the common factor is that all customers are running "Windows 7 Home Premium 64-bit (6.1, Build 7601) Service Pack 1" and have one of the following CPUs (according to DxDiag):</p>
<ul>
<li>AMD A6-3400M APU with Radeon(tm) HD Graphics (4 CPUs), ~1.4GHz</li>
<li>AMD A8-3500M APU with Radeon(tm) HD Graphics (4 CPUs), ~1.5GHz</li>
<li>AMD A8-3850 APU with Radeon(tm) HD Graphics (4 CPUs), ~2.9GHz</li>
</ul>
<p>According to Wikipedia's <a href="http://en.wikipedia.org/wiki/AMD_Fusion">AMD Fusion article</a>, these are all "Llano" model AMD Fusion chips based on the K10 core and were released in June 2011, which is when we first started getting reports.</p>
<p>The most common customer system is the Toshiba Satellite L775D, but we also have crash reports from HP Pavilion dv6 & dv7 and Gateway systems.</p>
<p>Could this crash be caused by a CPU error (see <a href="http://support.amd.com/us/Processor_TechDocs/44739.pdf">Errata for AMD Family 12h Processors</a>), or is there some other possible explanation that I'm overlooking? (According to Raymond, it <a href="http://blogs.msdn.com/b/oldnewthing/archive/2005/04/12/407562.aspx">could be overclocking</a>, but it's odd that just this specific CPU model is affected, if so.)</p>
<p>Honestly, it doesn't seem possible that it's really a CPU or OS error, because the customers aren't getting bluescreens or crashes in other applications. There must be some other, more likely, explanation--but what?</p>
<p><em>Update 15 August:</em> I've acquired a Toshiba L745D notebook with an AMD A6-3400M processor and can reproduce the crash consistently when running the program. The crash is always on the same instruction; <code>.time</code> reports anywhere from 1m30s to 7m of user time before the crash. One fact (that may be pertinent to the issue) that I neglected to mention in the original post is that the application is multi-threaded and has both high CPU and I/O usage. The application spawns four worker threads by default and posts 80+% CPU usage (there is some blocking for I/O as well as for mutexes in the SQLite code) until it crashes. I modified the application to only use two threads, and it still crashed (although it took longer to happen). I'm now running a test with just one thread, and it hasn't crashed yet.</p>
<p>Note also that it doesn't appear to be purely a CPU load problem; I can run Prime95 without errors on the system and it will boost the CPU temperature to >70°C, while my application barely gets the temperature above 50°C while it's running.</p>
<p><em>Update 16 August:</em> Perturbing the instructions slightly makes the problem "go away". For eaxmple, replacing the memory load (<code>mov eax,dword ptr [SQLite_Interop!sqlite3Hooks (71a7813c)]</code>) with <code>xor eax, eax</code> prevents the crash. Modifying the original C code to add an extra check to the <code>if( createFlag==1 )</code> statement changes the relative offsets of various jumps in the compiled code (as well as the location of the <code>test eax, eax</code> and <code>call eax</code> statements) and also seems to prevent the problem.</p>
<p>The strangest result I've found so far is that changing the <code>jne</code> at <code>719f9fa0</code> to two <code>nop</code> instructions (so that control <em>always</em> falls through to the <code>test eax, eax</code> instruction, no matter what the value of <code>createFlag</code>/<code>esi</code> is) allows the program to run without crashing.</p> | 7,642,385 | 3 | 14 | null | 2011-08-10 00:45:48.677 UTC | 10 | 2014-11-18 17:53:43.007 UTC | 2014-11-18 17:53:43.007 UTC | null | 2,019,281 | null | 23,633 | null | 1 | 70 | assembly|crash|x86|windbg|amd-processor | 3,495 | <p>I spoke to an AMD engineer at the Microsoft Build conference about this error, and showed him my repro. He emailed me this morning:</p>
<blockquote>
<p>We have investigated and found that this is due to a known errata in
the Llano APU family. It can be fixed via a BIOS update depending on
the OEM – if possible please recommend it to your customers (even
though you have a workaround).</p>
<p>In case you’re interested, the errata is 665 in the Family 12h
Revision Guide (see page 45):
<a href="http://support.amd.com/TechDocs/44739_12h_Rev_Gd.pdf#page=45" rel="noreferrer">http://support.amd.com/TechDocs/44739_12h_Rev_Gd.pdf#page=45</a></p>
</blockquote>
<p>Here's the description of that erratum:</p>
<h1>665 Integer Divide Instruction May Cause Unpredictable Behavior</h1>
<h2>Description</h2>
<p>Under a highly specific and detailed set of internal timing conditions, the processor core may abort a speculative DIV or IDIV integer divide instruction (due to the speculative execution being redirected, for example due to a mispredicted branch) but may hang or prematurely complete the first instruction of the non-speculative path.</p>
<h2>Potential Effect on System</h2>
<p>Unpredictable system behavior, usually resulting in a system hang.</p>
<h2>Suggested Workaround</h2>
<p>BIOS should set MSRC001_1029[31].</p>
<p>This workaround alters the DIV/IDIV instruction latency specified in the <em>Software Optimization Guide for AMD Family 10h and 12h Processors</em>, order# 40546. With this workaround applied, the DIV/IDIV latency for AMD Family 12h Processors are similar to the DIV/IDIV latency for AMD Family 10h Processors.</p>
<h2>Fix Planned</h2>
<p>No</p> |
35,837,990 | How to trigger omnicomplete/auto-completion on keystrokes in INSERT mode? | <p>VIM's omnicomplete autocompletion is not really working as expected.</p>
<p>Is there a way to make it smarter? Like, to monitor the context of surround text? (e.g. don't trigger if within comments or quotes)</p>
<p>I ask because I cannot get to a happy place since switching to Vim when compared to the autocomplete/IntelliSense in IDEs such as Visual Studio, IntelliJ, Sublime and Atom (I've used all of these for development in the past).</p>
<p>The basic goals to this question:</p>
<ul>
<li>Can Omnicomplete be triggered on A-Za-z keystrokes in INSERT mode? I already have it being triggered via "." dot symbols.</li>
<li>How to get Omnicomplete to insert the func's parameters?</li>
</ul>
<p>I am new to Vim for a few months and desperately trying to get a smooth workflow. But without a good autocomplete option, while forcing me to be more vigilant in learning the code I am trying to use, it is greatly slowly me down over other IDEs I've used in the past. </p>
<h1>Atom + Go-Plus</h1>
<p>Let's examine my expectations with Atom + Go-Plus.</p>
<p>I have a func named <code>func generate(entropy chan<- uint64)</code> located elsewhere in another Go file in the same package.</p>
<p>When I type the letter <code>g</code> on line 22, I immediately get a prompt with everything that begins with g: </p>
<p><a href="https://i.stack.imgur.com/ng7Zz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ng7Zz.png" alt="Atom's autocomplete with Go-Plus"></a></p>
<p>As you can see, there are 3 options that immediately pop up (the first two I think are just code snippets). I can use an arrow key to scroll down to either option. </p>
<p>If I select the 3rd option (or if I continue to type <code>gen</code> the field narrows down to only 1 option), and <code>press enter</code> Atom/Visual Studio/Sublime all fill out the details of the method for me:</p>
<p><a href="https://i.stack.imgur.com/0DuUo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0DuUo.png" alt="atom with go-plus autocompletion"></a></p>
<p>I did not type any of the above. It was inserted and I can override the details, modify them, or just TAB off and continue typing.</p>
<h1>Vim + Vim-Go (really Omnicomplete)</h1>
<p>Let's compare that with my current (maybe broken?) config of <code>omnicomplete</code>. I have this in my .vimrc:</p>
<p><code>
set completeopt=longest,menuone
</code></p>
<p>Within vim, if I type <code>gen</code>, all I get is what seems to be my previously entered text that I typed elsewhere in this buffer (and only in this buffer, not in other buffers). If I happen to misspell something, all I get the misspelled version I previously entered for the life that I have vim open. This tells me there is no IntelliSense/autocomplete at work - just something monitoring the keystrokes I make:</p>
<p><a href="https://i.stack.imgur.com/4lLQ3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4lLQ3.png" alt="vim with omnicomplete and autocomplete not working"></a></p>
<p>As you can see, autocomplete isn't working as I type. Though, this does come in handy with comments and strings in other places and I kind of like how vim remembers my free-text I type. </p>
<p>Not really sure what Vim option is enabling this; but, it is not autocompletion.</p>
<p>Now, I can press <code>CTRL-X + CTRL-O</code> to force autocompletion and get <code>generate()</code> to show up:</p>
<p><a href="https://i.stack.imgur.com/GR4bv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GR4bv.png" alt="vim with omnicomplete and autocomplete"></a></p>
<p>This is better; but, I would expect it to show me autocomplete options as I type: not requiring 3 additional keystrokes to make it happen. That is a whole lot of C-x C-o happenings throughout a few hours of coding.</p>
<p><strong>Is there a way to have Vim monitor my keystrokes in INSERT mode and display autocomplete if there is a matching ctag or function?</strong> That may be the answer to this functionality.</p>
<h1>Autocomplete with Parameters</h1>
<p>There is a 2nd problem with autocompletion with <code>omnicomplete</code> that I could overlook the C-x C-o requirement of the above if this worked: once I do select the method I want to autocomplete, it does not insert the parameters/fields for me.</p>
<p>Going back to the screenshot above, if I select that method, this is what I get:</p>
<p><a href="https://i.stack.imgur.com/mEbHN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mEbHN.png" alt="vim with vim-go autocomplete not fully completing"></a></p>
<p>Notice that <strong>it does not insert</strong> the func's paramters. It does not match the 2nd picture posted above, where the autocomplete in Atom, Sublime, and Visual Studio all complete the method with parameters showing.</p>
<p>I have read the vim wikia and have tried various options with <code>set completeopt</code> without any viable alternative. </p>
<p>For example, <code>set completeopt+=preview</code> gives me the preview window after selecting:</p>
<p><a href="https://i.stack.imgur.com/VIMOk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VIMOk.png" alt="enter image description here"></a></p>
<p>Why giving me the parameters in a preview, it still does not autocomplete my <code>line 22</code> of code and is often a distraction (I often times disable it because I type far faster than having to stop and "look up" all the time).</p>
<p>It took a lot of tweaking of the config file to get the below working; but, I was able to get "dot" autocompletion to work. So, there is some form of autocompletion working:</p>
<p><a href="https://i.stack.imgur.com/zr3wM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zr3wM.png" alt="vim and vim-go autocompletion with dot"></a></p>
<p>But again, it does not fill in the parameters once I select a function which is pretty annoying to have to type <code>ESC + back arrow + back arrow + : + GoDoc</code> just to see what it was: that's 10 character strokes to see what it was.</p>
<p>Sure, Atom, Sublime, and VS is much prettier when "dot autocompleting":</p>
<p><a href="https://i.stack.imgur.com/x7Hk3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/x7Hk3.png" alt="atom and go-plus dot autocompletion"></a></p>
<p>(it is also better ordered by types, though I do have vim setup to remember the last used at the top so that helps). But I don't care about pretty - I just want my parameters to show up when selecting with 'dot'. </p>
<p>Any advice in how to tweak my vim-go and related plugins would be very welcome as I'd prefer to stay with Vim over any IDEs. Thank you.</p>
<p><strong>EDIT:</strong> </p>
<p>I see that <a href="https://github.com/fatih/vim-go/pull/685" rel="noreferrer">the author of <code>vim-go</code></a> has worked on the parameters-completion part and got it working:</p>
<p><a href="https://i.stack.imgur.com/Qs4AR.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Qs4AR.gif" alt="autocompletion with parameters in vim-go"></a></p>
<p>Though, I can't seem to get it working on my install (still debugging it), I wanted to show others that it is indeed possible to have autocomplete with parameters being filled.</p> | 47,967,462 | 3 | 4 | null | 2016-03-07 07:06:40.117 UTC | 10 | 2022-01-23 23:36:21.203 UTC | 2016-06-25 14:41:23.777 UTC | null | 56,693 | null | 56,693 | null | 1 | 23 | vim|autocomplete|omnicomplete | 16,650 | <blockquote>
<p>Can Omnicomplete be triggered on A-Za-z keystrokes in INSERT mode?</p>
</blockquote>
<p>You can listen to <code>InsertCharPre</code> event and check what keys have been pressed.</p>
<pre><code>function! OpenCompletion()
if !pumvisible() && ((v:char >= 'a' && v:char <= 'z') || (v:char >= 'A' && v:char <= 'Z'))
call feedkeys("\<C-x>\<C-o>", "n")
endif
endfunction
autocmd InsertCharPre * call OpenCompletion()
</code></pre>
<p>Also you should <code>set completeopt+=menuone,noselect,noinsert</code> to avoid vim inserting completion text automatically. But keep in mind it is not common decision and you will probably have some issues. The one I have found is it breaks <code>cgn</code> command.</p>
<p>For further reading do <code>help InsertCharPre</code>, <code>help autocmd-events</code>, <code>help pumvisible()</code>, <code>help feedkeys()</code>.</p>
<blockquote>
<p>How to get Omnicomplete to insert the func's parameters?</p>
</blockquote>
<p>I used sublime for a some years and it represents builtin functions (default vim omnicompletion) with snippets. So if you want parameters to be inserted into the buffer you need to:</p>
<ol>
<li>Install snippet manager like <strong>ultisnips</strong>, <strong>neosnippet</strong>, <strong>minisnip</strong>, <strong>xptemplate</strong> or <a href="https://vimawesome.com/?q=snippet" rel="noreferrer">others</a>.</li>
<li>Create a bunch of snippets or install from somewhere.</li>
<li>Make your completion system recognize preferred snippet manager (many completion managers recognize <strong>ultisnips</strong>).</li>
</ol>
<p>If you change your mind in the way of using so called <strong>preview</strong> window you mentioned above here are some tips:</p>
<ol>
<li>It is possible to show preview window at the bottom of the screen <code>set splitbelow</code>.</li>
<li>You can <code>set previewheight</code> option to change its size.</li>
<li>To automatically close window after completion is done <code>autocmd CompleteDone * pclose</code>.</li>
</ol>
<p>For further reading do <code>help ins-completion</code> and <code>help preview-window</code></p> |
23,939,168 | Is C# type system sound and decidable? | <p>I know that Java's type system is unsound (it fails to type check constructs that are semantically legal) and undecidable (it fails to type check some construct).</p>
<p>For instance, if you copy/paste the following snippet in a class and compile it, the compiler will crash with a <code>StackOverflowException</code> (how apt). This is undecidability.</p>
<pre><code>static class ListX<T> {}
static class C<P> extends ListX<ListX<? super C<C<P>>>> {}
ListX<? super C<Byte>> crash = new C<Byte>();
</code></pre>
<p>Java uses wildcards with type bounds, which are a form of use-site variance. C# on the other hand, uses declaration site variance annotation (with the <code>in</code> and <code>out</code> keywords). It is known that declaration-site variance is weaker than use-site variance (use-site variance can express everything declaration-site variance can, and more -- on the down side, it's much more verbose).</p>
<p>So my question is: Is C# type system sound and decidable? If not, why?</p> | 23,968,075 | 3 | 3 | null | 2014-05-29 17:20:23.353 UTC | 23 | 2021-04-29 22:03:15.813 UTC | 2021-04-29 22:03:15.813 UTC | null | 1,377,706 | null | 298,664 | null | 1 | 53 | c#|types|covariance|type-systems | 10,034 | <blockquote>
<p>Is C# type system decidable?</p>
</blockquote>
<p>A type system is "decidable" if the compiler is in theory always able to decide whether the program type checks or not in finite time.</p>
<p><strong>The C# type system is not decidable.</strong></p>
<p>C# has "nominal" subtyping -- that is, you give classes and interfaces <em>names</em> and say what the base classes and interfaces are <em>by name</em> when you declare a class.</p>
<p>C# also has generic types, and, as of C# 4, covariance and contravariance of generic interfaces.</p>
<p>Those three things -- nominal subtyping, generic interfaces, and contravariance -- are sufficient to make a type system undecidable (in the absence of other restrictions on the ways that subtypes may mention each other.)</p>
<p>When this answer was originally written in 2014, that was suspected but not known. The history of this discovery is interesting.</p>
<p>First, the designers of the C# generic type system wondered the same thing, and wrote a paper in 2007 describing different ways in which type checking can go wrong, and what restrictions one can put on a nominal subtyping system that make it decidable.</p>
<p><a href="https://www.microsoft.com/en-us/research/publication/on-decidability-of-nominal-subtyping-with-variance/" rel="noreferrer">https://www.microsoft.com/en-us/research/publication/on-decidability-of-nominal-subtyping-with-variance/</a></p>
<p>A more gentle introduction to the problem can be found on my blog, here:</p>
<p><a href="https://ericlippert.com/2008/05/07/covariance-and-contravariance-part-11-to-infinity-but-not-beyond/" rel="noreferrer">https://ericlippert.com/2008/05/07/covariance-and-contravariance-part-11-to-infinity-but-not-beyond/</a></p>
<p><a href="https://cstheory.stackexchange.com/questions/18846/a-simple-decision-problem-whose-decidability-is-not-known/18866#18866">I have written about this subject on SE sites before</a>; a researcher noticed the problem mentioned in that posting and solved it; we now know that nominal subtyping is in general undecidable if there is generic contravariance thrown into the mix. You can encode a Turing Machine into the type system and force the compiler to emulate its operation, and since the question "does this TM halt?" is undecidable, so must type checking be undecidable.</p>
<p>See <a href="https://arxiv.org/abs/1605.05274" rel="noreferrer">https://arxiv.org/abs/1605.05274</a> for the details.</p>
<blockquote>
<p>Is the C# type system sound?</p>
</blockquote>
<p>A type system is "sound" if we are guaranteed that a program which type checks at compile time has no type errors at runtime.</p>
<p><strong>The C# type system is not sound.</strong></p>
<p>There are many reasons why it is not, but my least favourite is array covariance:</p>
<pre><code>Giraffe[] giraffes = new[] { new Giraffe() };
Animal[] animals = giraffes; // This is legal!
animals[0] = new Tiger(); // crashes at runtime with a type error
</code></pre>
<p>The idea here is that most methods that take arrays only read the array, they do not write it, and it is safe to read an animal out of an array of giraffes. Java allows this, and so the CLR allows it because the CLR designers wanted to be able to implement variations on Java. C# allows it because the CLR allows it. The consequence is that <em>every time you write anything into an array of a base class, the runtime must do a check to verify that the array is not an array of an incompatible derived class</em>. The common case gets slower so that the rare error case can get an exception.</p>
<p>That brings up a good point though: C# is at least well-defined as to the consequences of a type error. Type errors at runtime produce sane behaviour in the form of exceptions. It's not like C or C++ where the compiler can and will blithely generate code that does arbitrarily crazy things.</p>
<p>There are a few other ways in which the C# type system is unsound by design.</p>
<ul>
<li><p>If you consider getting a null reference exception to be a kind of runtime type error, then C# pre C# 8 is very unsound in that it does almost nothing to prevent this kind of error. C# 8 has many improvements in support for detecting nullity errors statically, but the null reference type checking is not sound; it has both false positives and false negatives. The idea is that some compile-time checking is better than none, even if it is not 100% reliable.</p>
</li>
<li><p>Many cast expressions allow the user to override the type system and declare "I know this expression will be of a more specific type at runtime, and if I'm wrong, throw an exception". (Some casts mean the opposite: "I know this expression is of type X, please generate code to convert it to an equivalent value of type Y". Those are generally safe.) Since this is a place where the developer is specifically saying that they know better than the type system, one can hardly blame the type system for the resulting crash.</p>
</li>
</ul>
<p>There are also a handful of features that generate cast-like behaviour even though there is no cast in the code. For example, if you have a list of animals you can say</p>
<pre><code>foreach(Giraffe g in animals)
</code></pre>
<p>and if there is a tiger in there, your program will crash. As the specification notes, the compiler simply inserts a cast on your behalf. (If you want to loop over all the giraffes and ignore the tigers, that's <code>foreach(Giraffe g in animals.OfType<Giraffe>())</code>.)</p>
<ul>
<li>The <code>unsafe</code> subset of C# makes all bets off; you can break the rules of the runtime arbitrarily with it. Turning off a safety system <strong>turns a safety system off</strong>, so it should not be surprising that C# is not sound when you turn off soundness checking.</li>
</ul> |
18,545,769 | will_paginate with endless Scrolling | Rails4 | <p><strong>THIS IS THE SOLUTION</strong></p>
<p>So i'm using <a href="https://github.com/mislav/will_paginate" rel="noreferrer">will_paginate</a> / <a href="https://github.com/yrgoldteeth/bootstrap-will_paginate" rel="noreferrer">Bootstrap Will Paginate</a> with Endless Scrolling.</p>
<p>To get the Pagination working:</p>
<p><strong>1.)</strong> In my Controller i updated my index action with</p>
<pre><code>@clips = Clip.order("created_at desc").page(params[:page]).per_page(20)
</code></pre>
<p><strong>2.)</strong> Edit my index view:</p>
<pre><code><%= will_paginate @clips%>
</code></pre>
<p><strong>DONE</strong></p>
<p>Pagination works just fine.</p>
<p><code>To Add Endless scrolling</code> i did the same steps as in my previous Rails 3 App.</p>
<p><strong>1.)</strong> Edit my clips.js.coffee
</p>
<pre><code>jQuery ->
$('#clips-masonry').imagesLoaded ->
$('#clips-masonry').masonry itemSelector: ".clips-masonry" # Thats my Masonry
if $('.pagination').length # Thats for the Endless Scrolling
$(window).scroll ->
url = $('.pagination .next_page a').attr('href')
if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50
# What to do at the bottom of the page
$('.pagination').text("Fetching more Clips...")
$.getScript(url)
$(window).scroll()
</code></pre>
<p><strong>2.)</strong> Create an index.js.erb with:</p>
<pre><code>$boxes = $('<%= j render(@clips) %>')
$('#clips-masonry').append( $boxes ).imagesLoaded( function(){
$('#clips-masonry').masonry( 'reload');
});
<% if @clips.next_page %>
$('.pagination').replaceWith('<%= j will_paginate(@clips) %>');
<% else %>
$('.pagination').remove();
<% end %>
</code></pre>
<p><strong>3.)</strong> Added format.js to my Controller index action</p>
<pre><code>def index
@clips = Clip.order("created_at desc").page(params[:page]).per_page(12)
respond_to do |format|
format.html
format.js
end
end
</code></pre>
<p><strong>4.)</strong> My _clip.html.erb is wrapped with the div</p>
<pre><code> <div class="clip-box clips-masonry" data-no-turbolink>
</code></pre> | 18,554,925 | 2 | 8 | null | 2013-08-31 07:36:09.313 UTC | 11 | 2018-06-25 14:15:33.293 UTC | 2013-09-01 03:27:13.057 UTC | null | 1,609,496 | null | 1,609,496 | null | 1 | 16 | javascript|ruby-on-rails|twitter-bootstrap|ruby-on-rails-4|will-paginate | 5,531 | <p>Ok, i got it working with my Updated Question, everyone who stumbles upon this problem, This is the solution. </p> |
15,612,589 | Getting SQL Error: ORA-00957: duplicate column name, while creating view | <p>I am trying to make a view, but I am getting a duplicate column name error. If I run the select query separately, then the query returns a result like:</p>
<pre><code>SELECT distinct app.APP_REF_NO, app.APP_STATUS, app.APP_DT, app.ATTEND_STAFF,
app.ATTEND_BRANCH, app.PRODUCT_TYPE, cust.CUST_ID,
cust.APP_JOINT_T, cust.ID1_TYPE, cust.ID1, cust.ID2_TYPE,
cust.ID2, cust.FIRST_NAME, cust.LAST_NAME, cust.FULL_NAME,
cust.FULL_NAME_CAP, cust.DOB, fac.FACILITY_NO, fac.PRODUCT_TYPE,
fac.PRODUCT_CODE, fac.MAIN_PROD_IND, fac.AMT_APPLIED
FROM
LOSA_APP app
LEFT JOIN
LOSA_CUST cust
ON
cust.APP_REF_NO = app.APP_REF_NO
LEFT JOIN
LOSA_FACILITIES fac
ON
fac.APP_REF_NO = app.APP_REF_NO
LEFT JOIN
OS_CURRENTSTEP STEP
ON
STEP.REF_ID = app.APP_REF_NO
WHERE (app.APP_STATUS ='P' OR app.APP_STATUS ='T' OR
((app.APP_STATUS='R' OR app.APP_STATUS='S') AND STEP.STEP_NAME='011'));
</code></pre>
<p>This query works fine. But when I try to run it as a view like:</p>
<pre><code>CREATE VIEW basit_test1 AS
SELECT distinct app.APP_REF_NO, app.APP_STATUS, app.APP_DT, app.ATTEND_STAFF,
app.ATTEND_BRANCH, app.PRODUCT_TYPE, cust.CUST_ID,
cust.APP_JOINT_T, cust.ID1_TYPE, cust.ID1, cust.ID2_TYPE,
cust.ID2, cust.FIRST_NAME, cust.LAST_NAME, cust.FULL_NAME,
cust.FULL_NAME_CAP, cust.DOB, fac.FACILITY_NO, fac.PRODUCT_TYPE,
fac.PRODUCT_CODE, fac.MAIN_PROD_IND, fac.AMT_APPLIED
FROM
LOSA_APP app
LEFT JOIN
LOSA_CUST cust
ON
cust.APP_REF_NO = app.APP_REF_NO
LEFT JOIN
LOSA_FACILITIES fac
ON
fac.APP_REF_NO = app.APP_REF_NO
LEFT JOIN
OS_CURRENTSTEP STEP
ON
STEP.REF_ID = app.APP_REF_NO
WHERE (app.APP_STATUS ='P' OR app.APP_STATUS ='T' OR
((app.APP_STATUS='R' OR app.APP_STATUS='S') AND STEP.STEP_NAME='011'));
</code></pre>
<p>Then I get the duplicate column name error. Why am I getting this error?</p> | 15,612,624 | 1 | 0 | null | 2013-03-25 10:23:00.41 UTC | null | 2017-02-06 20:29:23.97 UTC | 2017-02-06 20:29:23.97 UTC | null | 720,934 | null | 1,000,510 | null | 1 | 8 | sql|oracle11g | 45,657 | <p>you have two <code>product_type</code> columns:</p>
<pre><code>fac.PRODUCT_TYPE
</code></pre>
<p>and</p>
<pre><code>app.PRODUCT_TYPE
</code></pre>
<p>you should alias one of them eg</p>
<pre><code>app.PRODUCT_TYPE app_prod_type
</code></pre> |
5,343,778 | Getting a CSS element to automatically resize to content width, and at the same time be centered | <p>I have a CSS element, with a border around it, that could have one or multiple boxes in it, so the width of the entire div changes depending on how many boxes are present inside of it. However, I want this whole div to be centered on the screen.</p>
<p>Usually, to center things, I just use:</p>
<pre><code>margin-left: auto;
margin-right: auto;
</code></pre>
<p>But, this time, I have to either float the element or make it inline-block so the size of the div will be resized to the content, and if I do that, the margin-left and margin-right auto does not work, it always just stays on the left side of the screen.</p>
<p>Currently I have:</p>
<pre><code>#boxContainer {
display:inline-block;
clear:both;
border:thick dotted #060;
margin: 0px auto 10px auto;
}
</code></pre>
<p>I also tried with <code>float: left</code> instead of <code>display: inline-block</code>.</p>
<p>Does anyone know of a good way to both center a div and allow it to be resized to content simultaneously? Any help would be greatly appreciated.</p> | 5,343,821 | 2 | 1 | null | 2011-03-17 18:50:01.337 UTC | 6 | 2011-04-16 11:56:52.007 UTC | 2011-03-17 19:04:35.21 UTC | null | 20,578 | null | 622,846 | null | 1 | 15 | css|resize|center | 69,785 | <p>Have you tried keeping it inline-block, and putting it inside a block-level element that’s set to <code>text-align: center</code>?</p>
<p>E.g.</p>
<h3>HTML</h3>
<pre><code><div id="boxContainerContainer">
<div id="boxContainer">
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
</div>
</div>
</code></pre>
<h3>CSS</h3>
<pre><code>#boxContainerContainer {
background: #fdd;
text-align: center;
}
#boxContainer {
display:inline-block;
border:thick dotted #060;
margin: 0px auto 10px auto;
text-align: left;
}
#box1,
#box2,
#box3 {
width: 50px;
height: 50px;
background: #999;
display: inline-block;
}
</code></pre>
<p>Seems to work as you describe: <a href="http://jsfiddle.net/pauldwaite/pYaKB/" rel="noreferrer">http://jsfiddle.net/pauldwaite/pYaKB/</a></p> |
5,396,098 | how to parse a table from HTML using jsoup | <pre><code><td width="10"></td>
<td width="65"><img src="/images/sparks/NIFTY.png" /></td>
<td width="65">5,390.85</td>
<td width="65">5,428.15</td>
<td width="65">5,376.15</td>
<td width="65">5,413.85</td>
</code></pre>
<p>This is the HTML source from which i have to extract the values 5390.85,5428.15 , 5376.15 , 5413.85.
I wanted to do this using jsoup. But i am relatively new to jsoup( today i started using it). So how should i do this?</p>
<pre><code>URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url,3*1000);
String text = doc.body().text();
</code></pre>
<p>I have already extracted the content of the website using jsoup.
but how to extract the values i require?
Thanks in advance</p> | 5,396,838 | 2 | 1 | null | 2011-03-22 18:32:18.587 UTC | 10 | 2015-01-14 13:27:32.46 UTC | 2015-01-14 13:27:32.46 UTC | null | 1,138,559 | null | 640,739 | null | 1 | 24 | java|jsoup | 43,110 | <p>Try something like this:-</p>
<pre><code>URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url, 3000);
Element table = doc.select("table[class=niftyd]").first();
Iterator<Element> ite = table.select("td[width=65]").iterator();
ite.next(); // first one is image, skip it
System.out.println("Value 1: " + ite.next().text());
System.out.println("Value 2: " + ite.next().text());
System.out.println("Value 3: " + ite.next().text());
System.out.println("Value 4: " + ite.next().text());
</code></pre>
<p>Here's the printout:-</p>
<pre><code>Value 1: 5,390.85
Value 2: 5,428.15
Value 3: 5,376.15
Value 4: 5,413.85
</code></pre> |
16,400,810 | build-impl.xml:1031: The module has not been deployed | <p>I have been working on a Java web application and i am using <em>SmartGwt</em> on <em>Netbeans 7.3</em> and out of a sudden I encountered this problem. I tried cleaning the <code>build-impl.xml</code> then restarting the IDE and I should say I have fairly low knowledge on this. Can someone please tell me why it is giving an error and how I can fix that?</p>
<p>The error message says :</p>
<pre><code>nbproject/build-impl.xml:1031: The module has not been deployed. See the server log for details.
BUILD FAILED (total time: 4 seconds)
</code></pre>
<p>Note: i am using <em>Tomcat 7.0.34</em></p> | 16,575,263 | 10 | 0 | null | 2013-05-06 14:23:29.823 UTC | 5 | 2021-11-01 07:42:58.307 UTC | 2014-03-21 10:35:51.037 UTC | null | 876,739 | null | 2,274,311 | null | 1 | 11 | java|tomcat|web|netbeans-7 | 167,210 | <p>may its so late but the response useful for others so :
Sometimes, when you don't specify a server or servlet container at the
creation of the project, <em>NetBeans</em> fails to create a <code>context.xml</code> file. </p>
<ol>
<li>In your project under Web Pages, create a folder called <code>META-INF</code>. </li>
</ol>
<p>Do this by right mouse button clicking on Web pages, and select: </p>
<p><code>New->Other->Other->File Folder</code> </p>
<p>Name the folder <code>META-INF</code>. Case is important, even on Windows. </p>
<ol>
<li>Create a file called <code>context.xml</code> in the <code>META-INF</code> folder. </li>
</ol>
<p>Do this by right mouse button clicking on the new <code>META-INF</code> folder, and
select: </p>
<p><code>New->Other->XML->XML</code> Document </p>
<p>Name it context (NetBeans adds the <code>.xml</code>)
Select Well-formed Document
Press Finish </p>
<ol>
<li><p>Edit the new document (<code>context.xml</code>), and add the following: </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/app-name"/>
</code></pre></li>
</ol>
<p>Replace app-name with the name of your application.</p>
<p>Now your in-place deployment should work. If not, make sure that the
file can be read by everyone. </p>
<p>The <code>context.xml</code> file is specific to Tomcat. For more information about
that file, see the Tomcat documentation at <code>tomcat.apache.org</code>. </p> |
149,646 | Best way to make NSRunLoop wait for a flag to be set? | <p>In the Apple documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run" rel="noreferrer">NSRunLoop</a> there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.</p>
<pre><code>BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
</code></pre>
<p>I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a <code>NSLog</code> on the line after the flag is being set (in another method) and then a line after the <code>while()</code> there is a seemingly random wait between the two log statements of several seconds.</p>
<p>The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.</p>
<p>I have worked around this issue with the following code but it does not seem right that the original code doesn't work.</p>
<pre><code>NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil])
loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
</code></pre>
<p>using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.</p>
<p>Anyone any ideas why the original code exhibits this behaviour?</p> | 150,302 | 7 | 1 | null | 2008-09-29 17:00:58.16 UTC | 37 | 2013-12-30 13:27:27.97 UTC | 2008-11-09 21:51:18.203 UTC | Ned Batchelder | 14,343 | Dave Verwer | 4,496 | null | 1 | 40 | objective-c|cocoa|macos | 52,086 | <p>Runloops can be a bit of a magic box where stuff just happens.</p>
<p>Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit.</p>
<p>With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event.</p>
<p>With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind.</p>
<p>A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP. </p>
<p>You might want to play around with runloop observers so you can see exactly what the runloop is doing.</p>
<p>See <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW22" rel="noreferrer">this Apple doc</a> for more information.</p> |
217,655 | Using Entity Framework entities as business objects? | <p>I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects.
Is this OK? Please state your cons or pros. What to do in a case of WCF communication between business layer and presentation, how to send those objects as data members?</p> | 218,311 | 7 | 0 | null | 2008-10-20 06:34:59.617 UTC | 24 | 2011-07-01 02:58:46.647 UTC | 2008-10-20 12:59:44.567 UTC | John Topley | 1,450 | Aleksandar | 29,511 | null | 1 | 57 | .net|entity-framework|architecture | 26,596 | <p>I am using EF in this fashion and one nice feature is that generated entities are partial classes, allowing them to be extended in a way that is fairly protected from regeneration issues.</p>
<p>Also take a look at <a href="http://msdn.microsoft.com/en-us/library/cc716789.aspx" rel="noreferrer">this link on MSDN</a> which describes some common usage scenarios with EF in regards to Business Logic.</p> |
279,854 | How do I sort a vector of pairs based on the second element of the pair? | <p>If I have a vector of pairs:</p>
<pre><code>std::vector<std::pair<int, int> > vec;
</code></pre>
<p>Is there and easy way to sort the list in <strong>increasing</strong> order based on the second element of the pair?</p>
<p>I know I can write a little function object that will do the work, but is there a way to use existing parts of the <em>STL</em> and <code>std::less</code> to do the work directly?</p>
<p>EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:</p>
<pre><code>std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
</code></pre> | 279,878 | 7 | 3 | null | 2008-11-11 02:41:23.187 UTC | 76 | 2021-04-05 18:08:12.257 UTC | 2020-08-24 09:36:21.377 UTC | David Norman | 1,465,553 | David Norman | 34,502 | null | 1 | 146 | c++|stl|stdvector | 164,014 | <p><strong>EDIT</strong>: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type <code>auto</code>. <strong>This is my current favorite solution</strong></p>
<pre><code>std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
</code></pre>
<hr />
<p><strong>ORIGINAL ANSWER</strong>:</p>
<p>Just use a custom comparator (it's an optional 3rd argument to <code>std::sort</code>)</p>
<pre><code>struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
</code></pre>
<p>If you're using a C++11 compiler, you can write the same using lambdas:</p>
<pre><code>std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
</code></pre>
<p><strong>EDIT</strong>: in response to your edits to your question, here's some thoughts ...
if you <strong>really</strong> wanna be creative and be able to reuse this concept a lot, just make a template:</p>
<pre><code>template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
</code></pre>
<p>then you can do this too:</p>
<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
</code></pre>
<p>or even</p>
<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
</code></pre>
<p>Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P</p> |
1,190,600 | Retrieving the COM class factory for component error while generating word document | <p>I am trying to edit a word document from VB.NET using for the most part this code:</p>
<p><strong>How to automate Word from Visual Basic .NET to create a new document</strong>
<a href="http://support.microsoft.com/kb/316383" rel="nofollow noreferrer">http://support.microsoft.com/kb/316383</a></p>
<p>It works fine on my machine but when i publish to the server i get the following error.</p>
<blockquote>
<p>Retrieving the COM class factory for
component with CLSID
{000209FF-0000-0000-C000-000000000046}
failed due to the following error:
80070005.</p>
<p><strong>Description:</strong> An unhandled exception occurred during the
execution of the current web request.
Please review the stack trace for more
information about the error and where
it originated in the code.</p>
<p><strong>Exception Details:</strong> System.UnauthorizedAccessException:
Retrieving the COM class factory for
component with CLSID
{000209FF-0000-0000-C000-000000000046}
failed due to the following error:
80070005.</p>
</blockquote>
<p>The actual error happens when i try to just create a word application object</p>
<pre><code> Dim oWord As New Word.Application
</code></pre>
<p>Using Visual Studio 2008 and VB.NET 3.5. I made a reference to the "Microsoft Word 10.0 Object Library" and i see Interop.Word.dll file in the bin directory. </p>
<p>Using MS Office 2003 on development machine and Windows Server 2003</p>
<p>Still fairly new to .NET and don't have much knowledge about window server, but "UnauthorizedAccessException" sounds like a permission issue. I'm wondering if someone could point me in the right direction on what i might need to do to give my little application access to use word. </p> | 1,190,759 | 8 | 0 | null | 2009-07-27 21:06:12.193 UTC | 3 | 2014-12-12 04:40:23.51 UTC | 2012-12-07 11:38:20.503 UTC | null | 213,550 | null | 145,954 | null | 1 | 8 | asp.net|com|ms-word | 43,711 | <p>It definitely sounds like a permissions problem. Are you running your code in a windows service? The service normally runs as Local System, which may not have permission to access the Word object model. Additionally, if word is already running using the credentials of some other user then your program may not be able to access it via COM using different credentials. The office applications tend to be single instance which seems to exacerbate this problem.</p> |
900,055 | Is SQL or even TSQL Turing Complete? | <p>This came up at the office today. I have no plans of doing such a thing, but theoretically could you write a compiler in SQL? At first glance it appears to me to be turing complete, though extremely cumbersome for many classes of problems. </p>
<p>If it is not turing complete, what would it require to become so?</p>
<p>Note: I have no desire to do anything like write a compiler in SQL, I know it would be a silly thing to do, so if we can avoid that discussion I would appreciate it.</p> | 7,580,013 | 8 | 0 | null | 2009-05-22 21:21:37.927 UTC | 66 | 2022-04-08 21:36:42.88 UTC | null | null | null | null | 100,930 | null | 1 | 208 | sql|tsql|programming-languages|language-features | 88,251 | <p>It turns out that SQL can be Turing Complete even without a true 'scripting' extension such as PL/SQL or PSM (which are designed to be true programming languages, so that's kinda cheating).</p>
<p>In <a href="http://assets.en.oreilly.com/1/event/27/High%20Performance%20SQL%20with%20PostgreSQL%20Presentation.pdf" rel="noreferrer">this set of slides</a> Andrew Gierth proves that with CTE and Windowing SQL is Turing Complete, by constructing a <a href="http://mathworld.wolfram.com/CyclicTagSystem.html" rel="noreferrer">cyclic tag system</a>, which has been proved to be Turing Complete. The CTE feature is the important part however -- it allows you to create named sub-expressions that can refer to themselves, and thereby recursively solve problems.</p>
<p>The interesting thing to note is that CTE was not really added to turn SQL into a programming language -- just to turn a declarative querying language into a more powerful declarative querying language. Sort of like in C++, whose templates turned out to be Turing complete even though they weren't intended to create a meta programming language.</p>
<p>Oh, the <a href="http://wiki.postgresql.org/wiki/Mandelbrot_set" rel="noreferrer">Mandelbrot set in SQL</a> example is very impressive, as well :)</p> |
409,688 | Multithreaded paranoia | <p>This is a complex question, please consider carefully before answering.</p>
<p>Consider this situation. Two threads (a reader and a writer) access a single global <code>int</code>. Is this safe? Normally, I would respond without thought, yes!</p>
<p>However, it seems to me that Herb Sutter doesn't think so. In his articles on effective concurrency he discusses a <a href="http://www.ddj.com/cpp/210600279" rel="nofollow noreferrer">flawed lock-free queue</a> and the <a href="http://www.ddj.com/hpc-high-performance-computing/210604448" rel="nofollow noreferrer">corrected version</a>.</p>
<p>In the end of the first article and the beginning of the second he discusses a rarely considered trait of variables, write ordering. Int's are atomic, good, but ints aren't necessarily ordered which could destroy any lock-free algorithm, including my above scenario. I fully agree that the only way to <strong><em>guarantee</em></strong> correct multithreaded behavior on all platforms present and future is to use atomics(AKA memory barriers) or mutexes.</p>
<p>My question; is write re-odering ever a problem on real hardware? Or is the multithreaded paranoia just being pedantic?<br>
What about classic uniprocessor systems?<br>
What about simpler RISC processors like an embedded power-pc?</p>
<p><em>Clarification</em>: I'm more interested in what Mr. Sutter said about the hardware (processor/cache) reordering variable writes. I can stop the optimizer from breaking code with compiler switches or hand inspection of the assembly post-compilation. However, I'd like to know if the hardware can still mess up the code in practice.</p> | 409,715 | 9 | 4 | null | 2009-01-03 19:42:32.537 UTC | 8 | 2010-11-02 18:35:41.69 UTC | 2010-11-02 18:35:41.69 UTC | JesperE | 28,817 | Caspin | 28,817 | null | 1 | 29 | c++|c|multithreading|hardware | 2,063 | <p>Your idea of inspecting the assembly is not good enough; the reordering can happen at the hardware level.</p>
<p>To answer your question "is this ever a problem on read hardware:" <strong>Yes!</strong> In fact I've run into that problem myself.</p>
<p>Is it OK to skirt the issue with uniprocessor systems or other special-case situations? I would argue "no" because five years from now you might need to run on multi-core after all, and then finding all these locations will be tricky (impossible?).</p>
<p>One exception: Software designed for embedded hardware applications where indeed you have completely control over the hardware. In fact I have "cheated" like this in those situations on e.g. an ARM processor.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.