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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57,475,342 | wrapper.find with id in enzyme and jest doesn't find element | <p>I'm new to Jest and Enzyme testing, and I would like to know why the find function is not working with id.</p>
<p>//html from react, just the code where is the id increment</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-html lang-html prettyprint-override"><code><div className="App-body">
<div className="changePage">
<button className="Selections" onClick={this.decrementPage}>Previous</button>
<p className="changePageNumber">{this.state.page}</p>
<button className="Selections" id="increment" onClick={this.incrementPage}>Next</button>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>//test</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>it('next page', () => {
const wrapper = shallow(<Home />)
const incrementPage = wrapper.find('#increment')
incrementPage.simulate('click')
const countState = wrapper.state().page
expect(countState).toEqual(2)
})</code></pre>
</div>
</div>
</p>
<pre><code>Method “simulate” is meant to be run on 1 node. 0 found instead.
</code></pre>
<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>25 | //const text = wrapper.find('p').text()
26 | const incrementPage = wrapper.find('#increment')
> 27| incrementPage.simulate('click')
| ^ </code></pre>
</div>
</div>
</p> | 57,475,417 | 1 | 2 | null | 2019-08-13 09:56:39.173 UTC | 2 | 2019-08-13 11:28:56.973 UTC | 2019-08-13 11:28:56.973 UTC | null | 7,470,360 | null | 11,921,695 | null | 1 | 14 | reactjs|jestjs|enzyme | 52,193 | <p>Try using <code>mount</code> instead of <code>shallow</code>. <code>shallow</code> does not render beyond the first level of elements. In your case, only the div with className 'App-Body' is rendered</p> |
7,460,654 | How were graphical DOS Games written? | <p>I always wondered how the DOS games like <a href="http://www.dosgamesarchive.com/download/skyroads/" rel="noreferrer">Sky Roads</a>, <a href="http://www.dosgamesarchive.com/download/turbo/" rel="noreferrer">Turbo</a>, <a href="http://www.abandonia.com/en/games/2/Aladdin.html" rel="noreferrer">Aladdin</a>, <a href="http://www.dosgamesarchive.com/download/duke-nukem/" rel="noreferrer">Duke Nukem</a>, <a href="http://www.dosgamesarchive.com/download/commander-keen-6-aliens-ate-my-baby-sitter/" rel="noreferrer">Commander Keen 6</a> were written. I cannot find a good source. If I write a console application in C#, C++, Java etc.. It is always displayed and remains still. And it is always Text.</p>
<ol>
<li>How did they generate graphics?</li>
<li>Were there any libraries to use?</li>
<li>What languages they used?</li>
</ol>
<p>Any good source will be appreciated. </p> | 7,460,665 | 4 | 8 | null | 2011-09-18 09:38:03.143 UTC | 16 | 2019-10-15 19:48:38.46 UTC | 2011-09-18 09:43:26.15 UTC | user142019 | null | null | 337,504 | null | 1 | 33 | graphics|dos | 26,211 | <p>Assembler, Pascal and C were popular languages. Graphics were generated by directly interfacing with the display hardware, for instance the <a href="http://www.seasip.info/VintagePC/cga.html" rel="noreferrer">Color Graphics Adapter</a>. (<a href="http://www.seasip.info/VintagePC/cga.html" rel="noreferrer">CGA</a>)</p>
<p>Probably there were libraries, but not like today, and libraries were often not shared outside a company.</p>
<p>A resource which would have been relevant in say, 1988, can be found here: </p>
<p><a href="https://web.archive.org/web/20170910230837/http://gd.tuwien.ac.at/languages/c/programming-bbrown/advcw1.htm" rel="noreferrer">https://web.archive.org/web/20170910230837/http://gd.tuwien.ac.at/languages/c/programming-bbrown/advcw1.htm</a></p> |
7,347,386 | Get the difference between two lists using LINQ | <p>I have two lists and I need to compare them and only return a List of Items not in both.</p>
<pre><code>var listOfIds = new List<int> {1,2,4};
var persons = new ObservableCollection<Person>
{
new Person {Id = 1, Name = "Person 1"},
new Person {Id = 2, Name = "Person 2"},
new Person {Id = 3, Name = "Person 3"},
new Person {Id = 4, Name = "Person 4"}
};
</code></pre>
<p>In this example <code>new Person {Id = 3, Name = "Person 3"}</code> would be the result.
A Linq solution would be preferred.</p> | 7,347,402 | 4 | 0 | null | 2011-09-08 11:33:03.097 UTC | 2 | 2021-10-22 15:27:58.067 UTC | 2016-03-04 10:33:38.407 UTC | null | 42,841 | null | 363,274 | null | 1 | 35 | c#|.net|linq|list | 58,251 | <p>not in will work for you</p>
<pre><code>var listOfIds = new List<int> {1,2,4};
var query = from item in persons
where !listOfIds .Contains( item.id )
select item;
</code></pre>
<p>You can check for more detail : <a href="https://stackoverflow.com/questions/3047657/linq-to-sql-in-and-not-in">SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)</a> </p> |
7,438,112 | Disable IPython Exit Confirmation | <p>It's really irritating that every time I type <code>exit()</code>, I get prompted with a confirmation to exit; of course I want to exit! Otherwise, I would not have written <code>exit()</code>!!!</p>
<p>Is there a way to override IPython's default behaviour to make it exit without a prompt?</p> | 8,020,342 | 4 | 1 | null | 2011-09-15 22:21:16.57 UTC | 22 | 2017-07-17 03:35:28.66 UTC | 2013-03-01 22:03:08.523 UTC | null | 431,369 | null | 128,967 | null | 1 | 120 | python|ipython | 10,998 | <p>If you also want <code>Ctrl-D</code> to exit without confirmation, in IPython 0.11, add <code>c.TerminalInteractiveShell.confirm_exit = False</code> to your config file *.</p>
<p>If you don't have a config file yet, run <code>ipython profile create</code> to create one.</p>
<p>Note <a href="https://code.djangoproject.com/ticket/17078" rel="noreferrer">this ticket</a> if you're working within the Django shell.</p>
<hr>
<p>* The config file is located at: <code>$HOME/.ipython/profile_default/ipython_config.py</code></p> |
24,232,892 | Spring boot and SQLite | <p>I am trying to use SQLite with a Spring Boot app. I am aware of the awesome support in Spring Boot with for example MongoDB. But i cannot find a way to use Spring Boot with SQLite? Any suggestion where or how to start with using Spring Boot and SQLite??</p> | 24,233,241 | 2 | 1 | null | 2014-06-15 18:41:41.163 UTC | 16 | 2018-05-28 20:20:50.503 UTC | null | null | null | null | 185,432 | null | 1 | 35 | spring|sqlite|spring-boot | 53,686 | <p>Spring Boot doesn't work out of the box with SQLite (as it does for example with H2, HSQL or Apache Derby - any of which which I would suggest you use instead of SQLite). </p>
<p>First of all you need to override the data source to specify you SQLite data souce.
Use the following code in your configuration (uses <code>DataSourceBuilder</code> which was introduced in Spring Boot 1.1.0.M2)</p>
<pre><code>@Bean
public DataSource dataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.sqlite.JDBC");
dataSourceBuilder.url("jdbc:sqlite:your.db");
return dataSourceBuilder.build();
}
</code></pre>
<p>Then you need to create an SQLiteDialect because Hibernate does not already have one (based on the code from <a href="https://gist.github.com/virasak/54436" rel="noreferrer">here</a> but adapted for Hibernate 4)</p>
<pre><code>package your.package
import java.sql.Types;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.Hibernate;
import org.hibernate.type.StringType;
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
registerFunction( "mod", new SQLFunctionTemplate( StringType.INSTANCE, "?1 % ?2" ) );
registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE) );
}
public boolean supportsIdentityColumns() {
return true;
}
/*
public boolean supportsInsertSelectIdentity() {
return true; // As specify in NHibernate dialect
}
*/
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
public String appendIdentitySelectToInsert(String insertString) {
return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
append(insertString).
append("; ").append(getIdentitySelectString()).
toString();
}
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length()+20).
append(query).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
}
</code></pre>
<p>Finally in <code>application.properties</code> override the following settings</p>
<pre><code>spring.jpa.database-platform=your.package.SQLiteDialect
spring.jpa.hibernate.ddl-auto=create-drop
</code></pre>
<p>The first setting is needed in order for Spring Boot to inform Hibernate that it should use the SQLiteDialect that was created above.</p> |
24,202,473 | Does a sequential stream in Java 8 use the combiner parameter on calling collect? | <p>If I call collect on a sequential stream (eg. from calling Collection.stream()) then will it use the combiner parameter I pass to collect? I presume not but I see nothing in the documentation. If I'm correct, then it seems unfortunate to have to supply something that I know will not be used (if I know it is a sequential stream).</p> | 24,207,431 | 1 | 2 | null | 2014-06-13 09:49:32.39 UTC | 7 | 2014-07-18 14:20:53.343 UTC | 2014-07-18 14:20:53.343 UTC | null | 1,441,122 | null | 304,874 | null | 1 | 30 | java|java-8|java-stream | 5,454 | <p>Keep in mind to develop against interface specifications -- not against the implementation. The implementation might change with the next Java version, whereas the specification should remain stable.</p>
<p>The specification does not differentiate between sequential and parallel streams. For that reason, you should assume, that the <em>combiner</em> might be used. Actually, there are good examples showing that <em>combiners</em> for sequential streams can improve the performance. For example, the following <em>reduce</em> operation concatenates a list of strings. Executing the code without <em>combiner</em> has quadratic complexity. A smart execution with <em>combiner</em> can reduce the runtime by magnitudes.</p>
<pre><code>List<String> tokens = ...;
String result = tokens.stream().reduce("", String::concat, String::concat);
</code></pre> |
2,201,571 | How to prepend an element to an array in Powershell? | <p>The Powershell code:</p>
<pre><code>$list += "aa"
</code></pre>
<p>appends the element "aa" to the list $list. Is there a way to prepend an element? This is my solution, but there must be a way to do this in a single line.</p>
<pre><code>$tmp = ,"aa";
$tmp += $list
$list = $tmp
</code></pre> | 2,201,722 | 4 | 0 | null | 2010-02-04 17:00:53.503 UTC | 1 | 2018-04-16 06:16:50.823 UTC | 2010-02-04 17:13:56.347 UTC | null | 122,732 | null | 122,732 | null | 1 | 29 | powershell | 22,591 | <p>In your example above, you should just be able to do:</p>
<pre><code>$list = ,"aa" + $list
</code></pre>
<p>That will simply prepend "aa" to the list and make it the 0th element. Verify by getting <code>$list[0]</code>.</p> |
10,723,451 | What's the one-level sequence flattening function in Clojure? | <p>What's the one-level sequence flattening function in Clojure? I am using <code>apply concat</code> for now, but I wonder if there is a built-in function for that, either in standard library or clojure-contrib.</p> | 10,735,005 | 3 | 2 | null | 2012-05-23 15:43:08.107 UTC | 5 | 2019-05-02 05:37:45.023 UTC | null | null | null | null | 192,247 | null | 1 | 41 | clojure|functional-programming | 10,716 | <p>My general first choice is <code>apply concat</code>. Also, don't overlook <code>(for [subcoll coll, item subcoll] item)</code> -- depending on the broader context, this may result in clearer code.</p> |
7,041,292 | Launch new activity from PreferenceActivity | <p>Good day, friends.
I have a PreferenceActivity, it is filled from XML file.
When we press one item, we should launch new activity. How to do it? What should I write in XML-file or in the Java-class?</p> | 7,041,564 | 5 | 0 | null | 2011-08-12 14:08:34.623 UTC | 15 | 2014-11-21 04:03:55.347 UTC | null | null | null | null | 874,547 | null | 1 | 37 | android|android-activity|android-preferences|preferenceactivity | 26,195 | <p>After you add preferences using</p>
<pre><code>addPreferencesFromResource(R.xml.preferences);
</code></pre>
<p>find your preference that you want to set onClick using</p>
<pre><code>findPreference("foo_bar_pref");
</code></pre>
<p>and define it by casting like</p>
<pre><code>Preference fooBarPref = (Preference) findPreference("foo_bar_pref");
</code></pre>
<p>Then you can easily set its onClick using</p>
<pre><code>fooBarPref.setOnPreferenceClickListener (new OnPreferenceClickListener()){...}
</code></pre>
<p>You can start your new Activity (using an Intent) inside that listener.</p> |
7,173,691 | replacing div content with javascript | <p>I'm trying to do this with pure javascript, not with jquery. I have a div that has an id <code>test</code> and contains other divs inside it. How do I empty the content of this div and replace it with other html?</p>
<pre><code><div id="test">
<div>...</div>
<div>...</div>
<div>...</div>
</div>
</code></pre> | 7,173,726 | 6 | 0 | null | 2011-08-24 10:09:02.933 UTC | 8 | 2014-07-02 14:02:50.82 UTC | null | null | null | null | 710,316 | null | 1 | 46 | javascript | 112,876 | <pre><code>document.getElementById("test").innerHTML = "new content"
</code></pre> |
7,585,307 | How to correct TypeError: Unicode-objects must be encoded before hashing? | <p>I have this error:</p>
<pre><code>Traceback (most recent call last):
File "python_md5_cracker.py", line 27, in <module>
m.update(line)
TypeError: Unicode-objects must be encoded before hashing
</code></pre>
<p>when I try to execute this code in <strong>Python 3.2.2</strong>:</p>
<pre><code>import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides? ")
wordlist = input("What is your wordlist? (Enter the file name) ")
try:
hashdocument = open(hash_file, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
hash = hashdocument.readline()
hash = hash.replace("\n", "")
try:
wordlistfile = open(wordlist, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
pass
for line in wordlistfile:
# Flush the buffer (this caused a massive problem when placed
# at the beginning of the script, because the buffer kept getting
# overwritten, thus comparing incorrect hashes)
m = hashlib.md5()
line = line.replace("\n", "")
m.update(line)
word_hash = m.hexdigest()
if word_hash == hash:
print("Collision! The word corresponding to the given hash is", line)
input()
sys.exit()
print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()
</code></pre> | 7,585,378 | 10 | 1 | null | 2011-09-28 15:04:48.06 UTC | 48 | 2021-01-14 15:19:09.313 UTC | 2019-05-23 17:52:00.203 UTC | null | 4,304,503 | null | 906,738 | null | 1 | 439 | python|python-3.x|unicode|syntax-error|hashlib | 516,946 | <p>It is probably looking for a character encoding from <code>wordlistfile</code>.</p>
<pre><code>wordlistfile = open(wordlist,"r",encoding='utf-8')
</code></pre>
<p>Or, if you're working on a line-by-line basis:</p>
<pre><code>line.encode('utf-8')
</code></pre>
<hr />
<h2>EDIT</h2>
<p>Per the comment below and <a href="https://stackoverflow.com/a/22644618/57191">this answer</a>.</p>
<p>My answer above assumes that the desired output is a <code>str</code> from the <code>wordlist</code> file. If you are comfortable in working in <code>bytes</code>, then you're better off using <code>open(wordlist, "rb")</code>. But it is important to remember that your <code>hashfile</code> should <em>NOT</em> use <code>rb</code> if you are comparing it to the output of <code>hexdigest</code>. <code>hashlib.md5(value).hashdigest()</code> outputs a <code>str</code> and that cannot be directly compared with a bytes object: <code>'abc' != b'abc'</code>. (There's a lot more to this topic, but I don't have the time ATM).</p>
<p>It should also be noted that this line:</p>
<pre><code>line.replace("\n", "")
</code></pre>
<p>Should probably be</p>
<pre><code>line.strip()
</code></pre>
<p>That will work for both bytes and str's. But if you decide to simply convert to <code>bytes</code>, then you can change the line to:</p>
<pre><code>line.replace(b"\n", b"")
</code></pre> |
14,190,410 | Implementing one to one and group chat in android | <p>I am developing an Android app in which I have to implement <strong>chat messaging</strong>. I would like <strong>one to one chat</strong> or <strong>a group chat</strong>. </p>
<p>But I have no idea how to start. Please help me with this stuff. Any help will be appreciated.</p> | 14,190,579 | 2 | 0 | null | 2013-01-07 05:31:41.2 UTC | 11 | 2014-01-08 00:15:30.043 UTC | 2013-01-07 05:51:36.84 UTC | null | 57,611 | user1025050 | null | null | 1 | 14 | android|chat | 16,611 | <p>A simple chat mechanism will have 2 basic functionalities</p>
<ol>
<li><p>Send the message to server (with info about the recipient)</p></li>
<li><p>Receive the message from server (designated for my user name)</p></li>
</ol>
<p>First step is simple, we can create a web service which will accept the message with additional information about recipient(s). We can create it using any server side language.</p>
<p>Step 2, that is fetching the message from server can be done using 2 techniques, Pull the message (using polling) from server, or Push the message from server to android phone</p>
<ol>
<li><p>Polling: In this, the android device will keep accessing server after a few seconds to check if there is a message available for user. This again can be implemented using a simple async task at the client side which will keep calling a web service after say 2-3 seconds. This is fine to use if we are planning to enable chatting only when user is accessing the app (no notifications like gmail or facebook), so that we can kill the polling service when not in use (otherwise it will eat up resources).</p></li>
<li><p>Push notifications: a better option is to use push notifications. Android provide Google cloud messaging or GCM (<a href="http://developer.android.com/google/gcm/index.html" rel="noreferrer">http://developer.android.com/google/gcm/index.html</a>) which will help achieve push from server easily. Otherwise you can try a third party API like urbanairship or pushwoosh depending on your requirement. Push notifications will help the user to receive messages even when he is not using the app.</p></li>
</ol>
<p>So in nutshell, a webservice to receive the messages and a push notification mechanism should be sufficient to implement a chat service in android.</p>
<p>Little bit about UrbanAirship</p>
<p>I used UA in one of my projects for push notifications as I needed to support both iOS and Android. If you just want to support Android GCM might also be a good option. </p>
<p>Coming back to UA, check this for sample code and usage: <a href="https://docs.urbanairship.com/display/DOCS/Home" rel="noreferrer">https://docs.urbanairship.com/display/DOCS/Home</a></p>
<p>The way it works is simple, when someone installs the app and is connected to internet, app registers itself to the UA service. A unique code is specified for each installed app (this is the time when you can capture the user name and unique code and store somewhere in your DB). Next UA provides an API using which you can push a message to designated recipient(s), using the unique codes which are available with UA. These messages can be received by android app and used as per the requirement. Even if the app is not running we can show a notification just like when we receive an email or a message </p> |
13,959,048 | Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8' | <p>Simplest example of this, I get a collection and try to output it via Web API:</p>
<pre><code>// GET api/items
public IEnumerable<Item> Get()
{
return MyContext.Items.ToList();
}
</code></pre>
<p>And I get the error:</p>
<blockquote>
<p>Object of type
<br>'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]'
cannot be converted to type
<br>'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'</p>
</blockquote>
<p>This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:</p>
<pre><code>MyContext.Configuration.ProxyCreationEnabled = false;
</code></pre>
<p>But that defeats the purpose of a lot of what I am trying to do. Is there a better way?</p> | 23,372,600 | 11 | 3 | null | 2012-12-19 18:48:20.207 UTC | 11 | 2022-04-01 06:31:47.903 UTC | 2017-01-25 18:19:09.023 UTC | null | 1,704,458 | null | 14,777 | null | 1 | 40 | entity-framework|entity-framework-4|asp.net-web-api | 53,550 | <p>I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...</p>
<pre><code> [HttpGet]
[WithDbContextApi]
public HttpResponseMessage Get(int take = 10, int skip = 0)
{
CurrentDbContext.Configuration.ProxyCreationEnabled = false;
var lista = CurrentDbContext.PaymentTypes
.OrderByDescending(x => x.Id)
.Skip(skip)
.Take(take)
.ToList();
var count = CurrentDbContext.PaymentTypes.Count();
return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
}
</code></pre>
<p>Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case .
Hope it helps</p> |
14,199,784 | Convert CSV file into array of hashes | <p>I have a csv file, some hockey stats, for example:</p>
<pre><code>09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5
</code></pre>
<p>I want to save them in an array of hashes. I don't have any headers and I would like to add keys to each value like <code>"time" => "09.09.2008"</code> and so on. Each line should by accessible like <code>arr[i]</code>, each value by for example <code>arr[i]["time"]</code>. I prefer <code>CSV</code> class rather than <code>FasterCSV</code> or <code>split</code>. Can you show the way or redirect to some thread where a similar problem was solved?</p> | 14,199,962 | 9 | 2 | null | 2013-01-07 16:17:06.77 UTC | 10 | 2022-07-20 14:36:00.723 UTC | 2013-01-07 16:22:25.1 UTC | null | 314,166 | null | 1,955,522 | null | 1 | 64 | ruby|csv|multidimensional-array | 63,933 | <p>You can use the <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html">Ruby CSV parser</a> to parse it, and then use <code>Hash[ keys.zip(values) ]</code> to make it a hash.</p>
<p>Example:</p>
<pre><code>test = '''
09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5
'''.strip
keys = ['time', etc... ]
CSV.parse(test).map {|a| Hash[ keys.zip(a) ] }
</code></pre> |
14,130,184 | Storyboard uiviewcontroller, 'custom class' not showing in drop down | <p>I have a UIViewController I created in my apps storyboard, as well as a custom UIViewController subclass which I added to the project (and is correctly in the compile phase for my target). However when I go to set the 'Custom Class' property on the view-controller in Storyboard my custom class does not show up on the list.</p>
<ul>
<li>Checked that the class is part of my app's target, not tests'</li>
<li>Double checked that it is correctly a subclass of UIViewController</li>
<li>Compiled program just to make sure xcode was working with latest information</li>
<li>Restarted xcode</li>
</ul>
<p>What would cause my class to not show up in the 'Custom Class' drop down?</p> | 14,149,459 | 26 | 0 | null | 2013-01-02 22:22:59.707 UTC | 12 | 2021-12-24 07:50:52.097 UTC | null | null | null | null | 875,693 | null | 1 | 65 | ios|storyboard | 63,964 | <p>Two ways I found that solve the problem but they are work arounds:-</p>
<ol>
<li>Just type the view controllers name in the text field, or</li>
<li>close the project and then reopen it and in the project initialization it places the file on the list.</li>
</ol> |
47,272,178 | From where is my php.ini being loaded in php Docker container? | <p>I am running this <a href="https://github.com/docker-library/php/blob/bfe27759103fa6050601060165409b5b3be06395/5.6/jessie/apache/Dockerfile" rel="noreferrer">Docker instance of a linux debian:jessie</a> with php 5.6.</p>
<p>This is part of my phpinfo :</p>
<p><a href="https://i.stack.imgur.com/tP2i2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tP2i2.png" alt="enter image description here"></a></p>
<p>As we can see the <code>php.ini</code> should be located at </p>
<pre><code>/usr/local/etc/php
</code></pre>
<p>And this is what I have inside /usr/local/etc/</p>
<p><a href="https://i.stack.imgur.com/KqzKI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KqzKI.png" alt="enter image description here"></a></p>
<p>But there is no php.ini inside it.</p>
<p>I the other hand, I have the php.ini inside</p>
<p><a href="https://i.stack.imgur.com/dRlvY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dRlvY.png" alt="enter image description here"></a></p>
<p>So, from where exactly is my php.ini being loaded?</p>
<p>We dont even have a php process running but the php seems to be ok - being displayed phpinfo in the screen.</p>
<p><a href="https://i.stack.imgur.com/GVlT5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GVlT5.png" alt="enter image description here"></a> </p> | 47,272,568 | 5 | 4 | null | 2017-11-13 19:36:56.503 UTC | 4 | 2021-12-30 17:06:40.147 UTC | 2021-10-11 10:34:19.397 UTC | null | 14,032,355 | null | 3,788,767 | null | 1 | 18 | php|docker|ini | 61,392 | <p>Let try it as an answer:</p>
<p>It does not exist at all, which means php will run the default options.</p>
<p>Look at your docker file, it starts from a "clean" OS, installs Apache and PHP in it. But it never copies the php.ini file from the PHP installation into <code>/usr/local/etc/php</code>. Actually in lines 31 and 32 it creates the conf.d directory but that is it.</p>
<p>So I would suggest, at the end of your docker file, add code to copy <code>php.ini-production</code> to <code>/usr/local/etc/php.ini</code>, and edits as required. Or use default options.</p> |
43,070,702 | TypeScript Unexpected token, A constructor, method, accessor or property was expected | <p>Just trying to write a function within a class using typescript.</p>
<pre><code>class Test
{
function add(x: number, y: number): number {
return x + y;
}
}
</code></pre>
<p>This results in the following error:</p>
<blockquote>
<p>TypeScript Unexpected token, A constructor, method, accessor or
property was expected.</p>
</blockquote>
<p>I copied the example from: <a href="https://www.typescriptlang.org/docs/handbook/functions.html" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/functions.html</a></p>
<p>Am I missing something? I'm confused!</p> | 43,070,783 | 3 | 2 | null | 2017-03-28 13:18:37.58 UTC | 6 | 2021-12-22 15:53:10.613 UTC | 2017-03-28 13:29:22.297 UTC | null | 289,319 | null | 6,409,584 | null | 1 | 29 | javascript|typescript|ecmascript-6|es6-class | 94,709 | <p>You shouldn't use the <code>function</code> keyword in a Typescript class definition. Try this instead:</p>
<pre><code>class Test {
add(x: number, y: number): number {
return x + y;
}
}
</code></pre> |
9,507,829 | simple intro java game programming | <p>My question is where did i go wrong. it is supposed to make a frame where i can control an oval, move it around back forth left and right, and then make it move with the arrows. but right now i cant even make the oval, or even insert a word into it.</p>
<pre><code>import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class JavaGame extends JFrame{
int x, y;
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode ==e.VK_LEFT){
x--;
}
if(keyCode ==e.VK_RIGHT){
x++;
}
if(keyCode ==e.VK_DOWN){
y--;
}
if(keyCode==e.VK_UP){
y++;
}
}
public void keyReleased(KeyEvent e){
}
}
public JavaGame (){
addKeyListener(new AL());
setTitle("Game");
setSize(250,250);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void Paint(Graphics g){
x = 150;
y = 150;
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] Args){
new JavaGame();
}
}
</code></pre> | 9,507,866 | 2 | 1 | null | 2012-02-29 22:42:02.777 UTC | null | 2020-12-10 01:26:09.777 UTC | null | null | null | null | 1,241,388 | null | 1 | 0 | java | 55,170 | <p>Probably because <code>Paint</code> isn't a standard Java <code>paint</code> method. I don't see anything resembling an event loop, either--have you considered checking out any Swing tutorials/etc.?</p> |
44,455,001 | How to change pip3 command to be pip? | <p>I uninstalled <code>pip</code>, and I installed <code>pip3</code> instead. Now, I want to use <code>pip3</code> by typing <code>pip</code> only. The reason is I am used to type <code>pip</code> only and every guide uses the <code>pip</code> command, so every time I want to copy and paste commands, I have to modify <code>pip</code> to <code>pip3</code> which wastes time. When I type <code>pip</code> I have an error which is <code>pip: command not found</code> which means <code>pip</code> command is not taken. Is it possible to make <code>pip</code> points to <code>pip3</code>?</p> | 44,455,078 | 10 | 3 | null | 2017-06-09 10:07:17.313 UTC | 21 | 2022-08-17 22:54:14.81 UTC | 2017-06-09 10:14:41.623 UTC | null | 4,966,317 | null | 4,966,317 | null | 1 | 113 | pip | 164,581 | <p>You can use pip3 using the alias pip by adding alias to your <a href="https://unix.stackexchange.com/questions/129143/what-is-the-purpose-of-bashrc-and-how-does-it-work">.bashrc</a> file.</p>
<pre><code>alias pip=pip3
</code></pre>
<p>or by adding a symlink named pip to your <a href="https://askubuntu.com/questions/551990/what-does-path-mean">$PATH</a>, which points to the pip3 binary.</p>
<p>If there is no ~/.bashrc in your home directory on macOS, inputting</p>
<pre><code>alias pip=pip3
</code></pre>
<p>in your ~/.zprofile file has the same effect.</p> |
19,346,066 | R re-arrange dataframe: some rows to columns | <p>I'm not even sure how to title the question properly!</p>
<p>Suppose I have a dataframe d:</p>
<p><strong>Current dataframe:</strong></p>
<pre><code>d <- data.frame(sample = LETTERS[1:2], cat = letters[11:20], count = c(1:10))
sample cat count
1 A k 1
2 B l 2
3 A m 3
4 B n 4
5 A o 5
6 B p 6
7 A q 7
8 B r 8
9 A s 9
10 B t 10
</code></pre>
<p>and I'm trying to re-arrange things such that each cat value becomes a column of its own, sample remains a column (or becomes the row name), and count will be the values in the new cat columns, with 0 where a sample doesn't have a count for a cat. Like so:</p>
<p><strong>Desired dataframe layout:</strong></p>
<pre><code> sample k l m n o p q r s t
1 A 1 0 3 0 5 0 7 0 9 0
2 B 0 2 0 4 0 6 0 8 0 10
</code></pre>
<p>What's the best way to go about this?</p>
<p>This is as far as I've gotten:</p>
<pre><code>for (i in unique(d$sample)) {
s <- d[d$sample==i,]
st <- as.data.frame(t(s[,3]))
colnames(st) <- s$cat
rownames(st) <- i
}
</code></pre>
<p>i.e. looping through the samples in the original data frame, and transposing for each sample subset. So in this case I get</p>
<pre><code> k m o q s
A 1 3 5 7 9
</code></pre>
<p>and</p>
<pre><code> l n p r t
B 2 4 6 8 10
</code></pre>
<p>And this is where I get stuck. I've tried a bunch of things with <code>merge</code>, <code>bind</code>, <code>apply</code>,... but I can't seem to hit on the right thing. Plus, I can't help but wonder if that loop above is a necessary step at all - something with <code>unstack</code> perhaps?</p>
<p>Needless to say, I'm new to R... If someone can help me out, it would be greatly appreciated!</p>
<p>PS Reason I'm trying to re-arrange my dataframe is in the hopes of making plotting of the values easier (i.e. I want to show the actual df in a plot in table format).</p>
<p>Thank you!</p> | 19,346,198 | 3 | 2 | null | 2013-10-13 14:01:37.033 UTC | 9 | 2021-08-24 18:50:43.76 UTC | 2021-08-24 18:50:43.76 UTC | null | 14,314,520 | null | 2,864,441 | null | 1 | 17 | r|dataframe|reshape|tidyr | 30,298 | <p>Using <code>reshape</code> from base R: </p>
<pre><code>nn<-reshape(d,timevar="cat",idvar="sample",direction="wide")
names(nn)[-1]<-as.character(d$cat)
nn[is.na(nn)]<-0
> nn
sample k l m n o p q r s t
1 A 1 0 3 0 5 0 7 0 9 0
2 B 0 2 0 4 0 6 0 8 0 10
</code></pre> |
24,840,282 | Load image from url in notification Android | <p>In my android application, i want to set Notification icons dynamically which will be loaded from URL. For that, i have used <code>setLargeIcon</code> property of NotificationBuilder in <code>receiver</code>.I reffered many link and tried various solutions but couldn't get desired output. Though i downloaded that image from url and setting that bitmap in notification, it is not being displayed. Instead it displays the <code>setSmallIcon</code> image as large icon. I don't know where i am going wrong. Here i am posting my code. Please help me to solve this issue. Thank you.</p>
<p>Code:</p>
<pre><code>@SuppressLint("NewApi")
public class C2DMMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
Log.e("C2DM", "received message");
final String fullName = intent.getStringExtra("message");
final String payload1 = intent.getStringExtra("message1");
final String payload2 = intent.getStringExtra("message2");
final String userImage = intent.getStringExtra("userImage");
Log.e("userImage Url :", userImage); //it shows correct url
new sendNotification(context)
.execute(fullName, payload1, userImage);
}
}
private class sendNotification extends AsyncTask<String, Void, Bitmap> {
Context ctx;
String message;
public sendNotification(Context context) {
super();
this.ctx = context;
}
@Override
protected Bitmap doInBackground(String... params) {
InputStream in;
message = params[0] + params[1];
try {
in = new URL(params[2]).openStream();
Bitmap bmp = BitmapFactory.decodeStream(in);
return bmp;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
try {
NotificationManager notificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(ctx, NotificationsActivity.class);
intent.putExtra("isFromBadge", false);
Notification notification = new Notification.Builder(ctx)
.setContentTitle(
ctx.getResources().getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(result).build();
// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre> | 24,866,080 | 9 | 3 | null | 2014-07-19 12:15:03.137 UTC | 28 | 2021-02-21 15:03:31.353 UTC | 2018-12-24 04:05:06.407 UTC | null | 1,568,304 | null | 1,568,304 | null | 1 | 71 | android|bitmap|google-cloud-messaging|android-notifications|android-notification-bar | 84,360 | <p>Changed my code as below and its working now :</p>
<pre><code>private class sendNotification extends AsyncTask<String, Void, Bitmap> {
Context ctx;
String message;
public sendNotification(Context context) {
super();
this.ctx = context;
}
@Override
protected Bitmap doInBackground(String... params) {
InputStream in;
message = params[0] + params[1];
try {
URL url = new URL(params[2]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
try {
NotificationManager notificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(ctx, NotificationsActivity.class);
intent.putExtra("isFromBadge", false);
Notification notification = new Notification.Builder(ctx)
.setContentTitle(
ctx.getResources().getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(result).build();
// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre> |
274,659 | Do you have any SQL Injection Testing "Ammo"? | <p>When reading about SQL Injection and XSS i was wondering if you guys have a single string that could be used to identify those vulnerabilities and others.</p>
<p>A string that could be thrown into a website database to black box check if that field is safe or not. (going to do a large test on a few inhouse tools)</p>
<p>Rough example, wondering if you guys know of more?</p>
<p>"a' or '1'='1"</p>
<p>"center'> < script>alert('test')< /script>"</p>
<p>EDIT: Found a nice <a href="https://stackoverflow.com/questions/255723/xss-torture-test-does-it-exist">XSS question</a> on SO</p> | 274,667 | 5 | 1 | null | 2008-11-08 12:09:33.697 UTC | 13 | 2017-12-22 00:08:18.37 UTC | 2017-05-23 11:49:26.567 UTC | Paul | -1 | Ólafur Waage | 22,459 | null | 1 | 17 | testing|xss|sql-injection | 12,015 | <p>I've found some nice firefox addons that do the trick.</p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/7598" rel="noreferrer">XSS Me</a></p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/7597" rel="noreferrer">SQL Inject Me</a></p> |
74,267 | How to get an Batch file .bat continue onto the next statement if there is an error | <p>I'm trying to script the shutdown of my VM Servers in a .bat.
if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out.</p>
<pre><code>c:
cd "c:\Program Files\VMWare\VmWare Server"
vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q
vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q
vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q
robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0
vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start
vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start
vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start
</code></pre> | 74,321 | 5 | 0 | null | 2008-09-16 16:32:17.89 UTC | 1 | 2018-03-15 12:25:01.027 UTC | null | null | null | null | 11,538 | null | 1 | 20 | batch-file | 48,607 | <p>Run it inside another command instance with <code>CMD /C</code></p>
<pre><code>CMD /C vmware-cmd C:\...
</code></pre>
<p>This should keep the original BAT files running.</p> |
193,257 | In MS SQL Server, is there a way to "atomically" increment a column being used as a counter? | <p>Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?</p>
<pre><code>update mytable set counter = counter + 1
</code></pre>
<p>I would assume that in the general case, where this update statement is part of a larger transaction, that it wouldn't be. For example, I think this scenario is possible:</p>
<ul>
<li>update the counter within transaction #1</li>
<li>do some other stuff
in transaction #1</li>
<li>update the counter
with transaction #2</li>
<li>commit
transaction #2</li>
<li>commit transaction #1</li>
</ul>
<p>In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?</p>
<p>How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?</p> | 193,456 | 5 | 0 | null | 2008-10-10 22:39:25.557 UTC | 14 | 2019-09-26 19:21:59.217 UTC | 2015-12-17 20:52:07.75 UTC | null | 621,316 | Dan P | 26,651 | null | 1 | 43 | sql|sql-server-2005|transactions | 18,840 | <p>Read Committed Snapshot only deals with locks on selecting data from tables.</p>
<p>In t1 and t2 however, you're UPDATEing the data, which is a different scenario.</p>
<p>When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)</p>
<ul>
<li>counter = 0</li>
<li>t1 update counter (counter => 1)</li>
<li>t2 update counter (blocked)</li>
<li>t1 commit (counter = 1)</li>
<li>t2 unblocked (can now update counter) (counter => 2)</li>
<li>t2 commit</li>
</ul>
<hr>
<p>Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level. </p>
<p>You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.</p>
<pre><code>DECLARE @CounterInitialValue INT
DECLARE @NewCounterValue INT
SELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234
-- do stuff with the counter value
UPDATE MyTable
SET counter = counter + 1
WHERE
MyID = 1234
AND
counter = @CounterInitialValue -- prevents the update if counter changed.
-- the value of counter must not change in this scenario.
-- so we rollback if the update affected no rows
IF( @@ROWCOUNT = 0 )
ROLLBACK
</code></pre>
<p>This <a href="http://www.devx.com/codemag/Article/21570" rel="noreferrer">devx</a> article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.</p>
<hr>
<p>update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.</p>
<ul>
<li>counter = 0</li>
<li>t1 update counter (counter => 1)</li>
<li>t2 update counter (nested transaction) (counter => 2)</li>
<li>t2 commit</li>
<li>t1 commit (counter = 2)</li>
</ul>
<p>With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.</p> |
814,975 | getch is deprecated | <p>Somewhere back in time I did some C and C++ in college, but I didn't get to many attention to C++. Now I wish to pay some attention to C++ but when I'm using the <code>getch()</code> function, I get the warning from below.</p>
<blockquote>
<p>Warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.</p>
</blockquote>
<p>Now, I'm using VS 2005 express, and I don't know what to do about this warning. I need to use <code>getch()</code> after I <code>printf()</code> an error message or something else which require a key hit.</p>
<p>Can you help me with that?</p> | 814,983 | 6 | 5 | null | 2009-05-02 14:53:35.09 UTC | 7 | 2019-02-02 11:19:43.24 UTC | 2016-04-14 22:03:21.917 UTC | null | 15,168 | null | 91,061 | null | 1 | 17 | c|deprecated | 45,124 | <p>Microsoft decided to mark the name without underscore deprecated, because those names are reserved for the programmer to choose. Implementation specific extensions should use names starting with an underscore in the global namespace if they want to adhere to the C or C++ Standard - or they should mark themselves as a combined Standard compliant environment, such as POSIX/ANSI/ISO C, where such a function then corresponds to one of those Standards.</p>
<p>Read <a href="https://stackoverflow.com/questions/647704/why-is-getcwd-not-iso-c-compliant/647802#647802">this answer about getcwd()</a> too, for an explanation by P. J. Plauger, who knows stuff very well, of course. </p>
<p>If you are only interested to wait for some keys typed by the user, there really is no reason not to use <code>getchar</code>. But sometimes it's just more practical and convenient to the user to use <code>_getch</code> and friends. However, those are not specified by the C or C++ Standard and will thus limit the portability of your program. Keep that in mind.</p> |
909,856 | Why do I have to call super -dealloc last, and not first? | <p>correct example:</p>
<pre><code>- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
</code></pre>
<p>wrong example:</p>
<pre><code>- (void)dealloc {
[super dealloc];
[viewController release];
[window release];
}
</code></pre>
<p>Althoug in alsmost all other cases when overriding a method I would first call the super's method implementation, in this case apple always calls [super dealloc] in the end. Why?</p> | 909,925 | 6 | 0 | null | 2009-05-26 09:44:50.103 UTC | 13 | 2011-10-28 22:33:23.783 UTC | null | null | null | null | 62,553 | null | 1 | 30 | iphone|cocoa-touch|memory-management|uikit | 17,925 | <p>Its just a guideline. You can call other instructions after <code>[super dealloc]</code>. however you can not access variables of the superclass anymore because they are released when you call <code>[super dealloc]</code>. It is always safe to call the superclass in the last line. </p>
<p>Also KVO and depended (triggered) keys can produce side effects if they are depended of already released member variables. </p> |
875,205 | GDB cheat sheet | <p>Can anyone recommend a good cheat sheet for gbd? I'm experienced with windbg commands, I'm looking for gdb equivalents for lml (list loaded modules), ~*k (all threads stack), ba (break on access), dt (dump type), dv (dump frame variables), sxe (set up SEH handler) etc.
I understand there won't be a 1 to 1 equivalent, but I just need a condensed summary of most used/usefull commands.</p> | 875,217 | 6 | 0 | null | 2009-05-17 18:52:14.75 UTC | 22 | 2013-10-15 08:50:35.003 UTC | null | null | null | null | 105,929 | null | 1 | 31 | xcode|debugging|gdb | 20,923 | <p>I use this one personally: <a href="http://users.ece.utexas.edu/~adnan/gdb-refcard.pdf" rel="noreferrer">gdb's cheat sheet</a>
or <a href="http://refcards.com/docs/peschr/gdb/gdb-refcard-a4.pdf" rel="noreferrer">that link is not broken yet ..</a> .
I 've printed it at work.</p> |
717,224 | How can I get the selected text in a textarea? | <p>I'm trying to make my own <a href="https://en.wikipedia.org/wiki/WYSIWYG" rel="nofollow noreferrer">WYSIWYG</a> editor. Is there a way to get the text which has the user selected in a <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea" rel="nofollow noreferrer">textarea</a>?</p>
<p>For example, if the user selects some word and then clicks button, how do I find out which text was selected?</p>
<p>I'm using jQuery.</p> | 717,226 | 6 | 1 | null | 2009-04-04 14:57:08.85 UTC | 10 | 2022-05-09 15:26:37.293 UTC | 2022-05-09 15:06:01.16 UTC | null | 63,550 | Darth | 72,583 | null | 1 | 41 | javascript|jquery | 88,110 | <p>Try the jquery-fieldselection plugin.</p>
<p>You can download it from <a href="http://github.com/localhost/jquery-fieldselection/tree/master" rel="noreferrer">here</a>. There is an example too.</p> |
37,632,783 | VisualVM: CPU/Memory profiler stuck at "Connecting to the target JVM..." | <p>I have recently reinstalled Windows and I am using JDK 1.8 u91 with the built-in VisualVM. I have checked my proxy settings to ensure that they are all off, both in Windows proxy settings and within the proxy settings of VisualVM.</p>
<p>I have also tried reinstalling JDK, restarting computer, reinstalling Windows. I only have one JDK installed and the classpath is set to the JDK's bin folder in Windows.</p>
<p>All features besides CPU and memory profiling work in VisualVM. My application is ran from IntelliJ, but I have also tried running applications regularly from command line and VisualVM cannot connect to those either.</p>
<p>I have also tried downloading VisualVM off <a href="http://visualvm.java.net">http://visualvm.java.net</a> which also does not work.</p>
<p>I have no plugins installed.</p>
<p>Why does it hang? Is this is a bug introduced with the new JDK?</p> | 39,783,394 | 2 | 2 | null | 2016-06-04 16:55:36.4 UTC | 16 | 2018-04-10 11:31:05.317 UTC | null | null | null | null | 1,938,929 | null | 1 | 40 | java|profiling|profiler|visualvm|jvisualvm | 10,751 | <p><a href="https://java.net/jira/browse/VISUALVM-637" rel="noreferrer">See this bug report - VISUALVM-637</a></p>
<p>Solution: start JVisualVM using below command :</p>
<p><code>jvisualvm.exe -J-Dorg.netbeans.profiler.separateConsole=true</code></p>
<p>I've checked this (and it works !) at Windows 10 X64 with java version "1.8.0_102"</p> |
17,826,129 | Which tool allows to generate such nice source code pictures? | <p>examples below. I am pretty sure that there is online free tool that can do it. But I lost a link :(</p>
<p>May be someone has the link?</p>
<p><a href="http://habrastorage.org/storage2/c43/58e/013/c4358e0133268ad6afa9a9f9ef11c4af.png" rel="noreferrer">http://habrastorage.org/storage2/c43/58e/013/c4358e0133268ad6afa9a9f9ef11c4af.png</a>
<img src="https://i.stack.imgur.com/hx1uP.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/onv8R.png" alt="enter image description here"></p> | 17,826,196 | 3 | 1 | null | 2013-07-24 05:48:46.94 UTC | 10 | 2020-07-23 06:10:38.547 UTC | null | null | null | null | 929,298 | null | 1 | 20 | code-visualization | 12,534 | <p>This can be done with this tool: <a href="http://instaco.de/" rel="nofollow noreferrer">http://instaco.de/</a></p> |
1,346,238 | Method may only be called on a Type for which Type.IsGenericParameter is true | <p>I am getting this error on a routine which uses reflection to dump some object properties, something like the code below.</p>
<pre><code>MemberInfo[] members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance) ;
foreach (MemberInfo m in members)
{
PropertyInfo p = m as PropertyInfo;
if (p != null)
{
object po = p.GetValue(obj, null);
...
}
}
</code></pre>
<p>The actual error is "Exception has been thrown by the target of an invocation"
with an inner exception of "Method may only be called on a Type for which Type.IsGenericParameter is true."</p>
<p>At this stage in the debugger obj appears as </p>
<pre><code> {Name = "SqlConnection" FullName = "System.Data.SqlClient.SqlConnection"}
</code></pre>
<p>with the type System.RuntimeType</p>
<p>The method m is {System.Reflection.MethodBase DeclaringMethod} </p>
<p>Note that obj is of type System.RuntimeType and members contains 188 items whereas a simple
typeof(System.Data.SqlClient.SqlConnection).GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) only returns 65.</p>
<p>I tried checking isGenericParameter on both obj and p.PropertyType, but this seems to be false for most properties including those where p.GetValue works.</p>
<p>So what exactly is a "Type for which Type.IsGenericParameter is true" and more importantly
how do I avoid this error without a try/catch?</p> | 1,346,434 | 5 | 0 | null | 2009-08-28 10:42:24.41 UTC | 6 | 2021-02-15 03:44:53.65 UTC | null | null | null | null | 125,759 | null | 1 | 20 | c#|reflection | 64,168 | <p>Firstly, you've made an incorrect assumption, that is, you've assumed that <code>members</code> has returned the members of an instance of <code>System.Data.SqlClient.SqlConnection</code>, which it has not. What has been returned are the members of an instance of <code>System.Type</code>.</p>
<p>From the MSDN documentation for <a href="http://msdn.microsoft.com/en-us/library/system.type.declaringmethod.aspx" rel="nofollow noreferrer">DeclaringType</a>:</p>
<blockquote>
<p>Getting the <code>DeclaringMethod</code> property
on a type whose <code>IsGenericParameter</code>
property is false throws an
<code>InvalidOperationException</code>.</p>
</blockquote>
<p>So... it's understandable that an <code>InvalidOperationException</code> is being thrown, since naturally, you're not dealing with an open generic type here. See <a href="https://stackoverflow.com/questions/1346238/method-may-only-be-called-on-a-type-for-which-type-isgenericparameter-is-true/1346266#1346266">Marc Gravell's answer</a> for an explanation of open generic types.</p> |
1,679,045 | PHP exec() command: how to specify working directory? | <p>My script, let's call it execute.php, needs to start a shell script which is in Scripts subfolder. Script has to be executed so, that its working directory is Scripts. How to accomplish this simple task in PHP?</p>
<p>Directory structure looks like this:</p>
<pre><code>execute.php
Scripts/
script.sh
</code></pre> | 1,679,060 | 5 | 0 | null | 2009-11-05 08:08:59.597 UTC | 6 | 2021-04-04 23:03:38.49 UTC | 2021-04-04 23:03:21.41 UTC | null | 1,002,260 | null | 76,535 | null | 1 | 46 | php | 80,274 | <p>Either you change to that directory within the exec command (<code>exec("cd Scripts && ./script.sh")</code>) or you change the working directory of the PHP process using <a href="http://php.net/manual/en/function.chdir.php" rel="nofollow noreferrer"><code>chdir()</code></a>.</p> |
1,426,244 | Use external fonts in android | <p>I want to use external fonts in my app. I have tried adding new <code>fonts</code> using <code>AssetManager</code> but it did not work. Below is my code:</p>
<pre><code>Typeface face;
face = Typeface.createFromAsset(getAssets(), "font.otf");
textview.setTypeface(face);
</code></pre>
<p>but its not showing the text...</p>
<p>Please help me with this.</p> | 1,430,320 | 6 | 1 | null | 2009-09-15 09:58:26.283 UTC | 20 | 2017-12-27 10:33:59.433 UTC | 2017-12-27 10:33:59.433 UTC | null | 1,904,696 | null | 152,867 | null | 1 | 63 | android|fonts|android-widget | 85,903 | <p>AFAIK, Android does not support OpenType. Use a TrueType font instead.</p>
<hr>
<p><strong>UPDATE:</strong> Apparently OpenType is now supported, at least somewhat. It was not supported originally, so you will want to test your font thoroughly on whatever versions of Android your app will support.</p> |
1,382,573 | How do you use the "WITH" clause in MySQL? | <p>I am converting all my SQL Server queries to MySQL and my queries that have <code>WITH</code> in them are all failing. Here's an example:</p>
<pre><code>WITH t1 AS
(
SELECT article.*, userinfo.*, category.*
FROM question
INNER JOIN userinfo ON userinfo.user_userid = article.article_ownerid
INNER JOIN category ON article.article_categoryid = category.catid
WHERE article.article_isdeleted = 0
)
SELECT t1.*
FROM t1
ORDER BY t1.article_date DESC
LIMIT 1, 3
</code></pre> | 1,382,618 | 7 | 5 | null | 2009-09-05 05:45:26.76 UTC | 43 | 2019-09-07 02:33:43.49 UTC | 2016-09-26 08:24:00.973 UTC | null | 1,157,540 | null | 161,433 | null | 1 | 149 | mysql|common-table-expression|with-clause|subquery-factoring|mysql-8.0 | 297,163 | <p><strong>MySQL prior to version 8.0 <a href="http://bugs.mysql.com/bug.php?id=23156" rel="noreferrer">doesn't support the WITH clause</a></strong> (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:</p>
<ul>
<li>TEMPORARY tables</li>
<li>DERIVED tables </li>
<li>inline views (effectively what the WITH clause represents - they are interchangeable)</li>
</ul>
<p>The request for the feature dates back to 2006.</p>
<p>As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:</p>
<pre><code> SELECT *
FROM ARTICLE t
JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
JOIN CATEGORY c ON c.catid = t.article_categoryid
WHERE t.published_ind = 0
ORDER BY t.article_date DESC
LIMIT 1, 3
</code></pre>
<p>Here's a better example:</p>
<pre><code>SELECT t.name,
t.num
FROM TABLE t
JOIN (SELECT c.id
COUNT(*) 'num'
FROM TABLE c
WHERE c.column = 'a'
GROUP BY c.id) ta ON ta.id = t.id
</code></pre> |
1,563,030 | Anonymous code blocks in Java | <p>Are there any practical uses of anonymous code blocks in Java?</p>
<pre><code>public static void main(String[] args) {
// in
{
// out
}
}
</code></pre>
<p>Please note that this is not about <em>named</em> blocks, i.e.</p>
<pre><code>name: {
if ( /* something */ )
break name;
}
</code></pre>
<p>.</p> | 1,563,039 | 10 | 2 | null | 2009-10-13 21:34:11.66 UTC | 16 | 2022-08-03 10:08:52.98 UTC | null | null | null | null | 112,671 | null | 1 | 70 | java | 45,680 | <p>They restrict variable scope.</p>
<pre><code>public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}
</code></pre>
<p>In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.</p> |
33,609,404 | Node.js - How to generate random numbers in specific range using crypto.randomBytes | <p>How can I generate random numbers in a specific range using crypto.randomBytes?</p>
<p>I want to be able to generate a random number like this:</p>
<pre><code>console.log(random(55, 956)); // where 55 is minimum and 956 is maximum
</code></pre>
<p>and I'm limited to use <strong>crypto.randomBytes</strong> only inside <strong>random</strong> function to generate random number for this range.</p>
<p>I know how to convert generated bytes from randomBytes to hex or decimal but I can't figure out how to get a random number in a specific range from random bytes mathematically.</p> | 33,627,342 | 5 | 3 | null | 2015-11-09 12:44:59.377 UTC | 1 | 2020-12-14 15:54:32.897 UTC | 2015-11-09 13:40:39.077 UTC | null | 916,491 | null | 5,344,251 | null | 1 | 18 | node.js|math|random|cryptography | 52,025 | <p>Thanks to answer from @Mustafamg and huge help from @CodesInChaos I managed to resolve this issue. I made some tweaks and increase range to maximum 256^6-1 or 281,474,976,710,655. Range can be increased more but you need to use additional library for big integers, because 256^7-1 is out of Number.MAX_SAFE_INTEGER limits.</p>
<p>If anyone have same problem feel free to use it.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var crypto = require('crypto');
/*
Generating random numbers in specific range using crypto.randomBytes from crypto library
Maximum available range is 281474976710655 or 256^6-1
Maximum number for range must be equal or less than Number.MAX_SAFE_INTEGER (usually 9007199254740991)
Usage examples:
cryptoRandomNumber(0, 350);
cryptoRandomNumber(556, 1250425);
cryptoRandomNumber(0, 281474976710655);
cryptoRandomNumber((Number.MAX_SAFE_INTEGER-281474976710655), Number.MAX_SAFE_INTEGER);
Tested and working on 64bit Windows and Unix operation systems.
*/
function cryptoRandomNumber(minimum, maximum){
var distance = maximum-minimum;
if(minimum>=maximum){
console.log('Minimum number should be less than maximum');
return false;
} else if(distance>281474976710655){
console.log('You can not get all possible random numbers if range is greater than 256^6-1');
return false;
} else if(maximum>Number.MAX_SAFE_INTEGER){
console.log('Maximum number should be safe integer limit');
return false;
} else {
var maxBytes = 6;
var maxDec = 281474976710656;
// To avoid huge mathematical operations and increase function performance for small ranges, you can uncomment following script
/*
if(distance<256){
maxBytes = 1;
maxDec = 256;
} else if(distance<65536){
maxBytes = 2;
maxDec = 65536;
} else if(distance<16777216){
maxBytes = 3;
maxDec = 16777216;
} else if(distance<4294967296){
maxBytes = 4;
maxDec = 4294967296;
} else if(distance<1099511627776){
maxBytes = 4;
maxDec = 1099511627776;
}
*/
var randbytes = parseInt(crypto.randomBytes(maxBytes).toString('hex'), 16);
var result = Math.floor(randbytes/maxDec*(maximum-minimum+1)+minimum);
if(result>maximum){
result = maximum;
}
return result;
}
}</code></pre>
</div>
</div>
</p>
<p>So far it works fine and you can use it as really good random number generator, but I strictly not recommending using this function for any cryptographic services. If you will, use it on your own risk.</p>
<p>All comments, recommendations and critics are welcome!</p> |
8,414,008 | how to deploy my artifact on to my nexus? | <p>I am using nexus open source as my repository manager for Maven 3.0.3</p>
<p>Maven is able to create artifact *.jar.</p>
<p>Now, I would like to know how I can push the generated artifact *.jar to the nexus repo manager, so that other dependent modules can pull from it.</p>
<p>I referred to this <a href="http://www.vineetmanohar.com/2010/06/getting-started-with-nexus-maven-repo-manager/" rel="noreferrer">guide</a>. </p>
<p>In <code>settings.xml</code>, I have</p>
<pre><code> <server>
<id>nexus-site</id>
<username>admin</username>
<password>xxxx</password>
</server>
</code></pre>
<p>It fails. </p>
<p>How can invoke my deployment from mvn command or how to deploy my artifact on to my nexus?</p> | 8,414,151 | 4 | 2 | null | 2011-12-07 10:41:57.427 UTC | 6 | 2019-07-21 09:53:15.97 UTC | 2016-08-12 17:22:30.173 UTC | null | 455,020 | null | 855,474 | null | 1 | 25 | maven|maven-2|maven-3|nexus | 64,332 | <p>Just try</p>
<pre><code> mvn deploy
</code></pre>
<p>that will deploy your artifact to the nexus repo manager.</p>
<p>Have you configured the distributionManagement section ?</p> |
8,493,130 | How do I get a model from a Backbone.js collection by its id? | <p>In my app, everything I do with data is based on the primary key as the data is stored in the database. I would like to grab a model from a collection based on this key.</p>
<p>Using Collection.at() requires the array index, Collection.getByCid() requires the client ID that backbone randomly generates.</p>
<p>What is the best way to grab the model I want from the collection with the given id value? I figure the worst I could do would be to iterate over each item, .get('id'), and return that one.</p> | 8,493,503 | 2 | 2 | null | 2011-12-13 17:03:20.23 UTC | 4 | 2014-06-09 06:06:28.493 UTC | 2014-04-11 23:27:10.087 UTC | null | 538,646 | null | 538,646 | null | 1 | 40 | javascript|backbone.js | 64,960 | <p>Take a look at the get method, it may be of some help :) </p>
<p><a href="http://backbonejs.org/#Collection-get" rel="noreferrer">http://backbonejs.org/#Collection-get</a></p>
<blockquote>
<p><strong>get</strong> <em>collection.get(id)</em><br>
Get a model from a collection, specified by an id, a cid, or by passing in a model.</p>
</blockquote> |
18,185,305 | Storing bash output into a variable using eval | <p>I have a line of code</p>
<pre><code>eval echo \$$var
</code></pre>
<p>which prints a string. How can I store this string into a variable?</p> | 18,185,387 | 4 | 0 | null | 2013-08-12 11:00:40.95 UTC | 5 | 2020-09-25 05:30:31.32 UTC | null | null | null | null | 1,585,301 | null | 1 | 28 | bash | 47,950 | <p>Like this:</p>
<pre><code>eval c=\$$var
</code></pre>
<p>a better, safer way is to use indirection:</p>
<pre><code>c=${!var}
</code></pre> |
17,747,522 | How to delete a line from a text file using the line number in python | <p>here is an example text file</p>
<pre><code>the bird flew
the dog barked
the cat meowed
</code></pre>
<p>here is my code to find the line number of the phrase i want to delete</p>
<pre><code>phrase = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if phrase in line:
print 'found at line:', num
</code></pre>
<p>what can i add to this to be able to delete the line number (num)
i have tried</p>
<pre><code>lines = myFile.readlines()
del line[num]
</code></pre>
<p>but this doesnt work how should i approach this?</p> | 17,748,140 | 7 | 1 | null | 2013-07-19 13:37:49.247 UTC | 1 | 2021-04-07 06:40:25.97 UTC | null | null | null | null | 2,081,505 | null | 1 | 5 | python|python-3.x | 38,613 | <p>You could use the <code>fileinput</code> module to update the file - note this will remove <em>all</em> lines containing the phrase:</p>
<pre><code>import fileinput
for line in fileinput.input(filename, inplace=True):
if phrase in line:
continue
print(line, end='')
</code></pre> |
17,790,123 | Shell - check if a git tag exists in an if/else statement | <p>I am creating a deploy script for a zend application. The scrip is almost done only I want to verify that a tag exists within the repo to force tags on the team. Currently I have the following code:</p>
<pre><code># First update the repo to make sure all the tags are in
cd /git/repo/path
git pull
# Check if the tag exists in the rev-list.
# If it exists output should be zero,
# else an error will be shown which will go to the else statement.
if [ -z "'cd /git/repo/path && git rev-list $1..'" ]; then
echo "gogo"
else
echo "No or no correct GIT tag found"
exit
fi
</code></pre>
<p>Looking forward to your feedback!</p>
<h1>Update</h1>
<p>When I execute the following in the command line:</p>
<pre><code>cd /git/repo/path && git rev-list v1.4..
</code></pre>
<p>I get <strong>NO</strong> output, which is good. Though when I execute:</p>
<pre><code>cd /git/repo/path && git rev-list **BLA**..
</code></pre>
<p>I get an <strong>error</strong>, which again is good:</p>
<pre><code>fatal: ambiguous argument 'BLA..': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
</code></pre>
<p>The -z in the statement says, if sting is empty then... In other words, it works fine via command line. Though when I use the same command in a shell script inside a statement it does not seem to work.</p>
<pre><code>[ -z "'cd /git/repo/path && git rev-list $1..'" ]
</code></pre>
<p>This method what inspired by <a href="https://stackoverflow.com/questions/4127967/validate-if-commit-exists">Validate if commit exists</a></p>
<h1>Update 2</h1>
<p>I found the problem:</p>
<p>See <a href="https://stackoverflow.com/questions/2359270/using-if-elif-fi-in-shell-scripts">Using if elif fi in shell scripts</a> ></p>
<blockquote>
<p>sh is interpreting the && as a shell operator. Change it to -a, that’s
[’s conjunction operator:</p>
<p>[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ] Also, you should always
quote the variables, because [ gets confused when you leave off
arguments.</p>
</blockquote>
<p>in other words, I changed the <code>&&</code> to <code>;</code> and simplified the condition. Now it works beautiful.</p>
<pre><code>if cd /path/to/repo ; git rev-list $1.. >/dev/null
then
echo "gogo"
else
echo "WRONG"
exit
fi
</code></pre> | 17,793,125 | 7 | 6 | null | 2013-07-22 14:27:00.683 UTC | 12 | 2021-12-03 01:54:22.31 UTC | 2021-10-22 06:56:34.42 UTC | null | 586,229 | null | 2,269,694 | null | 1 | 70 | git|bash|shell | 61,943 | <p>You could use <code>git rev-parse</code> instead:</p>
<pre><code>if GIT_DIR=/path/to/repo/.git git rev-parse $1 >/dev/null 2>&1
then
echo "Found tag"
else
echo "Tag not found"
fi
</code></pre>
<p><code>git rev-list</code> invokes graph walking, where <code>git rev-parse</code> would avoid it. The above has some issues with possibly looking up an object instead of a tag. You can avoid that by using <code>^{tag}</code> following the tag name, but this only works for annotated tags and not lightweight tags:</p>
<pre><code>if GIT_DIR=/path/to/repo/.git git rev-parse "$1^{tag}" >/dev/null 2>&1
then
echo "Found tag"
else
echo "Tag not found"
fi
</code></pre>
<p>@Lassi also points out that if your tag name begins with a <code>-</code>, then it might get interpreted as an option instead. You can avoid that issue by looking for <code>refs/tags/$1</code> instead. So in summary, with the <code>rev-parse</code> version, you can look for <code>refs/tags/$1</code> to get both lightweight and annotated tags, and you can append a <code>^{tag}</code> to the end to enforce an annotated tag (<code>refs/tags/$1^{tag}</code>).</p>
<p>Also, as mentioned before by @forvaidya, you could simply list the tags and grep for the one you want:</p>
<pre><code>if GIT_DIR=/path/to/repo/.git git show-ref --tags | egrep -q "refs/tags/$1$"
then
echo "Found tag"
else
echo "Tag not found"
fi
</code></pre>
<p>You can also use <code>git tag --list</code> instead of <code>git show-ref --tags</code>:</p>
<pre><code>if GIT_DIR=/path/to/repo/.git git tag --list | egrep -q "^$1$"
then
echo "Found tag"
else
echo "Tag not found"
fi
</code></pre>
<p>If you know the tag though, I think it's best just to just look it up via <code>rev-parse</code>. One thing I don't like about the <code>egrep</code> version is that it's possible you could have characters that could get interpreted as regex sequences and either cause a false positive or false negative. The <code>rev-parse</code> version is superior in that sense, and in that it doesn't look at the whole list of tags.</p>
<p>Another option is to use the pattern feature of <code>git show-ref</code>:</p>
<pre><code>if GIT_DIR=/path/to/repo/.git git show-ref --tags "refs/tags/$1" >/dev/null 2>&1
then
echo "Found tag"
else
echo "Tag not found"
fi
</code></pre>
<p>This avoids the extra <code>egrep</code> invocation and is a bit more direct.</p> |
17,803,331 | How do I change the UUID of a virtual disk? | <p>I am trying to create a new virtual machine with Oracle VirtualBox, using an already-existing hard disk. When I try to select the existing hard disk file, a .vhd file, it displays an error saying the virtual hard disk cannot be used because the UUID already exists.</p>
<p>So I tried the following command to change its UUID.</p>
<pre><code>VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd
</code></pre>
<p>I get this error.</p>
<blockquote>
<p>Syntax error: Invalid UUID parameter</p>
</blockquote>
<p>How can I resolve this?</p> | 17,803,797 | 9 | 1 | null | 2013-07-23 06:55:14.69 UTC | 47 | 2020-06-12 18:39:23.627 UTC | 2019-04-11 09:02:33.847 UTC | null | 225,647 | null | 2,590,090 | null | 1 | 145 | virtual-machine|virtualbox | 246,419 | <p>The correct command is the following one.</p>
<pre><code>VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"
</code></pre>
<p>The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.</p> |
18,203,636 | Why do I have to specify data type each time in C to printf() and scanf()? | <p>As you can see from the code snippet below, I have declared one <code>char</code> variable and one <code>int</code> variable. When the code gets compiled, it must identify the data types of variables <code>str</code> and <code>i</code>.</p>
<p>Why do I need to tell again during scanning my variable that it's a string or integer variable by specifying <code>%s</code> or <code>%d</code> to <code>scanf</code>? Isn't the compiler mature enough to identify that when I declared my variables?</p>
<pre><code>#include <stdio.h>
int main ()
{
char str [80];
int i;
printf ("Enter your family name: ");
scanf ("%s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
return 0;
}
</code></pre> | 18,203,775 | 11 | 10 | null | 2013-08-13 07:57:45.45 UTC | 19 | 2021-01-29 13:11:26.757 UTC | 2021-01-29 13:11:26.757 UTC | null | 2,757,035 | null | 2,169,104 | null | 1 | 68 | c|compiler-construction|printf|scanf | 5,911 | <p>Because there's no portable way for a variable argument functions like <code>scanf</code> and <code>printf</code> to know the types of the variable arguments, not even how many arguments are passed.</p>
<p>See C FAQ: <a href="http://c-faq.com/varargs/nargs.html">How can I discover how many arguments a function was actually called with?</a></p>
<hr>
<p>This is the reason there must be at least one fixed argument to determine the number, and maybe the types, of the variable arguments. And this argument (the standard calls it <code>parmN</code>, see C11(<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1539.pdf">ISO/IEC 9899:201x</a>) §7.16 <em>Variable arguments </em>) plays this special role, and will be passed to the macro <code>va_start</code>. In another word, you can't have a function with a prototype like this in standard C:</p>
<pre><code>void foo(...);
</code></pre> |
42,122,522 | ReactJs: What should the PropTypes be for this.props.children? | <p>Given a simple component that renders its children:</p>
<pre><code>class ContainerComponent extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default ContainerComponent;
</code></pre>
<p><strong>Question: What should the propType of the children prop be?</strong></p>
<p>When I set it as an object, it fails when I use the component with multiple children:</p>
<pre><code><ContainerComponent>
<div>1</div>
<div>2</div>
</ContainerComponent>
</code></pre>
<blockquote>
<p>Warning: Failed prop type: Invalid prop <code>children</code> of type <code>array</code>
supplied to <code>ContainerComponent</code>, expected <code>object</code>.</p>
</blockquote>
<p>If I set it as an array, it will fail if I give it only one child, i.e.: </p>
<pre><code><ContainerComponent>
<div>1</div>
</ContainerComponent>
</code></pre>
<blockquote>
<p>Warning: Failed prop type: Invalid prop children of type object
supplied to ContainerComponent, expected array.</p>
</blockquote>
<p>Please advise, should I just not bother doing a propTypes check for children elements?</p> | 42,122,662 | 9 | 3 | null | 2017-02-08 20:00:18.597 UTC | 50 | 2022-03-31 11:50:15.03 UTC | 2017-02-08 20:14:56.513 UTC | null | 3,006,145 | null | 3,006,145 | null | 1 | 381 | reactjs|jsx|react-proptypes | 178,337 | <p>Try something like this utilizing <code>oneOfType</code> or <code>PropTypes.node</code></p>
<pre><code>import PropTypes from 'prop-types'
...
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
}
</code></pre>
<p>or</p>
<pre><code>static propTypes = {
children: PropTypes.node.isRequired,
}
</code></pre> |
44,536,340 | Typescript - What is the difference between null and undefined? | <p>I want to know what is the difference between null and undefined in typescript. I know in javascript it is possible to use both of them in order to check a variable has no value. But in typescript I want to know the difference exactly and when it is better to use each one of them.
Thanks.</p> | 44,536,499 | 2 | 8 | null | 2017-06-14 05:43:14.413 UTC | 1 | 2022-07-19 10:31:01.493 UTC | null | null | null | null | 7,649,991 | null | 1 | 42 | javascript|typescript|null|undefined | 48,850 | <p><a href="https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript">This post</a> explains the differences very well. They are the same in TypeScript as in JavaScript.</p>
<p>As for what you should use: You may define that on your own. You may use either, just be aware of the differences and it might make sense to be consistent.</p>
<p>The TypeScript coding style guide for the TypeScript source code (not an official "how to use TypeScript" guide) states that you should always use <code>undefined</code> and not <code>null</code>: <a href="https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined" rel="nofollow noreferrer">Typescript Project Styleguide</a>.</p> |
6,540,448 | How to program to old game consoles? | <p>I want to know how to program to old game consoles for fun.</p>
<p>Can I use a programming language such as C? Will I have to use assembly? I do not know any console compiler, assembler or API. I will need to compile into ROM image and test with emulators, because I do not own any console.</p>
<p>Each console has its interesting features and I would like to play with them.</p>
<ul>
<li>Atari 2600 (only 128 bytes of RAM)</li>
<li>NES (only 8-bit)</li>
<li>SNES (a good console, 16-bit)</li>
<li>PS1 (3D, complex)</li>
<li>Game Boy (simple, monochromatic)</li>
</ul> | 6,542,867 | 3 | 5 | null | 2011-06-30 20:03:35.42 UTC | 13 | 2021-01-20 09:55:03.403 UTC | null | null | null | null | 405,030 | null | 1 | 21 | compiler-construction|hardware|video-game-consoles | 2,917 | <p>Older systems like the Atari, NES, and GameBoy are typically programmed in Assembly or C. There are a variety of development tools for the GameBoy I've played around with such as:</p>
<p>Rednex Gameboy Development (ASM): <a href="http://www.otakunozoku.com/rednex-gameboy-development-system/" rel="nofollow noreferrer">http://www.otakunozoku.com/rednex-gameboy-development-system/</a><br>
GBDK (C): <a href="http://gbdk.sourceforge.net/" rel="nofollow noreferrer">http://gbdk.sourceforge.net/</a></p>
<p>And while there are a lot of dead links on it, this page has a lot of good information and links on GameBoy development in general:
<a href="http://www.devrs.com/gb/" rel="nofollow noreferrer">http://www.devrs.com/gb/</a></p>
<p>For the NES there are two assembly tutorials I know of. The second tutorial is linked to from the first with the claim it is superior but I can't really comment as the second link didn't exist last time I was interested in this topic.<br>
<a href="http://www.patater.com/nes-asm-tutorials" rel="nofollow noreferrer">http://www.patater.com/nes-asm-tutorials</a> <br>
<a href="http://www.nintendoage.com/forum/messageview.cfm?catid=22&threadid=7155" rel="nofollow noreferrer">http://www.nintendoage.com/forum/messageview.cfm?catid=22&threadid=7155</a> (this link is no longer valid, <a href="https://web.archive.org/web/20181209154852/http://nintendoage.com/forum/messageview.cfm?catid=22&threadid=7155" rel="nofollow noreferrer">use the wayback machine</a>)</p>
<p>If it isn't too new for you the GBA has a lot of great homebrew resources and is typically programmed using C. The wealth of information on the GBA makes it a good place to start:</p>
<p>DevKitPro provides a complete GNU toolchain for GBA development (DevKitARM + libgba): <a href="http://www.devkitpro.org/" rel="nofollow noreferrer">http://www.devkitpro.org/</a></p>
<p>TONC is a very good guide for the GBA with a lot of detailed explaination: <a href="http://www.coranac.com/tonc/text/" rel="nofollow noreferrer">http://www.coranac.com/tonc/text/</a></p>
<p>Lastly, the indispensible gbatek sheet that details the GBA's hardware. This will tell you what registers on the GBA you have to play with to change graphics modes, sound modes, use interrupts, etc.<br>
<a href="http://nocash.emubase.de/gbatek.htm" rel="nofollow noreferrer">http://nocash.emubase.de/gbatek.htm</a></p>
<p>Programming for these older game systems shares a lot in common with programming microcontrollers. Without some sort of abstraction layer you have to do a lot of bitwise manipulation of registers to do even the most basic things.</p>
<p>Edit: The main issue I came across when doing GBA programming was figuring out how the sound registers work. It was (is?) a real blind spot in terms of tutorials. The best resource at the time was studying the gbatek sheet and these sites:<br>
<a href="http://deku.rydia.net/program/sound1.html" rel="nofollow noreferrer">http://deku.rydia.net/program/sound1.html</a><br>
<a href="http://belogic.com/gba/" rel="nofollow noreferrer">http://belogic.com/gba/</a><br></p> |
57,270,302 | Can I switch a Google Play country without adding payment method? | <p>Here's the deal.
I need to check if our Platform supports payments over 1000000 currency via Google Play Store. </p>
<p>When I try to change the country in Account settings, Google asks for that country's payment method (Credit card). I don't have access to Vietnamese test cards and the ones from card generator don't work (obviously). Any ideas on how I can skip adding a payment method? The account is used only for Sandbox testing purposes.</p> | 57,272,458 | 1 | 3 | null | 2019-07-30 11:11:10.083 UTC | 1 | 2022-09-03 22:00:29.417 UTC | null | null | null | null | 11,857,179 | null | 1 | 9 | google-play-services | 41,069 | <p>Check out <a href="https://support.google.com/googleplay/forum/AAAA8CVOtD88MJNwwTRo94/?hl=en&gpf=d/topic/play/8MJNwwTRo94" rel="noreferrer">this</a> Page from the Google Play Support Page if you encounter a similar Problem.</p>
<blockquote>
<p>Also, you can't change the country for an existing payments profile. Hence, you need to create a new payments profile to add/associate it with a new/another country:</p>
<ol>
<li><p>Sign in to <a href="http://payments.google.com/#settings" rel="noreferrer">Settings</a>.</p>
</li>
<li><p>Under <strong>Payments profile</strong>, click the pencil icon next to <strong>Country</strong>.</p>
</li>
<li><p>Click the link to <strong>Create new profile</strong> from the message that appears.</p>
</li>
<li><p>Click <strong>Continue</strong> from the next message that appears.</p>
</li>
<li><p>From the drop-down list, choose the country to associate with the payments profile you're creating.</p>
</li>
<li><p>Enter the address information and click <strong>Submit</strong>.</p>
</li>
</ol>
<p>After that you'll be seeing an option "Close" at the bottom part of the selection where you need to close the payments account under your previous location.`</p>
</blockquote> |
18,511,700 | How to get a DataRow out the current row of a DataReader? | <p>Ok, I would like to extract a <code>DataRow</code> out a <code>DataReader</code>. I have been looking around for quite some time and it doesn't look like there is a simple way to do this.</p>
<p>I understand a <code>DataReader</code> is more a collection of rows but it only read one row at the time.</p>
<p>So my question: is there any way to extract a <code>DataRow</code> out the current row of a <code>DataReader</code>?</p> | 18,511,793 | 2 | 1 | null | 2013-08-29 12:58:31.417 UTC | 2 | 2018-03-30 05:12:19.577 UTC | 2014-07-27 12:17:50.323 UTC | null | 1,524,477 | null | 2,145,522 | null | 1 | 25 | c#|datarow|datareader | 49,846 | <blockquote>
<p>Is there any way to extract a DataRow out the current row of a
DataReader ?</p>
</blockquote>
<p>No, at least no simple way. Every DataRow belongs to one <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow.table(v=vs.110).aspx">Table</a>. You cannot leave that property empty, you cannot even change the table(without using ImportRow). </p>
<p>But if you need DataRows, why don't you fill a <code>DataTable</code> in the first place?</p>
<pre><code>DataTable table = new DataTable();
using(var con = new SqlConnection("...."))
using(var da = new SqlDataAdapter("SELECT ... WHERE...", con))
da.Fill(table);
// now you have the row(s)
</code></pre>
<p>If you really need to get the row(s) from the <code>DataReader</code> you can use <a href="http://msdn.microsoft.com/en-us/library/system.data.datatablereader.getschematable.aspx"><code>reader.GetSchemaTable</code></a> to get all informations about the columns:</p>
<pre><code>if (reader.HasRows)
{
DataTable schemaTable = reader.GetSchemaTable();
DataTable data = new DataTable();
foreach (DataRow row in schemaTable.Rows)
{
string colName = row.Field<string>("ColumnName");
Type t = row.Field<Type>("DataType");
data.Columns.Add(colName, t);
}
while (reader.Read())
{
var newRow = data.Rows.Add();
foreach (DataColumn col in data.Columns)
{
newRow[col.ColumnName] = reader[col.ColumnName];
}
}
}
</code></pre>
<p>But that is not really efficient.</p> |
19,019,005 | Create a list of 100 integers whose values equal their indexes | <p>Create a list of 100 integers whose value and index are the same, e.g.</p>
<pre><code>mylist[0] = 0, mylist[1] = 1, mylist[2] = 2, ...
</code></pre>
<p>Here is my code.</p>
<pre><code>x_list=[]
def list_append(x_list):
for i in 100:
x_list.append(i)
return(list_append())
print(x_list)
</code></pre> | 19,019,348 | 7 | 2 | null | 2013-09-26 03:49:08.657 UTC | null | 2020-04-29 08:37:14.283 UTC | 2016-05-10 20:58:08.413 UTC | null | 1,763,356 | null | 2,811,103 | null | 1 | 5 | python|list | 72,262 | <p>Since nobody else realised you're using Python 3, I'll point out that you should be doing <code>list(range(100))</code> to get the wanted behaviour.</p> |
18,774,355 | Adding kSOAP dependency to Gradle project | <p>I'm trying to make kSOAP working in my Android project with Gradle.</p>
<p>This is my project's build.gradle file:</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
maven {
url 'http://ksoap2-android.googlecode.com/svn/m2-repo'
}
}
android {
compileSdkVersion 18
buildToolsVersion "18.0.1"
defaultConfig {
minSdkVersion 7
targetSdkVersion 18
}
}
dependencies {
compile 'com.android.support:support-v4:18.0.0'
compile 'ch.acra:acra:4.5.0'
compile 'com.google.guava:guava:12.0'
compile 'com.google.code.ksoap2-android:ksoap2-android:3.0.0'
}
</code></pre>
<p>The library seems to be included in the project and compilation DOES work but when I try to import a class (ie SoapObject) it seems like the namespace does not even exist. The funny thing is that the other libraries (such as ACRA or Guava) are working fine. How can I solve this problem?</p> | 21,418,577 | 8 | 2 | null | 2013-09-12 21:07:27.047 UTC | 9 | 2019-12-10 00:48:40.823 UTC | null | null | null | null | 481,559 | null | 1 | 31 | android|maven|gradle|ksoap2 | 46,522 | <p>This took me a bit to figure out as well, but I have finally gotten it working. I've been working on a WSDL parser that parses for KSoap and finally got that working only to fight through Gradle with the import of ksoap. At anyrate here is how you do it.</p>
<pre><code>apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.8.+'
classpath 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'
}
}
repositories {
maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
dependencies {
compile 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'
}
</code></pre>
<p>Of course mine is a service library, so you may want to use apply plugin: 'android'.
Hopefully this helps and saves somebody some time.</p> |
5,324,689 | Custom adapter for GridView in Android | <p>I'm getting data from DB and displayed in a <code>GridView</code> fine. But I need to put a separate button below each text displayed. When I click the button, I have to do some stuff. Here I used a custom list adapter for retrieved data from DB. How could I do that?</p>
<p>My code:</p>
<pre><code>public class HomePage extends Activity {
private ArrayList<SingleElementDetails> allElementDetails=new ArrayList<SingleElementDetails>();
DBAdapter db=new DBAdapter(this);
String category, description;
String data;
String data1;
GridView gridview;
Button menu;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
menu=(Button)findViewById(R.id.menus);
menu.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
gridview=(GridView)findViewById(R.id.gridview);
allElementDetails.clear();
db.open();
long id;
//id=db1.insertTitle1(category, description,r_photo);
Cursor cursor = db.getAllTitles1();
while (cursor.moveToNext())
{
SingleElementDetails single=new SingleElementDetails();
single.setCateogry(cursor.getString(1));
single.setDescription(cursor.getString(2));
single.setImage(cursor.getBlob(3));
allElementDetails.add(single);
}
db.close();
CustomListAdapter adapter=new CustomListAdapter(HomePage.this,allElementDetails);
gridview.setAdapter(adapter);
}
});
}
}
</code></pre>
<p>My customListAdapter:</p>
<pre><code>import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomListAdapter extends BaseAdapter {
private ArrayList<SingleElementDetails> allElementDetails;
private LayoutInflater mInflater;
public CustomListAdapter(Context context, ArrayList<SingleElementDetails> results) {
allElementDetails = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return allElementDetails.size();
}
public Object getItem(int position) {
return allElementDetails.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(R.layout.listview1, null);
ImageView imageview = (ImageView) convertView.findViewById(R.id.image);
TextView textview = (TextView) convertView.findViewById(R.id.category_entry);
TextView textview1 = (TextView) convertView.findViewById(R.id.description_entry);
textview.setText(allElementDetails.get(position).getCategory());
textview1.setText(allElementDetails.get(position).getDescription());
byte[] byteimage=allElementDetails.get(position).getImage();
ByteArrayInputStream imageStream = new ByteArrayInputStream(byteimage);
BitmapFactory.Options op=new BitmapFactory.Options();
op.inSampleSize=12;
Bitmap theImage= BitmapFactory.decodeStream(imageStream,null,op);
imageview.setImageBitmap(theImage);
return convertView;
}
}
</code></pre> | 5,324,824 | 2 | 1 | null | 2011-03-16 11:39:05.72 UTC | 2 | 2018-11-09 07:45:19.923 UTC | 2018-11-09 07:45:19.923 UTC | null | 7,404,943 | null | 555,948 | null | 1 | 9 | android|gridview|onclick | 78,415 | <p>Instead of using CustomListAdapter, you will have to create your own adapter that extends BaseAdapter, create a layout for each grid item (extend LinearLayout) in this class have your textview then a button.</p>
<p>Nice Tut:</p>
<p><a href="http://www.stealthcopter.com/blog/2010/09/android-creating-a-custom-adapter-for-gridview-buttonadapter/" rel="noreferrer">Custom GridView</a></p> |
5,304,245 | Good books and resources on data parallel programming and algorithms | <p>I've read the following and most of the NVIDIA manuals and other content. I was also at <a href="http://www.nvidia.com/object/gpu_technology_conference.html" rel="noreferrer">GTC</a> last year for the papers and talks.</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0131387685" rel="noreferrer" rel="nofollow noreferrer">CUDA by Example: An Introduction to General-Purpose GPU Programming</a></p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0123814723" rel="noreferrer" rel="nofollow noreferrer">Programming Massively Parallel Processors: A Hands-on Approach</a></p>
<p>And I'm aware of the latest <a href="https://rads.stackoverflow.com/amzn/click/com/0123849888" rel="noreferrer" rel="nofollow noreferrer">GPU Computing Gems Emerald Edition</a> but haven't read it yet.</p>
<p>What other books and resources would you recommend? For instance I'm sure there's some great content from the first wave of data parallel programming in the 80s (the <a href="http://en.wikipedia.org/wiki/Connection_Machine" rel="noreferrer">Connection Machine</a> etc). I know a lot of research was done on data parallel algorithms for that generation of hardware.</p>
<p><strong>Followup... 30/Mar/2011</strong></p>
<p>I also discovered that the GPU Gems books 1-3 have some chapters on GPU computing, not just graphics. They're available free online, <a href="http://developer.nvidia.com/object/gpu_gems_home.html" rel="noreferrer">http://developer.nvidia.com/object/gpu_gems_home.html</a>. I've not had a chance to read them yet.</p> | 5,305,424 | 2 | 0 | null | 2011-03-14 20:42:40.89 UTC | 9 | 2011-03-30 04:03:57.28 UTC | 2011-03-30 04:03:57.28 UTC | null | 125,523 | null | 125,523 | null | 1 | 11 | algorithm|design-patterns|gpgpu|gpu | 1,530 | <p>Hillis & Steele [1986], <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.85.1876&rep=rep1&type=pdf">"Data Parallel Algorithms"</a>.</p> |
4,947,556 | What is a runloop? | <p>After reading the documentation for NSRunLoop I did not understand very much. I am spawning a secondary thread that has a NSTimer in it that launch every 1sec. Which update a label on the screen with the performSelectorOnMainThread..</p>
<p>However to get it to work I needed a runloop but I do not understand the concept of it?</p>
<p>Anyone who could try to explain it?</p>
<p>Thanks.</p> | 4,948,163 | 2 | 0 | null | 2011-02-09 16:21:08.483 UTC | 14 | 2011-02-09 18:40:53.317 UTC | 2011-02-09 18:40:53.317 UTC | null | 19,679 | null | 454,049 | null | 1 | 20 | iphone|objective-c|cocoa | 15,098 | <p>A run loop is effectively:</p>
<pre><code>while(... get an event ...)
... handle event ...;
</code></pre>
<p>It runs on a thread; the main thread has the main event loop where user events are processed and most UI drawing, etc, occurs. The <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html" rel="noreferrer">documentation explains it in detail</a>.</p>
<p>However, in your case, <strong>you don't need a thread</strong>.</p>
<p>It sounds like all you are doing is periodically updating a label in the UI; something that isn't terribly compute intensive.</p>
<p>Just schedule your timer in the main thread and be done with it. No need for spinning up a thread, using <code>performSelectorOnMainThread:</code>, or incurring all the complexities of guaranteeing data coherency across threads.</p>
<hr/>
<p>Sorry -- didn't understand your question.</p>
<p>Internally, a run loop works by basically putting a flag in the run loop that says "after this amount of time elapses, fire the timer". No additional threads involved and, better yet, it isn't polling to check the time. Think of a run loop as effectively maintaining a timeline. It'll passively let time elapse until there is something of interest found on the timeline (all without polling -- polling sucks. to be avoided.)</p>
<p>It does mean, though, that a Timer will never be 100% accurate. As well, if you have a timer repeating every second, it'll drift over time.</p>
<p>Also; instead of directly triggering a drawing event. Your timer should invalidate the view that needs updating, then let the underlying objects deal with when it is best to actually update the screen. </p> |
270,829 | Internationalizing Desktop App within a couple years... What should we do now? | <p>So we are sure that we will be taking our product internationally and will eventually need to internationalize it. How much internationalizing would you recommend we do as we go along?</p>
<p>I guess in other words, is there any internationalization that is easy now but can be much worse if we let the code base mature and that won't slow us down very much if we choose to start doing it now?</p>
<p>Tech used: C#, WPF, WinForms</p> | 270,839 | 7 | 0 | null | 2008-11-06 23:55:09.747 UTC | 16 | 2019-03-29 09:40:24.697 UTC | 2019-03-29 09:23:12.57 UTC | danimajo | 2,154,774 | Justin Bozonier | 9,401 | null | 1 | 17 | wpf|winforms|internationalization | 6,764 | <p>Prepare it now, before you write all the strings in the codebase itself.</p>
<p>Everything after now will be too late. It's now or never!</p>
<p>It's true that it is a bit of extra effort to prepare well now, but not doing it will end up being a lot more expensive. </p>
<p>If you won't follow all the guidelines in the links below, at least heed points 1,2 and 7 of the summary which are very cheap to do now and which cause the most pain afterwards in my experience.</p>
<p>Check these guidelines and see for yourself why it's better to start now and get everything prepared.</p>
<ol>
<li><p><a href="http://msdn.microsoft.com/en-us/library/h6270d0z(VS.71).aspx" rel="noreferrer">Developing world ready applications</a> </p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/w7x1y988(VS.71).aspx" rel="noreferrer">Best practices for developing world ready applications</a></p></li>
</ol>
<p>Little extract:</p>
<ol>
<li>Move all localizable resources to separate resource-only DLLs. Localizable resources include user interface elements such as strings, error messages, dialog boxes, menus, and embedded object resources. <em>(Moving the resources to a DLL afterwards will be a pain)</em></li>
<li>Do not hardcode strings or user interface resources. <em>(If you don't prepare, you know you will hardcode strings)</em></li>
<li>Do not put nonlocalizable resources into the resource-only DLLs. This causes confusion for translators. </li>
<li>Do not use composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages. <em>(After the interface design, changing phrases gets harder)</em></li>
<li>Avoid ambiguous constructs such as "Empty Folder" where the strings can be translated differently depending on the grammatical roles of the strings' components. For example, "empty" can be either a verb or an adjective, and this can lead to different translations in languages such as Italian or French. <em>(Same issue)</em></li>
<li>Avoid using images and icons that contain text in your application. They are expensive to localize. <em>(Use text rendered over the image)</em></li>
<li>Allow plenty of room for the length of strings to expand in the user interface. In some languages, phrases can require 50-75 percent more space. <em>(Same issue, if you don't plan for it now, redesign is more expensive)</em></li>
<li>Use the System.Resources.ResourceManager class to retrieve resources based on culture.</li>
<li>Use Microsoft Visual Studio .NET to create Windows Forms dialog boxes, so they can be localized using the Windows Forms Resource Editor (Winres.exe). Do not code Windows Forms dialog boxes by hand.</li>
</ol> |
517,580 | Library resolution with autoconf? | <p>I'm building my first autoconf managed package.</p>
<p>However I can't find any simple examples anywhere of how to specify a required library, and find that library where it might be in various different places.</p>
<p>I've currently got:</p>
<pre><code>AC_CHECK_LIB(['event'], ['event_init'])
</code></pre>
<p>but:</p>
<ol>
<li>It doesn't find the version installed in <code>/opt/local/lib</code></li>
<li>It doesn't complain if the library isn't actually found</li>
<li>I need to set the include path to <code>/opt/local/include</code> too</li>
</ol>
<p>any help, or links to decent tutorials much appreciated...</p> | 517,884 | 7 | 1 | null | 2009-02-05 19:40:32.813 UTC | 11 | 2018-10-25 08:33:56.837 UTC | null | null | null | Alnitak | 6,782 | null | 1 | 22 | autoconf | 26,643 | <p>You need to manually set <code>CFLAGS</code>, <code>CXXFLAGS</code> and <code>LDFLAGS</code> if you want gcc/g++ to look in non-standard locations. </p>
<p>So, before calling <code>AC_CHECK_LIB()</code>, do something like</p>
<pre><code>CFLAGS="$CFLAGS -I/opt/local/include"
CXXFLAGS="$CXXFLAGS -I/opt/local/include"
LDFLAGS="$LDFLAGS -L/opt/local/lib"
</code></pre>
<p>You don't need CXXFLAGS if you're only using gcc throughout your configure script.</p> |
991,036 | What is a Namespace? | <p>I didn't take the usual CS route to learning programming and I often hear about namespaces but I don't really understand the concept. The descriptions I've found online are usually in the context of C which I'm not familiar with.</p>
<p>I am been doing Ruby for 2 years and I'm trying to get a deeper understanding of the language and OOP.</p> | 991,060 | 7 | 1 | null | 2009-06-13 16:59:33.473 UTC | 10 | 2018-08-01 17:35:03.18 UTC | 2018-08-01 17:35:03.18 UTC | null | 23,528 | null | 10,258 | null | 1 | 22 | programming-languages | 20,758 | <p>A namespace provides a container to hold things like functions, classes and constants as a way to group them together logically and to help avoid conflicts with functions and classes with the same name that have been written by someone else.</p>
<p>In Ruby this is achieved using modules.</p> |
49,137 | Calling python from a c++ program for distribution | <p>I would like to call python script files from my c++ program.</p>
<p>I am not sure that the people I will distribute to will have python installed.</p> | 49,148 | 7 | 0 | null | 2008-09-08 03:53:39.56 UTC | 44 | 2022-09-20 19:15:33.853 UTC | 2022-09-20 19:15:33.853 UTC | Jeff V | 208,273 | Brian R. Bondy | 3,153 | null | 1 | 66 | c++|python|embedded-language | 104,821 | <p>Boost has a python interface library which could help you.</p>
<p><a href="http://www.boost.org/doc/libs/release/libs/python/doc/index.html" rel="noreferrer">Boost.Python</a></p> |
44,194 | How do I best generate a CSV (comma-delimited text file) for download with ASP.NET? | <p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>One an ASPX page, I've got the download link...</p>
<pre><code><asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
</code></pre>
<p>And then I've got the Download.aspx.vb Code Behind...</p>
<pre><code>Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
</code></pre> | 44,219 | 8 | 0 | null | 2008-09-04 17:07:17.16 UTC | 6 | 2013-10-31 15:18:55.677 UTC | null | null | null | Zack | 83 | null | 1 | 18 | asp.net|vb.net|file-io|csv | 60,432 | <p>CSV formatting has some gotchas. Have you asked yourself these questions:</p>
<ul>
<li>Does any of my data have embedded commas?</li>
<li>Does any of my data have embedded double-quotes?</li>
<li>Does any of my data have have newlines?</li>
<li>Do I need to support Unicode strings?</li>
</ul>
<p>I see several problems in your code above. The comma thing first of all... you are stripping commas:</p>
<pre><code>CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
</code></pre>
<p>Why? In CSV, you should be surrounding anything which has commas with quotes:</p>
<pre><code>CsvLine.Append(String.Format("\"{0:c}\"", b.Price))
</code></pre>
<p>(or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. <code>"</code> becomes <code>""</code>.</p>
<pre><code>b.Title.Replace("\"", "\"\"")
</code></pre>
<p>Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines <em>are</em> allowed in CSV files. It looks weird to humans, but it's all good.</p>
<p>A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).</p>
<p>And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and <em>vice versa</em>). Bottom line, use culture-agnostic formatting wherever possible.</p>
<p>While the issue here is <em>generating</em> CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="noreferrer">Fast CSV Reader</a> on <a href="http://www.codeproject.com" rel="noreferrer">CodeProject</a>. I've actually used it in production code and it is really really fast, and very easy to use!</p> |
316,236 | Difference between [UIImage imageNamed...] and [UIImage imageWithData...]? | <p>I want to load some images into my application from the file system. There's 2 easy ways to do this:</p>
<pre><code>[UIImage imageNamed:fullFileName]
</code></pre>
<p>or:</p>
<pre><code>NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];
[UIImage imageWithData:imageData];
</code></pre>
<p>I prefer the first one because it's a lot less code, but I have seen some people saying that the image is cached and that this method uses more memory? Since I don't trust people on most other forums, I thought I'd ask the question here, is there any practical difference, and if so which one is 'better'?</p>
<p>I have tried profiling my app using the Object Allocation instrument, and I can't see any practical difference, though I have only tried in the simulator, and not on an iPhone itself.</p> | 316,258 | 8 | 1 | null | 2008-11-25 02:53:28.067 UTC | 45 | 2013-08-19 14:37:28.5 UTC | 2013-07-10 11:43:08.87 UTC | null | 457,406 | rustyshelf | 6,044 | null | 1 | 65 | iphone|cocoa-touch | 54,800 | <p>It depends on what you're doing with the image. The <code>imageNamed:</code> method does cache the image, but in many cases that's going to help with memory use. For example, if you load an image 10 times to display along with some text in a table view, UIImage will only keep a single representation of that image in memory instead of allocating 10 separate objects. On the other hand, if you have a very large image and you're not re-using it, you might want to load the image from a data object to make sure it's removed from memory when you're done.</p>
<p>If you don't have any huge images, I wouldn't worry about it. Unless you see a problem (and kudos for checking Object Allocation instead of preemptively optimizing), I would choose less lines of code over negligible memory improvements.</p> |
589,096 | Parsing SQL code in C# | <p>I want to parse SQL code using C#.</p>
<p>Specifically, is there any freely available parser which can parse SQL code and generate a tree or any other structure out of it? It should also generate the proper tree for nested structures.</p>
<p>It should also return which kind of statement the node of this tree represents.</p>
<p>For example, if the node contains a loop condition then it should return that this is a "loop type" of a node.</p>
<p>Or is there any way by which I can parse the code in C# and generate a tree of the type I want?</p> | 589,138 | 8 | 1 | null | 2009-02-26 04:20:04.33 UTC | 42 | 2021-09-28 08:07:53.85 UTC | 2011-08-25 19:50:48.003 UTC | null | 63,550 | aaCog | 70,329 | null | 1 | 78 | c#|sql | 104,643 | <p>[Warning: answer may no longer apply as of 2021]</p>
<p>Use Microsoft <a href="http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework" rel="nofollow noreferrer">Entity Framework</a> (EF).</p>
<p>It has a "Entity SQL" parser which builds an expression tree,</p>
<pre><code>using System.Data.EntityClient;
...
EntityConnection conn = new EntityConnection(myContext.Connection.ConnectionString);
conn.Open();
EntityCommand cmd = conn.CreateCommand();
cmd.CommandText = @"Select t.MyValue From MyEntities.MyTable As t";
var queryExpression = cmd.Expression;
....
conn.Close();
</code></pre>
<p>Or something like that, check it out on MSDN.</p>
<p>And it's all on Ballmers tick :-)</p>
<p>There is also one on The Code Project, <em><a href="http://www.codeproject.com/KB/dotnet/SQL_parser.aspx" rel="nofollow noreferrer">SQL Parser</a></em>.</p>
<p>Good luck.</p> |
1,262,695 | Convert integers to strings to create output filenames at run time | <p>I have a program in Fortran that saves the results to a file. At the moment I open the file using </p>
<pre><code>OPEN (1, FILE = 'Output.TXT')
</code></pre>
<p>However, I now want to run a loop, and save the results of each iteration to the files <code>'Output1.TXT'</code>, <code>'Output2.TXT'</code>, <code>'Output3.TXT'</code>, and so on.</p>
<p>Is there an easy way in Fortran to constuct filenames from the loop counter <code>i</code>?</p> | 1,262,731 | 9 | 0 | null | 2009-08-11 20:22:30.527 UTC | 22 | 2018-04-28 18:37:39.173 UTC | 2017-09-29 14:39:31.427 UTC | null | 113,962 | null | 113,962 | null | 1 | 57 | string|integer|fortran | 153,461 | <p>you can write to a unit, but you can also write to a string</p>
<pre><code>program foo
character(len=1024) :: filename
write (filename, "(A5,I2)") "hello", 10
print *, trim(filename)
end program
</code></pre>
<p>Please note (this is the second trick I was talking about) that you can also build a format string programmatically.</p>
<pre><code>program foo
character(len=1024) :: filename
character(len=1024) :: format_string
integer :: i
do i=1, 10
if (i < 10) then
format_string = "(A5,I1)"
else
format_string = "(A5,I2)"
endif
write (filename,format_string) "hello", i
print *, trim(filename)
enddo
end program
</code></pre> |
1,119,605 | How can I make a TextBox be a "password box" and display stars when using MVVM? | <p>How can I do this in XAML:</p>
<p><em>PSEUDO-CODE:</em></p>
<pre><code><TextBox Text="{Binding Password}" Type="Password"/>
</code></pre>
<p>so that the user sees stars or dots when he is typing in the password.</p>
<p>I've tried <a href="http://pstaev.blogspot.com/2007/01/password-textbox-in-wpf.html" rel="noreferrer">various examples</a> which suggest <strong>PasswordChar</strong> and <strong>PasswordBox</strong> but can't get these to work.</p>
<p>e.g. I can do this as shown <a href="http://www.a2zdotnet.com/View.aspx?id=84" rel="noreferrer">here</a>:</p>
<pre><code><PasswordBox Grid.Column="1" Grid.Row="1"
PasswordChar="*"/>
</code></pre>
<p>but I of course want to bind the Text property to my ViewModel so I can send the value the bound TextBox when the button is clicked (not working with code behind), I want to do this:</p>
<pre><code><TextBox Grid.Column="1" Grid.Row="0"
Text="{Binding Login}"
Style="{StaticResource FormTextBox}"/>
<PasswordBox Grid.Column="1" Grid.Row="1"
Text="{Binding Password}"
PasswordChar="*"
Style="{StaticResource FormTextBox}"/>
</code></pre>
<p>But PasswordBox doesn't have a Text property.</p> | 1,119,649 | 9 | 2 | null | 2009-07-13 13:58:04.807 UTC | 3 | 2021-12-09 17:11:22.453 UTC | 2019-02-11 10:09:17.583 UTC | null | 1,194,402 | null | 4,639 | null | 1 | 61 | c#|wpf|xaml|mvvm|textbox | 132,617 | <p>To get or set the Password in a PasswordBox, use the Password property. Such as</p>
<pre><code>string password = PasswordBox.Password;
</code></pre>
<p>This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.</p> |
945,288 | Saving current directory to bash history | <p>I'd like to save the current directory where the each command was issued alongside the command in the history. In order not to mess things up, I was thinking about adding the current directory as a comment at the end of the line. An example might help:</p>
<pre><code>$ cd /usr/local/wherever
$ grep timmy accounts.txt
</code></pre>
<p>I'd like bash to save the last command as:</p>
<pre><code>grep timmy accounts.txt # /usr/local/wherever
</code></pre>
<p>The idea is that this way I could immediately see where I issued the command.</p> | 948,515 | 9 | 0 | null | 2009-06-03 15:01:17.813 UTC | 39 | 2019-12-08 11:20:47.96 UTC | null | null | null | null | 107,245 | null | 1 | 68 | bash | 11,977 | <h1>One-liner version</h1>
<p>Here is a one-liner version. It's the original. I've also posted a <a href="https://stackoverflow.com/a/960674/4518341">short function version</a> and a <a href="https://stackoverflow.com/a/960684/4518341">long function version</a> with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. This post has some information on how they all work which may not be duplicated in the others.</p>
<h3>Add the following to your <code>~/.bashrc</code> file:</h3>
<pre><code>export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]* }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'
</code></pre>
<p>This makes a history entry that looks like:</p>
<pre><code>rm subdir/file ### /some/dir
</code></pre>
<p>I use <code>###</code> as a comment delimiter to set it apart from comments that the user might type and to reduce the chance of collisions when stripping old path comments that would otherwise accumulate if you press enter on a blank command line. Unfortunately, the side affect is that a command like <code>echo " ### "</code> gets mangled, although that should be fairly rare.</p>
<p>Some people will find the fact that I reuse the same variable name to be unpleasant. Ordinarily I wouldn't, but here I'm trying to minimize the footprint. It's easily changed in any case.</p>
<p>It blindly assumes that you aren't using <code>HISTTIMEFORMAT</code> or modifying the history in some other way. It would be easy to add a <code>date</code> command to the comment in lieu of the <code>HISTTIMEFORMAT</code> feature. However, if you need to use it for some reason, it still works in a subshell since it gets unset automatically:</p>
<pre><code>$ htf="%Y-%m-%d %R " # save it for re-use
$ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
</code></pre>
<p>There are a couple of very small problems with it. One is if you use the <code>history</code> command like this, for example:</p>
<pre><code>$ history 3
echo "hello world" ### /home/dennis
ls -l /tmp/file ### /home/dennis
history 3
</code></pre>
<p>The result will not show the comment on the <code>history</code> command itself, even though you'll see it if you press up-arrow or issue another <code>history</code> command.</p>
<p>The other is that commands with embedded newlines leave an uncommented copy in the history in addition to the commented copy.</p>
<p>There may be other problems that show up. Let me know if you find any.</p>
<h3>How it works</h3>
<p>Bash executes a command contained in the <code>PROMPT_COMMAND</code> variable each time the <code>PS1</code> primary prompt is issued. This little script takes advantage of that to grab the last command in the history, add a comment to it and save it back.</p>
<p>Here it is split apart with comments:</p>
<pre><code>hpwd=$(history 1) # grab the most recent command
hpwd="${hpwd# *[0-9]* }" # strip off the history line number
if [[ ${hpwd%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
cwd=$OLDPWD
else
cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd" # strip off the old ### comment if there was one so they
# don't accumulate, then build the comment
history -s "$hpwd" # replace the most recent command with itself plus the comment
</code></pre> |
42,531 | How do I call ::CreateProcess in c++ to launch a Windows executable? | <p>Looking for an example that:</p>
<ol>
<li>Launches an EXE</li>
<li>Waits for the EXE to finish.</li>
<li>Properly closes all the handles when the executable finishes.</li>
</ol> | 42,544 | 10 | 0 | null | 2008-09-03 20:39:21.527 UTC | 27 | 2022-04-13 03:13:50.453 UTC | 2016-06-06 08:52:31.82 UTC | 1800 INFORMATION | 462,608 | jm | 814 | null | 1 | 58 | c++|windows|winapi | 186,342 | <p>Something like this:</p>
<pre><code>STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
</code></pre> |
140,439 | Authenticating against active directory using python + ldap | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>[email protected] password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p> | 140,495 | 11 | 1 | null | 2008-09-26 16:08:11.23 UTC | 61 | 2022-05-28 11:31:13.233 UTC | 2013-05-14 07:20:35.07 UTC | Rich B | 1,716,542 | 1729 | 4,319 | null | 1 | 95 | python|authentication|active-directory|ldap | 99,719 | <p>I was missing </p>
<pre><code>l.set_option(ldap.OPT_REFERRALS, 0)
</code></pre>
<p>From the init.</p> |
135,755 | How can I find the version of an installed Perl module? | <p>How do you find the version of an installed Perl module?</p>
<p>This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my <code>.bashrc</code></p>
<pre><code>function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
</code></pre> | 136,218 | 12 | 1 | null | 2008-09-25 20:16:24.507 UTC | 24 | 2017-11-20 16:52:49.163 UTC | 2009-07-19 16:26:16.483 UTC | brian d foy | 17,339 | dinomite | 17,339 | null | 1 | 62 | perl|module|version|cpan | 65,233 | <p>Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have?</p>
<p>I have this built into the <code>cpan</code> (which comes with perl) with the <code>-D</code> switch so you can see the version that you have installed and the current version on CPAN:</p>
<pre>
$ cpan -D Text::CSV_XS
Text::CSV_XS
-------------------------------------------------------------------------
Fast 8bit clean version of Text::CSV
H/HM/HMBRAND/Text-CSV_XS-0.54.tgz
/usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm
Installed: 0.32
CPAN: 0.54 Not up to date
H.Merijn Brand (HMBRAND)
[email protected]
</pre>
<p>If you want to see all of the out-of-date modules, use the <code>-O</code> (capital O) switch:</p>
<pre>
$ cpan -O
Module Name Local CPAN
-------------------------------------------------------------------------
Apache::DB 0.1300 0.1400
Apache::SOAP 0.0000 0.7100
Apache::Session 1.8300 1.8700
Apache::SizeLimit 0.0300 0.9100
Apache::XMLRPC::Lite 0.0000 0.7100
... and so on
</pre>
<p>If you want to see this for all modules you have installed, try the <code>-a</code> switch to create an autobundle.</p> |
410,002 | Fixing the PHP empty function | <p>PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the <code>empty()</code> function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?</p> | 410,200 | 13 | 3 | null | 2009-01-03 22:30:21.387 UTC | 11 | 2020-11-11 01:03:35.933 UTC | 2012-01-14 11:44:47.193 UTC | null | 367,456 | null | 25,411 | null | 1 | 34 | php|function|object | 17,037 | <p>This didn't work for me. </p>
<pre><code>if (empty($variable) && '0' != $variable) {
// Do something
}
</code></pre>
<p>I used instead:</p>
<pre><code>if (empty($variable) && strlen($variable) == 0) {
// Do something
}
</code></pre> |
279,673 | Save all files in Visual Studio project as UTF-8 | <p>I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).</p>
<p>I know how to save single files, but how about all files in a project?</p> | 850,751 | 13 | 2 | null | 2008-11-11 00:31:57.303 UTC | 30 | 2019-10-08 13:11:08.97 UTC | null | null | null | jesperlind | 33,349 | null | 1 | 91 | visual-studio|utf-8|character-encoding | 94,169 | <p>Since you're already in Visual Studio, why not just simply write the code?</p>
<pre class="lang-cs prettyprint-override"><code>foreach (var f in new DirectoryInfo(@"...").GetFiles("*.cs", SearchOption.AllDirectories)) {
string s = File.ReadAllText(f.FullName);
File.WriteAllText (f.FullName, s, Encoding.UTF8);
}
</code></pre>
<p>Only three lines of code! I'm sure you can write this in less than a minute :-)</p> |
704,558 | Custom UINavigationBar Background | <p>I've been trying to set up a custom background for the whole of my NavigationBar (not just the titleView) but have been struggling.</p>
<p>I found this thread</p>
<p><a href="http://discussions.apple.com/thread.jspa?threadID=1649012&tstart=0" rel="nofollow noreferrer">http://discussions.apple.com/thread.jspa?threadID=1649012&tstart=0</a></p>
<p>But am not sure how to implement the code snippet that is given. Is the code implemented as a new class? Also where do I instatiate the <code>UINavigationController</code> as I have an application built with the NavigationView template so it is not done in my root controller as per the example</p> | 2,720,196 | 15 | 1 | null | 2009-04-01 08:20:40.1 UTC | 60 | 2017-05-10 08:14:06.877 UTC | 2017-05-10 08:14:06.877 UTC | null | 753,878 | tigermain | 258 | null | 1 | 50 | iphone|objective-c | 52,940 | <p>You just have to overload drawRect like that :</p>
<pre><code>@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
</code></pre> |
891,031 | Is there a method that calculates a factorial in Java? | <p>I didn't find it, yet. Did I miss something?
I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse?
I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.</p> | 891,059 | 30 | 0 | null | 2009-05-21 01:31:33.97 UTC | 14 | 2021-06-25 12:15:34.35 UTC | 2020-05-15 17:39:35.083 UTC | null | 12,347,640 | c0d3x | null | null | 1 | 113 | java | 364,952 | <p>I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. <a href="http://www.luschny.de/math/factorial/FastFactorialFunctions.htm" rel="noreferrer">Here is a handful of implementations.</a></p> |
6,947,489 | What is the appropriate use of the Article element? | <p>I want to change</p>
<pre><code><section>
<header>...</header>
<p class="tweet">This is a tweet preview. You can... <em>6 Hours ago</em></p>
</section>
</code></pre>
<p>into</p>
<pre><code><section>
<header>...</header>
<article class="tweet">
<p>This is a tweet preview. You can... <time pubdate>6 Hours ago</time></p>
</article>
</section>
</code></pre>
<p>But after reading some <a href="http://html5doctor.com/the-article-element/">articles</a> on the <code><article></code> tag, I'm not sure that this is the best move. What would be better practice? </p> | 6,948,897 | 5 | 8 | null | 2011-08-04 19:32:39.32 UTC | 11 | 2022-01-04 18:55:51.57 UTC | 2022-01-04 18:55:51.57 UTC | null | 2,756,409 | null | 522,877 | null | 1 | 30 | html | 26,094 | <p>The important thing to understand about articles and sections is that they are sectioning elements. Each follows a common pattern:</p>
<pre><code><sectioning_element>
<heading_or_header>
... the body text and markup of the section
<footer>
</sectioning_element>
</code></pre>
<p>The footer is optional. Sectioning elements should have a "natural" heading. That is, it should be easy to write an <code><h?></code> element at the start of the section/article, that describes and summarises the entire content of the section/article, such that other things on the page not inside the section/article would not be described by the heading.</p>
<p>It's not necessary to explicitly include the natural heading on the page, if for example, it was self evident what the heading would be and for stylistic reasons you didn't want to display it, but you should be able to say easily what it would have been had you chosen to include it.*</p>
<p>For example, a section might have a natural heading "cars for sale". It's extremely likely that from the content contained within the section, it would be patently obvious that the section was about cars being for sale, and that including the heading would be redundant information. </p>
<p><code><section></code> tends to be used for grouping things. Their natural headers are typically plural. e.g. "Cars for Sale"</p>
<p><code><article></code> is for units of content. Their natural headers are usually a title for the whole of the text that follows. e.g. "My New Car" </p>
<p>So, if you're not grouping some things, then there's no need, and it's not correct, to use another sectioning element in between the header and footer of the section and your correct mark-up would be</p>
<pre><code><article class="tweet">
<header>...</header>
<p>This is a tweet preview. You can... <em>6 Hours ago</em></p>
</article>
</code></pre>
<p>assuming you can find a natural heading to go inside the <code><header></code> element. If you can't, then the correct mark-up is simply</p>
<pre><code><p class="tweet">This is a tweet preview. You can... <em>6 Hours ago</em></p>
</code></pre>
<p>or</p>
<pre><code><div class="tweet">
<p>This is a tweet preview. You can... <em>6 Hours ago</em></p>
</div>
</code></pre>
<hr>
<p>
* There's a case for including the natural heading anyway, and making it "display:none". Doing so will allow the section/article to be referenced cleanly by the document outline.
</p> |
6,785,875 | Develop android Application using Html,Css and JavaScript | <p>I would like to develop Android application using HTML, CSS and JavaScript with Android SDK. I dont want to use another tool like Titanium or PhoneGap.</p>
<p>Is it possible to make application using the HTML, CSS and JavaScript?</p>
<p>Are Android web apps as good as native apps? Can the same functionality be achieved through web apps?</p>
<p>If it is good in comparison of native applications, can any one tell me the proper way to do this or provide me good tutorial?</p> | 6,792,814 | 5 | 0 | null | 2011-07-22 05:08:03.783 UTC | 38 | 2022-07-04 16:29:45.413 UTC | 2018-05-03 00:21:08.163 UTC | null | -1 | null | 614,807 | null | 1 | 69 | android | 93,683 | <p>The Short answer: Yes, you can develop apps using HTML / CSS / Javascript. Take two WebView Tutorials and call me in the morning.</p>
<p>The Long Answer:
If you want to write apps for Android that use HTML / CSS / Javascript, you'll have to at least create a native WebView wrapper. This is relatively easy to do -- unless you want to hook into native functions, such as the accelerometer, camera, or even the Toast Messages (the little messages that pop up when something happens).</p>
<p>Accessing the native hardware and software through a webview requires you to write a JavascriptAdapter (available in Android 2+), and define some custom Javascript methods in the JavascriptAdapter. Those methods map to a java function, which DOES have access to the native OS facilities.</p>
<p>Frameworks such as Appcelerator and PhoneGap do exactly this, except they've already written the javascript functions for you, so it saves you from having to write those yourself.</p>
<p>In that sense, if you're going to write an app for Android using HTML / CSS / Javascript, it makes sense to use a framework. Otherwise, you're doing that work yourself.</p> |
6,677,875 | How do I turn off mouse block selection in IntelliJ? | <p>For some reason, dragging the mouse cursor started doing block selects instead of the normal line select mode:</p>
<p><img src="https://i.stack.imgur.com/70bmw.png" alt="enter image description here"></p>
<p>(Please ignore the fact that this image is from Visual Studio and not IntelliJ)</p>
<p>I tried pressing scroll-lock, pressing and releasing the alt/ctrl/shift keys, but still selecting doesn't revert to the normal "select full lines" mode. When I click and hold, then drag the mouse, I get a block (rectangle) selection.</p>
<p>Do you know how to undo this?</p>
<p>P.S. I'm running IntelliJ 9 on Ubuntu.</p>
<p>P.S. Holding SHIFT and pressing the up arrow button also does block select instead of normal multiline select.</p> | 6,678,024 | 5 | 1 | null | 2011-07-13 11:04:07.267 UTC | 23 | 2018-12-27 08:13:36.8 UTC | null | null | null | null | 11,236 | null | 1 | 108 | ubuntu|intellij-idea | 43,483 | <p>Use <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>Insert</kbd> to switch between <em>Column</em> and <em>Insert</em> selection mode.</p>
<hr>
<p>Copying comment from <em>brent.payne</em> below:</p>
<blockquote>
<p>If you are on ubuntu running on a bootcamp mac (macbook pro here) then the key stroke is <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>Fn</kbd> + <kbd>Enter</kbd>. <kbd>Fn</kbd> + <kbd>Enter</kbd> = <kbd>Ins</kbd> since no <kbd>Ins</kbd> key exists on the macbook pro</p>
</blockquote> |
6,983,141 | Changing cell color of excel sheet via VB.NET | <p>I am writing some data from database to the excel via visual basic.net.I need to change background of some cells and also need to make text bold. I need something like that :</p>
<pre><code> xlWorkSheet.Cells(rownumber, 1).BackgroundColor = Color.Yellow
xlWorkSheet.Cells(rownumber, 1).Font.isBold = True
</code></pre>
<p>Of course none of above is works.How can I achieve this? Thanks..</p> | 6,983,271 | 6 | 0 | null | 2011-08-08 13:51:13.777 UTC | 2 | 2020-02-12 14:04:18.383 UTC | null | null | null | null | 688,217 | null | 1 | 5 | vb.net|excel | 83,754 | <p>You need to create a Excel.Style object, and apply that to a range. Like this:</p>
<pre><code>Dim style As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
style.Font.Bold = True
style.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow)
xlWorkSheet.Cells(rownumber, 1).Style = "NewStyle"
</code></pre> |
6,687,630 | How to remove unused C/C++ symbols with GCC and ld? | <p>I need to optimize the size of my executable severely (<code>ARM</code> development) and
I noticed that in my current build scheme (<code>gcc</code> + <code>ld</code>) unused symbols are not getting stripped.</p>
<p>The usage of the <code>arm-strip --strip-unneeded</code> for the resulting executables / libraries doesn't change the output size of the executable <em>(I have no idea why, maybe it simply can't)</em>.</p>
<p>What would be the way <em>(if it exists)</em> to modify my building pipeline, so that the unused symbols are stripped from the resulting file?</p>
<hr>
<p>I wouldn't even think of this, but my current embedded environment isn't very "powerful" and
saving even <code>500K</code> out of <code>2M</code> results in a very nice loading performance boost.</p>
<p><strong>Update:</strong></p>
<p>Unfortunately the current <code>gcc</code> version I use doesn't have the <code>-dead-strip</code> option and the <code>-ffunction-sections... + --gc-sections</code> for <code>ld</code> doesn't give any significant difference for the resulting output.</p>
<p><em>I'm shocked that this even became a problem, because I was sure that <code>gcc + ld</code> should automatically strip unused symbols (why do they even have to keep them?).</em></p> | 6,770,305 | 11 | 8 | null | 2011-07-14 01:51:48.133 UTC | 73 | 2017-08-13 12:50:54.653 UTC | 2015-11-11 09:42:39.777 UTC | null | 895,245 | null | 346,332 | null | 1 | 142 | c++|c|gcc|ld|strip | 138,887 | <p>For GCC, this is accomplished in two stages:</p>
<p>First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:</p>
<pre><code>-fdata-sections -ffunction-sections
</code></pre>
<p>Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):</p>
<pre><code>-Wl,--gc-sections
</code></pre>
<p>So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):</p>
<pre><code>gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
</code></pre>
<p>(Note that -Os is an additional compiler flag that tells GCC to optimize for size)</p> |
6,537,535 | Check date with todays date | <p>I have written some code to check two dates, a start date and an end date. If the end date is before the start date, it will give a prompt that says the end date is before start date. </p>
<p>I also want to add a check for if the start date is before today (today as in the day of which the user uses the application) How would I do this? ( Date checker code below, also all this is written for android if that has any bearing)</p>
<pre><code>if (startYear > endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
} else if (startMonth > endMonth && startYear >= endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
} else if (startDay > endDay && startMonth >= endMonth && startYear >= endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
}
</code></pre> | 6,537,615 | 12 | 0 | null | 2011-06-30 15:51:07.333 UTC | 11 | 2021-01-16 00:17:54.863 UTC | 2018-03-15 05:29:42.517 UTC | null | 1,048,340 | null | 756,699 | null | 1 | 37 | java|android|date | 138,543 | <p>Does this help?</p>
<pre><code>Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
</code></pre> |
15,707,696 | new mysqli vs mysqli_connect | <p>What is difference between the new <code>mysqli</code> and <code>mysqli_connect</code>?
I know that executing a query is different;
<br />
for example: <code>mysqli->query()</code> and <code>mysqli_query()</code>
<br />
Why are there two different types, what is the need for the difference?</p> | 15,707,717 | 3 | 1 | null | 2013-03-29 16:51:21.513 UTC | 9 | 2020-01-20 08:36:58.863 UTC | 2014-05-08 01:41:34.46 UTC | null | 2,067,006 | null | 1,860,890 | null | 1 | 42 | php|mysqli | 53,664 | <p>One is for Procedural style programming and other is for OOP style programming. Both serve the same purpose; <code>Open a new connection to the MySQL server</code></p>
<p><strong>OOP Style usage</strong></p>
<pre><code>$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
</code></pre>
<p><strong>Procedural Style usage</strong></p>
<pre><code>$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
</code></pre>
<p>Reference: <a href="http://www.php.net/manual/en/mysqli.construct.php">PHP Manual</a></p> |
15,494,568 | HTML iframe - disable scroll | <p>I have following iframe in my site:</p>
<pre><code><iframe src="<<URL>>" height="800" width="800" sandbox="allow-same-origin allow-scripts allow-forms" scrolling="no" style="overflow: hidden"></iframe>
</code></pre>
<p>And it has scrolling bars.<br>
How to get rid of them?</p> | 15,494,969 | 12 | 4 | null | 2013-03-19 08:25:25.667 UTC | 9 | 2020-06-28 14:27:08.927 UTC | null | null | null | null | 1,788,195 | null | 1 | 98 | html|css|iframe | 432,453 | <p>Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the <code>scrolling</code> property (which was removed from the <a href="http://www.w3.org/TR/html5/embedded-content-0.html#the-iframe-element" rel="noreferrer">HTML5 specification</a>).</p>
<p><code>overflow</code> isn't a solution for HTML5 as the only modern browser which <strong>wrongly</strong> supports this is Firefox.</p>
<p>A current solution would be to combine the two:</p>
<pre class="lang-html prettyprint-override"><code><iframe src="" scrolling="no"></iframe>
</code></pre>
<pre class="lang-css prettyprint-override"><code>iframe {
overflow: hidden;
}
</code></pre>
<p>But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: <a href="http://www.christersvensson.com/html-tool/iframe.htm" rel="noreferrer">http://www.christersvensson.com/html-tool/iframe.htm</a></p>
<p><strong>Edit:</strong> I've checked and <code>scrolling="no"</code> will work in IE10, Chrome 25 and Opera 12.12.</p> |
10,429,838 | Uncaught TypeError: undefined is not a function on loading jquery-min.js | <p>I'm building a normal webpage which requires me to load about five CSS files and ten Javascript files.</p>
<ul>
<li>When loading them separately in the HTML page, my webpage loads fine.</li>
<li><p>Now for production, I concatenated all the Javascript into a single file, in the order needed, and all the CSS into another file. But when I try to run the web page with the concatenated files it throws an error saying:</p>
<p><code>Uncaught TypeError: undefined is not a function</code></p></li>
</ul>
<p>On the line where jquery.min.js is being loaded in the concatenated Javascript file.</p>
<p>What can I do to mitigate this? I want to concatenate all files and minify them for production. Please help.</p>
<p><br>
<strong>EDIT:</strong> I merged the Javascript and CSS in the order they were when they were being loaded individually and were working fine.</p> | 10,884,087 | 13 | 3 | null | 2012-05-03 10:48:49.283 UTC | 21 | 2016-01-19 21:02:19.77 UTC | 2013-03-04 04:38:26.737 UTC | null | 680,925 | null | 592,099 | null | 1 | 104 | javascript|jquery|minify | 451,142 | <p>Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with <code>(jQuery)</code> and you need to have <code>(jQuery);</code>.</p>
<p>As separate files the script will load just fine but as one individual file you need the semicolons.</p> |
10,563,789 | How to locate user with leaflet locate? | <p>I'm trying to locate a user and set the map to this position with leaflet:</p>
<pre><code> <script>
var map;
function initMap(){
map = new L.Map('map',{zoomControl : false});
var osmUrl = 'http://{s}.tile.openstreetmap.org/mapnik_tiles/{z}/{x}/{y}.png',
osmAttribution = 'Map data &copy; 2012 OpenStreetMap contributors',
osm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
map.setView(new L.LatLng(51.930156,7.189230), 7).addLayer(osm);
}
function locateUser(){
map.locate({setView : true});
}
</script>
</code></pre>
<p>On execute the browser ask for permission, but then nothing happens? What's wrong with my code?</p> | 10,653,213 | 3 | 4 | null | 2012-05-12 12:35:37.07 UTC | 3 | 2020-12-31 17:33:34.49 UTC | 2012-05-12 17:44:02.37 UTC | null | 253,832 | null | 253,832 | null | 1 | 11 | javascript|leaflet | 43,843 | <p>You have an issue with the scope of your map variable. I have posted an example that fixes your code here: <a href="http://jsfiddle.net/XwbsU/3/" rel="noreferrer">http://jsfiddle.net/XwbsU/3/</a></p>
<p>You should receive the browser geolocation popup when you click 'Find me!'.</p>
<p>Hopefully that helps you.</p> |
10,801,662 | Fixing 'PATH' in Environment Variables in Windows 7 for multiple applications | <p>After using JDK if I use ruby, I have to change 'PATH' in Environment Variables in Windows7. Is there a work around where I don't have to keep changing it even if I use multiple applications?</p> | 10,802,364 | 1 | 4 | null | 2012-05-29 14:57:33.74 UTC | 8 | 2013-11-27 23:04:49.017 UTC | 2013-11-27 23:04:49.017 UTC | null | 1,407,656 | user1403483 | null | null | 1 | 15 | java|ruby|windows|environment-variables | 44,328 | <p>Separate the paths to Ruby and Java with your system's path separator character.</p>
<p>In case of Windows 7, it's </p>
<pre><code>;
</code></pre>
<p>You'll be able to use both</p>
<p>Here's an example of Path variable with numerous applications.</p>
<pre><code>C:\Program Files\TortoiseHg\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\
</code></pre> |
50,344,403 | How to config SMTP Settings in Sentry? | <p>How to config SMTP Settings in <code>Sentry</code>?</p>
<p>I set my SMTP mail-server configuration on <code>onpremise/config.yml</code>, then I did as follows:</p>
<p><code>sudo docker-compose run --rm web upgrade</code><br>
<code>sudo docker-compose up -d</code> (before that, I removed previous consider containers) </p>
<p>But in Sentry mail setting panel not appeared my SMTP configs: </p>
<p><a href="https://i.stack.imgur.com/kYNY2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/kYNY2.jpg" alt="sentry SMTP setting "></a></p>
<hr>
<p><strong>NOTE</strong>: I'm using <a href="https://github.com/getsentry/onpremise" rel="noreferrer">onpremise</a> sentry docker package.</p>
<p>What should I do? </p>
<p>Any help with this would be greatly appreciated.</p> | 51,346,278 | 5 | 11 | null | 2018-05-15 07:17:58.327 UTC | 11 | 2021-06-25 21:25:23.997 UTC | 2019-11-03 10:42:50.893 UTC | null | 3,702,377 | null | 3,702,377 | null | 1 | 20 | docker|smtp|docker-compose|sentry | 19,827 | <p>Problem solved: </p>
<p>I updated my Sentry version from 8.22.0 to 9.0.0 with Dockerfile and configure config.yml file as following:</p>
<h2>A piece of config.yml on <a href="https://github.com/getsentry/onpremise" rel="noreferrer">onpremise</a> package:</h2>
<pre><code>###############
# Mail Server #
###############
mail.backend: 'smtp' # Use dummy if you want to disable email entirely
mail.host: 'smtp.gmail.com'
mail.port: 587
mail.username: '[email protected]'
mail.password: '********'
mail.use-tls: true
# The email address to send on behalf of
mail.from: '[email protected]'
</code></pre>
<h2>Dockerfile:</h2>
<pre><code>FROM sentry:9.0-onbuild
</code></pre>
<p>Or you can do <code>$ git pull</code> in <a href="https://github.com/getsentry/onpremise" rel="noreferrer">onpremise</a> path (to get latest changes).</p>
<h2>Finally:</h2>
<pre><code>docker-compose build
docker-compose run --rm web upgrade
docker-compose up -d
</code></pre>
<hr> |
35,509,611 | Mongoose - Save array of strings | <p>I can't save an array of strings into my DB using <code>Mongoose</code>.</p>
<p>(Note all code below is simplified for ease of writing here)</p>
<p>So i declare a variable of a person schema I have:</p>
<pre><code>var newPerson = new Person ({
tags: req.body.tags
});
</code></pre>
<p>The schema itself looks like:</p>
<pre><code>var personSchema = new mongoose.Schema({
tags: Array
});
</code></pre>
<p>And when it comes to saving its just a simple:</p>
<pre><code>newPerson.save(function(err) {
//basic return of json
});
</code></pre>
<p>So using Postman I send in an array in the body - however everytime I check the DB, it just shows one entry with the array as a whole i.e. how I sent it:</p>
<p><a href="https://i.stack.imgur.com/ovZwc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ovZwc.png" alt="enter image description here"></a></p>
<p>Any ideas what extra I'm supposed to do?</p> | 35,510,333 | 11 | 8 | null | 2016-02-19 16:04:34.1 UTC | 25 | 2022-09-12 12:13:12.447 UTC | 2018-06-18 15:40:22.123 UTC | null | 5,623,520 | null | 3,033,691 | null | 1 | 59 | node.js|mongodb|express|mongoose | 116,740 | <p>Write up from my comment: </p>
<p>The way to specify an array of strings in mongoose is like so:</p>
<pre><code>var personSchema = new mongoose.Schema({
tags: [{
type: String
}]
</code></pre>
<p>However, the problem here is most-likely to do with Postman as it is sending the 'array' as a string. You can check this by checking the type of <code>req.body.tags</code> like so:</p>
<pre><code>console.log(typeof req.body.tags)
</code></pre>
<p>If this returns a String, make sure to set the content-type in Postman to JSON as seen in <a href="https://imgur.com/4n3Zfep" rel="noreferrer">this</a> screenshot rather than the default 'form-data' option.</p> |
33,380,668 | How to set android TabLayout in the bottom of the screen? | <p>My question is how I can set the new android material design TabLayout to be in the bottom of the screen, kind of like Instagram's bottom toolbar. </p>
<p>If you have never seen Instagram's UI here is a screenshot of it :</p>
<p><img src="https://i.stack.imgur.com/12bur.jpg" alt="If you have never seen Instagram's UI here is a screenshot of it">. If there is a better way of approaching this, please feel free to post it here (with a code example if possible), I will greatly appreciate it.</p>
<p>Here is my code: activity_main.xml
</p>
<pre><code><android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code></pre>
<p></p>
<p>I have tried many methods and workarounds suggested by the Stack Overflow community, but none seems to work with this new implementation of tabs in android. I know this UI design does not follow android design guidelines, so please don't comment on it. This UI design is vital to my application's UX and I would appreciate getting an answer for it. Thank you!</p> | 33,381,112 | 7 | 6 | null | 2015-10-28 00:03:20.82 UTC | 17 | 2020-01-23 14:29:40.497 UTC | 2018-06-06 10:28:04.563 UTC | null | 13,860 | null | 2,864,163 | null | 1 | 31 | android|android-layout|android-tablayout | 53,965 | <p>I believe I have the best simple fix. Use a LinearLayout and set the height of the viewpager to be 0dp with a layout_weight="1". Make sure the LinearLayout has an orientation of vertical and that the viewpager comes before the TabLayout. Here is what mines looks like:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<include layout="@layout/toolbar" android:id="@+id/main_toolbar"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/white"/>
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/blue"
/>
</LinearLayout>
</code></pre>
<p>And as a bonus, you should create your toolbar only once as toolbar.xml. So that way all you have to do is used the include tag. Makes your layout's more clean. Enjoy!</p>
<p><strong>toolbar.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</code></pre>
<p><strong>Update 11.2.2016:</strong> For those of you who don't know how to inflate the toolbar, here is how. Make sure that your Activity extends AppCompatActivity so you can call setSupportActionBar() and getSupportActionBar(). </p>
<pre><code>Toolbar mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code></pre> |
13,309,686 | How to do structured programming using blocks in Objective-C | <p>When using methods which return blocks they can be very convenient.
However, when you have to string a few of them together it gets messy really quickly</p>
<p>for instance, you have to call 4 URLs in succession:</p>
<pre><code>[remoteAPIWithURL:url1 success:^(int status){
[remoteAPIWithURL:url2 success:^(int status){
[remoteAPIWithURL:url3 success:^(int status){
[remoteAPIWithURL:url2 success:^(int status){
//succes!!!
}];
}];
}];
}];
</code></pre>
<p>So for every iteration I go one level deeper, and I don't even handle errors in the nested blocks yet.</p>
<p>It gets worse when there is an actual loop. For instance, say I want to upload a file in 100 chunks:</p>
<pre><code>- (void) continueUploadWithBlockNr:(int)blockNr
{
if(blocknr>=100)
{
//success!!!
}
[remoteAPIUploadFile:file withBlockNr:blockNr success:^(int status)
{
[self continueUploadWithBlockNr:blockNr];
}];
}
</code></pre>
<p>This feels very unintuitive, and gets very unreadable very quick.</p>
<p>In .Net they solved all this using the async and await keyword, basically unrolling these continuations into a seemingly synchronous flow.</p>
<p>What is the best practice in Objective C?</p> | 13,473,686 | 8 | 7 | null | 2012-11-09 14:14:08.76 UTC | 9 | 2012-11-20 16:12:37.573 UTC | 2012-11-18 12:50:07.68 UTC | null | 558,816 | null | 71,883 | null | 1 | 10 | objective-c|lambda|objective-c-blocks|continuations|structured-programming | 1,147 | <p>Your question immediately made me think of recursion. Turns out, <a href="http://ddeville.me/2011/10/recursive-blocks-objc/" rel="nofollow">Objective-c blocks can be used in recursion</a>. So I came up with the following solution, which is easy to understand and can scale to N tasks pretty nicely.</p>
<pre><code>// __block declaration of the block makes it possible to call the block from within itself
__block void (^urlFetchBlock)();
// Neatly aggregate all the urls you wish to fetch
NSArray *urlArray = @[
[NSURL URLWithString:@"http://www.google.com"],
[NSURL URLWithString:@"http://www.stackoverflow.com"],
[NSURL URLWithString:@"http://www.bing.com"],
[NSURL URLWithString:@"http://www.apple.com"]
];
__block int urlIndex = 0;
// the 'recursive' block
urlFetchBlock = [^void () {
if (urlIndex < (int)[urlArray count]){
[self remoteAPIWithURL:[urlArray objectAtIndex:index]
success:^(int theStatus){
urlIndex++;
urlFetchBlock();
}
failure:^(){
// handle error.
}];
}
} copy];
// initiate the url requests
urlFetchBlock();
</code></pre> |
13,636,290 | variadic template of a specific type | <p>I want a variadic template that simply accepts unsigned integers.
However, I couldn't get the following to work.</p>
<pre><code>struct Array
{
template <typename... Sizes> // this works
// template <unsigned... Sizes> -- this does not work (GCC 4.7.2)
Array(Sizes... sizes)
{
// This causes narrowing conversion warning if signed int is supplied.
unsigned args[] = { sizes... };
// ...snipped...
}
};
int main()
{
Array arr(1, 1);
}
</code></pre>
<p>Any help appreciated.</p>
<p>EDIT: In case you're wondering, I'm trying to use variadic template to replicate the following.</p>
<pre><code>struct Array
{
Array(unsigned size1) { ... }
Array(unsigned size1, unsigned size2) { ... }
Array(unsigned size1, unsigned size2, unsigned size3) { ... }
// ...
Array(unsigned size1, unsigned size2, ..., unsigned sizeN) { ... }
};
</code></pre> | 13,636,357 | 4 | 5 | null | 2012-11-29 22:55:22.463 UTC | 8 | 2020-01-29 16:26:43.927 UTC | 2012-11-29 23:08:54.047 UTC | null | 383,306 | null | 383,306 | null | 1 | 20 | c++|gcc|c++11|variadic-templates | 7,716 | <p>I'm not sure why you expected that to work. Clang tells me the error is <code>unknown type name 'Sizes'</code> in the declaration of the constructor. Which is to be expected, since <code>Sizes</code> isn't a type (or rather, a template pack of types), it's a template pack of values.</p>
<p>It's unclear what exactly you're trying to do here. If you pass integral values in as template parameters, what are the constructor parameters supposed to be?</p>
<hr>
<p><strong>Update</strong>: With your new code all you need is a <code>static_cast<unsigned>()</code>.</p>
<pre><code>struct Array
{
template <typename... Sizes> // this works
Array(Sizes... sizes)
{
unsigned args[] = { static_cast<unsigned>(sizes)... };
// ...snipped...
}
};
</code></pre> |
13,277,667 | C# string replace does not actually replace the value in the string | <p>I am trying to replace a part of string with another another string. To be more precise
I have <code>C:\Users\Desktop\Project\bin\Debug</code></p>
<p>and I am trying to replace <code>\bin\Debug</code> with <code>\Resources\People</code></p>
<p>I have tried the following:</p>
<ol>
<li><p><code>path.Replace(@"\bin\Debug", @"\Resource\People\VisitingFaculty.txt");</code></p></li>
<li><p><code>path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");</code></p></li>
</ol>
<p>None of the above two seems to work, as the string remains the same and nothing is replaced. Am I doing something wrong? </p> | 13,277,669 | 3 | 9 | null | 2012-11-07 20:29:36.183 UTC | 5 | 2020-07-20 18:58:18.89 UTC | 2018-12-31 08:29:42.447 UTC | null | 1,766,548 | null | 1,766,548 | null | 1 | 41 | c#|.net|string | 81,537 | <p>The problem is that strings are immutable. The methods replace, substring, etc. do not change the string itself. They create a new string and replace it. So for the above code to be correct, it should be</p>
<pre><code>path1 = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
</code></pre>
<p>Or just</p>
<pre><code>path = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
</code></pre>
<p>if another variable is not needed.</p>
<p>This answer is also a reminder that strings are immutable. Any change you make to them will in fact create a new string. So keep that in mind with everything that involves strings, including memory management.
As stated in the documentation <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/" rel="noreferrer">here</a>.</p>
<blockquote>
<p>String objects are immutable: they cannot be changed after they have
been created. All of the String methods and C# operators that appear
to modify a string actually return the results in a new string object</p>
</blockquote> |
13,730,982 | Force line break (<br/>) in header (<h1>) in Markdown | <p>I'm trying to create a two-line <code><h1></code> in Markdown, something along the lines of:</p>
<pre><code><h1>Title<br/>byline</h1>
</code></pre>
<p>The Markdown docs say:</p>
<blockquote>
<p>When you do want to insert a <code><br /></code> break tag using Markdown, you end a line with two or more spaces, then type return.</p>
</blockquote>
<p>Unfortunately, this only seems to work for paragraphs -- if I try it with an <code><h1></code> (dots · indicate spaces):</p>
<pre><code>#·Title··
byline
</code></pre>
<p>the trailing spaces are ignored and I just get:</p>
<pre><code><h1>Title</h1>
<p>byline</p>
</code></pre>
<p>Can anyone tell me a workaround for this?</p>
<p>P.S. I'm using vanilla Markdown 1.0.1 from the command line.</p> | 13,731,060 | 3 | 3 | null | 2012-12-05 19:32:29.957 UTC | 11 | 2022-05-20 09:52:52.28 UTC | 2017-02-11 16:58:45.987 UTC | null | 926,639 | null | 27,358 | null | 1 | 51 | html|header|markdown|line-breaks | 51,112 | <p>Turns out the answer is just "use <code><br/></code>." </p>
<pre class="lang-none prettyprint-override"><code># Title <br/> byline
</code></pre>
<p>produces</p>
<pre class="lang-html prettyprint-override"><code><h1>Title <br/> byline</h1>
</code></pre>
<p>** <strong>facepalm</strong> **</p> |
13,578,416 | Read binary stdout data like screencap data from adb shell? | <p>Is it possible to read binary stdout from an adb shell command? For example, all examples of how to use screencap include two steps:</p>
<pre><code>adb shell screencap -p /sdcard/foo.png
adb pull /sdcard/foo.png
</code></pre>
<p>However, the service supports writing to stdout. You can for instance, do the following:</p>
<pre><code>adb shell "screencap -p > /sdcard/foo2.png"
adb pull /sdcard/foo2.png
</code></pre>
<p>And this works equally well. But, what about reading the output across ADB? What I want to do is the following:</p>
<pre><code>adb shell screencap -p > foo3.png
</code></pre>
<p>And avoid the intermediate write to the SD card. This generates something that <em>looks</em> like a PNG file (running <code>strings foo3.png</code> generates something with an IHDR, IEND, etc.) and is approximately the same size, but the file is corrupted as far as image readers are concerned.</p>
<p>I have also attempted to do this using ddmlib in java and the results are the same. I would be happy to use any library necessary. My goal is to reduce total time to get the capture. On my device, using the two-command solution, it takes about 3 seconds to get the image. Using ddmlib and capturing stdout takes less than 900ms, but it doesn't work!</p>
<p>Is it possible to do this?</p>
<p>EDIT: Here is the hexdump of two files. The first one, screen.png came from stdout and is corrupted. The second one, xscreen is from the two-command solution and works. The images should be visually identical.</p>
<pre><code>$ hexdump -C screen.png | head
00000000 89 50 4e 47 0d 0d 0a 1a 0d 0a 00 00 00 0d 49 48 |.PNG..........IH|
00000010 44 52 00 00 02 d0 00 00 05 00 08 06 00 00 00 6e |DR.............n|
00000020 ce 65 3d 00 00 00 04 73 42 49 54 08 08 08 08 7c |.e=....sBIT....||
00000030 08 64 88 00 00 20 00 49 44 41 54 78 9c ec bd 79 |.d... .IDATx...y|
00000040 9c 1d 55 9d f7 ff 3e 55 75 f7 de b7 74 77 d2 d9 |..U...>Uu...tw..|
00000050 bb b3 27 10 48 42 16 c0 20 01 86 5d 14 04 11 dc |..'.HB.. ..]....|
00000060 78 44 9d c7 d1 d1 11 78 70 7e 23 33 8e 1b 38 33 |xD.....xp~#3..83|
00000070 ea 2c 8c 8e 0d 0a 08 a8 23 2a 0e 10 82 ac c1 40 |.,......#*.....@|
00000080 12 02 81 24 64 ef ec 5b ef fb 5d 6b 3b bf 3f ea |...$d..[..]k;.?.|
00000090 de db dd 49 27 e9 ee 74 77 3a e3 79 bf 5e 37 e7 |...I'..tw:.y.^7.|
$ hexdump -C xscreen.png | head
00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR|
00000010 00 00 02 d0 00 00 05 00 08 06 00 00 00 6e ce 65 |.............n.e|
00000020 3d 00 00 00 04 73 42 49 54 08 08 08 08 7c 08 64 |=....sBIT....|.d|
00000030 88 00 00 20 00 49 44 41 54 78 9c ec 9d 77 98 1c |... .IDATx...w..|
00000040 c5 99 ff 3f d5 dd 93 37 27 69 57 5a e5 55 4e 08 |...?...7'iWZ.UN.|
00000050 24 a1 00 58 18 04 26 08 8c 01 83 31 38 c0 19 9f |$..X..&....18...|
00000060 ef 7c c6 3e 1f 70 f8 7e 67 ee 71 e2 b0 ef ce f6 |.|.>.p.~g.q.....|
00000070 f9 ec 73 04 1b 1c 31 60 23 84 30 22 88 a0 40 10 |..s...1`#.0"..@.|
00000080 08 65 69 95 d3 4a 9b c3 c4 4e f5 fb a3 67 66 77 |.ei..J...N...gfw|
00000090 a5 95 b4 bb da a4 73 7d 9e 67 55 f3 ed 50 5d dd |......s}.gU..P].|
</code></pre>
<p>Just at quick glance it seems like a couple of extra 0x0d (13) bytes get added. Carriage return?? Does that ring any bells? Is it mixing in some blank lines?</p> | 14,353,315 | 19 | 5 | null | 2012-11-27 06:16:52.733 UTC | 44 | 2022-07-17 04:43:40.237 UTC | 2022-04-29 08:58:18.913 UTC | null | 150,978 | null | 1,743,517 | null | 1 | 71 | android|adb | 43,939 | <p>Sorry to be posting an answer to an old question, but I just came across this problem myself and wanted to do it only through the shell. This worked well for me:</p>
<pre><code>adb shell screencap -p | sed 's/^M$//' > screenshot.png
</code></pre>
<p>That <code>^M</code> is a char I got by pressing ctrl+v -> ctrl+m, just noticed it doesn't work when copy-pasting.</p>
<pre><code>adb shell screencap -p | sed 's/\r$//' > screenshot.png
</code></pre>
<p>did the trick for me as well.</p> |
20,743,121 | How can I get SQL result into a STRING variable? | <p>I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way?
I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).</p> | 20,743,259 | 5 | 2 | null | 2013-12-23 12:01:17.467 UTC | 2 | 2018-10-19 18:21:45.113 UTC | 2013-12-23 12:02:36.683 UTC | null | 447,156 | null | 1,243,819 | null | 1 | 7 | c#|sql|sql-server|string|save | 83,559 | <p>This isn't the single greatest example in history, as if you don't return any rows from the database you'll end up with an exception, but if you want to use a stored procedure from the database, rather than running a <code>SELECT</code> statement straight from your code, then this will allow you to return a string:</p>
<pre><code>public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
</code></pre>
<p>It can definitely be improved, but it would give you a starting point to work from if you want to go down a stored procedure route.</p> |
20,503,060 | How to decrypt the first message sent from Mifare Desfire EV1 | <p>Does anyone have a clue how to decrypt the first message sent from the card? I mean after the authentication success and then you send a command (for example 0x51 (GetRealTagUID). It returns 00+random32bits (always different). I try to decrypt it with:</p>
<pre><code> private byte[] decrypt(byte[] raw, byte[] encrypted, byte[] iv)
throws Exception {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
</code></pre>
<p>And calling it with decrypt(sessionKey, response, iv)</p>
<p>IV = all zeros (16 bytes)</p>
<p>response = that 32randombits after the 0x51 command (just removed the two zeros)</p>
<p>Someone told me, that the IV changes after the first sent command (0x51). How to generate the right IV for decrypting that response? I think the all zeros is wrong, because the decrypted message is always different and it should be always same with the same card.</p>
<p>-EDIT-</p>
<p>After applying your (Michael Roland) instructions, the decrypted response is still just random bits. Here is my code (I think I'm doing something wrong):</p>
<pre><code> byte[] x = encrypt(sessionKey, iv, iv);
byte[] rx = rotateBitsLeft(x);
if ((rx[15] & 0x01) == 0x01)
rx[15] = (byte) (rx[15] ^ 0x87);
if ((rx[15] & 0x01) == 0x00)
rx[15] = (byte) (rx[15] ^ 0x01);
byte[] crc_k1 = rx;
byte[] rrx = rotateBitsLeft(rx);
if ((rrx[15] & 0x01) == 0x01)
rrx[15] = (byte) (rrx[15] ^ 0x87);
if ((rrx[15] & 0x01) == 0x00)
rrx[15] = (byte) (rrx[15] ^ 0x01);
byte[] crc_k2 = rrx;
byte[] command = { (byte) 0x51, (byte) 0x80, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00 };
for (int i = 0; i < 16; i++){
command[i] = (byte) (command[i] ^ crc_k2[i]);
}
byte[] iv2 = encrypt(sessionKey, command, iv);
byte[] RealUID = decrypt(sessionKey, ReadDataParsed, iv2);
Log.e("RealUID", ByteArrayToHexString(RealUID));
</code></pre>
<p>-EDIT3-</p>
<p>Still returning always different values. I think the problem might lie here:</p>
<pre><code>byte[] iv2 = encrypt(sessionKey, command, iv);
</code></pre>
<p>What IV to use when creating the new IV for decrypting the response? It is all zeros there.</p> | 20,504,667 | 2 | 3 | null | 2013-12-10 19:01:42.537 UTC | 10 | 2019-12-13 01:32:41.527 UTC | 2013-12-11 17:46:45.103 UTC | null | 3,045,817 | null | 3,045,817 | null | 1 | 3 | java|encryption|cryptography|aes|mifare | 3,864 | <p>After authentication, the IV is reset to all-zeros. As you use AES authentication, you then have to calculate the CMAC for every follow-up command (even if CMAC is not actually appended to the command). So the CMAC calculation for your command will lead to correct IV initialization for decoding the response. I.e. the CMAC for the command is equal to the IV for decrypting the response. Similarly, for all further commands, the IV is the last cipher block from the previous encryption/CMAC.</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p><strong>How to calculate CMAC pad XOR value</strong></p>
<ul>
<li>Encrypt one block of zeros (<code>0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00</code>) with session key (using IV of zeros). -> <code>x[0..15]</code></li>
<li>Rotate <code>x[0..15]</code> one bit to the left. -> <code>rx[0..15]</code></li>
<li>If the last bit (bit 0 in <code>rx[15]</code>) is one: xor <code>rx[15]</code> with <code>0x86</code>.</li>
<li>Store <code>rx[0..15]</code> as <code>crc_k1[0..15]</code>.</li>
<li>Rotate <code>rx[0..15]</code> one bit to the left. -> <code>rrx[0..15]</code></li>
<li>If the last bit (bit 0 in <code>rrx[15]</code>) is one: xor <code>rrx[15]</code> with <code>0x86</code>.</li>
<li>Store <code>rrx[0..15]</code> as <code>crc_k2[0..15]</code>.</li>
</ul>
<p><strong>How to calculate CMAC</strong></p>
<ul>
<li>You pad the command using <code>0x80 0x00 0x00 ...</code> to the block size of the cipher (16 bytes for AES). If the command length matches a multiple of the block size, no padding is added.</li>
<li>For your command (<code>0x51</code>) this would look like: <code>0x51 0x80 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00</code></li>
<li>If padding was added, xor the last 16 bytes of the padded command with <code>crc_k2[0..15]</code>.</li>
<li>If no padding was added, xor the last 16 bytes of the command with <code>crc_k1[0..15]</code>.</li>
<li>Encrypt (in send mode, i.e. <code>enc(IV xor datablock)</code>, cipher text of previous block is new IV) the result with the session key.</li>
<li>The ciphertext of the last block is the CMAC and the new IV.</li>
</ul>
<hr>
<p><strong>UPDATE 2:</strong></p>
<p><strong>How to rotate a bit vector to the left for one bit</strong></p>
<pre><code>public void rotateLeft(byte[] data) {
byte t = (byte)((data[0] >>> 7) & 0x001);
for (int i = 0; i < (data.length - 1); ++i) {
data[i] = (byte)(((data[i] << 1) & 0x0FE) | ((data[i + 1] >>> 7) & 0x001));
}
data[data.length - 1] = (byte)(((data[data.length - 1] << 1) & 0x0FE) | t);
}
</code></pre> |
24,080,275 | Plotting multiple line graph using pandas and matplotlib | <p>I have the following data in a pandas dataframe</p>
<pre><code> date template score
0 20140605 0 0.138786
1 20140605 1 0.846441
2 20140605 2 0.766636
3 20140605 3 0.259632
4 20140605 4 0.497366
5 20140606 0 0.138139
6 20140606 1 0.845320
7 20140606 2 0.762876
8 20140606 3 0.261035
9 20140606 4 0.498010
</code></pre>
<p>For every day there will be 5 templates and each template will have a score.</p>
<p>I want to plot the date in the x axis and score in the y axis and a separate line graph for each template in the same figure.</p>
<p>Is it possible to do this using matplotlib?</p> | 24,082,767 | 4 | 2 | null | 2014-06-06 11:02:21.247 UTC | 6 | 2015-12-05 20:34:54.947 UTC | null | null | null | null | 24,949 | null | 1 | 20 | python|matplotlib|plot|pandas | 44,690 | <p>You can use an approach like the following one. You can simply slice the dataframe according to the values of each template, and subsequently use the dates and scores for the plot.</p>
<pre><code>from pandas import *
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
#The following part is just for generating something similar to your dataframe
date1 = "20140605"
date2 = "20140606"
d = {'date': Series([date1]*5 + [date2]*5), 'template': Series(range(5)*2),
'score': Series([random() for i in range(10)]) }
data = DataFrame(d)
#end of dataset generation
fig, ax = plt.subplots()
for temp in range(5):
dat = data[data['template']==temp]
dates = dat['date']
dates_f = [dt.datetime.strptime(date,'%Y%m%d') for date in dates]
ax.plot(dates_f, dat['score'], label = "Template: {0}".format(temp))
plt.xlabel("Date")
plt.ylabel("Score")
ax.legend()
plt.show()
</code></pre> |
24,367,930 | Very strange behavior of operator 'is' with methods | <p>Why is the first result <code>False</code>, should it not be <code>True</code>?</p>
<pre><code>>>> from collections import OrderedDict
>>> OrderedDict.__repr__ is OrderedDict.__repr__
False
>>> dict.__repr__ is dict.__repr__
True
</code></pre> | 24,368,034 | 2 | 4 | null | 2014-06-23 14:00:37.793 UTC | 8 | 2014-10-20 13:02:15.117 UTC | 2014-10-20 13:02:15.117 UTC | null | 100,297 | null | 665,926 | null | 1 | 47 | python|python-2.7|methods|python-internals | 2,342 | <p>For user-defined functions, in Python 2 <em>unbound</em> and <em>bound</em> methods are created on demand, through the <a href="https://docs.python.org/2/howto/descriptor.html">descriptor protocol</a>; <code>OrderedDict.__repr__</code> is such a method object, as the wrapped function is implemented as a <a href="http://hg.python.org/cpython/file/e28004fb30c0/Lib/collections.py#l164">pure-Python function</a>.</p>
<p>The descriptor protocol will call the <a href="https://docs.python.org/2/reference/datamodel.html#object.__get__"><code>__get__</code> method</a> on objects that support it, so <code>__repr__.__get__()</code> is called whenever you try to access <code>OrderedDict.__repr__</code>; for classes <code>None</code> (no instance) and the class object itself are passed in. Because you get a <em>new</em> method object each time the function <code>__get__</code> method is invoked, <code>is</code> fails. It is not the same method object.</p>
<p><code>dict.__repr__</code> is not a custom Python function but a C function, and its <code>__get__</code> descriptor method <a href="http://hg.python.org/cpython/file/e28004fb30c0/Objects/descrobject.c#l59">essentially just returns <code>self</code> when accessed on the class</a>. Accessing the attribute gives you the same object each time, so <code>is</code> works:</p>
<pre><code>>>> dict.__repr__.__get__(None, dict) is dict.__repr__ # None means no instance
True
</code></pre>
<p>Methods have a <code>__func__</code> attribute referencing the wrapped function, use that to test for identity:</p>
<pre><code>>>> OrderedDict.__repr__
<unbound method OrderedDict.__repr__>
>>> OrderedDict.__repr__.__func__
<function __repr__ at 0x102c2f1b8>
>>> OrderedDict.__repr__.__func__.__get__(None, OrderedDict)
<unbound method OrderedDict.__repr__>
>>> OrderedDict.__repr__.__func__ is OrderedDict.__repr__.__func__
True
</code></pre>
<p>Python 3 does away with <em>unbound</em> methods, <code>function.__get__(None, classobj)</code> returns the function object itself (so it behaves like <code>dict.__repr__</code> does). But you will see the same behaviour with <em>bound</em> methods, methods retrieved from an instance.</p> |
29,347,253 | SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1) | <p>I am trying to get specific data from the database by using column <code>SongID</code> when a user clicks a link but I am getting this error: </p>
<blockquote>
<p>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where
clause' (SQL: select * from <code>songs</code> where <code>id</code> = 5 limit 1)</p>
</blockquote>
<p>The Controller Class:</p>
<pre><code><?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
class SongsController extends Controller {
public function index()
{
$name = $this->getName();
$songs = DB::table('songs')->get();
return view('songs.index', compact('songs','name'));
}
public function show($id)
{
$name = $this->getName();
$song = DB::table('songs')->find($id);
return view('songs.show', compact('song','name'));
}
private function getName()
{
$name = 'Tupac Amaru Shakur';
return $name;
}
}
</code></pre>
<p>Migration:</p>
<pre><code> public function up()
{
Schema::create('songs', function($table)
{
$table->increments('SongID');
$table->string('SongTitle')->index();
$table->string('Lyrics')->nullable();
$table->timestamp('created_at');
});
}
</code></pre> | 29,347,507 | 6 | 2 | null | 2015-03-30 13:17:14.937 UTC | 10 | 2022-07-29 13:28:12.04 UTC | 2018-09-11 15:11:16.067 UTC | user5942421 | 9,373,268 | null | 2,391,964 | null | 1 | 41 | php|mysql|laravel|laravel-5 | 167,409 | <p>When you use <code>find()</code>, it automatically assumes your primary key column is going to be <code>id</code>. In order for this to work correctly, you should set your primary key in your model.</p>
<p>So in <code>Song.php</code>, within the class, add the line...</p>
<pre><code>protected $primaryKey = 'SongID';
</code></pre>
<p>If there is any possibility of changing your schema, I'd highly recommend naming all your primary key columns <code>id</code>, it's what Laravel assumes and will probably save you from more headaches down the road.</p> |
16,191,236 | Tomcat startup fails due to 'java.net.SocketException Invalid argument' on Mac OS X | <p>We have an application that runs on Tomcat 6 (6.0.35.0 to be precise), and most of our engineers on Mac OS are having problems starting Tomcat due to the socketAccept call in the Catalina.await method throwing a SocketException:</p>
<pre><code>SEVERE: StandardServer.await: accept:
java.net.SocketException: Invalid argument
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.socketAccept(PlainSocketImpl.java)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
at java.net.ServerSocket.implAccept(ServerSocket.java:522)
at java.net.ServerSocket.accept(ServerSocket.java:490)
at org.apache.catalina.core.StandardServer.await(StandardServer.java:431)
at org.apache.catalina.startup.Catalina.await(Catalina.java:676)
at org.apache.catalina.startup.Catalina.start(Catalina.java:628)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
at mycompany.tomcat.startup.ThreadDumpWrapper.main(ThreadDumpWrapper.java:260)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.tanukisoftware.wrapper.WrapperStartStopApp.run(WrapperStartStopApp.java:238)
at java.lang.Thread.run(Thread.java:722)
</code></pre>
<p>This causes Tomcat to shut down immediately after startup (and no small amount of rage).
We think this has been with us for the duration on Mac OS w/ Java 1.7, in the last several months a lot of us have switched to Macbook Pros. Up until now, the only symptom was occasional zero byte responses from Tomcat, due to this exception also being thrown on a socketRead. Errors don't hit the logs and we'd individually shrugged it off as an isolated problem, and only found the cause when the startup problem started and I set a SocketException breakpoint:</p>
<pre><code>Daemon Thread [http-8080-1] (Suspended (breakpoint at line 47 in SocketException))
SocketException.<init>(String) line: 47
SocketInputStream.socketRead0(FileDescriptor, byte[], int, int, int) line: not available [native method]
SocketInputStream.socketRead0(FileDescriptor, byte[], int, int, int) line: not available
SocketInputStream.read(byte[], int, int, int) line: 150
SocketInputStream.read(byte[], int, int) line: 121
InternalInputBuffer.fill() line: 735
InternalInputBuffer.parseRequestLine() line: 366
Http11Processor.process(Socket) line: 814
Http11Protocol$Http11ConnectionHandler.process(Socket) line: 602
JIoEndpoint$Worker.run() line: 489
Thread.run() line: 722
</code></pre>
<p>For arguments:</p>
<pre><code>arg0 FileDescriptor (id=499)
fd 1097
useCount AtomicInteger (id=503)
value 2
arg1 (id=502)
arg2 0
arg3 8192
arg4 20000
</code></pre>
<p>The problem is time sensitive. Increasing startup time due to application changes (lots more Spring introspection/singleton overhead) seems to be the factor that causes this to affect Tomcat startup; the tipping point being about 160 seconds. We can mitigate the problem by disabling some of the non-mandatory contexts we don't need during development to reduce startup time, but I'd prefer to find the root cause.</p>
<h2>Application configuration</h2>
<p>The specifics of the application are far too complex to go into too much detail, but I have a hunch that this might relate to an earlier bind, so I'll at least list the listening ports on my machine:</p>
<pre><code>localhost:32000 - Java service wrapper port
*:10001 - RMI registry
*:2322 - Java debug
*:56566 - RMI
*:8180 - Tomcat HTTP connector
*:8543 - Tomcat HTTPS connector
*:2223 - Tomcat Internal HTTP connector (used for cross-server requests)
*:14131 - 'Locking' port to determine if an internal service is running
*:56571 - EhCache RMI
*:56573 - RMI
*:62616 - ActiveMQ broker
*:5001 - SOAPMonitorService
*:8109 - Tomcat shutdown port
</code></pre>
<h2>Items ruled out</h2>
<ul>
<li>The most obvious solution: <code>-Djava.net.preferIPv4Stack=true</code>. I've always had that option configured</li>
<li>Any recent configuration change to our base application configuration, libraries, JVM options (there aren't any)</li>
<li>A JDK regression. I've tested JDK 1.7.0_09, 11, 15, 17 and 21 (the JDKs I've had installed on my machine for the duration)</li>
<li>Mac OS update. Mac OS 10.7.x and 10.8.0 through 1.8.3 are affected</li>
<li>File descriptor limits - increased from <code>5000</code> to <code>10000</code></li>
<li>Disabling IPv6 completely on the main ethernet interface</li>
<li>Setting breakpoints, and removing the first contexts to be affected by the SocketException (they're outgoing HTTP calls to web services). No change</li>
<li>Configuring <code>/etc/hosts</code> so the machine hostname resolves to localhost, and configuring JVM options to prefer IPv4 and to <em>not</em> prefer IPv6 addresses (This answer: <a href="https://stackoverflow.com/a/16318860/364206">https://stackoverflow.com/a/16318860/364206</a>)</li>
</ul>
<p>For those interested in hosts configuration, it's the same as default. I can reproduce this on a Fusion VM w/ a clean install of 10.8:</p>
<pre><code>##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost
</code></pre>
<h2>Java code investigation</h2>
<p>Due to the apparent time sensitive nature of the issue, setting breakpoints to troubleshoot the issue causes it to not occur. As requested in the comments, I also captured <code>arg0</code> for <code>SocksSocketImpl(PlainSocketImpl).socketAccept(SocketImpl)</code>, nothing seems out of the ordinary. </p>
<pre><code>arg0 SocksSocketImpl (id=460)
address InetAddress (id=465)
canonicalHostName null
holder InetAddress$InetAddressHolder (id=475)
address 0
family 0
hostName null
applicationSetProxy false
closePending false
cmdIn null
cmdOut null
cmdsock null
CONNECTION_NOT_RESET 0
CONNECTION_RESET 2
CONNECTION_RESET_PENDING 1
external_address null
fd FileDescriptor (id=713)
fd -1
useCount AtomicInteger (id=771)
value 0
fdLock Object (id=714)
fdUseCount 0
localport 0
port 0
resetLock Object (id=716)
resetState 0
server null
serverPort 1080
serverSocket null
shut_rd false
shut_wr false
socket Socket (id=718)
bound false
closed false
closeLock Object (id=848)
connected false
created false
impl null
oldImpl false
shutIn false
shutOut false
socketInputStream null
stream false
timeout 0
trafficClass 0
useV4 false
</code></pre>
<p>I think all of the threads where the exceptions are thrown are victims of an earlier call, one that doesn't result in a SocketException so I haven't been able to catch it. Being able to start Tomcat by reducing startup times convinces me that the trigger is probably some scheduled task that performs a socket based operation, which then affects other socket operations.</p>
<p>That doesn't explain how and why this could affect several threads, no matter what we're doing to cause this condition, mysterious SocketExceptions shouldn't bubble up from native code and cause these exceptions simultaneously on multiple threads - that is, two threads making outgoing web service calls, the Tomcat await call, and several TP processor threads repeatedly.</p>
<h2>JNI code investigation</h2>
<p>Given the generic message, I assumed that an <code>EINVAL</code> error must be returned from one of the system calls in the socketAccept JNI code, so I traced the system calls leading up to the exception; there's no <code>EINVAL</code> returned from any system call. So, I went to the OpenJDK sources looking for conditions in the socketAccept code that would set and then throw an <code>EINVAL</code>, but I also couldn't find any code that sets <code>errno</code> to <code>EINVAL</code>, or calls <code>NET_ThrowByNameWithLastError</code>, <code>NET_ThrowCurrent</code> or <code>NET_ThrowNew</code> in a way that would throw a SocketException with this default error message. </p>
<p>As far as the system calls, we don't seem to get as far as the accept system call:</p>
<pre><code> PID/THRD RELATIVE ELAPSD CPU SYSCALL(args) = return
6606/0x2c750d: 221538243 5 0 sigprocmask(0x1, 0x0, 0x14D8BE100) = 0x0 0
6606/0x2c750d: 221538244 3 0 sigaltstack(0x0, 0x14D8BE0F0, 0x0) = 0 0
6606/0x2c750d: 221538836 14 10 socket(0x2, 0x1, 0x0) = 1170 0
6606/0x2c750d: 221538837 3 0 fcntl(0x492, 0x3, 0x4) = 2 0
6606/0x2c750d: 221538839 3 1 fcntl(0x492, 0x4, 0x6) = 0 0
6606/0x2c750d: 221538842 5 2 setsockopt(0x492, 0xFFFF, 0x4) = 0 0
6606/0x2c750d: 221538852 7 4 bind(0x492, 0x14D8BE5D8, 0x10) = 0 0
6606/0x2c750d: 221538857 5 2 listen(0x492, 0x1, 0x4) = 0 0
6606/0x2c750d: 221539625 6 2 psynch_cvsignal(0x7FEFBFE00868, 0x10000000200, 0x100) = 257 0
6606/0x2c750d: 221539633 4 1 write(0x2, "Apr 18, 2013 11:05:35 AM org.apache.catalina.core.StandardServer await\nSEVERE: StandardServer.await: accept: \njava.net.SocketException: Invalid argument\n\tat java.net.PlainSocketImpl.socketAccept(Native Method)\n\tat java.net.PlainSocketImpl.socketAcce", 0x644) = 1604 0
</code></pre>
<p>So, I <em>think</em> the problem occurs in the timeout handling code at the top of the accept loop in <code>socketAccept</code>, but I couldn't find any case where <code>NET_Timeout</code> would set <code>errno</code> to <code>EINVAL</code>, and result in this SocketException being thrown. I'm referring to this code; I assume the jdk7u branch is for the most part what ships in the Oracle JDK:</p>
<ul>
<li><a href="http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/PlainSocketImpl.c" rel="nofollow noreferrer">http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/PlainSocketImpl.c</a></li>
<li><a href="http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/bsd_close.c" rel="nofollow noreferrer">http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/bsd_close.c</a></li>
<li><a href="http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/net_util_md.c" rel="nofollow noreferrer">http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/d4bf5c15837c/src/solaris/native/java/net/net_util_md.c</a></li>
</ul>
<h2>Help!</h2>
<p>I can't find anyone in the outside world affected by this particular problem on Mac OS, but almost everyone here is affected. There must be some application configuration that contributes, but I've exhausted every avenue I can think of to find the root cause.</p>
<p>Pointers on troubleshooting or insight on a possible cause would be much appreciated.</p> | 16,352,837 | 4 | 7 | null | 2013-04-24 11:48:58.59 UTC | 9 | 2014-11-25 14:28:20.263 UTC | 2017-05-23 11:51:34.767 UTC | null | -1 | null | 364,206 | null | 1 | 29 | tomcat|java-native-interface|java | 14,850 | <p>Have you tried <a href="http://publib.boulder.ibm.com/infocenter/java7sdk/v7r0/topic/com.ibm.java.lnx.70.doc/diag/understanding/jni_debug.html" rel="nofollow noreferrer">turning on JNI debugging</a> with <code>-Xcheck:jni</code>? Interestingly the <a href="http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-VM/html/clopts.html#gbmtq" rel="nofollow noreferrer">Oracle documentation</a> uses a <code>PlainSocketImpl.socketAccept</code> error as an example of when to use this. </p>
<p>Note also that the implication of <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7131399" rel="nofollow noreferrer">Bug 7131399</a> is that the JNI uses <code>poll()</code> on most platforms but <code>select()</code> on Mac OS due to a problem with <code>poll()</code> on the Mac. So maybe <code>select()</code> is broken too. Digging in a bit further, select() will return EINVAL if "ndfs is greater than FD_SETSIZE and _DARWIN_UNLIMITED_SELECT is not defined." FD_SETSIZE is 1024 and it sounds like you have a ton of applications loading up, so perhaps it all filters down to waiting on more that 1024 FDs at one time.</p>
<p>For extra credit, see if <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7129798" rel="nofollow noreferrer">the related (supposedly fixed) Java bug</a> is in fact fixed on your machine. The bug report has pointers to test cases.</p>
<hr>
<p>Thanks to Old Pro's answer, I confirmed that the <code>select()</code> FD_SETSIZE limitation is the cause. I located an existing bug for this limitation:</p>
<p><a href="https://bugs.openjdk.java.net/browse/JDK-8021820" rel="nofollow noreferrer">https://bugs.openjdk.java.net/browse/JDK-8021820</a></p>
<p>The problem can be reproduced with the following code:</p>
<pre><code>import java.io.*;
import java.net.*;
public class SelectTest {
public static void main(String[] args) throws Exception {
// Use 1024 file descriptors. There'll already be some in use, obviously, but this guarantees the problem will occur
for(int i = 0; i < 1024; i++) {
new FileInputStream("/dev/null");
}
ServerSocket socket = new ServerSocket(8080);
socket.accept();
}
}
</code></pre>
<p>Almost a year later, Java 7u60 has a fix this problem:</p>
<p><a href="http://www.oracle.com/technetwork/java/javase/2col/7u60-bugfixes-2202029.html" rel="nofollow noreferrer">http://www.oracle.com/technetwork/java/javase/2col/7u60-bugfixes-2202029.html</a></p>
<p>I also discovered the Tomcat's WebappClassLoader closes file handles after 90 seconds, which explains why setting break points prevented the issue from occurring. </p> |
58,331,479 | How to globally set default options for System.Text.Json.JsonSerializer? | <p>Instead of this:</p>
<pre class="lang-cs prettyprint-override"><code>JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// etc.
};
var so = JsonSerializer.Deserialize<SomeObject>(someJsonString, options);
</code></pre>
<p>I would like to do something like this:</p>
<pre class="lang-cs prettyprint-override"><code>// This property is a pleasant fiction
JsonSerializer.DefaultSettings = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// etc.
};
// This uses my options
var soA = JsonSerializer.Deserialize<SomeObject>(someJsonString);
// And somewhere else in the same codebase...
// This also uses my options
var soB = JsonSerializer.Deserialize<SomeOtherObject>(someOtherJsonString);
</code></pre>
<p>The hope is to not have to pass an instance of <code>JsonSerializerOptions</code> for our most common cases, and override for the exception, not the rule.</p>
<p>As indicated in <a href="https://stackoverflow.com/questions/21815759/set-default-global-json-serializer-settings">this q & a</a>, this is a useful feature of Json.Net. I looked in <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=netcore-3.0" rel="noreferrer">the documentation</a> for <code>System.Text.Json</code> as well as <a href="https://github.com/dotnet/core" rel="noreferrer">this GitHub repo</a> for .NET Core. And <a href="https://github.com/dotnet/corefx/tree/master/src/System.Text.Json/src/System/Text/Json" rel="noreferrer">this one</a>.</p>
<p>There doesn't seem to be an analog for managing JSON serialization defaults in .NET Core 3. Or am I overlooking it?</p>
<hr />
<ul>
<li><p><strong>UPDATE [2020-07-18]:</strong> <em>See <a href="https://stackoverflow.com/a/59457858/1011722">this answer</a> for a <strong><a href="https://www.nuget.org/packages/Fetchgoods.Text.Json.Extensions/" rel="noreferrer">nuget package</a></strong> with convenience methods that honor default settings.</em></p>
</li>
<li><p><strong>UPDATE [2019-12-23]:</strong> <em>Due in part to vocal <a href="https://github.com/dotnet/runtime/issues/31094" rel="noreferrer">community input</a> this issue has been <a href="https://stackoverflow.com/a/59457858/1011722">added to the roadmap</a> for .NET 5.0.</em></p>
</li>
<li><p><strong>UPDATE [2019-10-10]:</strong> <em>If interested in seeing this behavior implemented for <em><strong><code>System.Text.Json.JsonSerializer</code></strong></em> head on over to <strong><a href="https://github.com/dotnet/runtime/issues/31094" rel="noreferrer">the open GitHub issue</a></strong> pointed out by <a href="https://stackoverflow.com/a/58331570/1011722">Chris Yungmann</a> and weigh in.</em></p>
</li>
</ul> | 58,331,570 | 6 | 4 | null | 2019-10-10 21:42:41.077 UTC | 8 | 2021-05-03 03:06:00.037 UTC | 2020-07-20 02:20:22 UTC | null | 1,011,722 | null | 1,011,722 | null | 1 | 63 | c#|json|serialization|.net-core|system.text.json | 31,745 | <p>No, <code>JsonSerializerOptions</code> does not expose the <a href="https://github.com/dotnet/corefx/blob/2b2dd5120029081af767e0eea5e813fd68bded11/src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs#L20" rel="noreferrer">default options</a>. If you are using a particular web framework there may be a way to specify (de-)serialization settings through that. Otherwise, I suggest creating your own convenience methods.</p>
<p>See also <a href="https://github.com/dotnet/corefx/issues/41612" rel="noreferrer">this open issue</a>.</p> |
17,410,744 | How to update Oracle Timestamp value from the current to a timestamp from the past | <p>I have an Oracle Table called <code>EVENT_TABLE_T</code>. It has a column called <code>LAST_UPDATE_DT</code>. One sample value from this column is: <code>01-JUL-13 11.20.22.37448900 AM</code>. There are over 700 rows that have this same timestamp value.
I would like to update this value to 45 days before this date, using a SQL statement.
For example,<code>01-JUL-13 11.20.22.37448900 AM</code>, after my mental arithmetic, should become: <code>15-May-13 11.00.00......</code> (exactly 45 days).
If this is successful, I would like to apply an update on a different value in <code>LAST_UPDATE_DT</code> that reflects a value that goes back back 46 days.</p>
<p>What I hope to accomplish by asking this question is to be able to learn the basics of Oracle dates and timestamps and apply them to my batch processing work.
I would like to be able to run this update sql statement from Oracle SQL Developer and also from inside a Java <code>PreparedStatement.</code></p>
<p>Thanks in advance for your help.</p> | 17,411,246 | 2 | 0 | null | 2013-07-01 18:00:17.793 UTC | 5 | 2018-02-17 07:03:33.153 UTC | 2013-07-01 20:20:42.967 UTC | null | 6,742 | null | 1,535,794 | null | 1 | 11 | sql|oracle | 86,853 | <p>You can simply subtract a time interval from the timestamp.</p>
<pre><code>UPDATE EVENT_TABLE_T
SET LAST_UPDATE_DT = last_update_dt - interval '45' day
WHERE LAST_UPDATE_DT = TO_TIMESTAMP('01-JUL-2013 11:20:22:37448900','DD-MON-YYYY HH24: MI:SS:FF')
</code></pre> |
45,148,292 | Python Pandas read_excel dtype str replace nan by blank ('') when reading or when writing via to_csv | <p>Python version: Python 2.7.13 :: Anaconda custom (64-bit)
Pandas version: pandas 0.20.2</p>
<p>Hello,</p>
<p>I have a quite simple requirement.
I would like to read an excel file and write a specific sheet to a csv file.
Blank values in the source Excel file should be treated / written as blank when writing the csv file.
However, my blank records are always written as 'nan' to the output file. (without the quotes)</p>
<p>I read the Excel file via method</p>
<p><strong>read_excel(xlsx, sheetname='sheet1', dtype = str)</strong></p>
<p>I am specifying dtype because I have some columns that are numbers but should be treated as string. (Otherwise they might lose leading 0s etc)
i.e. I would like to read the exact value from every cell.</p>
<p>Now I write the output .csv file via
<strong>to_csv(output_file,index=False,mode='wb',sep=',',encoding='utf-8')</strong></p>
<p>However, my result csv file contains nan for all blank cells from the excel file.</p>
<p>What am I missing? I already tried .fillna('', inplace=True) function but it seems to be doing nothing to my data.
I also tried to add parameter na_rep ='' to the to_csv method but without success.</p>
<p>Thanks for any help!</p>
<p>Addendum: Please find hereafter a reproducible example.</p>
<p>Please find hereafter a reproducible example code.
Please first create a new Excel file with 2 columns with the following content:
COLUMNA COLUMNB COLUMNC
01 test
02 test<br>
03 test</p>
<p>(I saved this Excel file to c:\test.xls
Please note that 1st and 3rd row for column B as well as the 2nd row for Column C is blank/empty)</p>
<p>Now here is my code:</p>
<pre><code>import pandas as pd
xlsx = pd.ExcelFile('c:\\test.xlsx')
df = pd.read_excel(xlsx, sheetname='Sheet1', dtype = str)
df.fillna('', inplace=True)
df.to_csv('c:\\test.csv', index=False,mode='wb',sep=',',encoding='utf-8', na_rep ='')
</code></pre>
<p>My result is:<br>
COLUMNA,COLUMNB,COLUMNC<br>
01,nan,test<br>
02,test,nan<br>
03,nan,test </p>
<p>My desired result would be:<br>
COLUMNA,COLUMNB,COLUMNC<br>
01,,test<br>
02,test,<br>
03,,test </p> | 45,148,344 | 3 | 5 | null | 2017-07-17 15:38:54.693 UTC | 1 | 2022-08-08 02:47:20.02 UTC | 2017-07-17 16:18:00.037 UTC | null | 8,320,489 | null | 8,320,489 | null | 1 | 19 | python|excel|csv|pandas|nan | 61,363 | <p>Since you are dealing with <code>nan</code> strings, you can use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace</code></a> function:</p>
<pre><code>df = pd.DataFrame({'Col1' : ['nan', 'foo', 'bar', 'baz', 'nan', 'test']})
df.replace('nan', '')
Col1
0
1 foo
2 bar
3 baz
4
5 test
</code></pre>
<p>All <code>'nan'</code> string values will be replaced by the empty string <code>''</code>. <code>replace</code> is not in-place, so make sure you assign it back:</p>
<pre><code>df = df.replace('nan', '')
</code></pre>
<p>You can then write it to your file using <code>to_csv</code>.</p>
<hr />
<p>If you are actually looking to fill NaN values with blank, use <code>fillna</code>:</p>
<pre><code>df = df.fillna('')
</code></pre> |
17,138,792 | Pass array literal to PostgreSQL function | <p>I have a Postgres function which contains a select statement. I need to add a condition using a passed in variable containing an array of string values.</p>
<pre><code>CREATE OR REPLACE FUNCTION get_questions(vcode text)
RETURN return_value as $f$
DECLARE vresult return_value;
BEGIN
--snip--
SELECT id, title, code
FROM questions WHERE code NOT IN (vcode);
--snip--
</code></pre>
<p><code>questions</code> table:</p>
<pre><code>id ,title, code
1, "title1", "qcode1"
2, "title2", "qcode2"
3, "title3", "qcode3"
4, "title4", "qcode4"
</code></pre>
<p>How should the <code>vcode</code> literal be formatted in PHP and what should be the syntax of the condition?</p>
<p>Using PostgreSQL 9.1.1, PHP 5.3.6, <code>pg_query_params</code>.</p> | 17,139,751 | 1 | 5 | null | 2013-06-16 23:48:10.497 UTC | 6 | 2022-06-13 22:39:42.26 UTC | 2015-02-24 22:21:01.857 UTC | null | 939,860 | null | 2,254,435 | null | 1 | 20 | php|sql|arrays|postgresql|parameter-passing | 45,668 | <p>SQL <code>NOT IN</code> works with <em>sets</em>. Since you are passing an <em>array</em>, use <code><> ALL</code>.</p>
<p>You have to be careful not to involve any <code>NULL</code> values with such an expression, because <code>NULL <> anything</code> never evaluates to <code>TRUE</code> and therefore never qualifies in a <code>WHERE</code> clause.</p>
<p>Your function could look like this:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION get_questions(vcode text[])
RETURNS TABLE(id int, title text, code text)
LANGUAGE sql AS
$func$
SELECT q.id, q.title, q.code
FROM questions q
WHERE q.code <> ALL ($1);
$func$;
</code></pre>
<p>Call with <a href="https://www.postgresql.org/docs/current/arrays.html#ARRAYS-INPUT" rel="nofollow noreferrer"><strong>array literal</strong></a>:</p>
<pre><code>SELECT * FROM get_questions('{qcode2, qcode2}');
</code></pre>
<p>Or with an <a href="https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-ARRAY-CONSTRUCTORS" rel="nofollow noreferrer"><strong>array constructor</strong></a>):</p>
<pre><code>SELECT * FROM get_questions(ARRAY['qcode2', 'qcode2']);
</code></pre>
<p>Or you could use a <code>VARIADIC</code> parameter:</p>
<pre><code>CREATE OR REPLACE FUNCTION get_questions(VARIADIC vcode text[]) ...
</code></pre>
<p>... and pass a <em>list</em> of values:</p>
<pre><code>SELECT * FROM get_questions('qcode2', 'qcode2');
</code></pre>
<p>Details:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/17978310/select-rows-such-that-names-match-elements-of-input-array-for-pgsql-function/17978831#17978831">Return rows matching elements of input array in plpgsql function</a></li>
</ul>
<h3>Major points:</h3>
<p>Using a simple SQL function since there is nothing in your question that would require the procedural elements of PL/pgSQL.</p>
<p>The input parameter is an array of text: <code>text[]</code></p>
<p>To return multiple rows from your query use <a href="https://www.postgresql.org/docs/current/sql-createfunction.html" rel="nofollow noreferrer"><code>RETURNS TABLE</code></a> for the return type.</p>
<p>Referring to the in parameter with the positional parameter <code>$1</code> since referring by name was only introduced with version 9.2 for SQL functions (as opposed to plpgsql functions where this has been around for some versions now).</p>
<p>Table-qualify column names that would otherwise conflict with <code>OUT</code> parameters of the same name defined in the <code>RETURNS</code> clause.</p>
<h3><code>LEFT JOIN unnest($1)</code> / <code>IS NULL</code></h3>
<p>Faster for long arrays (> ~ 80 elements, it depends):</p>
<pre class="lang-sql prettyprint-override"><code>SELECT q.id, q.title, q.code
FROM questions q
LEFT JOIN unnest($1) c(code) USING (code)
WHERE c.code IS NULL;
</code></pre>
<p>This variant (as opposed to the above) ignores NULL values in the input array.</p> |
17,419,570 | Bind DoubleClick Command from DataGrid Row to VM | <p>I have a Datagrid and don't like my workaround to fire a double click command on my viewmodel for the clicked (aka selected) row.</p>
<p>View:</p>
<pre><code> <DataGrid EnableRowVirtualization="True"
ItemsSource="{Binding SearchItems}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Single"
SelectionUnit="FullRow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</DataGrid>
</code></pre>
<p>ViewModel:</p>
<pre><code> public ICommand MouseDoubleClickCommand
{
get
{
if (mouseDoubleClickCommand == null)
{
mouseDoubleClickCommand = new RelayCommand<MouseButtonEventArgs>(
args =>
{
var sender = args.OriginalSource as DependencyObject;
if (sender == null)
{
return;
}
var ancestor = VisualTreeHelpers.FindAncestor<DataGridRow>(sender);
if (ancestor != null)
{
MessengerInstance.Send(new FindDetailsMessage(this, SelectedItem.Name, false));
}
}
);
}
return mouseDoubleClickCommand;
}
}
</code></pre>
<p>I want to get rid of the view related code (the one with the dependency object and the visual tree helper) in my view model, as this breaks testability somehow. But on the other hand this way I avoid that something happens when the user doesn't click on a row but on the header for example.</p>
<p>PS: I tried having a look at attached behaviors, but I cannot download from Skydrive at work, so a 'built in' solution would be best.</p> | 17,422,019 | 4 | 0 | null | 2013-07-02 07:12:42.243 UTC | 9 | 2016-09-08 10:53:20.823 UTC | null | null | null | null | 966,786 | null | 1 | 21 | wpf|mvvm|binding|datagrid|command | 34,589 | <p>Why don't you simply use the <code>CommandParameter</code>?</p>
<pre><code><DataGrid x:Name="myGrd"
ItemsSource="{Binding SearchItems}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Single"
SelectionUnit="FullRow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}"
CommandParameter="{Binding ElementName=myGrd, Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</DataGrid>
</code></pre>
<p>Your command is something like this:</p>
<pre><code>public ICommand MouseDoubleClickCommand
{
get
{
if (mouseDoubleClickCommand == null)
{
mouseDoubleClickCommand = new RelayCommand<SearchItem>(
item =>
{
var selectedItem = item;
});
}
return mouseDoubleClickCommand;
}
}
</code></pre>
<p>EDIT: I now use this instead of <code>Interaction.Triggers</code>:</p>
<pre><code><DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding Path=MouseDoubleClickCommand}"
CommandParameter="{Binding ElementName=myGrd, Path=SelectedItem}" />
</DataGrid.InputBindings>
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.