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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,619,562 |
Joining multiple fields in text files on Unix
|
<p>How can I do it?</p>
<p><em>File1</em> looks like this:</p>
<pre><code>foo 1 scaf 3
bar 2 scaf 3.3
</code></pre>
<p><em>File2</em> looks like this:</p>
<pre><code>foo 1 scaf 4.5
foo 1 boo 2.3
bar 2 scaf 1.00
</code></pre>
<p>What I want to do is to find lines that co-occur in <em>File1</em> and <em>File2</em>
when fields <em>1,2, and 3</em> are the same.</p>
<p>Is there a way to do it?</p>
| 2,619,621 | 11 | 1 | null |
2010-04-12 02:30:00.173 UTC
| 11 |
2021-02-06 21:50:33.29 UTC
|
2016-07-08 06:55:02.06 UTC
| null | 6,136,214 | null | 67,405 | null | 1 | 14 |
linux|bash|unix|join
| 35,358 |
<p>you can try this</p>
<pre><code>awk '{
o1=$1;o2=$2;o3=$3
$1=$2=$3="";gsub(" +","")
_[o1 FS o2 FS o3]=_[o1 FS o2 FS o3] FS $0
}
END{ for(i in _) print i,_[i] }' file1 file2
</code></pre>
<p>output</p>
<pre><code>$ ./shell.sh
foo 1 scaf 3 4.5
bar 2 scaf 3.3 1.00
foo 1 boo 2.3
</code></pre>
<p>If you want to omit uncommon lines </p>
<pre><code>awk 'FNR==NR{
s=""
for(i=4;i<=NF;i++){ s=s FS $i }
_[$1$2$3] = s
next
}
{
printf $1 FS $2 FS $3 FS
for(o=4;o<NF;o++){
printf $i" "
}
printf $NF FS _[$1$2$3]"\n"
} ' file2 file1
</code></pre>
<p>output</p>
<pre><code>$ ./shell.sh
foo 1 scaf 3 4.5
bar 2 scaf 3.3 1.00
</code></pre>
|
2,969,561 |
How to parse mathematical expressions involving parentheses
|
<p>This isn't a school assignment or anything, but I realize it's a mostly academic question. But, what I've been struggling to do is parse 'math' text and come up with an answer.</p>
<p>For Example - I can figure out how to parse '5 + 5' or '3 * 5' - but I fail when I try to correctly chain operations together.</p>
<p>(5 + 5) * 3</p>
<p>It's mostly just bugging me that I can't figure it out. If anyone can point me in a direction, I'd really appreciate it.</p>
<p><strong>EDIT</strong>
Thanks for all of the quick responses. I'm sorry I didn't do a better job of explaining.</p>
<p>First - I'm not using regular expressions. I also know there are already libraries available that will take, as a string, a mathematical expression and return the correct value. So, I'm mostly looking at this because, sadly, I don't "get it".</p>
<p>Second - What I've tried doing (is probably misguided) but I was counting '(' and ')' and evaluating the deepest items first. In simple examples, this worked; but my code is not pretty and more complicated stuff crashes. When I 'calculated' the lowest level, I was modifying the string.</p>
<p>So...
(5 + 5) * 3</p>
<p>Would turn into
10 * 3</p>
<p>Which would then evaluate to
30</p>
<p>But it just felt 'wrong'.</p>
<p>I hope that helps clarify things. I'll certainly check out the links provided. </p>
| 2,969,583 | 13 | 10 | null |
2010-06-03 20:34:38.807 UTC
| 11 |
2021-06-06 17:17:26.317 UTC
|
2010-06-03 21:03:12.653 UTC
| null | 8,027 | null | 73,381 | null | 1 | 18 |
.net|math|parsing
| 26,506 |
<p>Ages ago when working on a simple graphing app, I used <a href="http://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="noreferrer">this algorithm</a> (which is reasonably easy to understand and works great for simple math expressions like these) to first turn the expression into <a href="http://en.wikipedia.org/wiki/Reverse_Polish_notation" rel="noreferrer">RPN</a> and then calculated the result. RPN was nice and fast to execute for different variable values.</p>
<p>Of course, language parsing is a very wide topic and there are many other ways of going about it (and pre-made tools for it too)</p>
|
2,943,222 |
Find objects between two dates MongoDB
|
<p>I've been playing around storing tweets inside mongodb, each object looks like this:</p>
<pre><code>{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
"following" : null,
"followers_count" : 5,
"utc_offset" : null,
"location" : "",
"profile_text_color" : "000000",
"friends_count" : 11,
"profile_link_color" : "0000ff",
"verified" : false,
"protected" : false,
"url" : null,
"contributors_enabled" : false,
"created_at" : "Sun May 30 18:47:06 +0000 2010",
"geo_enabled" : false,
"profile_sidebar_border_color" : "87bc44",
"statuses_count" : 13,
"favourites_count" : 0,
"description" : "",
"notifications" : null,
"profile_background_tile" : false,
"lang" : "en",
"id" : 149978111,
"time_zone" : null,
"profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
"floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
"floatApprox" : 15061838001
}
</code></pre>
<p>How would I write a query which checks the <em>created_at</em> and finds all objects between 18:47 and 19:00? Do I need to update my documents so the dates are stored in a specific format?</p>
| 2,943,685 | 17 | 4 | null |
2010-05-31 11:34:43.757 UTC
| 120 |
2022-08-31 06:30:37.71 UTC
|
2015-08-11 07:20:56.743 UTC
| null | 2,476,755 | null | 45,350 | null | 1 | 530 |
mongodb|datetime|twitter|mongodb-query
| 938,279 |
<p><strike><a href="http://cookbook.mongodb.org/patterns/date_range/" rel="noreferrer">Querying for a Date Range (Specific Month or Day)</a></strike> in the <strike><a href="http://cookbook.mongodb.org/" rel="noreferrer">MongoDB Cookbook</a></strike> has a very good explanation on the matter, but below is something I tried out myself and it seems to work.</p>
<pre><code>items.save({
name: "example",
created_at: ISODate("2010-04-30T00:00:00.000Z")
})
items.find({
created_at: {
$gte: ISODate("2010-04-29T00:00:00.000Z"),
$lt: ISODate("2010-05-01T00:00:00.000Z")
}
})
=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }
</code></pre>
<p>Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.</p>
<pre><code>items.save({
name: "example",
created_at: "Sun May 30 18.49:00 +0000 2010"
})
items.find({
created_at: {
$gte:"Mon May 30 18:47:00 +0000 2015",
$lt: "Sun May 30 20:40:36 +0000 2010"
}
})
=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }
</code></pre>
<p>In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.</p>
|
3,211,595 |
Renaming files in a folder to sequential numbers
|
<p>I want to rename the files in a directory to sequential numbers. Based on creation date of the files.</p>
<p>For Example <code>sadf.jpg</code> to <code>0001.jpg</code>, <code>wrjr3.jpg</code> to <code>0002.jpg</code> and so on, the number of leading zeroes depending on the total amount of files (no need for extra zeroes if not needed).</p>
| 3,211,670 | 28 | 4 | null |
2010-07-09 10:06:06.463 UTC
| 169 |
2022-08-04 22:55:00.327 UTC
|
2016-01-05 15:46:10.6 UTC
| null | 1,843,331 | null | 259,316 | null | 1 | 309 |
bash|rename|batch-rename
| 310,820 |
<p>Try to use a loop, <code>let</code>, and <code>printf</code> for the padding:</p>
<pre><code>a=1
for i in *.jpg; do
new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
mv -i -- "$i" "$new"
let a=a+1
done
</code></pre>
<p>using the <code>-i</code> flag prevents automatically overwriting existing files, and using <code>--</code> prevents <code>mv</code> from interpreting filenames with dashes as options.</p>
|
40,583,721 |
print() to console log with color
|
<p>The code is:</p>
<pre><code>let redColor = "\u{001B}[0;31m"
var message = "Some Message"
print(redColor + message) //This doesn't work
print("\(redColor)\(message)") //This also doesn't work
</code></pre>
<p>and the output would look like this:</p>
<pre><code>[0;31mSome Message
</code></pre>
<p>I've also read this post: <a href="https://stackoverflow.com/questions/27807925/color-ouput-with-swift-command-line-tool">Color ouput with Swift command line tool</a>, and it doesn't seem to work.</p>
<p>I don't want to use libraries.</p>
| 41,740,104 | 7 | 9 | null |
2016-11-14 07:23:56.273 UTC
| 8 |
2022-02-26 09:52:21.66 UTC
|
2020-10-02 14:17:12.713 UTC
| null | 5,623,035 | null | 5,928,180 | null | 1 | 40 |
swift|xcode|debugging|logging|colors
| 18,119 |
<p>Nowadays, Xcode debugging console doesn't support coloring.</p>
|
25,388,214 |
How do I change navigationBar font in Swift?
|
<p>This is what I have tried so far, but receiving an error (I have correctly implemented CaviarDreams to the project):</p>
<pre><code>self.navigationController.navigationBar.titleTextAttributes = NSFontAttributeName[UIFont .fontWithName(CaviarDreams.ttf, size: 20)]
</code></pre>
<p>Error says: <code>Use of unresolved identifier 'CaviarDreams</code></p>
| 25,388,549 | 9 | 0 | null |
2014-08-19 16:12:21.94 UTC
| 13 |
2021-01-06 23:56:07.85 UTC
|
2021-01-06 23:56:07.85 UTC
| null | 1,783,163 | null | 2,514,271 | null | 1 | 34 |
swift|uinavigationbar|navigationbar
| 43,926 |
<p>Try this:</p>
<pre><code>self.navigationController.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "CaviarDreams", size: 20)!]
</code></pre>
<p><strong>Edit:</strong> Now, UIFont must be unwrapped to be able to be used here.</p>
<p><strong>Swift 5</strong> (+ safe handling of optional <code>UIFont</code>)</p>
<pre><code>self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont(name: "Caviar-Dreams", size: 20) ?? UIFont.systemFont(ofSize: 20)]
</code></pre>
|
25,163,433 |
Can you execute an Applescript script from a Swift Application
|
<p>I have a simple AppleScript that sends an email. How can I call it from within a Swift application?</p>
<p>(I wasn't able to find the answer via Google.)</p>
| 25,235,047 | 7 | 0 | null |
2014-08-06 14:45:19.75 UTC
| 18 |
2022-08-26 04:26:52.127 UTC
|
2015-10-13 14:21:32.667 UTC
| null | 168,594 | null | 110,701 | null | 1 | 30 |
swift|applescript
| 23,738 |
<p>Tested: one can do something like this (arbitrary script path added):</p>
<pre><code>import Foundation
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["~/Desktop/testscript.scpt"]
task.launch()
</code></pre>
|
42,189,301 |
Axios (in React-native) not calling server in localhost
|
<p>I'm building a really easy api and react-native application. The server works well (tested with PostMan) but the application doesn't call the server. It blocks when axios has to send the post request (see below).</p>
<p>I'm desperate :-( Loosing too mush time in it. Please, if you can help me...</p>
<p>Here is my code LogIn page. It dispatch the action creator (working with redux) giving email and password:</p>
<pre><code>...
const LogIn = React.createClass({
submitLogin() {
// log in the server
if (this.props.email !== '' && this.props.psw !== '') {
if (this.props.valid === true) {
this.props.dispatch(logIn(this.props.email, this.props.psw));
} else {
this.props.dispatch(errorTyping());
}
}
},
...
</code></pre>
<p>email and password are weel retrieved and sent to the action creator:</p>
<pre><code>import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
return function (dispatch) {
console.log(email);
console.log(password);
console.log(SIGNIN_URL);
return axios.post(SIGNIN_URL, { email, password })
.then(
(response) => {
console.log(response);
const { token, userId } = response.data;
dispatch(authUser(userId));
}
)
.catch(
(error) => {
console.log('Could not log in');
}
);
};
};
const authUser = (userId) => {
return {
type: 'AUTH_USER',
userId
};
};
...
</code></pre>
<p>The three console.log() before axios show the data in the correct way. SIGNIN_URL is exactly the same I use in postman. ...but axios doesn't call.</p>
<p>Just to give all the cards, this is my store:</p>
<pre><code>import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
const store = createStore(reducer, initialState, compose(
applyMiddleware(thunk),
autoRehydrate()
));
persistStore(store, { storage: AsyncStorage });
return store;
};
</code></pre>
<p>There's no error message in the debugger (but the one given by the axios call ('Could not log in')</p>
<p>I'm on windows 10, with:</p>
<pre><code>"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"
</code></pre>
<p>The call fails even when I prepare a simple GET call and the server is supposed to give back a simple message (tested with postman and browser):</p>
<pre><code>exports.test = () => {
return function () {
return axios.get('https://localhost:3000/v1/test')
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
</code></pre>
<p>Last, I tryed also to modify the call adding a header as the following, because the api is coded to accept json:</p>
<pre><code>const head = {
headers: { 'Content-Type': 'application/json' }
};
exports.test = () => {
return function () {
return axios.get('https://api.github.com/users/massimopibiri', head)
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
</code></pre>
<p>but even this didn't work. hope somebody can help me. Other similar issues didn't.</p>
| 42,189,984 | 13 | 1 | null |
2017-02-12 15:16:43.85 UTC
| 12 |
2022-07-27 01:25:23.107 UTC
| null | null | null | null | 6,090,589 | null | 1 | 32 |
node.js|react-native|axios
| 83,222 |
<p>The solution came from a different source, but I post it here to help others looking for the same issue. Basically I used Android AVD (emulator) to build the application. But the emulator is in fact another machine, and that's why it couldn't call the localhost.</p>
<p>To solve the probleme, I had to send the request in the following way:</p>
<pre><code>https://10.0.2.2:3000/v1/test
</code></pre>
<p>instead of:</p>
<pre><code>https://localhost:3000/v1/test
</code></pre>
|
10,713,155 |
Knockout, CKEditor & Single Page App
|
<p>I have a situation involving KnockoutJS & CKEditor.</p>
<p>Basically we've got part of our site that is 'single page' app style, currently it just involves 2 pages but will likely expand over time, currently it's just a 'listings' page and a 'manage' page for the items in the list.</p>
<p>The manage page itself requires some sort of rich text editor, we've gone with CKEditor for a company wide solution.</p>
<p>Because these 2 pages are 'single page' style obviously CKEditor can't register against the manage elements because they aren't there on page load - simple enough problem to fix. So as a sample I attached CKEditor on a click event which worked great. The next problem was that then the Knockout observables that had been setup weren't getting updated because CKEditor doesn't actually modify the textarea it's attached too it creates all these div's/html elements that you actually edit.</p>
<p>After a bit of googleing I found an example of someone doing this with TinyMCE - <a href="http://jsfiddle.net/rniemeyer/GwkRQ/">http://jsfiddle.net/rniemeyer/GwkRQ/</a> so I thought I could adapt something similar to this for CKEditor.</p>
<p>Currently I'm quite close to having a working solution, I've got it initialising and updating the correct observables using this technique (I'll post code at the bottom) and even posting back to the server correctly - fantastic.</p>
<p>The problem I'm currently experiencing is with the 'Single Page' app part and the reinitialisation of CKEditor.</p>
<p>Basically what happens is you can click from list to manage then save (which goes back to the list page) then when you go to another 'manage' the CKEditor is initialised but it doesn't have any values in it, I've checked the update code (below) and 'value' definitely has the correct value but it's not getting pushed through to the CKEditor itself.</p>
<p>Perhaps it's a lack of understanding about the flow/initialisation process for CKEditor or a lack of understanding about knockout bindings or perhaps it's a problem with the framework that's been setup for our single page app - I'm not sure.</p>
<p>Here is the code:</p>
<pre><code>//Test one for ckeditor
ko.bindingHandlers.ckeditor = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
var options = allBindingsAccessor().ckeditorOptions || {};
var modelValue = valueAccessor();
$(element).ckeditor();
var editor = $(element).ckeditorGet();
//handle edits made in the editor
editor.on('blur', function (e) {
var self = this;
if (ko.isWriteableObservable(self)) {
self($(e.listenerData).val());
}
}, modelValue, element);
//handle destroying an editor (based on what jQuery plugin does)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
var existingEditor = CKEDITOR.instances[element.name];
existingEditor.destroy(true);
});
},
update: function (element, valueAccessor, allBindingsAccessor, context) {
//handle programmatic updates to the observable
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).html(value);
}
};
</code></pre>
<p>So in the HTML it's a fairly standard knockout 'data-bind: ckeditor' that applyies the bindings for it when the ViewModel is initialised.</p>
<p>I've put debugger; in the code to see the flow, it looks like when I load the first time it calls init, then update, when I go in the second time it hits the ko.utils.domNodeDisposal to dispose of the elements.</p>
<p>I've tried not destroying it which CKEditor then complains that something already exists with that name. I've tried not destroying it and checking for if it exists and initialising if it doesn't - that works the first time but the second time we have no CKEditor.</p>
<p>I figure there's just one thing I'm missing that will make it work but I've exhausted all options. </p>
<p>Does anyone have any knowledge on integrating these 3 things that can help me out?</p>
<p>Are there any knockout experts out there that might be able to help me out?</p>
<p>Any help would be much appreciated.</p>
<p>MD </p>
| 10,925,902 | 7 | 0 | null |
2012-05-23 03:44:18.83 UTC
| 9 |
2015-05-26 12:54:23.42 UTC
| null | null | null | null | 1,021,316 | null | 1 | 16 |
asp.net-mvc|knockout.js|ckeditor|singlepage
| 7,190 |
<p>For anyone interested I sorted it:</p>
<p>All it was was a basic order of execution, I just needed to set the value to the textarea html before it got initialised.</p>
<p>Note this uses a jquery adaptor extension to do the .ckeditor() on the element.</p>
<p>There is probably also a better way to do the 'blur' part.</p>
<p>This extension also doesn't work with options at the moment but that should be quite simple in comparison.</p>
<pre><code>ko.bindingHandlers.ckeditor = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
var options = allBindingsAccessor().ckeditorOptions || {};
var modelValue = valueAccessor();
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).html(value);
$(element).ckeditor();
var editor = $(element).ckeditorGet();
//handle edits made in the editor
editor.on('blur', function (e) {
var self = this;
if (ko.isWriteableObservable(self)) {
self($(e.listenerData).val());
}
}, modelValue, element);
}
};
</code></pre>
|
10,852,652 |
Difference between dataType jsonp and JSON
|
<p>I download Jquery UI autoload, looking to remote-jsonp.html. This is ajax function but i open console.. I can't see any request in my console...</p>
<p>What is difference between dataType;"jsonp" and dataType;"JSON"</p>
<pre><code>$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
</code></pre>
<p><strong>Reference</strong> <a href="http://jqueryui.com/demos/autocomplete/remote-jsonp.html">http://jqueryui.com/demos/autocomplete/remote-jsonp.html</a></p>
| 10,852,664 | 2 | 0 | null |
2012-06-01 14:57:32.943 UTC
| 8 |
2014-02-12 12:57:04.617 UTC
|
2014-02-12 12:57:04.617 UTC
| null | 3,012,290 | null | 612,854 | null | 1 | 19 |
javascript|jquery|ajax|jquery-ui
| 48,052 |
<p><code>dataType: jsonp</code> for cross-domain request, that means request to different domain and <code>dataType: json</code> for same domain-same origin request.</p>
<blockquote>
<p>Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the
end of your URL to specify the callback. Disables caching by appending
a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache
option is set to true.</p>
</blockquote>
<p>Read about <strong><a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin policy</a></strong></p>
<p>Read more about <strong><a href="http://api.jquery.com/jQuery.ajax/">jQuery AJAX</a></strong></p>
|
33,443,146 |
Remove image from cache in Glide library
|
<p>I am using Glide in one of my projects to show image from file.</p>
<p>Below is my code how I am showing the image:</p>
<pre><code>Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.into(mImage);
</code></pre>
<p>The image at this location(<code>imagePath</code>) keeps on changing. By default Glide cache the image it shows in the <code>ImageView</code>. Because of this, the Glide was showing the first image from cache for new images at that location.</p>
<p>If I change the image at location <code>imagePath</code> with some other image having same name then the Glide is showing the first image instead of new one.</p>
<p>Two queries are:</p>
<ol>
<li><p>Is it possible to always the image from File and not cache? This way problem will be solved.</p></li>
<li><p>Is it possible to clear image from cache before getting newly replaced image? This will also solve the problem.</p></li>
</ol>
| 33,451,376 | 18 | 0 | null |
2015-10-30 19:00:16.037 UTC
| 34 |
2021-06-23 09:43:35.99 UTC
|
2015-10-31 09:49:17.987 UTC
| null | 2,837,959 | null | 1,150,434 | null | 1 | 93 |
android|caching|android-glide
| 103,551 |
<p>This is how I solved this problem.</p>
<p><strong>Method 1: When the URL changes whenever image changes</strong></p>
<pre><code>Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mImage);
</code></pre>
<p>diskCacheStrategy() can be used to handle the disk cache and you can skip the memory cache using skipMemoryCache() method.</p>
<p><strong>Method 2: When URL doesn't change, however, image changes</strong></p>
<p>If your URL remains constant then you need to use Signature for image cache.</p>
<pre><code>Glide.with(yourFragment)
.load(yourFileDataModel)
.signature(new StringSignature(yourVersionMetadata))
.into(yourImageView);
</code></pre>
<p>Glide signature() offers you the capability to mix additional data with the cache key.</p>
<ul>
<li>You can use <code>MediaStoreSignature</code> if you are fetching content from media store. <code>MediaStoreSignature</code> allows you to mix the date modified time, mime type, and orientation of a media store item into the cache key. These three attributes reliably catch edits and updates allowing you to cache media store thumbs.</li>
<li>You may <code>StringSignature</code> as well for content saved as Files to mix the file date modified time.</li>
</ul>
|
23,421,507 |
Get service status from remote server using powershell
|
<p>How to get the service status for a remote computer that needs a user name and password to log in?</p>
<p>I am trying to find a solution using the following code:</p>
<p><code>$serviceStatus = get-service -ComputerName $machineName -Name $service</code></p>
<p>The default syntax for the <code>get-service</code> command is:</p>
<pre><code>Parameter Set: Default
Get-Service [[-Name] <String[]> ] [-ComputerName <String[]> ] [-DependentServices] [-Exclude <String[]> ] [-Include <String[]> ] [-RequiredServices] [ <CommonParameters>]
Parameter Set: DisplayName
Get-Service -DisplayName <String[]> [-ComputerName <String[]> ] [-DependentServices] [-Exclude <String[]> ] [-Include <String[]> ] [-RequiredServices] [ <CommonParameters>]
Parameter Set: InputObject
Get-Service [-ComputerName <String[]> ] [-DependentServices] [-Exclude <String[]> ] [-Include <String[]> ] [-InputObject <ServiceController[]> ] [-RequiredServices] [ <CommonParameters>]
</code></pre>
<p>This does not have an option for username and password.</p>
| 23,421,592 | 4 | 0 | null |
2014-05-02 05:41:53.343 UTC
| 5 |
2020-07-08 16:54:34.267 UTC
| null | null | null | null | 1,631,315 | null | 1 | 11 |
powershell|service|remote-server
| 83,825 |
<p>As far as I know, Get-Service <a href="http://connect.microsoft.com/PowerShell/feedback/details/567007/get-service-cmdlets-needs-a-credential-parameter" rel="noreferrer">doesn't accept a credential parameter</a>. However, you can do it through <a href="http://technet.microsoft.com/en-us/library/ee176860.aspx" rel="noreferrer">WMI</a>:</p>
<pre><code>$cred = get-Credential -credential <your domain user here>
Get-WMIObject Win32_Service -computer $computer -credential $cred
</code></pre>
<p><strong>Update after comment:</strong></p>
<p>You can save credentials as a securestring into a file, and then reload it for manually creating a credential without having a prompt. See information <a href="http://social.technet.microsoft.com/wiki/contents/articles/4546.working-with-passwords-secure-strings-and-credentials-in-windows-powershell.aspx" rel="noreferrer">here</a>.</p>
|
18,956,611 |
Why does my programmatically created screenshot look so bad on iOS 7?
|
<p>I am trying to implement sharing app with facebook.
I used this code to take the screenshot:</p>
<pre><code>CGSize imageSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
UIGraphicsBeginImageContext(imageSize);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code></pre>
<p>It works great on iOS 6, but in iOS 7 the image looks very bad.
I used this answer: <a href="https://stackoverflow.com/questions/7964153/ios-whats-the-fastest-most-performant-way-to-make-a-screenshot-programaticall">iOS: what's the fastest, most performant way to make a screenshot programmatically?</a>
for trying to fix it, and it helped, still the screenshot looks bad.
The screen gets another color, and some objects (like labels) aren't showing on the image taken.
Any help?</p>
<p>----Update----</p>
<p>I managed to solve the most objects, by change them to retain instead of weak. My main problem remained my tableview, that shown as a big white block (It supposed to be transparent, with labels with white text, so all we see is white cells). I did try to define the table background as clearcolor,not helps.. </p>
<p>----Last Update---</p>
<p>There are wonderful answers here that not really regarding to my issue.. I wanted to make it work on device that runs with iOS7 but without using iOS7 SDK, since it takes to much effort to switch the project SDK in this point, when the project is almost done.</p>
<p>Anyway, I added the peace of code that finally solved my issue:</p>
<p>This change simply solve the problem:</p>
<pre><code>UIGraphicsBeginImageContextWithOptions(imageSize, NO , 0.0f);
</code></pre>
<p>instead of:</p>
<pre><code>UIGraphicsBeginImageContext(imageSize);
</code></pre>
| 18,956,842 | 5 | 0 | null |
2013-09-23 10:08:20.087 UTC
| 22 |
2016-04-01 19:32:33.657 UTC
|
2017-05-23 11:53:12.433 UTC
| null | -1 | null | 1,868,679 | null | 1 | 29 |
ios|objective-c|iphone|xcode|screenshot
| 38,562 |
<p>New <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/snapshotViewAfterScreenUpdates:" rel="noreferrer">API</a> has been added since iOS 7, that should provide efficient way of getting snapshot</p>
<ul>
<li><p><code>snapshotViewAfterScreenUpdates:</code> renders the view into a UIView with unmodifiable <code>content</code></p></li>
<li><p><code>resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets</code> : same thing, but with resizable insets</p></li>
<li><p><code>drawViewHierarchyInRect:afterScreenUpdates:</code> : same thing if you need all subviews to be drawn too (like labels, buttons...)</p></li>
</ul>
<p>You can use the <code>UIView</code> returned for any UI effect, or render in into an image like you did if you need to export.</p>
<p>I don't know how good this new method performs VS the one you provided (although I remember Apple engineers saying this new API was more efficient)</p>
|
19,068,862 |
How to overplot a line on a scatter plot in python?
|
<p>I have two vectors of data and I've put them into <code>pyplot.scatter()</code>. Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using <code>scikitlearn</code> and <code>np.polyfit()</code>.</p>
| 19,069,001 | 8 | 0 | null |
2013-09-28 16:05:10.46 UTC
| 38 |
2022-04-03 07:46:17.387 UTC
|
2022-04-03 07:45:56.187 UTC
| null | 13,138,364 | null | 1,849,997 | null | 1 | 77 |
python|numpy|matplotlib|linear-regression|scatter-plot
| 212,959 |
<pre><code>import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt
# Sample data
x = np.arange(10)
y = 5 * x + 10
# Fit with polyfit
b, m = polyfit(x, y, 1)
plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/rnWmJ.png" alt="enter image description here"></p>
|
36,862,564 |
Changing the background color of Tab Bar
|
<p>I am trying to get desired color rendered in the background of Tab Bar however I am facing problems.
These are the things that I tried :-</p>
<ol>
<li><p>Changing the background color of tab bar object from storyboard. The color rendered is always lighter than the desired color.</p></li>
<li><p>Programmatically changing the color of the tab bar using the following code inside <code>viewDidLoad()</code> method</p>
<pre><code> self.tabBar.translucent = false
self.tabBar.backgroundColor = UIColor(hexString: "323B61")
</code></pre>
<p>It doesn't change the color. Instead , the color rendered is white. </p></li>
</ol>
<p>How can I get the desired color for Tab Bar?</p>
| 36,862,601 | 6 | 0 | null |
2016-04-26 10:41:37.99 UTC
| 13 |
2021-10-26 10:51:07.273 UTC
| null | null | null | null | 5,856,164 | null | 1 | 63 |
ios|swift|uitabbarcontroller|uitabbar
| 90,596 |
<p>To change background colour of UITabBar</p>
<pre><code>TabBarController* Tcontroller =(TabBarController*)self.window.rootViewController;
Tcontroller.tabBar.barTintColor=[UIColor yourcolour];
</code></pre>
<p><strong>Swift 3</strong></p>
<p>Based on the code above, you can get it by doing this</p>
<pre><code>let Tcontroller = self.window.rootViewController as? UITabBarController
Tcontroller?.tabBar.barTintColor = UIColor.black // your color
</code></pre>
<p>or in more general</p>
<pre><code>UITabBar.appearance().barTintColor = UIColor.black // your color
</code></pre>
|
62,846,123 |
Getting Error from webpack-cli: "TypeError: merge is not a function" in webpack config
|
<p>I'm using webpack-merge to combine two webpack.config files together but I keep getting the error
"TypeError: merge is not a function when I run the command "webpack --config ./config/webpack.config.prod.js"</p>
<p>Has anybody else run across this issue?</p>
<p>webpack.config.prod.js</p>
<pre><code>const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const TerserPlugin = require('terser-webpack-plugin');
const commonConfig= require('./webpack.config.common');
const merge = require('webpack-merge');
module.exports = merge(commonConfig, {
//config code
})
</code></pre>
| 62,846,324 | 2 | 0 | null |
2020-07-11 06:55:38.793 UTC
| 9 |
2021-03-13 09:12:26.21 UTC
| null | null | null | null | 3,448,008 | null | 1 | 48 |
reactjs|webpack|webpack-4|webpack-cli|webpack-merge
| 27,981 |
<p>You are importing <code>merge</code> incorrectly. Try it like this:</p>
<pre class="lang-js prettyprint-override"><code>const { merge } = require('webpack-merge');
</code></pre>
<p><strong>UPD:</strong>
Based on the <a href="https://github.com/survivejs/webpack-merge/blob/50bf401c7f2d205721e8cfa9a03ea47cf80058ec/CHANGELOG.md#503--2020-07-06" rel="noreferrer">following changelog</a>, starting with <code>webpack-merge</code> 5.0.3 and higher, you should use the code I provided above. If the version is lower than 5.0.3, then you need to use:</p>
<pre class="lang-js prettyprint-override"><code>const merge = require('webpack-merge');
</code></pre>
|
28,332,103 |
Problems installing laravel with composer
|
<p><strong>Problem:</strong> I'm wanting to explore laravel 5, and failing miserably at installing it. I'm using this guide: <a href="http://laravel.com/docs/5.0">http://laravel.com/docs/5.0</a> and need someone to help me understand the instructions.</p>
<p><strong>Background and What I've Tried</strong></p>
<p>I'm running Mac OSX 10.10.2 (Yosemite) and MAMP. </p>
<p>So far, I've downloaded Composer to my home folder using terminal. There is just a composer.phar file sitting there.</p>
<p>When I run:</p>
<pre><code>composer global require "laravel/installer=~1.1"
</code></pre>
<p>I get the message:</p>
<pre><code>Changed current directory to /Users/MYUSERNAME/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
</code></pre>
<p>I assume that is ok because when I run the following in terminal, I get the composer logo and a list of options</p>
<pre><code>~ MYUSERNAME$ composer
</code></pre>
<p>I'm not 100% sure what the following means, from the Laravel Docs:</p>
<pre><code>"Make sure to place the ~/.composer/vendor/bin directory in your PATH so the
laravel executable can be located by your system."
</code></pre>
<p>Because I can't figure it out, the following steps throw errors, such as: </p>
<pre><code>-bash: laravel: command not found
</code></pre>
<p>I've been going through a few forums, and it's suggested that I need to update my PHP.ini file - this seems more related to Composer install, and not specifically Laravel. Because composer is working, this seems to be a dead end.</p>
<p>Ideally, I want to install Laravel 5 to the directory </p>
<pre><code>HomeFolder/sites/test
</code></pre>
<p>because Composer.phar is in my home folder, I think the command should be:</p>
<pre><code>php composer laravel new sites/test
</code></pre>
<p>or just </p>
<pre><code>composer laravel new sites/test
</code></pre>
<p>As mentioned, it just (correctly) throws errors. </p>
<p><strong>Question:</strong>
If anyone can help solve my total user error, by explaining what "Make sure to place the ~/.composer/vendor/bin directory in your PATH so the laravel executable can be located by your system." means to a n00b, that'd be really appreciated.</p>
<p>Many thanks!</p>
| 28,332,285 | 3 | 0 | null |
2015-02-04 21:47:20.61 UTC
| 6 |
2016-01-05 17:23:17.753 UTC
|
2015-02-04 21:53:41.34 UTC
| null | 1,163,740 | null | 1,163,740 | null | 1 | 10 |
php|laravel|composer-php|laravel-5
| 43,932 |
<p>Laravel is a PHP framework (makes writing PHP applications easy)</p>
<p>Composer is a PHP package and dependency manager. (makes installing and updating third party code libraries easy)</p>
<p>When you run</p>
<pre><code>$ composer global require "laravel/installer=~1.1"
</code></pre>
<p>You're using composer to install the <code>laravel/installer=~1.1</code> package into composer's "global" project folder (usually <code>~/.composer</code>). This is what installed the command line program named <code>laravel</code>.</p>
<p>The command line program named <code>laravel</code> is a shell script for installing the PHP framework (Also named Laravel).</p>
<p>Your "Unix Path" is a list of folders where a command line script will search for an executable. Usually is has folders like <code>/usr/bin</code>, <code>/usr/local/bin</code>, etc. This is why when you run <code>ls</code>, you're actually running <code>/usr/bin/ls</code> -- the shell knows to check each folder in the path for a location. You can view your current path by typing</p>
<pre><code>$ echo $PATH
</code></pre>
<p>So, the problem is composer installed the <code>laravel</code> command line program to a folder that's not in your unix path. You need to add this folder to your unix path. You can do this by running the following (assuming you're using <code>bash</code>, which is OS X's default shell)</p>
<pre><code>$ PATH=$PATH:~/.composer/vendor/bin
</code></pre>
<p>If you run that, you should be able to run the <code>laravel</code> command line program and continue your installation. </p>
<p>Most people add this to their <code>.bash_profile</code> or <code>.bashrc</code> files. The <a href="https://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path">Unix Stack Exchange</a> has a lot of good information if you're interested in learning how to do this. </p>
|
8,901,488 |
Android: Java, C or C++?
|
<p>I wrote some simple apps in Android using Java.<br/>
But later I found this: </p>
<blockquote>
<p>It provides headers and libraries that allow you to build activities,
handle user input, use hardware sensors, access application resources,
and more, when programming in C or C++. (<a href="http://developer.android.com/sdk/ndk/index.html">Source</a>)</p>
</blockquote>
<p>How is it related to this:</p>
<blockquote>
<p>Android applications are written in the Java programming language. (<a href="http://developer.android.com/guide/topics/fundamentals.html">Source</a>)</p>
</blockquote>
<p>Are all three languages possible?<br/>
Sorry for the dumb question.</p>
| 8,901,522 | 6 | 0 | null |
2012-01-17 20:43:33.357 UTC
| 8 |
2020-11-25 09:48:09.75 UTC
| null | null | null | null | 982,865 | null | 1 | 32 |
java|android|c++|c
| 26,435 |
<p>The article you link to has good information. It also links to <a href="http://developer.android.com/sdk/ndk/overview.html" rel="noreferrer">http://developer.android.com/sdk/ndk/overview.html</a> which says: </p>
<blockquote>
<p>The NDK will not benefit most applications. As a developer, you need
to balance its benefits against its drawbacks; notably, using native
code does not result in an automatic performance increase, but always
increases application complexity. In general, you should only use
native code if it is essential to your application, not just because
you prefer to program in C/C++.</p>
<p>Typical good candidates for the NDK are self-contained, CPU-intensive
operations that don't allocate much memory, such as signal processing,
physics simulation, and so on. Simply re-coding a method to run in C
usually does not result in a large performance increase. When
examining whether or not you should develop in native code, think
about your requirements and see if the Android framework APIs provide
the functionality that you need. The NDK can, however, can be an
effective way to reuse a large corpus of existing C/C++ code.</p>
</blockquote>
|
57,332,430 |
adding width to drawer in flutter
|
<p>I want to be able to add width to this drawer because it takes up too much of the screen when open and I want to lessen the width a bit, is this possible and how would I do this?</p>
<p>here is my scaffold</p>
<pre><code>Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("App Name"),
centerTitle: true,
),
body: new Center(
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text('Test123') ,
accountEmail: Text('test@123.com'),
currentAccountPicture: Image.network('https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a89c3e38-b6f3-48a0-9f9e-df9a0129fb93/daghh5x-4a77b3ec-fd4f-4d17-9f84-5963a8cb5c03.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E4OWMzZTM4LWI2ZjMtNDhhMC05ZjllLWRmOWEwMTI5ZmI5M1wvZGFnaGg1eC00YTc3YjNlYy1mZDRmLTRkMTctOWY4NC01OTYzYThjYjVjMDMucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.dWTFMrwnbAbj5TtUp9U_vQsohW7MnkRPymzR5wZQoV8'),
),
ListTile(
title: Text('data'),
),
],
),
),
);
</code></pre>
| 57,333,040 | 4 | 0 | null |
2019-08-02 19:28:21.617 UTC
| 3 |
2022-02-13 16:57:27.6 UTC
| null | null | null | null | 11,388,321 | null | 1 | 31 |
flutter
| 31,182 |
<p>Wrap the Drawer widget inside a Container widget and pass the width parameter to the Container.</p>
<pre><code>drawer: Container(
width: 50,
child: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text('Test123'),
accountEmail: Text('test@123.com'),
currentAccountPicture: Image.network(
'https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a89c3e38-b6f3-48a0-9f9e-df9a0129fb93/daghh5x-4a77b3ec-fd4f-4d17-9f84-5963a8cb5c03.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E4OWMzZTM4LWI2ZjMtNDhhMC05ZjllLWRmOWEwMTI5ZmI5M1wvZGFnaGg1eC00YTc3YjNlYy1mZDRmLTRkMTctOWY4NC01OTYzYThjYjVjMDMucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.dWTFMrwnbAbj5TtUp9U_vQsohW7MnkRPymzR5wZQoV8'),
),
ListTile(
title: Text('data'),
),
],
),
),
),
</code></pre>
|
57,553,973 |
Where should I place my Vaadin 10+ static files?
|
<p>In Vaadin 10-14, where should I place my static files, such as CSS, JavaScript, and Polymer templates? How about static files such as images?</p>
<p>Also, how do I import these files in Vaadin? Is there a difference between Vaadin 14 with npm and Vaadin 10-13 with bower?</p>
| 57,553,974 | 3 | 1 | null |
2019-08-19 09:31:20.063 UTC
| 9 |
2021-06-02 18:39:44.047 UTC
| null | null | null | null | 3,358,029 | null | 1 | 19 |
spring|polymer|vaadin|stylesheet|vaadin-flow
| 7,963 |
<p>All paths are relative to the project root, e.g. where the <code>pom.xml</code> file is located in a Maven project.</p>
<p>JavaScript imported using <code>@JsModule</code> uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" rel="noreferrer">strict mode</a>. Among other things, this means that global variables must be defined on the <code>window</code> object, <code>window.x = ...</code>, instead of just <code>x = ...</code>.</p>
<hr>
<h2>Vaadin 14 with npm</h2>
<h3>Non-Spring Boot projects (war packaging)</h3>
<ul>
<li>CSS files
<ul>
<li><code>@CssImport("./my-styles/styles.css")</code><sup>[1]</sup></li>
<li><code>/frontend/my-styles/styles.css</code></li>
</ul></li>
<li>JavaScript and Polymer templates
<ul>
<li><code>@JsModule("./src/my-script.js")</code><sup>[1]</sup></li>
<li><code>/frontend/src/my-script.js</code></li>
</ul></li>
<li>Static files, e.g. images
<ul>
<li><code>new Image("img/flower.jpg", "A flower")</code></li>
<li><code>/src/main/webapp/img/flower.jpg</code></li>
</ul></li>
</ul>
<h3>Spring Boot projects (jar packaging)</h3>
<ul>
<li>CSS files
<ul>
<li><code>@CssImport("./my-styles/styles.css")</code><sup>[1]</sup></li>
<li><code>/frontend/my-styles/styles.css</code></li>
</ul></li>
<li>JavaScript and Polymer templates
<ul>
<li><code>@JsModule("./src/my-script.js")</code><sup>[1]</sup></li>
<li><code>/frontend/src/my-script.js</code></li>
</ul></li>
<li>Static files, e.g. images
<ul>
<li><code>new Image("img/flower.jpg", "A flower")</code></li>
<li><code>/src/main/resources/META-INF/resources/img/flower.jpg</code></li>
</ul></li>
</ul>
<h3>Add-ons (jar packaging)</h3>
<ul>
<li>CSS files
<ul>
<li><code>@CssImport("./my-styles/styles.css")</code><sup>[1]</sup></li>
<li><code>/src/main/resources/META-INF/resources/frontend/my-styles/styles.css</code></li>
</ul></li>
<li>JavaScript and Polymer templates
<ul>
<li><code>@JsModule("./src/my-script.js")</code><sup>[1]</sup></li>
<li><code>/src/main/resources/META-INF/resources/frontend/src/my-script.js</code></li>
</ul></li>
<li>Static files, e.g. images
<ul>
<li><code>new Image("img/flower.jpg", "A flower")</code></li>
<li><code>/src/main/resources/META-INF/resources/img/flower.jpg</code></li>
</ul></li>
</ul>
<hr>
<h2>Vaadin 10-13, Vaadin 14 in compatibility mode</h2>
<h3>Non-Spring Boot projects (war packaging)</h3>
<ul>
<li>CSS files
<ul>
<li><code>@StyleSheet("css/styles.css")</code><sup>[2]</sup></li>
<li><code>/src/main/webapp/frontend/css/styles.css</code></li>
</ul></li>
<li>Polymer templates, custom-style and dom-module styles
<ul>
<li><code>@HtmlImport("src/template.html")</code></li>
<li><code>/src/main/webapp/frontend/src/template.html</code></li>
</ul></li>
<li>JavaScript
<ul>
<li><code>@JavaScript("js/script.js")</code><sup>[3]</sup></li>
<li><code>/src/main/webapp/frontend/js/script.js</code></li>
</ul></li>
<li>Static files, e.g. images
<ul>
<li><code>new Image("img/flower.jpg", "A flower")</code></li>
<li><code>/src/main/webapp/img/flower.jpg</code></li>
</ul></li>
</ul>
<h3>Spring Boot projects and add-ons (jar packaging)</h3>
<ul>
<li>CSS files
<ul>
<li><code>@StyleSheet("css/styles.css")</code><sup>[2]</sup></li>
<li><code>/src/main/resources/META-INF/resources/frontend/css/styles.css</code></li>
</ul></li>
<li>Polymer templates, custom-style and dom-module styles
<ul>
<li><code>@HtmlImport("src/template.html")</code></li>
<li><code>/src/main/resources/META-INF/resources/frontend/src/template.html</code></li>
</ul></li>
<li>JavaScript
<ul>
<li><code>@JavaScript("js/script.js")</code><sup>[3]</sup></li>
<li><code>/src/main/resources/META-INF/resources/frontend/js/script.js</code></li>
</ul></li>
<li>Static files, e.g. images
<ul>
<li><code>new Image("img/flower.jpg", "A flower")</code></li>
<li><code>/src/main/resources/META-INF/resources/img/flower.jpg</code></li>
</ul></li>
</ul>
<hr>
<h2>Footnotes</h2>
<p><sup>[1]</sup> The <code>@JsModule</code> and <code>@CssImport</code> annotations can also be used for importing from an npm package. In this case, the path is defined as <code>@JsModule("@polymer/paper-input")</code> or <code>@CssImport("some-package/style.css")</code>. <strong>Paths referring to the local frontend directory should be prefixed with <code>./</code></strong></p>
<p><sup>[2]</sup> The <code>@StyleSheet</code> annotation can also be used in Vaadin 14 with npm. The same paths as in V10-V13 can be used, including the <code>context://</code> protocol <code>@StyleSheet("context://style.css")</code>, which resolves the path relative to the context path of the web application, like other static files. <strong>Styles included this way may cause issues with web components</strong>.</p>
<p><sup>[3]</sup> The <code>@JavaScript</code> annotation can also be used in Vaadin 14 with npm. <strong>The V14 <code>/frontend</code> folder should then be used</strong>,.</p>
|
48,316,365 |
React fragment shorthand failing to compile
|
<p>The project in question is using React-16.2.0 which has the capability to use Fragments and the Fragment shorthand.</p>
<p><a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html" rel="noreferrer">https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html</a></p>
<p>While the full-length syntax works fine...</p>
<pre><code>import React, { Fragment, Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<Fragment>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</Fragment>
)
}
};
export default TestingFragment
</code></pre>
<p>The shorthand fails to compile and I am at a loss as to why this is. Fore example...</p>
<pre><code>import React, { Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</>
)
}
};
export default TestingFragment
</code></pre>
<p>Which fails to compile as follows...</p>
<pre><code>Failed to compile
./src/testingFragments.js
Syntax error: Unexpected token (6:4)
4 | render() {
5 | return (
> 6 | <>
| ^
7 | <span>This is a fragment of text </span>
8 | <div>Another part of the fragment</div>
9 | </>
This error occurred during the build time and cannot be dismissed.
</code></pre>
<p>Is there something here I am missing about the Fragment shorthand syntax?</p>
| 48,803,293 | 3 | 1 | null |
2018-01-18 07:59:57.973 UTC
| 7 |
2021-11-27 23:46:53.463 UTC
| null | null | null | null | 4,182,529 | null | 1 | 45 |
javascript|reactjs|create-react-app
| 24,151 |
<p>I think this is a reason:</p>
<p><a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax" rel="noreferrer">https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax</a></p>
<p><strong><a href="https://i.stack.imgur.com/b5fc9.jpg" rel="noreferrer">screenshot</a></strong></p>
<p>create-react-apps currently use <strong>Babel 6.26.0</strong>
for full support React.Fragment is needed <strong>Babel v7.0.0-beta.31</strong> and above</p>
<p>======================= EDIT</p>
<p>It's working now with create-react-app v2
<a href="https://reactjs.org/blog/2018/10/01/create-react-app-v2.html" rel="noreferrer">https://reactjs.org/blog/2018/10/01/create-react-app-v2.html</a></p>
|
30,284,237 |
What is the purpose of "uber mode" in hadoop?
|
<p>Hi I am a big data newbie. I searched all over the internet to find what exactly uber mode is. The more I searched the more I got confused. Can anybody please help me by answering my questions?</p>
<ul>
<li>What does uber mode do? </li>
<li>Does it works differently in mapred 1.x and 2.x?</li>
<li>And where can I find the setting for it?</li>
</ul>
| 31,250,087 | 4 | 0 | null |
2015-05-17 06:58:04.25 UTC
| 16 |
2017-02-23 06:14:51.67 UTC
|
2015-11-03 15:25:58.11 UTC
| null | 861,423 | null | 2,120,416 | null | 1 | 30 |
hadoop|mapreduce
| 29,614 |
<p><strong>What is UBER mode in Hadoop2?</strong> </p>
<p>Normally mappers and reducers will run by ResourceManager (RM), RM will create separate container for mapper and reducer.
Uber configuration, will allow to run mapper and reducers in the same process as the ApplicationMaster (AM). </p>
<p><strong>Uber jobs :</strong></p>
<p>Uber jobs are jobs that are executed within the MapReduce ApplicationMaster. Rather then communicate with RM to create the mapper and reducer containers.
The AM runs the map and reduce tasks within its own process and avoided the overhead of launching and communicate with remote containers.</p>
<p><strong>Why</strong></p>
<p>If you have a small dataset or you want to run MapReduce on small amount of data, Uber configuration will help you out, by reducing additional time that MapReduce normally spends in mapper and reducers phase.</p>
<p><strong>Can I configure an <em>Uber</em> for all MapReduce job?</strong></p>
<p>As of now,
map-only jobs and
jobs with one reducer are supported. </p>
|
848,794 |
Sending email in Java using Apache Commons email libs
|
<p>I am using Apache Commons Email library to send emails, but I am not able to send them via GMail SMTP server.<br>
Can anyone provide sample code which works with GMail SMTP server and others?</p>
<p>I am using the following code which does not work:</p>
<pre><code>String[] recipients = {"receiver@gmail.com"};
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setAuthentication("sender@gmail.com", "mypasswd");
email.setDebug(true);
email.setSmtpPort(465);
for (int i = 0; i < recipients.length; i++)
{
email.addTo(recipients[i]);
}
email.setFrom("sender@gmail.com", "Me");
email.setSubject("Test message");
email.setMsg("This is a simple test of commons-email");
email.send();
</code></pre>
| 848,814 | 3 | 0 | null |
2009-05-11 16:02:57.673 UTC
| 14 |
2015-10-01 15:41:47.683 UTC
|
2012-05-18 13:14:11.987 UTC
| null | 21,234 | null | 93,796 | null | 1 | 12 |
java|email|smtp|gmail|apache-commons-email
| 32,322 |
<p>Sending emails to the GMail SMTP server requires authentication and SSL. The username and password is pretty straight forward. Make sure you have the following properties set to enable authentication and SSL and it should work.</p>
<pre><code>mail.smtp.auth=true
mail.smtp.starttls.enable=true
</code></pre>
<p>To the sample code add the following to enabled TLS.</p>
<p>For API-Versions < 1.3 use:<br>
<code>email.setTSL(true);</code><br>
the method is deprecated for versions >= 1.3, and instead you should use: <code>email.setStartTLSEnabled(true);</code></p>
|
980,337 |
How to know if the code is inside TransactionScope?
|
<p>What is the best way to know if the code block is inside TransactionScope?<br>
Is Transaction.Current a realiable way to do it or there are any subtleties?<br>
Is it possible to access internal ContextData.CurrentData.CurrentScope (in System.Transactions) with reflection? If yes, how?</p>
| 1,079,879 | 3 | 0 | null |
2009-06-11 10:14:26.007 UTC
| 7 |
2020-09-09 14:33:06.027 UTC
|
2016-04-03 05:54:48.21 UTC
| null | 41,956 | null | 94,990 | null | 1 | 33 |
c#|.net|transactionscope
| 13,006 |
<p>Here is more reliable way (as I said, Transaction.Current can be set manually and it doesn't always mean we are really in TransactionScope). It's also possible to get this information with reflection, but emiting IL works 100 times faster than reflection.</p>
<pre><code>private Func<TransactionScope> _getCurrentScopeDelegate;
bool IsInsideTransactionScope
{
get
{
if (_getCurrentScopeDelegate == null)
{
_getCurrentScopeDelegate = CreateGetCurrentScopeDelegate();
}
TransactionScope ts = _getCurrentScopeDelegate();
return ts != null;
}
}
private Func<TransactionScope> CreateGetCurrentScopeDelegate()
{
DynamicMethod getCurrentScopeDM = new DynamicMethod(
"GetCurrentScope",
typeof(TransactionScope),
null,
this.GetType(),
true);
Type t = typeof(Transaction).Assembly.GetType("System.Transactions.ContextData");
MethodInfo getCurrentContextDataMI = t.GetProperty(
"CurrentData",
BindingFlags.NonPublic | BindingFlags.Static)
.GetGetMethod(true);
FieldInfo currentScopeFI = t.GetField("CurrentScope", BindingFlags.NonPublic | BindingFlags.Instance);
ILGenerator gen = getCurrentScopeDM.GetILGenerator();
gen.Emit(OpCodes.Call, getCurrentContextDataMI);
gen.Emit(OpCodes.Ldfld, currentScopeFI);
gen.Emit(OpCodes.Ret);
return (Func<TransactionScope>)getCurrentScopeDM.CreateDelegate(typeof(Func<TransactionScope>));
}
[Test]
public void IsInsideTransactionScopeTest()
{
Assert.IsFalse(IsInsideTransactionScope);
using (new TransactionScope())
{
Assert.IsTrue(IsInsideTransactionScope);
}
Assert.IsFalse(IsInsideTransactionScope);
}
</code></pre>
|
1,005,206 |
Does SQLite lock the database file on reads?
|
<p>I'm investigating SQLite as a storage engine, and am curious to know whether SQLite locks the database file on reads.</p>
<p>I am concerned about read performance as my planned project will have few writes, but many reads. If the database does lock, are there measures that can be taken (such as memory caching) to mitigate this?</p>
| 1,005,218 | 3 | 0 | null |
2009-06-17 05:08:25.793 UTC
| 13 |
2020-01-14 00:11:02.883 UTC
| null | null | null | null | 64,053 | null | 1 | 49 |
sqlite
| 41,395 |
<p>From its <a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">Wikipedia page</a>:</p>
<blockquote>
<p>Several computer processes or threads may access the same database without problems. Several read accesses can be satisfied in parallel.</p>
</blockquote>
<p>More precisely, from its <a href="http://www.sqlite.org/faq.html#q5" rel="noreferrer">FAQ</a>:</p>
<blockquote>
<p>Multiple processes can have the same database open at the same time. Multiple processes can be doing a SELECT at the same time. But only one process can be making changes to the database at any moment in time, however.</p>
</blockquote>
<p>A single write to the database however, <em>does</em> lock the database for a short time so nothing can access it at all (not even reading). Details may be found in <a href="http://www.sqlite.org/lockingv3.html" rel="noreferrer"><em>File Locking And Concurrency In SQLite Version 3</em></a>. Basically reading the database is no problem unless someone wants to write to the database immediately. In that case the DB is locked exclusively for the time it takes to execute that transaction and the lock is released afterwards. However, details are scarce on what exactly does with read operations on the datapase in the time of a PENDING or EXCLUSIVE lock. My guess is that they either return <code>SQLITE_BUSY</code> or block until they can read. In the first case, it shouldn't be too hard to just try again, especially if you are expecting few writes.</p>
|
683,339 |
How do I find the absolute position of an element using jQuery?
|
<p>Is there a way of finding the absolute position of an element, i.e. relative to the start of the window, using jQuery?</p>
| 683,564 | 3 | 1 | null |
2009-03-25 20:36:52.21 UTC
| 66 |
2022-06-28 10:17:46.257 UTC
|
2009-03-26 01:30:01.223 UTC
| null | 45,433 |
akshat
| 29,653 | null | 1 | 425 |
javascript|jquery
| 383,883 |
<p><a href="http://docs.jquery.com/CSS/offset" rel="noreferrer"><code>.offset()</code></a> will return the offset position of an element as a simple object, eg:</p>
<pre><code>var position = $(element).offset(); // position = { left: 42, top: 567 }
</code></pre>
<p>You can use this return value to position other elements at the same spot:</p>
<pre><code>$(anotherElement).css(position)
</code></pre>
|
39,580,063 |
Remove the first N items that match a condition in a Python list
|
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p>
<p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p>
<pre><code>n = 3
def condition(x):
return x < 5
data = [1, 10, 2, 9, 3, 8, 4, 7]
out = do_remove(data, n, condition)
print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains)
</code></pre>
| 39,580,621 | 7 | 0 | null |
2016-09-19 18:46:05.587 UTC
| 13 |
2019-04-27 15:29:55.987 UTC
|
2016-09-20 14:49:29.863 UTC
| null | 400,617 | null | 939,259 | null | 1 | 59 |
python|list|list-comprehension
| 8,167 |
<p>One way using <a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse"><code>itertools.filterfalse</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.count"><code>itertools.count</code></a>:</p>
<pre><code>from itertools import count, filterfalse
data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)
</code></pre>
<p>Then <code>list(output)</code>, gives you:</p>
<pre><code>[10, 9, 8, 4, 7]
</code></pre>
|
39,828,043 |
Gradle error: Write access is allowed from event dispatch thread only in Android Studio
|
<p>After updating Android Studio to version 2.2 (on Windows 10) and somehow next morning I received such error when gradle built on any project: </p>
<blockquote>
<p>Write access is allowed from event dispatch thread only</p>
</blockquote>
<p>Despite that gradlew -build command worked and completed successfully.
I tried typical Android dev's of WTF repairing set: clean build, invalidate caches, removing build folders, removing .gradle folder, tried different gradle settings, even reinstalling Android Studio and nothing helped.</p>
<p>I've created this question only to share my experience with community, because I wasted two hours on it. </p>
| 39,828,044 | 5 | 1 | null |
2016-10-03 09:10:11.537 UTC
| 21 |
2019-07-03 04:05:30.46 UTC
|
2019-07-03 04:04:44.86 UTC
| null | 107,625 | null | 3,379,437 | null | 1 | 122 |
android|android-studio|gradle|android-gradle-plugin|gradlew
| 61,216 |
<p>So the problem was concluded in that Android Studio conflicted with my installed JDK version, so it was resolved when I checked JDK location (File → Project Structure → SDK Location), ticked 'Use embedded JDK' checkbox and set JDK location to 'path to Android Studio'\Android Studio\jre</p>
|
6,434,088 |
What specific use cases call for BOSH over WebSockets and long-polling?
|
<p><a href="http://xmpp.org/extensions/xep-0124.html" rel="noreferrer">BOSH</a> is...</p>
<blockquote>
<p>a transport protocol that emulates the semantics of a long-lived, bidirectional TCP connection between two entities (such as a client and a server) by efficiently using multiple synchronous HTTP request/response pairs without requiring the use of frequent polling or chunked responses.</p>
</blockquote>
<p>This sounds like <a href="http://en.wikipedia.org/wiki/WebSockets" rel="noreferrer">WebSockets</a> and HTTP long-polling except that it uses two open HTTP connections instead of one and doesn't extend the HTTP protocol. </p>
<p>What are the differences between the two protocols, and what use case would prefer WebSockets over BOSH?</p>
| 6,442,488 | 1 | 0 | null |
2011-06-22 01:59:14.4 UTC
| 34 |
2017-04-25 14:33:19.903 UTC
|
2017-04-25 14:33:19.903 UTC
| null | 1,028,230 | null | 102,704 | null | 1 | 43 |
http|comet|websocket
| 17,519 |
<p><strong>First let me address WebSockets readiness</strong>:</p>
<p>WebSockets implementation of the <a href="https://datatracker.ietf.org/doc/html/draft-hixie-thewebsocketprotocol-76" rel="nofollow noreferrer">Hixie-76</a> protocol are shipped and enabled by default in Chrome, Safari and iOS (iPhone and iPad). The Hixie-76 protocol is also shipped but disabled by default in Firefox 4 and Opera 11. The <a href="https://github.com/gimite/web-socket-js" rel="nofollow noreferrer">web-socket-js</a> project is a Flash shim/polyfill that adds WebSocket (Hixie-76) support to any browser with Flash.</p>
<p>In other words, WebSockets is available for almost every browser in the wild.</p>
<p>The reason why Opera and Mozilla chose to disable the protocol by default is because of a theoretical concern that there might be some broken HTTP proxies/intermediaries that could be attacked/poisoned using the Hixie versions of the protocol. The same concern applies to Flash but Mozilla and Opera felt a higher duty of responsibility for code that they ship. The HyBi versions of the protocol (the protocol was moved to the IETF HyBi working group) address the security concern.</p>
<p>Mozilla, Opera, Google, and Microsoft are all working on HyBi protocol implementations (although Microsoft is maintaining theirs as a <a href="http://html5labs.interoperabilitybridges.com/prototypes/websockets/websockets/info" rel="nofollow noreferrer">separate download</a> for now). There is a <a href="https://github.com/gimite/web-socket-js/tree/hybi-07" rel="nofollow noreferrer">branch of web-socket-js</a> with HyBi-07 support.</p>
<p><strong>Update</strong>: As of Feb, 2013, the latest <a href="https://www.rfc-editor.org/rfc/rfc6455" rel="nofollow noreferrer">HyBi/IETF RFC 6455 spec</a> is supported by Chrome 14, Firefox 7, IE10, Opera 12.1, Safari 6.0 and by the <a href="https://github.com/gimite/web-socket-js" rel="nofollow noreferrer">web-socket-js</a> Flash shim/polyfill. On mobile devices IETF6455 is supported by Safari on iOS 6.0, Opera Mobile 12.1, Chrome 14 for Android, Firefox 7 for Android, and Blackberry 7. The original default Android browser does not have any WebSocket support.</p>
<p>WebSocket servers are easy to implement. There are numerous standalone and plugin implementations most of which support both Hixie-76 and HyBi protocol versions:</p>
<ul>
<li><a href="http://git.warmcat.com/cgi-bin/cgit/libwebsockets/" rel="nofollow noreferrer">libwebsockets</a></li>
<li><a href="http://blogs.webtide.com/gregw/entry/jetty_websocket_server" rel="nofollow noreferrer">Jetty</a></li>
<li><a href="http://code.google.com/p/pywebsocket/" rel="nofollow noreferrer">pywebsockets</a></li>
<li><a href="https://github.com/kanaka/websockify" rel="nofollow noreferrer">websockify</a></li>
<li><a href="http://socket.io" rel="nofollow noreferrer">Socket.IO</a></li>
<li><a href="http://code.google.com/p/phpwebsocket/" rel="nofollow noreferrer">phpwebsocket</a></li>
<li><a href="http://search.cpan.org/%7Evti/Protocol-WebSocket-0.00901/lib/Protocol/WebSocket.pm" rel="nofollow noreferrer">Protocol::WebSocket (perl)</a></li>
<li><a href="https://github.com/igrigorik/em-websocket" rel="nofollow noreferrer">em-websocket (ruby)</a></li>
<li><a href="https://github.com/miksago/node-websocket-server" rel="nofollow noreferrer">node-websocket-server</a></li>
</ul>
<p><strong>BOSH vs WebSockets</strong>:</p>
<ul>
<li><strong>latency</strong>: While the BOSH draft document claims very low-latency, it will be difficult for BOSH to compete with WebSockets. Unless you have ideal conditions where HTTP/1.1 is supported all the way through all intermediaries and by the target server, the BOSH client and connection manager will need to re-establish connections after every packet and every request timeout. This will significantly increase latency and latency jitter. Low jitter is often more important for real-time applications than average latency. WebSocket connections will be very similar in latency and jitter to raw TCP connections. And even under ideal conditions, the client-to-server latency of BOSH communication (and therefore round-trip) will always be higher than WebSockets: BOSH still has to abide by HTTP request-response semantics. HTTP streaming enables multiple responses per request (by splitting a "single" response into multiple parts) but not vice-versa (each client message is a new request).</li>
<li><strong>small-packet overhead</strong>: In WebSockets there are two bytes of framing overhead for small
messages. In BOSH, every message has HTTP request and response headers (easily 180+ bytes for each round-trip). In addition, each message is wrapped in XML (supposedly optional but the spec doesn't define how) with several session related attributes.</li>
<li><strong>complexity</strong>: while BOSH uses existing mechanisms in the browser, it requires a moderately complex JavaScript library to implement the BOSH semantics. Managing this in Javascript will also increase latency and jitter compared to a native/browser (or even Flash) implementation.</li>
<li><strong>traction</strong>: BOSH started life as a way to make XMPP more efficient. It grew up out of the XMPP community and from what I can tell has gotten very little traction outside of that community. The draft documents for BOSH and XMPP are split apart, but there seems to be very little real world use of BOSH without XMPP.</li>
</ul>
<p><strong>Update</strong>:</p>
<p>Just found a video where Ian Fette discusses the <a href="http://www.youtube.com/watch?v=qzA60hHca9s&feature=player_embedded#at=2650" rel="nofollow noreferrer">advantages of WebSockets over the Channel API which is similar to BOSH</a> (at 44:00)</p>
|
24,430,121 |
How to use font awesome in a fxml project (javafx)
|
<p>I want to use font font awesome in my project but I have no idea how to use font awesome in my project.</p>
<p>I had found some example but they can't be use in fxml.</p>
<p><a href="https://bitbucket.org/Jerady/fontawesomefx" rel="noreferrer">font awesome javafx</a> </p>
<p>I need help how to use it in my project using fxml</p>
<p>Thank you.</p>
| 24,433,222 | 6 | 0 | null |
2014-06-26 12:07:37.54 UTC
| 2 |
2019-05-17 14:07:40.307 UTC
|
2018-10-18 18:33:26.633 UTC
| null | 2,503,722 | null | 3,749,316 | null | 1 | 14 |
java|javafx|javafx-2|javafx-8|fxml
| 49,818 |
<p>I think this is what you need <a href="http://fxexperience.com/controlsfx/features/" rel="nofollow noreferrer">ControlFX</a> that include font awesome support.
see the <a href="https://controlsfx.bitbucket.io/" rel="nofollow noreferrer">javadoc</a> for more info (But I tested it one day and it works fine)</p>
|
5,965,007 |
How can I set a fixed height for my entire webpage?
|
<p>I thought this was a simple fix:</p>
<pre><code>body
{
height: 1054px;
}
html
{
height: 1054px;
}
</code></pre>
<p>Wouldn't this set the max height of the page to <code>1054px</code>? I have also tried these workarounds but they didn't work with what I wanted:</p>
<pre><code>html
{
overflow: hidden;
}
<body><table id = "myTable"><tr><td> ..... </tr></td></body>
#myTable
{
height: 100%;
}
</code></pre>
<p>How do I set an absolute height for a webpage? Also I am more interested in why the <code>body</code> and <code>html</code> <code>height</code> calls wouldn't work. I do a lot of <code>position: relative</code> calls, would that have an effect on it?</p>
| 5,965,074 | 3 | 3 | null |
2011-05-11 13:25:28.367 UTC
| 3 |
2012-09-08 22:00:20.907 UTC
|
2011-05-11 13:32:29.66 UTC
| null | 20,578 | null | 650,489 | null | 1 | 6 |
html|css
| 88,572 |
<p><code>width</code> and <code>height</code> do set absolute widths and heights of an element respectively. <code>max-width</code>, <code>max-height</code>, <code>min-width</code> and <code>min-height</code> are seperate properties.</p>
<p>Example of a page with 1054px square content and a full background:</p>
<pre><code>html {
min-width: 100%;
min-height: 100%;
background-image: url(http://www.example.com/somelargeimage.jpg);
background-position: top center;
background-color: #000;
}
body {
width: 1054px;
height: 1054px;
background-color: #FFF;
}
</code></pre>
<p>However, since you seem to be table styling (urgh), it would probably be far more sensible to set the height of the table to 1054px and let the body adjust itself automatically to encompass the entire table. (Keep the html style proposed above, of course.)</p>
|
5,747,401 |
How to replace value in list at same collection location
|
<p>How do I replace a value in a collection list at the same location?</p>
<pre><code>0 = cat
1 = dog
2 = bird
</code></pre>
<p>replace <code>2</code> with <code>snail</code>?</p>
| 5,747,420 | 3 | 1 | null |
2011-04-21 17:08:23.23 UTC
| 3 |
2019-01-16 12:19:36.703 UTC
|
2013-05-24 06:47:54.54 UTC
| null | 1,049,308 | null | 230,434 | null | 1 | 39 |
c#
| 80,829 |
<p>Do you mean:</p>
<pre><code>yourCollection[2] = "Snail";
</code></pre>
|
5,993,621 |
Fastest way to search a list in python
|
<p>When you do something like <code>"test" in a</code> where <code>a</code> is a list does python do a sequential search on the list or does it create a hash table representation to optimize the lookup? In the application I need this for I'll be doing a lot of lookups on the list so would it be best to do something like <code>b = set(a)</code> and then <code>"test" in b</code>? Also note that the list of values I'll have won't have duplicate data and I don't actually care about the order it's in; I just need to be able to check for the existence of a value.</p>
| 5,993,659 | 4 | 0 | null |
2011-05-13 14:45:38.74 UTC
| 11 |
2016-09-14 12:32:16.823 UTC
| null | null | null | null | 38 | null | 1 | 39 |
python|list|search|find|set
| 62,423 |
<blockquote>
<p>Also note that the list of values I'll have won't have duplicate data and I don't actually care about the order it's in; I just need to be able to check for the existence of a value.</p>
</blockquote>
<p>Don't use a list, use a <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="noreferrer"><code>set()</code></a> instead. It has exactly the properties you want, including a blazing fast <code>in</code> test.</p>
<p>I've seen speedups of 20x and higher in places (mostly heavy number crunching) where one list was changed for a set.</p>
|
5,922,287 |
Rails 3: yield/content_for with some default value?
|
<p>Is there any way to detect if <code>#content_for</code> was actually applied to a <code>yield</code> scope in Rails?</p>
<p>A classic example being something like:</p>
<pre><code><title><%= yield :page_title %></title>
</code></pre>
<p>If a template doesn't set that with</p>
<pre><code><% content_for :page_title, "Something here" %>
</code></pre>
<p>Is there a way to have the layout put something else there instead?</p>
<p>I tried defining it with <code>#content_for</code> in the layout itself, but this just causes the text to be doubled-up. I also tried:</p>
<pre><code><%= (yield :page_title) or default_page_title %>
</code></pre>
<p>Where <code>#default_page_title</code> is a view helper.</p>
<p>This just left the block completely empty.</p>
| 5,922,305 | 4 | 0 | null |
2011-05-07 16:06:28.243 UTC
| 12 |
2014-10-20 11:19:18.113 UTC
| null | null | null | null | 322,122 | null | 1 | 64 |
ruby-on-rails|ruby|yield
| 17,517 |
<p>You can use <code>content_for?</code> to check if there is content with a specific name:</p>
<pre><code><% if content_for?(:page_title) %>
<%= yield(:page_title) %>
<% else %>
<%= default_page_title %>
<% end %>
</code></pre>
<p>or</p>
<pre><code><%= content_for?(:page_title) ? yield(:page_title) : default_page_title %>
</code></pre>
<p>Then in your views you can specify the content like</p>
<pre><code><% content_for :page_title do %>
Awesome page
<% end %>
</code></pre>
|
32,163,517 |
Run javascript code in Webview
|
<p>I have a webview i am using in android and I'm trying to trigger javascript on a button click. I'm trying to use the code below to change the color of the class to red. But I cant seem to get it working</p>
<pre><code>final WebView wb=(WebView)findViewById(R.id.webView2);
wb.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};");
</code></pre>
| 32,163,655 | 2 | 1 | null |
2015-08-23 05:33:41.67 UTC
| 12 |
2020-01-05 19:26:41.02 UTC
| null | null | null | null | 2,423,476 | null | 1 | 20 |
javascript|android|webview
| 26,254 |
<p>From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below</p>
<pre><code> if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};", null);
} else {
webView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};");
}
</code></pre>
<p>Enable Javascript for your webview by adding the following line </p>
<pre><code>wb.getSettings().setJavaScriptEnabled(true);
</code></pre>
|
5,617,175 |
ArrayList replace element if exists at a given index?
|
<p>How to replace element if exists in an ArrayList at a given index?</p>
| 9,700,356 | 5 | 0 | null |
2011-04-11 05:39:54.787 UTC
| 7 |
2020-07-12 21:01:30.17 UTC
|
2018-03-14 12:39:11.4 UTC
| null | 1,000,551 | null | 689,853 | null | 1 | 85 |
java|arraylist
| 89,150 |
<pre><code> arrayList.set(index i,String replaceElement);
</code></pre>
|
5,813,077 |
iPhone/iOS JSON parsing tutorial
|
<p>As a learning experience, I want to make an iPhone application that calls a webserver/webservice, retrieves a JSON response, and uses that response to populate the rows of a <code>UITableView</code> (assuming it converts the JSON into an <code>NSArray</code> first).</p>
<p>Anyone know of anything that might be useful?</p>
| 5,813,223 | 6 | 0 | null |
2011-04-28 02:54:24.97 UTC
| 81 |
2016-12-20 06:20:45.203 UTC
|
2016-12-20 06:20:45.203 UTC
| null | 4,078,527 | null | 480,807 | null | 1 | 103 |
iphone|objective-c|ios|json|uitableview
| 137,155 |
<p>You will love this <a href="https://github.com/stig/json-framework/">framework</a>.</p>
<p>And you will love this <a href="http://ditchnet.org/httpclient/">tool</a>.</p>
<p>For learning about JSON you might like this <a href="http://json.org/">resource</a>.</p>
<p>And you'll probably love this <a href="http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c">tutorial</a>.</p>
|
9,969,833 |
Programmatically determine via ifdef if a label is defined within a Translation Unit
|
<p>I have the following bit of code, I expect that given cstdio is included that the first line will be printed, however the second line is printed. </p>
<p>What am I doing wrong? is it possible to know if labels such as printf or strncmp or memcpy have been defined in the current translation unit at compile time?</p>
<pre><code>#include <iostream>
#include <cstdio>
int main()
{
#ifdef printf
std::cout << "printf is defined.\n";
#else
std::cout << "printf NOT defined!\n";
#endif
return 0;
}
</code></pre>
<p>Is the reason because the preprocessor is run before variables and labels are introduced into the scope/TU?</p>
<p>In short is the following code bogus? :</p>
<p><a href="http://code.google.com/p/cmockery/source/browse/trunk/src/example/calculator.c#35" rel="nofollow">http://code.google.com/p/cmockery/source/browse/trunk/src/example/calculator.c#35</a></p>
| 9,969,890 | 3 | 6 | null |
2012-04-02 01:12:00.92 UTC
| 8 |
2012-04-02 01:47:37.907 UTC
|
2012-04-02 01:47:37.907 UTC
| null | 755,004 | null | 755,004 | null | 1 | 2 |
c++|label|conditional-compilation
| 366 |
<p><code>#ifdef</code> only applies to preprocessor macros, defined with <code>#define</code>, not to symbols like function names and variables. You can imagine the preprocessor as an actual separate preliminary step, like running your code through a perl script, that occurs before the "real" compiler gets a crack at it.</p>
<p>So there is no programmatic way to check whether symbols like <code>printf</code> are defined in the current scope. If you use one and it's not defined, you'll get a compiler error. The normal thing to do is to <code>#include</code> a header file with the required definition in the source file where you reference it, not to write a source file that will adapt itself to different possible sets of headers.</p>
<p>As a hack, and depending on your environment and specific problem, the header file that does define <code>printf</code> (or whatever function you care about) may also contain some preprocessor <code>#define</code>s that you could check for.</p>
|
1,320,931 |
How to correctly use ABPersonViewController with ABPeoplePickerNavigationController to view Contact information?
|
<p>Update 9/2/10: This code no longer works as of the iOS 4 update--it fails with an internal assertion. There is now a great Address Book API example available in the iPhone SDK Reference Library called "QuickContacts."</p>
<p>The example code is available here; it will help you solve this problem:
<a href="http://developer.apple.com/iphone/library/samplecode/QuickContacts/Introduction/Intro.html" rel="noreferrer">http://developer.apple.com/iphone/library/samplecode/QuickContacts/Introduction/Intro.html</a></p>
<hr>
<p>I'm attempting to add a feature to my app that allows the user to select a contact from an <strong>ABPeoplePickerNavigationController</strong>, which then displays an <strong>ABPersonViewController</strong> corresponding to the contact they picked. At that point, I want the user to be able to click on a contact's phone number and have my app respond with custom behavior.</p>
<p>I've got the <strong>ABPeoplePickerNavigationController</strong> working fine, but I'm running into a problem displaying the <strong>ABPersonViewController</strong>. I can get the <strong>ABPersonViewController</strong> to animate onto the screen just fine, but it only displays the contact's photo, name, and company name. None of the contact's other fields are displayed.</p>
<p>I'm using the 'displayedProperties' element in the <strong>ABPersonViewController</strong> to tell the program to display phone numbers. This creates some strange behavior; when I select a contact that has no phone numbers assigned, the contact shows up with "No Phone Numbers" written in the background (as you'd expect), but when selecting a contact that does have a phone number, all I get is a blank contact page (without the "No Phone Numbers" text).</p>
<p>Here's the method in my <strong>ABPeoplePickerNavigationController delegate</strong> class that I'm using to create my <strong>PersonViewController</strong> class, which implements the <strong>ABPersonViewController interface:</strong></p>
<pre><code>- (BOOL) peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
BOOL returnState = NO;
PersonViewController *personView = [[PersonViewController alloc] init];
[personView displayContactInfo:person];
[peoplePicker pushViewController:personView animated:YES];
[personView release];
return returnState;
}
</code></pre>
<p>Here's my <strong>PersonViewController.h</strong> header file:</p>
<pre><code>#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AddressBookUI/AddressBookUI.h>
@interface PersonViewController : UIViewController <ABPersonViewControllerDelegate>
{
}
- (void) displayContactInfo: (ABRecordRef)person;
@end
</code></pre>
<p>Finally, here's my <strong>PersonViewController.m</strong> that's creating the <strong>ABPersonViewController</strong> to view the selected contact:</p>
<pre><code>#import "PersonViewController.h"
@implementation PersonViewController
- (void) displayContactInfo: (ABRecordRef)person
{
ABPersonViewController *personController = [[ABPersonViewController alloc] init];
personController.personViewDelegate = self;
personController.allowsEditing = NO;
personController.displayedPerson = person;
personController.addressBook = ABAddressBookCreate();
personController.displayedProperties = [NSArray arrayWithObjects:
[NSNumber numberWithInt:kABPersonPhoneProperty],
nil];
[self setView:personController.view];
[[self navigationController] pushViewController:personController animated:YES];
[personController release];
}
- (BOOL) personViewController:(ABPersonViewController*)personView shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
return YES;
}
@end
</code></pre>
<p>Does anyone have any idea as to why I'm seeing this blank Contact screen instead of one with clickable phone number fields?</p>
<hr>
<p>Alright, I think I'm getting closer to finding the problem. I'm fairly sure it's with this part of the displayContactInfo call above:</p>
<pre><code>[self setView:personController.view];
</code></pre>
<p>When I omit this line, all I see is a blank screen when I click a contact. The ABPeoplePickerNavigationController is pushing the PersonViewController onto the NavigationController stack. The PersonViewController then instantiates an ABPersonViewController object, but for whatever reason the ABPersonViewController never gets properly added to the NavigationController stack.</p>
<p>Does anyone know how to add the ABPersonViewController to the stack, rather than just the PersonViewController?</p>
| 1,356,215 | 1 | 0 | null |
2009-08-24 07:34:49.757 UTC
| 9 |
2012-05-16 05:14:57.353 UTC
|
2012-04-20 07:00:15.007 UTC
| null | 579,628 | null | 153,081 | null | 1 | 19 |
iphone|ios|addressbook
| 31,333 |
<p>Just a heads-up to anyone who runs into this problem themselves: I was able to product the correct behavior by instantiating the ABPersonViewController in its delegate's <strong>viewDidLoad()</strong> method as below:</p>
<p>As before, here's my <strong>ABPeoplePickerNavigationController delegate's</strong> method:</p>
<pre><code>- (BOOL) peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
BOOL returnState = NO;
PersonViewController *personView = [[PersonViewController alloc] init];
[peoplePicker pushViewController:personView animated:YES];
[personView displayContactInfo:person];
[personView release];
return returnState;
}
</code></pre>
<p><strong>Here's my PersonViewController.h (ABPersonViewController delegate) header file:</strong></p>
<pre><code>#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AddressBookUI/AddressBookUI.h>
@interface PersonViewController : UIViewController <ABPersonViewControllerDelegate>
{
ABPersonViewController *personController;
}
- (void) displayContactInfo: (ABRecordRef)person;
@end
</code></pre>
<p>Finally, here's the <strong>delegate's implementation (PersonViewController.m):</strong></p>
<pre><code>#import "PersonViewController.h"
@implementation PersonViewController
- (void) viewDidLoad
{
}
- (void) viewDidUnload
{
[personController release];
}
- (void) displayContactInfo: (ABRecordRef)person
{
personController = [[ABPersonViewController alloc] init];
[personController setDisplayedPerson:person];
[personController setPersonViewDelegate:self];
[personController setAllowsEditing:NO];
personController.addressBook = ABAddressBookCreate();
personController.displayedProperties = [NSArray arrayWithObjects:
[NSNumber numberWithInt:kABPersonPhoneProperty],
nil];
[self setView:personController.view];
}
- (BOOL) personViewController:(ABPersonViewController*)personView shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
// This is where you pass the selected contact property elsewhere in your program
[[self navigationController] dismissModalViewControllerAnimated:YES];
return NO;
}
@end
</code></pre>
<p>Hopefully this ends up being helpful for someone. The <strong>AddressBook UI framework</strong> was a bit tricky for me to wrap my head around (although I'm new to iPhone development so I'm still learning a lot of the nuances of iPhone program organization).</p>
|
1,270,001 |
Visual Studio 2008 Output - Hide dll loads and unloads
|
<p>Visual Studio automatically displays dll loads/unloads in its output panel, like so:</p>
<pre><code>'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\wbem\fastprox.dll'
'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\ntdsapi.dll'
'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\wldap32.dll'
'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\wbem\wbemsvc.dll'
'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\wbem\wbemprox.dll'
'DialogAppDEBUG.exe': Unloaded 'C:\WINDOWS\system32\wbem\wbemcomn.dll'
</code></pre>
<p>Is there anyway to temporarily disable this? When doing extensive debugging via DebugOutputString(), those messages always tend to push my prints off the panel and I have to search around for them, making the process much more cumbersome. I've Googled and searched through all of the VS options I could think of, but to no avail...</p>
| 1,682,418 | 1 | 1 | null |
2009-08-13 04:17:00.34 UTC
| 2 |
2009-11-05 18:00:00.907 UTC
| null | null | null | null | 136,785 | null | 1 | 28 |
visual-studio-2008|panel
| 3,794 |
<p>Asked the same thing today, and the answer was as simple as:</p>
<blockquote>
<p>Right click in the Output window when
you're running your program and
uncheck all of the messages you don't
want to see (like Thread Exit
messages).</p>
</blockquote>
<p>In your case, uncheck "Module Load messages"</p>
|
19,365,758 |
How do I store a value from a SELECT statement in a variable in a MySQL Stored Procedure?
|
<p>This may be a super easy question to answer, but I am unsure how to do this correctly.</p>
<p>Here is my query within the procedure:</p>
<pre><code>SELECT COUNT(barcode) AS count FROM movieitems;
</code></pre>
<p>How do I store the return value of this statement (for example, the value in <code>count</code> is <code>5</code>) into a variable? I want to be able to access the <code>count</code> value throughout the rest of my procedure.</p>
| 19,365,810 | 2 | 0 | null |
2013-10-14 17:25:56.073 UTC
| 6 |
2013-10-14 17:30:40.073 UTC
| null | null | null | null | 546,509 | null | 1 | 29 |
mysql|sql|stored-procedures
| 84,020 |
<p>In a stored procedure do this:</p>
<pre><code>SELECT COUNT(barcode) AS count into @myVar FROM movieitems;
</code></pre>
|
41,126,943 |
Wireshark - you don't have permission to capture on that device mac
|
<p>I installed Wireshark and during the installation it showed an error but the installation itself completed. When I ran the program and tried to capture packets on my network, it showed this error:</p>
<p><img src="https://i.stack.imgur.com/IWFlY.png" alt="You don't have permission to capture on that device" /></p>
<p>I'm new to mac so i don't even know how to properly ask.</p>
<p>Could someone help me?</p>
| 42,368,892 | 9 | 0 | null |
2016-12-13 17:18:45.497 UTC
| 28 |
2021-12-23 07:43:23.017 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 7,263,962 | null | 1 | 46 |
macos|permissions|wireshark
| 83,014 |
<p>According to User: <a href="https://ask.wireshark.org/questions/578/mac-os-cant-detect-any-interface" rel="noreferrer">gmale's answer on ask.wireshark.org</a>, he solved his problem in this way and I'm sure that it could solve yours as well. It says:</p>
<p>1- <strong>Open Terminal</strong></p>
<p>To see your exact <strong>user name</strong> (for me that was <strong>AliGht</strong>)</p>
<p>2- <strong>Type 'whoami'</strong></p>
<p><a href="https://i.stack.imgur.com/gS8vi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gS8vi.png" alt="enter image description here"></a></p>
<p>3- <strong>execute the following commands:</strong></p>
<pre><code>cd /dev
sudo chown AliGht:admin bp*
</code></pre>
<p>and enter your <strong>computer password</strong>:</p>
<p><a href="https://i.stack.imgur.com/Pta6J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Pta6J.png" alt="enter image description here"></a></p>
<p>4- <strong>now type this command:</strong> </p>
<pre><code>ls -la | grep bp
</code></pre>
<p>The last command will display a list of files such as:</p>
<p><a href="https://i.stack.imgur.com/x5dmT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/x5dmT.png" alt="enter image description here"></a></p>
<p>5- Make sure all of them have your <strong>user name</strong> and <strong>admin</strong> as the user/group. For some reason, the <strong>last one didn't get assigned properly so I had to run the command</strong>:</p>
<pre><code>sudo chown AliGht:admin bpf4
</code></pre>
<p>so the last command fixed my problem as you see in the last image:</p>
<p><a href="https://i.stack.imgur.com/a59hY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a59hY.png" alt="enter image description here"></a></p>
<p><strong>Done!</strong></p>
<p><strong>If your WireShark is open then close it and open it again.</strong></p>
<p>All credits of this tutorial goes to user <a href="https://ask.wireshark.org/questions/578/mac-os-cant-detect-any-interface" rel="noreferrer">gmale on ask.wireshark.org</a>,</p>
<p><strong>If you want to open WireShark always as administrator then take a look to another <a href="https://stackoverflow.com/a/42574321/3618481">post</a> which I created a shortcut for it via Applescript, and this is the only way which you can open the WireShark always as administrator even when you turn off/on your mac.</strong></p>
|
19,242,747 |
JavaFX Editable ComboBox : Showing toString on item selection
|
<p>I have a <code>ComboBox<Person></code>, of type <code>Person</code>, in which I have added few object of <code>Person</code> class.</p>
<p>I have used <code>setCellFactory(Callback)</code> method to show <code>Person</code> name in <code>ComboBox</code> drop down</p>
<pre><code>combobox.setCellFactory(
new Callback<ListView<Person >, ListCell<Person >>() {
@Override
public ListCell<Person > call(ListView<Person > p) {
ListCell cell = new ListCell<Person >() {
@Override
protected void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText("");
} else {
setText(item.getName());
}
}
};
return cell;
}
});
</code></pre>
<p>And, <code>setButtonCell(ListCell)</code> method to show name in <code>combobox</code> on selection.</p>
<pre><code>combobox.setButtonCell(
new ListCell<Object>() {
@Override
protected void updateItem(Person t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText("");
} else {
setText(t.getName());
}
}
});
</code></pre>
<p>This works perfectly good with normal case but when I use editable <code>combobox</code> then this fails.</p>
<p>When I write , <code>combobox.setEditable(true);</code> then on item selection the text field (editor) of <code>combobox</code> shows <code>toString()</code> method of <code>Person</code> class.</p>
<p>Normal Case :
<img src="https://i.stack.imgur.com/YlYh2.jpg" alt="Normal Case" /></p>
<p>Editable Case :
<img src="https://i.stack.imgur.com/0m20H.jpg" alt="Editable Case" /></p>
<p>Is there any solution for this?</p>
<p>I have a model class:</p>
<pre><code>public class Person {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "name=" + name + ", age=" + age + '}';
}
}
</code></pre>
| 20,470,223 | 2 | 0 | null |
2013-10-08 08:30:02.197 UTC
| 9 |
2021-02-11 06:58:55.677 UTC
|
2021-02-11 06:58:55.677 UTC
| null | 2,164,365 | null | 1,795,947 | null | 1 | 12 |
combobox|javafx-2|javafx|javafx-8
| 18,974 |
<p>Here is an answer to my own question which I found best after many efforts and corrections.</p>
<pre><code>mainComboBox.setButtonCell(
new ListCell<Object>() {
@Override
protected void updateItem(Object t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText("");
} else {
setText(getStringField(t));
}
}
});
mainComboBox.setConverter(
new StringConverter() {
private Map<String, Object> map = new HashMap<>();
@Override
public String toString(Object t) {
if (t != null) {
String str = getStringField(t);
map.put(str, t);
return str;
} else {
return "";
}
}
@Override
public Object fromString(String string) {
if (validate && !map.containsKey(string)) {
mainComboBox.setValue(null);
mainComboBox.getEditor().clear();
return null;
}
return map.get(string);
}
});
mainComboBox.setCellFactory(
new Callback<ListView<Object>, ListCell<Object>>() {
@Override
public ListCell<Object> call(ListView<Object> p) {
ListCell cell = new ListCell<Object>() {
@Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText("");
} else {
setText(getStringField(item));
}
}
};return cell;
}
});
</code></pre>
<p>And with required function of <code>getStringField(Object)</code>,</p>
<pre><code>public String getStringField(Object o) {
return ((Pesron) o).getName();
}
</code></pre>
|
19,167,901 |
File not shown in git diff after a git add. How do I know it will be committed?
|
<p>I had an untracked file which was not appearing in a git diff and when I added it to the 'changes to be committed' area, it still doesn't show up in the git diff. I shows up with a <code>git status -v</code> when I do a diff against HEAD.</p>
<p>I'm still very new to git, so could anyone please tell me if the file will be committed even if it doesn't show up in a regular diff, as it has been added to the staging area?</p>
| 19,168,261 | 5 | 0 | null |
2013-10-03 19:44:13.633 UTC
| 3 |
2018-07-31 15:28:26.8 UTC
|
2016-09-19 21:33:58.227 UTC
| null | 2,301,450 | null | 1,732,772 | null | 1 | 41 |
git|file|commit|git-commit|git-diff
| 32,330 |
<p>If you'd like to see the <em>staged</em> changes in a diff, you can still use <code>git diff</code>, you just need to pass the <code>--staged</code> flag:</p>
<pre class="lang-sh prettyprint-override"><code>david@pav:~/dummy_repo$ echo "Hello, world" > hello.txt
david@pav:~/dummy_repo$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
# hello.txt
nothing added to commit but untracked files present
david@pav:~/dummy_repo$ git add hello.txt
david@pav:~/dummy_repo$ git diff
david@pav:~/dummy_repo$ git diff --staged
diff --git a/hello.txt b/hello.txt
new file mode 100644
index 0000000..76d5293
--- /dev/null
+++ b/hello.txt
@@ -0,0 +1 @@
+Hello, world
</code></pre>
<p>If you only care about which files are staged, you can of course do a <code>git status</code>, but <code>git diff --staged --name-only</code> will give each staged filename on its own line.</p>
|
26,538,421 |
How do I play sound on button click in android studio?
|
<p>I would like that when the button is pressed the sound file starts to play.I have already created the raw folder and put the .wav file there. The problem is that i don't know how to do this thing. I checked similar questions here but they don't seem to fix my problem. What should i do? Thank you in advance.</p>
<p>Here is my code:</p>
<pre><code>import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import android.media.MediaPlayer;
import android.view.View.OnClickListener;
public class MyActivity extends ActionBarActivity {
int clicked= 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//start
//end
final TextView text = (TextView) findViewById(R.id.textView);
text.setText("Score: 0");
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clicked++;
text.setText("Score: " + clicked);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>Here the xml codes :
</p>
<pre><code><ImageView
android:layout_width="100dp"
android:layout_height="173dp"
android:id="@+id/imageView"
android:background="@drawable/aidsv"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:adjustViewBounds="false" />
<Button
android:layout_width="200dp"
android:layout_height="29dp"
android:text="Click me!"
android:id="@+id/button"
android:background="@drawable/redbottone"
android:layout_marginTop="39dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="120dp"
android:layout_height="42dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: "
android:id="@+id/textView"
android:textColor="#FF0000"
android:background="@drawable/sfondotempo"
android:autoText="false"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp" />
</code></pre>
<p></p>
| 26,538,468 | 1 | 0 | null |
2014-10-23 22:16:24.727 UTC
| 2 |
2020-12-20 00:18:20.263 UTC
|
2020-12-20 00:18:20.263 UTC
| null | 1,783,163 | null | 4,135,362 | null | 1 | 2 |
android|button|android-studio
| 76,064 |
<pre><code> Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);
Button play_button = (Button)this.findViewById(R.id.button);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
</code></pre>
<p>Place your sound in res/raw folder.</p>
|
26,787,628 |
How do I specify relative paths in CMAKE?
|
<p>I want to specify a path that is relative to the current directory within CMake and have not been able to find a solution.</p>
<p>My project lies in a path something like:</p>
<pre><code>C:/Projects/ProjectA/CMakeLists.txt
</code></pre>
<p>and I want to specify the name of the relative path of the following directory using the set() command:</p>
<pre><code>C:/External/Library
</code></pre>
<p>In other words, what is the CMake translation of</p>
<pre><code>../../External/Library?
</code></pre>
| 26,787,695 | 1 | 0 | null |
2014-11-06 19:16:29.263 UTC
| 1 |
2022-03-21 16:02:50.793 UTC
|
2022-03-21 16:00:39.843 UTC
| null | 212,378 | null | 1,620,721 | null | 1 | 24 |
cmake
| 38,456 |
<p>The is almost exactly the same, except that you have allow for CMake to run in another location for "out-of-tree" builds. You do this by specifying the path relative to <code>${CMAKE_CURRENT_SOURCE_DIR}</code>, which is the directory containing the current CMakeLists.txt file.</p>
<pre><code>${CMAKE_CURRENT_SOURCE_DIR}/../../External/Library
</code></pre>
<p>But, you might want to reconsider, and instead use <a href="https://cmake.org/cmake/help/latest/command/find_library.html" rel="nofollow noreferrer"><code>FIND_LIBRARY()</code></a> and <a href="https://cmake.org/cmake/help/latest/command/find_file.html" rel="nofollow noreferrer"><code>FIND_FILE()</code></a> commands to search a set of predefined locations, so that users of your library don't have to keep the same relative structure.</p>
|
36,215,244 |
Disable entire form elements with respect to a state. React
|
<p>I am disabling the inputs using the <code>isFetching</code> prop,
but this is getting reduntant as I have to keep this in every input field.
Is there a way to disable the entire form?
Like a <code>disable</code> property in <code><form></code> tag or something?</p>
<pre><code><form>
<input type="text" disabled={this.props.isFetching} />
<input type="text" disabled={this.props.isFetching} />
</form>
</code></pre>
| 36,216,001 | 3 | 0 | null |
2016-03-25 06:39:34.677 UTC
| 5 |
2017-09-18 22:30:27.213 UTC
|
2017-04-23 13:02:58.84 UTC
| null | 4,205,470 | null | 3,783,888 | null | 1 | 29 |
javascript|html|forms|reactjs
| 36,760 |
<p>I think this should solve your problem <a href="https://stackoverflow.com/a/17186342/3298693">https://stackoverflow.com/a/17186342/3298693</a>.</p>
<p>You should insert your form inside an element <code><fieldset disabled="disabled"></code>. This will make the whole form disabled.</p>
|
42,467,663 |
How to Async/await in List.forEach() in Dart
|
<p>I'm writing some kind of bot (command line application) and I'm having trouble with async execution when I'm using the "forEach" method.
Here is a simplified code of what I'm trying to do :</p>
<pre><code>main() async {
print("main start");
await asyncOne();
print("main end");
}
asyncOne() async {
print("asyncOne start");
[1, 2, 3].forEach(await (num) async {
await asyncTwo(num);
});
print("asyncOne end");
}
asyncTwo(num) async
{
print("asyncTwo #${num}");
}
</code></pre>
<p>And here is the output :</p>
<pre><code>main start
asyncOne start
asyncOne end
main end
asyncTwo #1
asyncTwo #2
asyncTwo #3
</code></pre>
<p>What I'm trying to get is :</p>
<pre><code>main start
asyncOne start
asyncTwo #1
asyncTwo #2
asyncTwo #3
asyncOne end
main end
</code></pre>
<p>If someone knows what I'm doing wrong I would appreciate it.</p>
| 42,467,822 | 6 | 1 | null |
2017-02-26 11:02:45.19 UTC
| 13 |
2022-05-10 22:31:06.087 UTC
|
2021-04-14 05:07:56.423 UTC
|
user10563627
| null | null | 7,091,129 | null | 1 | 96 |
flutter|dart|asynchronous|foreach
| 28,067 |
<p>I don't think it's possible to achieve what you want with the <code>forEach</code> method. However it will work with a <code>for</code> loop. Example;</p>
<pre><code>asyncOne() async {
print("asyncOne start");
for (num number in [1, 2, 3])
await asyncTwo(number);
print("asyncOne end");
}
</code></pre>
|
51,444,059 |
How to iterate over two dataloaders simultaneously using pytorch?
|
<p>I am trying to implement a Siamese network that takes in two images. I load these images and create two separate dataloaders.</p>
<p>In my loop I want to go through both dataloaders simultaneously so that I can train the network on both images.</p>
<pre><code>for i, data in enumerate(zip(dataloaders1, dataloaders2)):
# get the inputs
inputs1 = data[0][0].cuda(async=True);
labels1 = data[0][1].cuda(async=True);
inputs2 = data[1][0].cuda(async=True);
labels2 = data[1][1].cuda(async=True);
labels1 = labels1.view(batchSize,1)
labels2 = labels2.view(batchSize,1)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs1 = alexnet(inputs1)
outputs2 = alexnet(inputs2)
</code></pre>
<p>The return value of the dataloader is a tuple.
However, when I try to use <code>zip</code> to iterate over them, I get the following error:</p>
<pre><code>OSError: [Errno 24] Too many open files
Exception NameError: "global name 'FileNotFoundError' is not defined" in <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f2d3c00c190>> ignored
</code></pre>
<p>Shouldn't zip work on all iterable items? But it seems like here I can't use it on dataloaders.</p>
<p>Is there any other way to pursue this? Or am I approaching the implementation of a Siamese network incorrectly?</p>
| 51,444,290 | 5 | 2 | null |
2018-07-20 13:50:42.443 UTC
| 8 |
2021-12-09 07:07:02.86 UTC
| null | null | null | null | 7,560,762 | null | 1 | 13 |
python|machine-learning|zip|conv-neural-network|pytorch
| 27,493 |
<p>I see you are struggling to make a right dataloder function. I would do:</p>
<pre><code>class Siamese(Dataset):
def __init__(self, transform=None):
#init data here
def __len__(self):
return #length of the data
def __getitem__(self, idx):
#get images and labels here
#returned images must be tensor
#labels should be int
return img1, img2 , label1, label2
</code></pre>
|
32,656,837 |
Changing the drawable size inside a button
|
<p>I want to create a <code>Button</code> like this:</p>
<p><a href="https://i.stack.imgur.com/yynI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yynI2.png" alt="Button Example" /></a></p>
<p><strong>Here is my code:</strong></p>
<pre><code><Button
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:drawablePadding="10dp"
android:id="@+id/button"
android:text="Play Game"
android:background="@drawable/ronaldo"
android:drawableRight="@drawable/messi" />
</code></pre>
<p>But the <code>messi.jpeg</code> is too large, and it doesn't show the text in this situation. How to decrease the image size to fit the button?</p>
<p>May anyone help me to solve this problem?</p>
| 32,657,198 | 9 | 2 | null |
2015-09-18 16:27:49.203 UTC
| 2 |
2022-05-19 00:32:23.09 UTC
|
2022-01-03 08:18:42.103 UTC
| null | 4,742,830 | null | 4,742,830 | null | 1 | 14 |
android|android-layout|android-drawable|android-button|android-image
| 54,656 |
<h1>Solution 1:</h1>
<p>Adding a drawable to a button has very limited functions. You can't change the drawable size, so the best way to fix it is to add a button with an image view beside it in a linear layout like this:</p>
<pre><code><LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/ronaldo"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:background="@null"
android:text="Play Game"
android:textColor="#ff0000"
android:textStyle="italic" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:src="@drawable/messi" />
</LinearLayout>
</code></pre>
<h1>Solution 2:</h1>
<p>You can also do the following if you prefer this one, but you will have to add onClickListener() for each one of them:</p>
<pre><code><LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/ronaldo"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:background="@null"
android:text="Play Game"
android:textColor="#ff0000"
android:textStyle="italic" />
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:src="@drawable/messi" />
</LinearLayout>
</code></pre>
<h1>Solution 3:</h1>
<p>As you have suggested in the comments, you would do something like this:</p>
<pre><code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="@drawable/ronaldo">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_alignLeft="@+id/buttonLayout"
android:layout_alignRight="@+id/buttonLayout"
android:background="@null" />
<LinearLayout
android:id="@+id/buttonLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:gravity="center"
android:text="Play Game"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ff0000"
android:textStyle="italic" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:src="@drawable/messi" />
</LinearLayout>
</RelativeLayout>
</code></pre>
|
32,838,760 |
How to resolve relative paths in python?
|
<p>I have Directory structure like this</p>
<pre><code>projectfolder/fold1/fold2/fold3/script.py
</code></pre>
<p>now I'm giving script.py a path as commandline argument of a file which is there in </p>
<pre><code>fold1/fold_temp/myfile.txt
</code></pre>
<p>So basically I want to be able to give path in this way </p>
<pre><code>../../fold_temp/myfile.txt
>>python somepath/pythonfile.py -input ../../fold_temp/myfile.txt
</code></pre>
<p>Here problem is that I might be given full path or relative path so I should be able to decide and based on that I should be able to create absolute path.</p>
<p>I already have knowledge of functions related to path. </p>
<p><a href="https://stackoverflow.com/questions/918154/relative-paths-in-python">Question 1</a></p>
<p><a href="https://stackoverflow.com/questions/1270951/python-how-to-refer-to-relative-paths-of-resources-when-working-with-code-repo">Question 2</a></p>
<p>Reference questions are giving partial answer but I don't know how to build full path using the functions provided in them. </p>
| 32,839,385 | 4 | 2 | null |
2015-09-29 08:01:04.72 UTC
| 8 |
2021-09-02 16:50:36.153 UTC
|
2017-05-23 11:54:05.047 UTC
| null | -1 | null | 5,246,524 | null | 1 | 30 |
python|path
| 54,410 |
<pre><code>import os
dir = os.path.dirname(__file__)
path = raw_input()
if os.path.isabs(path):
print "input path is absolute"
else:
path = os.path.join(dir, path)
print "absolute path is %s" % path
</code></pre>
<p>Use os.path.isabs to judge if input path is absolute or relative, if it is relative, then use os.path.join to convert it to absolute</p>
|
9,487,077 |
How to view the log of all commands?
|
<p>I'm trying to view all commands that I've entered into the unix environment in my Git Bash.</p>
<p>So I'm not trying to view the list of possible commands for Git Hub. Neither am I trying to view the logs for pushes and pulls.</p>
<p>I just want to view what I entered in the command line. This is because I recently encountered a connection problem in which I couldn't push or pull from my git. It just happened suddenly. One minute ago, I was still pushing and pulling perfectly.</p>
<p>Then, someone helped me to resolve it via the command prompt in git bash.</p>
<p>Right now, my friend has the same problem. So I'm looking for the command logs in hopes that it will solve his problem too.</p>
<p>Write failed: Broken pipe
fatal: The remote end hung up unexpectedly.</p>
| 9,487,703 | 3 | 0 | null |
2012-02-28 17:47:50.733 UTC
| 3 |
2016-06-16 19:51:32.673 UTC
|
2013-04-30 04:32:14.373 UTC
| null | 635,608 | null | 1,110,767 | null | 1 | 14 |
unix|logging|github|git-bash
| 62,128 |
<p>You can do this with <code>cat $HISTFILE</code>.</p>
<p>Bash by default stores the last 500 commands in a history file, most likely called ~/.bash_history. This file is in the variable $HISTFILE (and the size is in $HISTFILESIZE). You can get the path to the history file with <code>echo $HISTFILE</code>.</p>
|
9,061,800 |
How do I autocrop a UIImage?
|
<p>I have a UIImage which contains a shape; the rest is transparent. I'd like to get another UIImage by cropping out as much of the transparent part as possible, still retaining all of the non-transparent pixels - similar to the autocrop function in GIMP. How would I go about doing this?</p>
| 13,922,413 | 6 | 0 | null |
2012-01-30 09:33:01.32 UTC
| 16 |
2021-06-28 20:15:26.703 UTC
|
2012-01-31 09:50:15.123 UTC
| null | 30,461 | null | 15,371 | null | 1 | 15 |
ios|cocoa-touch|uikit|uiimage|core-graphics
| 6,565 |
<p>This approach may be a little more invasive than what you were hoping for, but it gets the job done. What I'm doing is creating a bitmap context for the UIImage, obtaining a pointer to the raw image data, then sifting through it looking for non-transparent pixels. My method returns a CGRect which I use to create a new UIImage.</p>
<pre><code>- (CGRect)cropRectForImage:(UIImage *)image {
CGImageRef cgImage = image.CGImage;
CGContextRef context = [self createARGBBitmapContextFromImage:cgImage];
if (context == NULL) return CGRectZero;
size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);
CGRect rect = CGRectMake(0, 0, width, height);
CGContextDrawImage(context, rect, cgImage);
unsigned char *data = CGBitmapContextGetData(context);
CGContextRelease(context);
//Filter through data and look for non-transparent pixels.
int lowX = width;
int lowY = height;
int highX = 0;
int highY = 0;
if (data != NULL) {
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */;
if (data[pixelIndex] != 0) { //Alpha value is not zero; pixel is not transparent.
if (x < lowX) lowX = x;
if (x > highX) highX = x;
if (y < lowY) lowY = y;
if (y > highY) highY = y;
}
}
}
free(data);
} else {
return CGRectZero;
}
return CGRectMake(lowX, lowY, highX-lowX, highY-lowY);
}
</code></pre>
<p>The method to create the Bitmap Context:</p>
<pre><code>- (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)inImage {
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void *bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
// Get image width, height. We'll use the entire image.
size_t width = CGImageGetWidth(inImage);
size_t height = CGImageGetHeight(inImage);
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (width * 4);
bitmapByteCount = (bitmapBytesPerRow * height);
// Use the generic RGB color space.
colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL) return NULL;
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
CGColorSpaceRelease(colorSpace);
return NULL;
}
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
context = CGBitmapContextCreate (bitmapData,
width,
height,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedFirst);
if (context == NULL) free (bitmapData);
// Make sure and release colorspace before returning
CGColorSpaceRelease(colorSpace);
return context;
}
</code></pre>
<p>And finally, get your new cropped UIImage from the returned CGRect:</p>
<pre><code>CGRect newRect = [self cropRectForImage:oldImage];
CGImageRef imageRef = CGImageCreateWithImageInRect(oldImage.CGImage, newRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
</code></pre>
<p>I grabbed a bit of that code from <a href="http://www.markj.net/iphone-uiimage-pixel-color/" rel="noreferrer">this very useful article</a>. Hope it helps!</p>
|
9,459,030 |
Django when to use teardown method
|
<p>According to the docs:</p>
<blockquote>
<p>A TestCase, on the other hand, does not truncate tables and reload
initial data at the beginning of a test. Instead, it encloses the test
code in a database transaction that is rolled back at the end of the
test. It also prevents the code under test from issuing any commit or
rollback operations on the database, to ensure that the rollback at
the end of the test restores the database to its initial state. In
order to guarantee that all TestCase code starts with a clean
database, the Django test runner runs all TestCase tests first, before
any other tests (e.g. doctests) that may alter the database without
restoring it to its original state.</p>
</blockquote>
<p>So if I have a test that looks like this:</p>
<pre><code>class GeneralUserCreateTest(TestCase):
def setUp(self):
create_roletypes()
create_permissiontypes()
self.client = Client()
self.event = create_event()
def test_create(self):
create_url = reverse('event_user_signup', args=[self.event.slug])
post_data = {
'signup-account-email': 'foo@bar.com',
'signup-account-password': 'foobar',
'signup-account-password2': 'foobar',
'signup-account-first_name': 'Foo',
'signup-account-last_name': 'Bar',
}
response = self.client.post(create_url, data=post_data)
self.assertEqual(response.status_code, 302)
# check creation of user object
self.assertEqual(User.objects.filter(email=post_data['signup-account-email']).count(), 1)
user = User.objects.get(username=post_data['signup-account-email'])
# user and profile objects created
self.assertEqual(User.objects.all().count(), 1)
self.assertEqual(Profile.objects.all().count(), 1)
# get the first user and profile object to test against submitted field
user = User.objects.all()[0]
profile = Profile.objects.all()[0]
role = Role.objects.filter(event=self.event, profiles=profile)[0]
self.assertEqual(role.roletype.name, 'General')
self.assertEqual(user.username, post_data['signup-account-email'])
self.assertEqual(user.email, post_data['signup-account-email'])
self.assertEqual(profile.first_name, post_data['signup-account-first_name'])
self.assertEqual(profile.last_name, post_data['signup-account-last_name'])
</code></pre>
<p>Is it still necessary to run a <code>teardown</code> method or does the <code>TestCase</code> class take care of it? If so, when should one use the <code>teardown</code> method given the availability of the <code>TestCase</code> class?</p>
| 9,459,139 | 3 | 0 | null |
2012-02-27 01:34:52.637 UTC
| 4 |
2013-07-22 00:00:52.157 UTC
|
2012-02-27 10:36:02.08 UTC
| null | 99,876 | null | 131,238 | null | 1 | 30 |
django
| 25,095 |
<p>For the purposes of the database, <code>tearDown</code> is pretty pointless, because each test is run in a transaction. However, not everything in a test involves the database. You might test file creation/reading, spin off processes, open network connections, etc. These types of things usually require you to "close" them after you're done. This is what <code>tearDown</code> is for, i.e. cleaning up stuff from your <code>setUp</code> method, not related to the database. (Though, if you were actually directly connecting to a database, i.e. as the actual Django tests must do to make sure all the DBAPI stuff works properly, you'd need to do clean up there too.)</p>
|
31,105,846 |
How to send a pdf file from Node/Express app to the browser
|
<p>In my Node/Express app I have the following code, which suppose to read a PDF document from a file, and send it to the browser:</p>
<pre><code>var file = fs.createReadStream('./public/modules/datacollectors/output.pdf', 'binary');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
res.pipe(file, 'binary');
res.end();
</code></pre>
<p>I do not get any errors, but I do not get the file in my browser either.
What am I doing wrong?</p>
| 31,106,110 | 6 | 1 | null |
2015-06-28 23:26:13.76 UTC
| 13 |
2022-03-08 11:53:25.993 UTC
|
2015-06-29 00:34:08.527 UTC
| null | 1,266,650 | null | 518,012 | null | 1 | 43 |
node.js|express
| 115,805 |
<p>You have to pipe from Readable Stream to Writable stream not the other way around:</p>
<pre><code>var file = fs.createReadStream('./public/modules/datacollectors/output.pdf');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
file.pipe(res);
</code></pre>
<p>Also you are setting encoding in wrong way, pass an object with encoding if needed. </p>
|
34,204,447 |
git rebase --continue no changes
|
<p>I have two branches with two features: <code>banch_1</code> and <code>branch_2</code>.
<code>branch_2</code> uses feature from <code>branch_1</code>.
I've made changes in the <code>branch_1</code> and want to rebase <code>branch_2</code> on <code>branch_1</code> to get changes from <code>branch_1</code> into <code>branch_2</code>.</p>
<p>So, I'm checking out on branch_2:</p>
<pre><code>git checkout branch_2
</code></pre>
<p>And trying to rebase on branch_1:</p>
<pre><code>git rebase branch_1
</code></pre>
<p>After that I get 'Merge conflict' for two files. So I run</p>
<pre><code>git mergetool -t meld
</code></pre>
<p>and resolving that conflicts, choosing changes from <code>branch_1</code>. </p>
<p>I'm saving files and going to terminal, typing
<code>git status</code> and see that there is no changes in git index. Next I run <code>git rebase --continue</code> and getting </p>
<pre><code>No changes - did you forget to use 'git add'?
</code></pre>
<p>error. But there is nothing to add!
I type <code>git log</code> and see commit from <code>branch_1</code> but there is no commit from <code>branch_2</code>.</p>
<p>What I'm doing wrong?</p>
| 34,205,948 | 1 | 2 | null |
2015-12-10 14:30:48.943 UTC
| 4 |
2018-05-15 09:59:03.857 UTC
|
2015-12-10 14:33:49.123 UTC
| null | 1,401,900 | null | 1,858,864 | null | 1 | 50 |
git|git-rebase
| 19,577 |
<p>If I understand correctly, when you're getting the merge conflict, you're accepting all the changes from <code>branch_1</code>, meaning that that particular commit from <code>branch_2</code> is irrelevant - any changes in that commit are identical to the incoming changes from <code>branch_1</code>.</p>
<p>When git is saying</p>
<blockquote>
<p>No changes - did you forget to use 'git add'?</p>
</blockquote>
<p>it's telling you that the commit you're trying to apply doesn't make any changes to the repo, and therefore there's no reason for it to exist.</p>
<p>The simple solution to that is <code>git rebase --skip</code>, which just says "ignore this commit and move on" as suggested in @C-Otto's comment. This will skip the commit you're currently dealing with, and move on to subsequent ones.</p>
<p>You might also find it easier to use interactive rebasing (<code>git rebase -i</code>), which first presents you with a list of the commits it will apply, and gives you various options for what to do with each individual commit. In this case, if you identify a commit that is no longer relevant, you can skip it up-front, so you'll never see the conflict in the first place.</p>
|
22,627,473 |
hive check comma separated String contains a string
|
<p>I have a column in hive table <code>list_ids</code> which is a list of ids stored as comma separated string.</p>
<p>how can I write a query for this column to check if it stores a particular id </p>
<p>Example:</p>
<pre><code> list_ids = "abc,cde,efg"
</code></pre>
<p>I want to something like </p>
<pre><code> select * from table_name where list_ids contains cde;
</code></pre>
| 22,820,346 | 3 | 0 | null |
2014-03-25 07:00:38.577 UTC
| 7 |
2018-05-04 17:30:15.367 UTC
|
2014-03-25 07:05:28.86 UTC
| null | 1,120,015 | null | 2,978,621 | null | 1 | 21 |
string|hive
| 53,750 |
<p>Use Hive standard functions <code>split</code> and <code>array_contains</code></p>
<p><code>split(string str, string pat)</code> returns <code>array<string></code> by splitting str around pat (regular expression)</p>
<p><code>array_contains(array<T>, value)</code> returns <code>true</code> if array contains value</p>
<p><strong><code>select * from table_name where array_contains(split(list_ids,','),'cde')</code></strong></p>
|
22,799,300 |
How to unpack a Series of tuples in Pandas?
|
<p>Sometimes I end up with a series of tuples/lists when using Pandas. This is common when, for example, doing a group-by and passing a function that has multiple return values:</p>
<pre><code>import numpy as np
from scipy import stats
df = pd.DataFrame(dict(x=np.random.randn(100),
y=np.repeat(list("abcd"), 25)))
out = df.groupby("y").x.apply(stats.ttest_1samp, 0)
print out
y
a (1.3066417476, 0.203717485506)
b (0.0801133382517, 0.936811414675)
c (1.55784329113, 0.132360504653)
d (0.267999459642, 0.790989680709)
dtype: object
</code></pre>
<p>What is the correct way to "unpack" this structure so that I get a DataFrame with two columns?</p>
<p>A related question is how I can unpack either this structure or the resulting dataframe into two Series/array objects. This almost works:</p>
<pre><code>t, p = zip(*out)
</code></pre>
<p>but it <code>t</code> is</p>
<pre><code> (array(1.3066417475999257),
array(0.08011333825171714),
array(1.557843291126335),
array(0.267999459641651))
</code></pre>
<p>and one needs to take the extra step of squeezing it.</p>
| 36,816,769 | 5 | 1 | null |
2014-04-02 00:14:32.223 UTC
| 12 |
2022-02-26 05:58:31.367 UTC
| null | null | null | null | 1,533,576 | null | 1 | 44 |
python|pandas
| 34,761 |
<p>maybe this is most strightforward (most pythonic i guess):</p>
<pre><code>out.apply(pd.Series)
</code></pre>
<p>if you would want to rename the columns to something more meaningful, than:</p>
<pre><code>out.columns=['Kstats','Pvalue']
</code></pre>
<p>if you do not want the default name for the index:</p>
<pre><code>out.index.name=None
</code></pre>
|
7,519,467 |
Line plot with arrows in matplotlib
|
<p>I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point.</p>
<p>I know of the <code>arrow</code> function, but that only seems to do individual arrows. Before I work out a way to try and use this to do a whole plot, is there a nicer way to do it?</p>
| 7,543,518 | 2 | 0 | null |
2011-09-22 18:13:29.193 UTC
| 11 |
2011-09-25 03:48:38.417 UTC
| null | null | null | null | 1,912 | null | 1 | 35 |
python|plot|matplotlib
| 28,290 |
<p>You can do this with <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver" rel="noreferrer">quiver</a>, but it's a little tricky to get the keyword arguments right.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)
plt.figure()
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/ij4zM.png" alt="enter image description here"></p>
|
7,122,325 |
SocketException: Permission Denied?
|
<p>My LogCat reads:</p>
<pre><code>08-19 09:29:01.964: WARN/System.err(311): java.net.SocketException: Permission denied
08-19 09:29:02.204: WARN/System.err(311): at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocketImpl(Native Method)
08-19 09:29:02.214: WARN/System.err(311): at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocket(OSNetworkSystem.java:186)
08-19 09:29:02.214: WARN/System.err(311): at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:265)
08-19 09:29:02.224: WARN/System.err(311): at java.net.Socket.checkClosedAndCreate(Socket.java:873)
08-19 09:29:02.224: WARN/System.err(311): at java.net.Socket.connect(Socket.java:1020)
08-19 09:29:02.224: WARN/System.err(311): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
08-19 09:29:02.224: WARN/System.err(311): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)
08-19 09:29:02.224: WARN/System.err(311): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)
08-19 09:29:02.224: WARN/System.err(311): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)
08-19 09:29:02.234: WARN/System.err(311): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1152)
08-19 09:29:02.234: WARN/System.err(311): at java.net.URL.openStream(URL.java:653)
08-19 09:29:02.244: WARN/System.err(311): at around.lowell.Main.onCreate(Main.java:57)
08-19 09:29:02.244: WARN/System.err(311): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-19 09:29:02.244: WARN/System.err(311): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-19 09:29:02.244: WARN/System.err(311): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-19 09:29:02.244: WARN/System.err(311): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-19 09:29:02.244: WARN/System.err(311): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-19 09:29:02.244: WARN/System.err(311): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 09:29:02.244: WARN/System.err(311): at android.os.Looper.loop(Looper.java:123)
08-19 09:29:02.244: WARN/System.err(311): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-19 09:29:02.254: WARN/System.err(311): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 09:29:02.254: WARN/System.err(311): at java.lang.reflect.Method.invoke(Method.java:521)
08-19 09:29:02.254: WARN/System.err(311): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-19 09:29:02.264: WARN/System.err(311): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-19 09:29:02.264: WARN/System.err(311): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>The code that I have recently implemented that it is generating this error for in my Android app is:</p>
<pre><code> FileOutputStream fOut = null;
try {
fOut = this.openFileOutput("employeeInformation.xml", MODE_PRIVATE);
try {
InputStream is = new URL("http://totheriver.com/learn/xml/code/employees.xml").openStream();
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
fOut.write(buffer);
} catch(Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
</code></pre>
<p>Does anyone know what the problem is?</p>
| 7,122,367 | 2 | 1 | null |
2011-08-19 13:31:19.653 UTC
| 4 |
2016-07-19 14:56:39.483 UTC
|
2011-08-23 02:22:18.507 UTC
| null | 834,063 | null | 834,063 | null | 1 | 50 |
android|url|inputstream|permission-denied|socketexception
| 51,423 |
<p>Add Internet permission to your manifest:</p>
<pre><code><uses-permission android:name="android.permission.INTERNET"/>
</code></pre>
|
32,062,051 |
How to make 'submit' button disabled?
|
<p>How to disable the "Submit" button until the form is valid? </p>
<p>Does angular2 have an equivalent to ng-disabled that can be used on the Submit button? (ng-disabled doesn't work for me.)</p>
| 32,082,365 | 8 | 1 | null |
2015-08-18 01:09:33.247 UTC
| 16 |
2019-09-06 04:39:34.687 UTC
|
2019-09-06 04:38:16.147 UTC
| null | 5,468,463 | null | 865,955 | null | 1 | 172 |
forms|angular
| 286,682 |
<p>As seen in this Angular <a href="https://github.com/angular/angular/blob/57496926cad0d840092c7623079883983ca07d53/modules/examples/src/model_driven_forms/index.ts" rel="noreferrer">example</a>, there is a way to disable a button until the whole form is valid:</p>
<pre><code><button type="submit" [disabled]="!ngForm.valid">Submit</button>
</code></pre>
|
19,067,632 |
Difference between LET and SETQ?
|
<p>I'm programming on Ubuntu using GCL. From the documentation on Common Lisp from various sources, I understand that <code>let</code> creates <em>local</em> variables, and <code>setq</code> sets the values of <em>existing</em> variables. In cases below, I need to create two variables and sum their values.</p>
<h3>Using <code>setq</code></h3>
<pre><code>(defun add_using_setq ()
(setq a 3) ; a never existed before , but still I'm able to assign value, what is its scope?
(setq b 4) ; b never existed before, but still I'm able to assign value, what is its scope?
(+ a b))
</code></pre>
<h3>Using <code>let</code></h3>
<pre><code>(defun add_using_let ( )
(let ((x 3) (y 4)) ; creating variables x and y
(+ x y)))
</code></pre>
<p>In both the cases I seem to achieve the same result; what is the difference between using <code>setq</code> and <code>let</code> here? Why can't I use <code>setq</code> (since it is syntactically easy) in all the places where I need to use <code>let</code>?</p>
| 19,067,897 | 4 | 1 | null |
2013-09-28 13:44:04.43 UTC
| 8 |
2020-06-12 14:39:34.633 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 2,826,354 | null | 1 | 32 |
lisp|common-lisp
| 16,208 |
<p><code>setq</code> <em>assigns</em> a value to a variable, whereas <code>let</code> introduces new variables/bindings. E.g., look what happens in </p>
<pre><code>(let ((x 3))
(print x) ; a
(let ((x 89))
(print x) ; b
(setq x 73)
(print x)) ; c
(print x)) ; d
3 ; a
89 ; b
73 ; c
3 ; d
</code></pre>
<p>The outer <code>let</code> creates a local variable <code>x</code>, and the inner <code>let</code> creates another local variable shadowing the inner one. Notice that using <code>let</code> to shadow the variable doesn't affect the shadowed variable's value; the <code>x</code> in line <code>d</code> is the <code>x</code> introduced by the outer <code>let</code>, and its value hasn't changed. <code>setq</code> only affects the variable that it is called with. This example shows <code>setq</code> used with local variables, but it can also be with special variables (meaning, dynamically scoped, and usually defined with <code>defparameter</code> or <code>defvar</code>:</p>
<pre><code>CL-USER> (defparameter *foo* 34)
*FOO*
CL-USER> (setq *foo* 93)
93
CL-USER> *foo*
93
</code></pre>
<p>Note that <code>setq</code> doesn't (portably) <em>create</em> variables, whereas <code>let</code>, <code>defvar</code>, <code>defparameter</code>, &c. do. The behavior of <code>setq</code> when called with an argument that isn't a variable (yet) isn't defined, and it's up to an implementation to decide what to do. For instance, SBCL complains loudly:</p>
<pre><code>CL-USER> (setq new-x 89)
; in: SETQ NEW-X
; (SETQ NEW-X 89)
;
; caught WARNING:
; undefined variable: NEW-X
;
; compilation unit finished
; Undefined variable:
; NEW-X
; caught 1 WARNING condition
89
</code></pre>
<p>Of course, the best ways to get a better understanding of these concepts are to read and write more Lisp code (which comes with time) and to read the entries in the HyperSpec and follow the cross references, especially the glossary entries. E.g., the short descriptions from the HyperSpec for <code>setq</code> and <code>let</code> include:</p>
<ul>
<li><p><a href="http://www.lispworks.com/documentation/HyperSpec/Body/s_setq.htm" rel="noreferrer"><code>SETQ</code></a> </p>
<blockquote>
<p>Assigns values to <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#variable" rel="noreferrer"><em>variables</em></a>.</p>
</blockquote></li>
<li><p><a href="http://www.lispworks.com/documentation/HyperSpec/Body/s_let_l.htm" rel="noreferrer"><code>LET</code></a></p>
<blockquote>
<p>let and let* create new variable <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_b.htm#binding" rel="noreferrer"><em>bindings</em></a> and execute a series
of forms that use these bindings.</p>
</blockquote></li>
</ul>
<p>You may want to read more about variables and bindings. <code>let</code> and <code>let*</code> also have some special behavior with dynamic variables and <code>special</code> declarations (but you probably won't need to know about that for a while), and in certain cases (that you probably won't need to know about for a while) when a variable isn't actually a variable, <code>setq</code> is actually equivalent to <code>setf</code>. The HyperSpec has more details.</p>
<p>There are some not-quite duplicate questions on Stack Overflow that may, nonetheless, help in understanding the use of the various variable definition and assignment operators available in Common Lisp:</p>
<ul>
<li><a href="https://stackoverflow.com/q/3855862/1281433">setq and defvar in lisp</a></li>
<li><a href="https://stackoverflow.com/q/8927741/1281433">What's difference between defvar, defparameter, setf and setq</a></li>
<li><a href="https://stackoverflow.com/q/14314834/1281433">Assigning variables with setf, defvar, let and scope</a></li>
<li><a href="https://stackoverflow.com/q/3860866/1281433">In Lisp, how do I fix "Warning: Assumed Special?"</a> (re: using <code>setq</code> on undefined variables)</li>
<li><a href="https://stackoverflow.com/q/3518874/1281433">Difference between let* and set? in Common Lisp</a></li>
</ul>
|
18,933,321 |
Can I safely delete contents of Xcode Derived data folder?
|
<p>I am running low on disk space and checked through a third party utility that among other things that ~/Library/Developer/Xcode/DerivedData directory is taking about 22GB of disk space.</p>
<p>I searched stackoverflow and found this post </p>
<p><a href="https://stackoverflow.com/questions/7279141/what-can-i-safely-delete-in-my-library-developer-xcode-deriveddata-directory">How can I safely delete in my ~/Library/Developer/Xcode/DerivedData directory?</a></p>
<p>The accepted answer to this question suggests that I should not touch / remove folders from this directory. so what I did was</p>
<ul>
<li>Found an existing build project folder for an app that I have available on Appstore</li>
<li>Deleted the folder from derived dir</li>
<li>launched XCode 5</li>
<li>Open that project</li>
<li>Clean Build </li>
<li>Tested and compiled it on a simulator</li>
<li>ReArchived </li>
<li>Everything worked. Nothing was broken.</li>
</ul>
<p>Unless I missed something in that posts answer I want to make sure by asking experienced developers that if I delete all the folders from DerivedData it will not hurt me in building, testing and compiling those projects. </p>
| 18,933,382 | 12 | 1 | null |
2013-09-21 13:46:21.453 UTC
| 96 |
2022-06-15 02:58:22.56 UTC
|
2017-05-23 12:02:51.417 UTC
| null | -1 | null | 1,058,419 | null | 1 | 336 |
ios|xcode
| 258,753 |
<p>Yes, you can delete all files from <code>DerivedData</code> sub-folder <code>(Not DerivedData Folder)</code> directly. </p>
<p>That will not affect your project work. Contents of <code>DerivedData</code> folder is generated during the build time and you can delete them if you want. It's not an issue.</p>
<p>The contents of <code>DerivedData</code> will be recreated when you build your projects again. </p>
<p><strong>Xcode8+ Update</strong></p>
<p>From the Xcode8 that removed project option from the window tab so you can still use first way:</p>
<pre><code>Xcode -> Preferences -> location -> click on small arrow button as i explain in my first answer.
</code></pre>
<p><strong>Xcode7.3 Update</strong>
For remove particular project's DeriveData you just need to follow the following steps:</p>
<p>Go to <code>Window -> Project</code>:</p>
<p><a href="https://i.stack.imgur.com/nrUTo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nrUTo.png" alt="enter image description here"></a></p>
<p>You can find the list of project and you can either go the <code>DerivedData</code> Folder or you can direct delete individual Project's <code>DerivedData</code></p>
<p><a href="https://i.stack.imgur.com/ICgNp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ICgNp.png" alt="enter image description here"></a></p>
<hr>
<p>I am not working on Xcode5 but in 4.6.3 you can find <code>DerivedData</code> folder as found in the below image:</p>
<p><img src="https://i.stack.imgur.com/TmJ9F.png" alt="enter image description here"></p>
<p><strong>After clicking on Preferences..</strong></p>
<p><img src="https://i.stack.imgur.com/N4USo.png" alt="enter image description here"></p>
<p><strong>You get this window</strong></p>
<p><img src="https://i.stack.imgur.com/ZbdlR.png" alt="enter image description here"></p>
|
37,959,751 |
How to use Font Awesome icon in android application?
|
<p>I want to use Font Awesome's icon set in my android application. I have some <code>TextView</code> to set those icons. I don't want to use any png image. My Textview is like this -></p>
<pre><code><TextView
android:id="@+id/userLogin"
android:text="Login Now"
android:clickable="true"
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</code></pre>
<p>No, I want to put a icon before the text Login Now. How to do that ?</p>
| 37,959,881 | 11 | 2 | null |
2016-06-22 06:01:46.247 UTC
| 10 |
2022-07-01 14:54:58.413 UTC
| null | null | null |
user6355963
| null | null | 1 | 23 |
android|textview
| 45,757 |
<p>You can follow this <a href="https://stackoverflow.com/questions/15210548/how-to-use-a-icons-and-symbols-from-font-awesome-on-native-android-application">answer</a>.</p>
<p>First Download the fontawesome.ttf from <a href="http://fontawesome.io/" rel="noreferrer">here</a>. And put the file in <strong>asset/fontawesome.ttf</strong>.</p>
<p>Then Make a <code>FontAwesome</code> class which actually represents the textview of <code>FontAwesome</code> like this way.</p>
<pre><code>public class FontAwesome extends TextView {
public FontAwesome(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public FontAwesome(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontAwesome(Context context) {
super(context);
init();
}
private void init() {
//Font name should not contain "/".
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"fontawesome.ttf");
setTypeface(tf);
}
}
</code></pre>
<p>now you can use the Fontawesome class as your need and also follow the <a href="http://fontawesome.io/cheatsheet/" rel="noreferrer">cheatsheet.</a> to get your icon's Unicode.</p>
<p>So, your TextView will be like this.</p>
<pre><code><PACKAGE_NAME.FontAwesome
android:id="@+id/userLogin"
android:text="&#xf007; Login Now"
android:clickable="true"
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</code></pre>
|
36,715,776 |
Upload pdf file using Laravel 5
|
<p>I'm using Laravel 5.2 and I want to make a form which can upload a pdf file with it. I want to add that file on folder "files" in "public" folder. <br> <br>here is my view:</p>
<pre><code><div class="form-group">
<label for="upload_file" class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input class="form-control" type="file" name="upload_file" id="upload_file">
</div>
</div>
</code></pre>
<p>and what should I do next? what should I add in my controller and route?</p>
| 36,715,965 | 6 | 1 | null |
2016-04-19 10:31:44.003 UTC
| 1 |
2020-02-03 06:02:36.463 UTC
| null | null | null | null | 2,330,708 | null | 1 | 6 |
php|laravel|http|file-upload|laravel-5
| 50,406 |
<p>First you should add <code>enctype="multipart/form-data"</code> to your <code><form></code> tag. Then in your controller handle the file upload as follow:</p>
<pre><code>class FileController extends Controller
{
// ...
public function upload(Request $request)
{
$uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension());
$request->get('upload_file')->move(public_path('files') . $uniqueFileName);
return redirect()->back()->with('success', 'File uploaded successfully.');
}
// ...
}
</code></pre>
<p><a href="https://laravel.com/docs/5.2/requests#files" rel="noreferrer">Link to Laravel Docs for Handling File Uploads</a></p>
<p>Laravel casts the file type params in request to <code>UploadedFile</code> objects. You can see Symfony's <code>UploadedFile</code> class <a href="https://github.com/symfony/http-foundation/blob/master/File/UploadedFile.php" rel="noreferrer">here</a> for available methods and attributes.</p>
|
37,087,325 |
How to convert string to unicode(UTF-8) string in Swift?
|
<p>How to convert string to unicode(UTF-8) string in Swift?</p>
<p>In Objective I could write smth like that:</p>
<pre><code>NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];
</code></pre>
<p>how to do smth similar in Swift?</p>
| 37,087,408 | 3 | 2 | null |
2016-05-07 10:24:43.25 UTC
| 3 |
2021-06-29 10:10:18.897 UTC
| null | null | null | null | 4,702,826 | null | 1 | 17 |
ios|swift|unicode|utf-8|utf-16
| 77,186 |
<p>Use this code,</p>
<pre><code>let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))
</code></pre>
<p>hope its helpful</p>
|
21,266,948 |
Use git to manage home directory
|
<p>I'd like to create <strong>one single git repo</strong> in my Linux $HOME directory. In this repo - obviously - I could add everything under version control, but this wouldn't make any sense. I'd like to only add the files and folders that are relevant to me, like <em>.vimrc</em>, <em>.vim</em>, <em>.bashrc</em>, etc. (probably only hidden files and folders, but maybe not)</p>
<p>I know I could leverage <em>.gitignore</em> to try and achieve such behavior but that would be painful and virtually un-maintainable. Instead, what I'd want to know is if there'd be any way to manually declare files and folders that I would want to manage, and only that.</p>
| 21,267,097 | 5 | 2 | null |
2014-01-21 19:07:58.29 UTC
| 23 |
2021-10-08 23:28:40.48 UTC
|
2014-01-21 19:12:19.397 UTC
| null | 68,587 | null | 3,046,043 | null | 1 | 50 |
git
| 20,355 |
<p><strong>.gitignore</strong></p>
<pre><code># Ignore everything
*
# But not these files...
!*.vimrc
!*.vim
!*.bashrc
!.gitignore
# etc...
</code></pre>
<p>My home directory is also on <a href="https://github.com/vanniktech/config-home" rel="nofollow noreferrer">GitHub</a>.</p>
|
21,344,842 |
if 'a' or 'b' in L, where L is a list (Python)
|
<p>I am having trouble with the following logic:</p>
<p>Lets say I have a list <code>L = ['a', 'b', 'c']</code></p>
<hr>
<p>Both items are in the list...</p>
<pre><code>if ('a' or 'b') in L:
print 'it\'s there!'
else:
print 'No sorry'
</code></pre>
<p>prints <code>It's there!</code></p>
<hr>
<p>Only the first item is in the list...</p>
<pre><code>if ('a' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
</code></pre>
<p>prints <code>It's there!</code></p>
<hr>
<p>Neither item in the list...</p>
<pre><code>if ('e' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
</code></pre>
<p>prints <code>No sorry</code></p>
<hr>
<p><strong>Here's the confusing one</strong> Only the <em>second</em> item in the list...</p>
<pre><code>if ('e' or 'a') in L:
print 'it\'s there!'
else:
print 'No sorry'
</code></pre>
<p>prints <code>No sorry</code></p>
<hr>
<p>I do not understand why this is not registering as a true statement. How does this generalize to an <strong>or</strong> statement with <em>n</em> conditionals?</p>
<p><sub>Forehead-slapping easy answer in 3,2,1...</sub></p>
| 21,344,886 | 4 | 2 | null |
2014-01-25 00:16:56.45 UTC
| 5 |
2022-08-15 09:09:27.167 UTC
| null | null | null | null | 2,224,777 | null | 1 | 19 |
python
| 47,866 |
<p>Let's break down the expression:</p>
<p><code>('e' or 'a')</code> will first check if <code>'e'</code> is True. If it is, the expression will return <code>'e'</code>. If not, it will return <code>'a'</code>.</p>
<p>Since all non-empty strings returns <code>True</code>, this expression will always return <code>'e'</code>. This means that <code>if ('e' or 'a') in L:</code> can be translated to <code>if 'e' in L</code>, which in this case is <code>False</code>.</p>
<p>A more generic way to check if a list contains at least one value of a set of values, is to use the <code>any</code> function coupled with a generator expression.</p>
<pre><code>if any(c in L for c in ('a', 'e')):
</code></pre>
|
28,187,786 |
Monit daemon - error connecting to the monit daemon
|
<p>I installed monit and tried to check the status using below command.</p>
<pre><code>monit status
</code></pre>
<p>But end up with below error.</p>
<pre><code>monit: error connecting to the monit daemon
</code></pre>
<p>How can I fix this?</p>
| 28,187,787 | 2 | 1 | null |
2015-01-28 08:36:17.887 UTC
| 9 |
2017-05-01 07:29:54.307 UTC
| null | null | null | null | 1,263,783 | null | 1 | 46 |
linux|ubuntu|debian|monitoring|monit
| 19,301 |
<p>edit vim <code>/etc/monit/monitrc</code>, starting from line 118 and uncomment below lines</p>
<pre><code> set httpd port 2812
use address localhost # only accept connection from localhost
allow localhost # allow localhost to connect to the server and
allow admin:monit
</code></pre>
<p><code>sudo monit reload</code> to take affect</p>
<p><a href="http://dasunhegoda.com/what-why-how-monit/756/">Read more</a></p>
|
1,365,649 |
How to handle string encoding in java?
|
<p>I was really discouraged by java's string encoding.
There are many auto conversions in it. and I can't found the regular.
Anyone have good idea?
for example:
In a jsp page, it has such link</p>
<pre><code>http://localhost:8080/helloworld/hello?world=凹ㄉ
</code></pre>
<p>And then we need to process it, so we do this:</p>
<pre><code>String a = new String(request.getParameter("world").toString().getBytes("ISO-8859-1"),
"UTF-8");
a = "http://localhost/" + a;
</code></pre>
<p>And when I debug it, I found a is right. </p>
<p>And then I pass this to a session object:
request.getSession().setAttribute("hello", a);</p>
<p>Later in a jsp page with encoding "Big5", and i try to get the attribute and display,
And i found the characters "凹ㄉ" are corrupted.</p>
<p>How can I solve this?</p>
| 1,365,686 | 3 | 0 | null |
2009-09-02 03:01:28.84 UTC
| 2 |
2020-05-25 08:24:53.187 UTC
|
2010-09-27 14:16:35.007 UTC
| null | 139,010 | null | 140,899 | null | 1 | 2 |
java|string|character-encoding
| 43,059 |
<p>That is not how you convert between character sets. What you need to be worrying about is this part:</p>
<pre><code> request.getParameter("world").toString().getBytes("ISO-8859-1")
</code></pre>
<p>Once you have it as a string, it is stored internally as 16 bit unicode. Getting it as bytes and then telling java to treat those bytes as if they were UTF-8 is not going to do anything good.</p>
<p>If you found it to be fine, that is just a coincidence. Once you call that getParameter("world").toString() you have your unicode string. The further decoding and encoding will just break certain characters, it just happens to not break yours.</p>
<p>The question is how you get that attribute to display later? You say the jsp page's encoding is not unicode, but rather Big5, so what are you doing to get that string out of the attribute map and put it on that page? That is the likely source of the problem. Given the misunderstanding about how to handle the character conversion in getting the parameter, it would be likely that there are some mistakes on that Big5 page as well.</p>
<p>By the way, do you really need to use Big5? Would UTF-16 work (if not UTF-8)? It could certainly remove some headaches.</p>
|
2,166,039 |
Java: how to get a File from an escaped URL?
|
<p>I'm receiving an URL that locates a local file (the fact that I receive an URL is not in my control). The URL is escaped validly as defined in RFC2396. How can I transform this to a Java File object?</p>
<p>Funnily enough, the URL getFile() method returns a String, not a File.</p>
<p>I've created a directory called "/tmp/some dir" (with a spacing character between "some" and "dir"), which is correctly located by the following URL: "file:///tmp/some%20dir" (quotes added for clarity).</p>
<p>How can I convert that URL to a Java File?</p>
<p>To give more detail about my issue, the following prints false:</p>
<pre><code>URL url = new URL( "file:///tmp/some%20dir" );
File f = new File( url.getFile() );
System.out.println( "Does dir exist? " + f.exists() );
</code></pre>
<p>While the following (manually replacing "%20" with a space) prints true:</p>
<pre><code>URL url = new URL( "file:///tmp/some%20dir" );
File f = new File( url.getFile().replaceAll( "%20", " " ) );
System.out.println( "Does dir exist? " + f.exists() );
</code></pre>
<p>Note that I'm not asking <em>why</em> the first example prints false nor <em>why</em> the second example using my hacky <em>replaceAll</em> prints true, I'm asking how to convert an escaped URL into a Java File object.</p>
<p><strong>EDIT</strong>: thanks all, this was nearly a dupe but not exactly.</p>
<p>Stupidly I was looking for a helper method inside the URL class itself.</p>
<p>The following works as expected to get a Java File from a Java URL:</p>
<pre><code>URL url = new URL( "file:///home/nonet/some%20dir" );
File f = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) );
</code></pre>
| 2,166,059 | 3 | 1 | null |
2010-01-29 23:39:36.52 UTC
| 4 |
2015-04-03 16:41:55.37 UTC
|
2010-01-29 23:49:58.82 UTC
| null | 257,356 | null | 257,356 | null | 1 | 46 |
java|file|url|escaping
| 54,708 |
<pre><code>URLDecoder.decode(url);//deprecated
URLDecoder.decode(url, "UTF-8"); //use this instead
</code></pre>
<p>See related question <a href="https://stackoverflow.com/questions/623861/how-do-you-unescape-urls-in-java">How do you unescape URLs in Java?</a></p>
|
1,745,105 |
Postgres dump of only parts of tables for a dev snapshot
|
<p>On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 gigs in size. </p>
<p>The challenge is that the data for our business entities are scattered across many tables. We want to create some sort of filtered snapshot so that only <em>some</em> of the entities are included in the dump. That way we can get fresh snapshots every month or so for dev and testing.</p>
<p>For example, let's say we have entities that have these many-to-many relationships:</p>
<ul>
<li>Company has N Divisions</li>
<li>Division has N Employees</li>
<li>Employee has N Attendance Records</li>
</ul>
<p>There are maybe 1000 companies, 2500 divisions, 175000 employees, and tens of millions of attendance records. We want a replicable way to pull, say, the first 100 companies <em>and all of its constituent divisions, employees, and attendance records</em>.</p>
<p>We currently use pg_dump for the schema, and then run pg_dump with --disable-triggers and --data-only to get all the data out of the smaller tables. We don't want to have to write custom scripts to pull out part of the data because we have a fast development cycle and are concerned the custom scripts would be fragile and likely to be out of date.</p>
<p>How can we do this? Are there third-party tools that can help pull out logical partitions from the database? What are these tools called?</p>
<p>Any general advice also appreciated!</p>
| 1,746,215 | 3 | 0 | null |
2009-11-16 21:54:33.76 UTC
| 25 |
2016-09-18 20:17:59.013 UTC
| null | null | null | null | 212,420 | null | 1 | 110 |
postgresql
| 44,065 |
<p>On your larger tables you can use the COPY command to pull out subsets...</p>
<pre><code>COPY (SELECT * FROM mytable WHERE ...) TO '/tmp/myfile.tsv'
COPY mytable FROM 'myfile.tsv'
</code></pre>
<p><a href="http://www.postgresql.org/docs/8.4/interactive/sql-copy.html" rel="noreferrer">https://www.postgresql.org/docs/current/static/sql-copy.html</a></p>
<p>You should consider maintaining a set of development data rather than just pulling a subset of your production. In the case that you're writing unit tests, you could use the same data that is required for the tests, trying to hit all of the possible use cases.</p>
|
8,929,738 |
SQLAlchemy declarative: defining triggers and indexes (Postgres 9)
|
<p>Is there a way in the SQLAlchemy class of a table to define/create triggers and indexes for that table?</p>
<p>For instance if i had a basic table like ...</p>
<pre><code>class Customer(DeclarativeBase):
__tablename__ = 'customers'
customer_id = Column(Integer, primary_key=True,autoincrement=True)
customer_code = Column(Unicode(15),unique=True)
customer_name = Column(Unicode(100))
search_vector = Column(tsvector) ## *Not sure how do this yet either in sqlalchemy*.
</code></pre>
<p>I now want to create a trigger to update "search_vector"</p>
<pre><code>CREATE TRIGGER customers_search_vector_update BEFORE INSERT OR UPDATE
ON customers
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(search_vector,'pg_catalog.english',customer_code,customer_name);
</code></pre>
<p>Then I wanted to add that field also as an index ...</p>
<pre><code>create index customers_search_vector_indx ON customers USING gin(search_vector);
</code></pre>
<p>Right now after i do any kind of database regeneration from my app i have to do the add column for the tsvector column, the trigger definition, and then the index statement from psql. Not the end of the world but its easy to forget a step. I am all about automation so if I can get this all to happen during the apps setup then bonus!</p>
| 8,931,084 | 1 | 1 | null |
2012-01-19 16:35:37.153 UTC
| 10 |
2012-08-22 04:45:44.38 UTC
|
2012-08-22 04:45:44.38 UTC
| null | 157,176 | null | 761,029 | null | 1 | 29 |
postgresql|sqlalchemy|turbogears
| 10,837 |
<p><strong>Indicies</strong> are straight-forward to create. For single-column with <code>index=True</code> parameter like below:</p>
<pre><code>customer_code = Column(Unicode(15),unique=True,index=True)
</code></pre>
<p>But if you want more control over the name and options, use the explicit <a href="http://www.sqlalchemy.org/docs/core/schema.html?highlight=column#sqlalchemy.schema.Index">Index()</a> construct:</p>
<pre><code>Index('customers_search_vector_indx', Customer.__table__.c.search_vector, postgresql_using='gin')
</code></pre>
<p><strong>Triggers</strong> can be created as well, but those need to still be <code>SQL</code>-based and hooked to the <code>DDL</code> events. See <a href="http://www.sqlalchemy.org/docs/core/schema.html#customizing-ddl">Customizing DDL</a> for more info, but the code might look similar to this:</p>
<pre><code>from sqlalchemy import event, DDL
trig_ddl = DDL("""
CREATE TRIGGER customers_search_vector_update BEFORE INSERT OR UPDATE
ON customers
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(search_vector,'pg_catalog.english',customer_code,customer_name);
""")
tbl = Customer.__table__
event.listen(tbl, 'after_create', trig_ddl.execute_if(dialect='postgresql'))
</code></pre>
<p><em>Sidenote: I do not know how to configure <code>tsvector</code> datatype: deserves a separate question.</em></p>
|
19,607,448 |
Execute statement by shortcut in MySQLWorkbench
|
<p>How can I execute any statement in MySQLWorkbench using shortcut? Now I have to press button (yellow lightning). Of course I have read this in the documentation: <a href="https://dev.mysql.com/doc/workbench/en/wb-keys.html#wb-shortcuts-query-menu" rel="nofollow noreferrer">Table 14.6 - query menu</a> (Table 14.6 - query menu) but I don't know what does mean <code>Modifier+Return</code> ?</p>
<p>As we can read <code>Modifier</code> is <code>Ctrl</code> (in Windows) but what is <code>Return</code>?</p>
| 19,608,015 | 7 | 1 | null |
2013-10-26 13:44:54.113 UTC
| 11 |
2021-11-18 21:40:44.157 UTC
|
2021-11-12 08:30:38.707 UTC
| null | 10,158,227 | null | 2,213,654 | null | 1 | 56 |
mysql|mysql-workbench
| 58,783 |
<p><code>Return</code> = <code>Enter</code> key. So <code>Ctrl + Enter</code> key should execute.</p>
|
24,959 |
Debugging asp.net with firefox and visual studio.net - very slow compared to IE
|
<p>Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower
than using IE.</p>
<p>I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again.</p>
<p>Does anyone know what i'm on about and can point me in the right direction please?</p>
<p>Cheers
John</p>
<h2>edit</h2>
<p>sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc)</p>
<p>hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays.</p>
<p>hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code.</p>
<p>i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out.</p>
| 24,982 | 4 | 0 | null |
2008-08-24 10:28:10.373 UTC
| 13 |
2010-03-21 03:39:37.207 UTC
|
2009-03-23 09:20:03.197 UTC
|
moocha
| 14,444 |
john
| 2,041 | null | 1 | 18 |
debugging|firefox|visual-studio-2005
| 10,046 |
<p>bingo. found the <a href="http://dotnetslackers.com/ASP_NET/re-122146_Speeding_Up_FireFox_When_Using_the_ASP_NET_Development_Server_from_Localhost.aspx" rel="noreferrer">article</a> i read before. </p>
<p>i just changed my network.dns.ipv4OnlyDomains property in about:config to localhost. restarted firefox and now firefox performs the same as IE when debugging asp.net with visual studio (2005).</p>
<p>hope this helps anyone else that has the same problem.</p>
|
923,283 |
What is the minimal setup required to deploy a .NET application with Oracle client 11?
|
<p>What is the minimal setup required to be able to deploy a .NET application that talks to an Oracle database?</p>
| 923,413 | 4 | 1 | null |
2009-05-28 21:23:47.047 UTC
| 31 |
2015-11-06 07:19:40.99 UTC
| null | null | null | null | 549 | null | 1 | 37 |
oracle|odp.net
| 29,781 |
<p>Josh-</p>
<p>Thank you very much for taking the time to answer. Your instructions helped a whole lot, and are very close to what I have found on my own.</p>
<p>Interestingly enough, I found it can be slimmed a little more.</p>
<p>For those in my situation who</p>
<ol>
<li>Do not want their users to have to install ODAC or the full-size Oracle Client</li>
<li>Do not care about the re-usability of the particular client installtion</li>
<li>Need a "clickOnce" compatible solution</li>
</ol>
<p>I found a way to do that.</p>
<p>a. Download the "Oracle Instant Client 11.1.0.6 - Basic Lite".
b. unzip to any folder and copy the following files to your Visual Studio project root:</p>
<ul>
<li>oci.dll</li>
<li>ociw32.dll</li>
<li>orannzsbb11.dll</li>
<li>oraocci11.dll</li>
<li>oraociicus11.dll</li>
<li><p>msvcr71.dll (not necessary, should be supplied with most Windows versions)</p>
<p>(the first five are the minimum needed for the Oracle Instant Client, the last is the microsoft common runtime they use.)</p></li>
</ul>
<p>c. Download the ODAC 11 XCopy (the current version is 11.1.0.6) and unzip.</p>
<ul>
<li><p>OraOps11w.dll - in the odp.net20 folder, goes in your project root.</p>
<p>(this file is what the Oracle.DataAccess.dll talks to and uses to work with the Instant Client files).</p></li>
</ul>
<p>d. For compatibility with ClickOnce deployment, select these files in your project and make sure they are "Content" and "Copy Local" in your project. The manifest will then deploy them properly.</p>
<p><strong>Result..</strong>. the payload added to your project is 30mb, which kinda sucks, but much better than 100+ or 400+, supports western characters, but kicks butt in that </p>
<ol>
<li>it requires no path, </li>
<li>requires no registry entries, </li>
<li>is isolated in deployment and does not hose other Oracle Client installations, </li>
<li>works will all DBs back through 9.2.</li>
</ol>
|
195,625 |
What is the time complexity of popping elements from list in Python?
|
<p>I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity? </p>
| 195,647 | 4 | 0 | null |
2008-10-12 15:58:59.077 UTC
| 17 |
2022-06-19 22:50:06.147 UTC
|
2022-06-19 22:50:06.147 UTC
|
Haldun
| 224,132 |
Haldun
| 21,000 | null | 1 | 69 |
python|list|performance
| 69,705 |
<p><code>Pop()</code> for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element. I would expect <code>pop()</code> for an arbitrary element to be O(N) and require on average N/2 operations since you would need to move any elements beyond the element you are removing one position up in the array of pointers.</p>
|
22,261,048 |
Using glyphicon as background image in CSS: rails 4 + bootstrap 3
|
<p>I'm using bootstrap's collapse.js to expand and collapse some input groups in a rails app. I'm using JS to determine if the group is expanded or not and have created CSS classes to add a "+" or "-" to show whether it's open or closed:</p>
<p>Open:
<img src="https://i.stack.imgur.com/rJxVb.png" alt="enter image description here"></p>
<p>Closed:
<img src="https://i.stack.imgur.com/vh6rj.png" alt="enter image description here"></p>
<p>As you can see from the CSS, I'm using a background image that's a png within my images:</p>
<pre><code>.expandable {
background: url('/assets/plus.png');
padding-top: 4px;
width: 400px;
height: 30px;
background-repeat: no-repeat;
padding-left: 55px;
display: block;
}
.expanded {
background: url('/assets/minus.png');
padding-top: 4px;
width: 400px;
height: 30px;
background-repeat: no-repeat;
padding-left: 55px;
display: block;
}
</code></pre>
<p>I would like to use the glyphicon-plus and glyphicon-minus instead of these .png files. </p>
<p>What's the best way to accomplish this?</p>
<p><strong>Updated:</strong></p>
<p>In order to get the proper styling, I changed the CSS to:</p>
<pre><code>.expandable {
height:40px;
width:50%;
margin:6px;
}
.expandable:before{
content:"\2b";
font-family:"Glyphicons Halflings";
line-height:1;
margin:5px;
}
.expanded {
height:40px;
width:50%;
margin:6px;
}
.expanded:before{
content:"\2212";
font-family:"Glyphicons Halflings";
line-height:1;
margin:5px;
}
</code></pre>
<p>And for reference, my HTML is:</p>
<pre><code><div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<p1 class="panel-title" >
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="expandable">
Provider details
</a>
<p2>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
blah, blah....
</code></pre>
<p>And JS to detect the opening/closing of the sections:</p>
<pre><code>$ ->
$(".expandable").click () ->
$this = $(this)
if $this.hasClass("expandable")
$this.removeClass("expandable").addClass "expanded"
else $this.removeClass("expanded").addClass "expandable" if $this.hasClass("expanded")
return
return
</code></pre>
| 22,261,963 | 2 | 1 | null |
2014-03-07 21:30:58.763 UTC
| 1 |
2017-03-28 07:27:17.823 UTC
|
2014-03-07 23:53:35.67 UTC
| null | 2,977,778 | null | 2,977,778 | null | 1 | 16 |
html|css|ruby-on-rails|twitter-bootstrap|glyphicons
| 49,630 |
<p>Here, try this <strong><a href="http://www.bootply.com/119952" rel="noreferrer">Bootply</a></strong>. Would this suffice? </p>
<pre><code><div id="lol"></div>
</code></pre>
<hr>
<pre><code>#lol{
height:40px;
border:1px solid #555;
width:50%;
margin:30px;
}
#lol:before{
content:"\2b";
font-family:"Glyphicons Halflings";
line-height:1;
margin:10px;
display:inline-block;
}
</code></pre>
|
14,037,016 |
In Java, should I use ArrayList<Long> or long[] ?
|
<p>I am writing a program which accepts 400 numbers of type <code>long</code> and will modify some of them depending on conditions at runtime and I want to know whether to use <code>ArrayList<Long></code> or <code>long[]</code>. </p>
<p>Which will be faster to use? I am thinking of using <code>long[]</code> because size is fixed.</p>
| 14,037,041 | 6 | 6 | null |
2012-12-26 06:54:07.76 UTC
| 1 |
2017-10-03 08:42:43.14 UTC
|
2012-12-26 07:24:26.757 UTC
| null | 254,477 | null | 513,340 | null | 1 | 3 |
java|arrays|performance|arraylist
| 54,811 |
<p>When the size is fixed, <code>long[]</code> is faster, but it allows a less maintainable API, because it does not implement the <code>List</code> interface.</p>
<p>Note a <code>long[]</code> is faster for 2 reasons:</p>
<ol>
<li>Uses primitive <code>long</code>s and not box object <code>Long</code>s (also enables better cache performace, since the <code>long</code>s are allocated contigously and the <code>Long</code>s aren't guaranteed to)</li>
<li>An array is much simpler and more efficient DS.</li>
</ol>
<p>Nevertheless, for simpler maintainability - I would have used a <code>List<Long></code>, unless performace is very critical at this part of the program.</p>
<p>If you use this collection very often in a tight loop - and your profiler says it is indeed a bottleneck - I would then switch to a more efficient <code>long[]</code>.</p>
|
14,141,307 |
Change link href via jQuery
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery">How to change the href for a hyperlink using jQuery</a> </p>
</blockquote>
<p>I'm using Drupal and system generate my title. </p>
<p>E.G.</p>
<pre><code> <a class="jquery-once-3-processed" id="quicktabs-tab-galeri-1"
href="/?q=node&amp;qt-galeri=1#qt-galeri">NEWS</a>
</code></pre>
<p>I want change this <code>href</code> link via jQuery. How can i do this? Thank you.</p>
| 14,141,341 | 3 | 1 | null |
2013-01-03 14:57:02.97 UTC
| null |
2013-01-03 15:01:04.893 UTC
|
2017-05-23 12:25:51.337 UTC
| null | -1 | null | 1,485,921 | null | 1 | 5 |
javascript|jquery
| 52,821 |
<pre><code>$("#quicktabs-tab-galeri-1").attr("href", new_href);
</code></pre>
<p>That should do the trick for you.</p>
|
34,538,879 |
Unicode in Github markdown
|
<p>I just made a failed attempt to put unicode in Github markdown (in a README.md file) in my project.</p>
<p>I tried this:</p>
<pre><code>(U+262E)
</code></pre>
<p>but it was not interpreted as unicode. Is there a way to put unicode characters in Github markdown?</p>
| 36,616,878 | 7 | 4 | null |
2015-12-30 23:30:39.76 UTC
| 10 |
2021-11-14 23:16:10.393 UTC
|
2017-07-28 17:38:55.27 UTC
| null | 1,223,975 | null | 1,223,975 | null | 1 | 60 |
github|unicode|markdown|github-flavored-markdown
| 45,599 |
<p>I believe the correct answer is to use unicode characters of the following (decimal) form </p>
<pre><code>&#9658;
&#767;
&#2400;
</code></pre>
<p>the above become:</p>
<p>►
˿
ॠ</p>
<p>Try it for yourself on Github and see. You have to paste the raw character strings, not the unicode symbol itself. It's <strong>not</strong> about what shows up in your editor, it's what actually displays on github.com.</p>
|
25,205,750 |
Quickly square a double
|
<p>I am looking for the fastest way to square a double (<code>double d</code>). So far I came up with two approaches:</p>
<pre><code>1. d*d
2. Math.pow(d, 2)
</code></pre>
<p>To test the performance I set up three test cases, in each I generate random numbers using the same seed for the three cases and just calculate the squared number in a loop 100 000 000 times.</p>
<p>In the first test case numbers are generated using <code>random.nextDouble()</code>, in the second case using <code>random.nextDouble()*Double.MAX_VALUE</code> and in the third one using <code>random.nextDouble()*Double.MIN_VALUE</code>.</p>
<p>The results of a couple of runs (approximate results, theres always some variation, run using java 1.8, compiled for java 1.6 on Mac OSX Mavericks)</p>
<pre><code>Approach | Case 1 | Case 2 | Case 3
---------•--------•--------•-------
1 | ~2.16s | ~2.16s | ~2.16s
2 | ~9s | ~30s | ~60s
</code></pre>
<p>The conclusion seems to be that approach 1 is way faster but also that <code>Math.pow</code> seems to behave kind of weird.</p>
<p>So I have two questions:</p>
<ol>
<li><p>Why is <code>Math.pow</code> so slow, and why does it cope badly with <code>> 1</code> and even worse with <code>< -1</code> numbers?</p></li>
<li><p>Is there a way to improve the performance over what I suggested as approach 1? I was thinking about something like:</p>
<pre><code>long l = Double.doubleToRawLongBits(d);
long sign = (l & (1 << 63));
Double.longBitsToDouble((l<<1)&sign);
</code></pre></li>
</ol>
<p>But that is a) wrong, and b) about the same speed as approach 1.</p>
| 25,205,921 | 3 | 3 | null |
2014-08-08 14:25:09.36 UTC
| 2 |
2020-04-27 12:47:51.267 UTC
|
2020-04-27 12:47:51.267 UTC
| null | 183,704 | null | 253,387 | null | 1 | 25 |
java|performance|math|multiplication
| 50,659 |
<p>The fastest way to square a number is to multiply it by itself.</p>
<blockquote>
<p>Why is <code>Math.pow</code> so slow?</p>
</blockquote>
<p>It's really not, but it is performing <a href="http://en.wikipedia.org/wiki/Exponentiation" rel="noreferrer">exponentiation</a> instead of simple multiplication.</p>
<blockquote>
<p>and why does it cope badly with > 1 and even worse with < -1 numbers</p>
</blockquote>
<p>First, because it does the math. From the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-" rel="noreferrer">Javadoc</a> it also contains tests for many corner cases. Finally, I would not rely too much on your micro-benchmark.</p>
|
61,835,971 |
ES7, ES8, ES9, ES10, ES11 Browser support
|
<p>Regarding compatibility between ECMAScript specification and actual implementation;</p>
<p>It is fairly easy to check out the data about <a href="https://caniuse.com/#search=ECMAScript%206" rel="noreferrer">browser support for ECMAScript2015 (ES6)</a>, but I found it pretty difficult to have an equivalently clear table for all the following ES versions (ES7+).</p>
<p><em>By the time this question is asked:</em></p>
<ul>
<li><p>Mozilla has some info <a href="https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/ECMAScript_Next_support_in_Mozilla" rel="noreferrer">on their website</a>: it is possible to see that ES7 and ES8 are fully supported, ES9 still has some problems and ES10 is supported on the latest versions.</p>
</li>
<li><p>I can also guess that IE11 never progressed after ES5.</p>
</li>
<li><p>I did not find anything for the other browsers, just some stolen info here and there.</p>
</li>
</ul>
<p><strong>How can I check what the current browser-support level is?</strong></p>
| 61,836,170 | 2 | 1 | null |
2020-05-16 11:23:41.2 UTC
| 7 |
2022-04-27 03:18:26.297 UTC
|
2022-04-26 09:26:13.797 UTC
| null | 1,614,677 | null | 4,628,597 | null | 1 | 49 |
javascript|ecmascript-2016|ecmascript-2017
| 27,327 |
<p>Browser vendors don't implement specific <em>versions</em>, but specific <em>features</em>. Almost every modern browser is still missing features from ES2017-ES2020. Hence there is not and won't be a table where you can see an ES version to browser version mapping.</p>
<p>But that is not a problem because you as a developer do the same. You use features, not versions of ECMAScript. Caniuse is still a great resource to check for support of individual features. If you are not happy with the data presentation on Caniuse, maybe these <a href="https://kangax.github.io/compat-table/es2016plus/" rel="noreferrer">compatibility tables</a> are better for you. Additionally, you can use polyfills and Babel for transpiling of newer features to older runtimes.</p>
|
6,525,916 |
Dynamically Display String text on Android Screen
|
<p>I have an array of classes that contain two strings for each class. I'm trying to display these two strings (they're sentences) on the screen when a button is clicked at two different locations (middle of the screen, and the other sentence right above that).</p>
<p>The problem is that I only know how to get text on the screen through the XML layout file, not dynamically. How would I go about doing this? I already have the buttons and background done in XML.</p>
<p>Thanks!</p>
| 6,526,075 | 2 | 0 | null |
2011-06-29 19:10:47.85 UTC
| 2 |
2012-03-26 04:55:20.763 UTC
|
2011-06-29 19:12:55.087 UTC
| null | 21,234 | null | 819,486 | null | 1 | 8 |
android
| 68,811 |
<p>To add a view dynamically. Use the addView function.</p>
<pre><code>public MyActivity extends Activity {
private TextView myText = null;
@Override
public onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.mylayout);
LinearLayout lView = (LinearLayout)findViewById(R.id.mylinearlayout);
myText = new TextView();
myText.setText("My Text");
lView.addView(myText);
}
</code></pre>
<p>If you don't want to use an xml file at all:</p>
<pre><code>//This is in the onCreate method
LinearLayout lView = new LinearLayout(this);
myText = new TextView(this);
myText.setText("My Text");
lView.addView(myText);
setContentView(lView);
</code></pre>
|
55,283,725 |
unit test mocha Visual Studio Code describe is not defined
|
<p>If i run in the console the test runs fine</p>
<pre><code> mocha --require ts-node/register tests/**/*.spec.ts
</code></pre>
<p>Note: I installed mocha and mocha -g</p>
<p>I want to run unit test from Visual Studio Code</p>
<p>launcgh.js file</p>
<pre><code> "version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--require",
"ts-node/register",
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/tests/**/*.spec.ts"
],
"internalConsoleOptions": "openOnSessionStart"
},
</code></pre>
<p>Very simple Test file</p>
<pre><code> import { expect } from 'chai';
const hello = () => 'Hello world!';
describe('Hello function', () => {
it('should return hello world', () => {
const result = hello();
expect(result).to.equal('Hello world!');
});
});
</code></pre>
<p>but in the Visual studio Code debug console</p>
<pre><code> /usr/local/bin/node --inspect-brk=15767 node_modules/mocha/bin/_mocha --require ts-node/register -u tdd --timeout 999999 --colors /Applications/MAMP/htdocs/ddd-board-game/backend/tests/**/*.spec.ts
Debugger listening on ws://127.0.0.1:15767/bdec2d9c-39a7-4fb7-8968-8cfed914ea8d
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
/Applications/MAMP/htdocs/ddd-board-game/backend/tests/dummy.spec.ts:3
source-map-support.js:441
describe('Hello function', () => {
^
ReferenceError: describe is not defined
source-map-support.js:444
at Object.<anonymous> (/Applications/MAMP/htdocs/ddd-board-game/backend/tests/dummy.spec.ts:1:1)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Module.m._compile (/Applications/MAMP/htdocs/ddd-board-game/backend/node_modules/ts-node/src/index.ts:414:23)
</code></pre>
| 55,883,516 | 3 | 2 | null |
2019-03-21 15:17:22.29 UTC
| 5 |
2020-12-08 00:19:57.98 UTC
| null | null | null | null | 5,708,097 | null | 1 | 37 |
typescript|unit-testing|visual-studio-code|mocha.js
| 11,410 |
<p>Finally!!! After a long search and reading some tutorials and comments I found the solution: the problem was with the config.</p>
<p>Open the test config file and delete the following lines:</p>
<pre><code> "-u", <<<< delete this line
"tdd", <<<< delete this line
</code></pre>
<p>launch.js</p>
<pre><code> "version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--require",
"ts-node/register",
"-u", <<<< delete this line
"tdd", <<<< delete this line
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/tests/**/*.spec.ts"
],
"internalConsoleOptions": "openOnSessionStart"
},
</code></pre>
<p>Run the test again and it will work.</p>
|
7,157,129 |
What is the mimeType attribute in <data> used for?
|
<p>I really can’t get the meaning of mimeType. I know that it exists so that the <code>getType</code> method in <code>ContentProvider</code> knows what to match with it. But I’m still not sure what it means or how it’s used.</p>
| 7,159,778 | 3 | 1 | null |
2011-08-23 06:33:56.26 UTC
| 38 |
2019-05-18 21:07:40.723 UTC
|
2018-12-11 17:19:13.617 UTC
| null | 7,379,765 | null | 674,199 | null | 1 | 48 |
android|mime-types
| 37,742 |
<p>Any <code>ContentProvider</code> usually defines the type of data it handles (e.g. <a href="http://developer.android.com/resources/samples/NotePad/src/com/example/android/notepad/NotePadProvider.html" rel="noreferrer">NotePadProvider</a> handles a <code>Notes</code> data type defined in an inner class of <a href="http://developer.android.com/resources/samples/NotePad/src/com/example/android/notepad/NotePad.html" rel="noreferrer">NotePad</a>). A MIME type is just a standardized way to define that data type by giving it a unique name. This allows the data type to be communicated to code that works with a <code>ContentProvider</code> in a standardized way.</p>
<p>It also helps a <code>ContentProvider</code> that handles several different types of data to keep things organized, e.g. a <code>RailwayContentProvider</code> might handle trains, stations and tickets and can use the MIME type to tell each one apart.</p>
<p><strong>Why MIME types?</strong></p>
<p>The use of MIME types is a natural consequence when you think about how a <code>ContentProvider</code> is accessed through URIs, i.e. something like an URL on the Internet. Just like on the Internet there are MIME types like <code>text/html</code> for web pages and <code>image/jpeg</code> for .jpg images, Android wants you to define a custom MIME type for any data type your <code>ContentProvider</code> handles.</p>
<p><strong>An example custom MIME type</strong></p>
<p>In the NotePad (linked above) class of the NotePad example project, you'll find:</p>
<pre><code>public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note";
</code></pre>
<p>This field defines a custom MIME type (recognizable by the <code>type/subtype</code> pattern).</p>
<p>Android suggests you use <code>vnd.android.cursor.dir/...</code> as the first part for any kind of "directory listing" (multiple items) and <code>vnd.android.cursor.item/...</code> as the first part for any kind of single item.</p>
<p>For the subtype, it's again suggested to start it with <code>vnd.</code> and then add something like your reverse domain name/package name, e.g. <code>vnd.android.cursor.item/vnd.com.mydomain.myapp.mydata</code></p>
<p>To avoid all those <code>vnd...</code> strings in your code, there's also some constants in <code>ContentResolver</code> like <a href="http://developer.android.com/reference/android/content/ContentResolver.html#CURSOR_DIR_BASE_TYPE" rel="noreferrer">CURSOR_DIR_BASE_TYPE</a> and <a href="http://developer.android.com/reference/android/content/ContentResolver.html#CURSOR_ITEM_BASE_TYPE" rel="noreferrer">CURSOR_ITEM_BASE_TYPE</a>.</p>
|
7,838,910 |
faces-redirect and the back button cause other links to work incorrectly
|
<p>I have a question surrounding faces navigation. </p>
<p>So I have a page that takes a request parameter to load a specific user. This page displays a list of commandLink that, when clicked, redirect to another page using implicit navigation. The user is loaded by calling a method in a "preRenderView".</p>
<p>The page that we redirect to also takes a request parameter to determine which case to load. The page is also using a preRenderView. </p>
<p>Both pages have beans that are view scoped. </p>
<p>This all works awesome for the FIRST link that is pressed. The first page redirects to the new URL and the case loads as expected. </p>
<p>HOWEVER, if I click the browser's back button and then click another link the page DOESN'T redirect. It refreshes (instead) and, obviously, doesn't shop the case. </p>
<p>After the refresh, I can click a link and it will redirect properly.</p>
<p>Now, all of this works totally fine when the first page's bean is kept in the session but I don't want to abuse the session state and I don't think it should be required for me to keep this data in the session.</p>
<p>I know I can fix this by having the page automatically reload when I click the back button (because the view will be recreated) but I'm not sure if that's the correct solution either. (nor am I sure how I would force this)</p>
<p>Does anyone have any suggestions? This seems like a fairly common use case but I couldn't really find any examples.</p>
<p>Thanks!</p>
| 7,840,789 | 1 | 0 | null |
2011-10-20 16:09:58.887 UTC
| 8 |
2013-04-11 12:58:11.44 UTC
|
2013-04-11 12:58:11.44 UTC
| null | 1,065,197 | null | 534,184 | null | 1 | 6 |
jsf|redirect|jsf-2
| 3,212 |
<p>Basically, you need to tell the browser to not cache the dynamically generated JSF pages while having view state saving method set to (default) <code>server</code>. The view state is tracked by a <code><input type="hidden" name="javax.faces.ViewState"></code> field in the form of the generated JSF page with the view state identifier as input value. When you submit a page and navigate to a different page, then the view state is trashed in the server side and do not exist anymore. Getting the page back from the browser cache would still give you that old view state identifier as value of the hidden input. Submitting that form won't work at all as no view state in the server side can be found.</p>
<p>You want to get a fresh new page straight from the server instead of from the browser cache. In order to tell the browser to do that, create a <code>Filter</code> like this:</p>
<pre><code>@WebFilter(servletNames={"Faces Servlet"})
public class NoCacheFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
if (!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
httpRes.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
httpRes.setHeader("Pragma", "no-cache"); // HTTP 1.0.
httpRes.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
// ...
}
</code></pre>
<p>This way the back button will send a fullworthy HTTP request which should recreate the view state and result in a page with a form with the proper view state hidden field value.</p>
|
2,277,770 |
Setting a button's text to have some bold characters in WPF
|
<p>I'd like to know if it is possible to define as the text of a <code>Button</code> in WPF, something like:
a <strong>b</strong> c</p>
<p>I've tried setting
<a href="http://img651.imageshack.us/img651/1838/ctldhrzhy41gbrcch4dpjz4.png" rel="noreferrer">alt text http://img651.imageshack.us/img651/1838/ctldhrzhy41gbrcch4dpjz4.png</a></p>
<p>but that doesn't seem to work.</p>
<p>Is it only possible to use the <code>Bold</code> tag with <code>FlowDocument</code>s?</p>
<p>Thanks</p>
| 2,277,811 | 4 | 0 | null |
2010-02-17 01:40:16.153 UTC
| 3 |
2019-12-15 16:52:06.507 UTC
|
2011-09-23 19:03:48.317 UTC
| null | 305,637 | null | 130,758 | null | 1 | 16 |
c#|.net|wpf|button|styles
| 50,406 |
<p>Use a <code>TextBlock</code> to hold the formatted text:</p>
<pre><code><Button>
<TextBlock>Hey <Bold>you</Bold>!!!</TextBlock>
</Button>
</code></pre>
<p>Per your comment, if you want to be explicit about the fact that this sets the <code>Content</code> property, you can use XAML property element syntax to do so:</p>
<pre><code><Button>
<Button.Content>
<TextBlock>Hey <Bold>you</Bold>!!!</TextBlock>
</Button.Content>
</Button>
</code></pre>
<p>However this is redundant because <code>Button</code> has a <code>ContentPropertyAttribute</code> which makes the first version exactly equivalent to the second anyway.</p>
|
1,474,135 |
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
|
<p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p>
<pre><code>class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
# Local Stuff
image_url_s = models.CharField(max_length=128, blank=True)
image_url_m = models.CharField(max_length=128, blank=True)
# Admin
class Admin: pass
</code></pre>
<p>I have added a new class to my model:</p>
<pre><code>class Team(models.Model):
name = models.CharField(max_length=128)
manager = models.ForeignKey(User, related_name='manager')
members = models.ManyToManyField(User, blank=True)
</code></pre>
<p>And it is registered into the Admin:</p>
<pre><code>class TeamAdmin(admin.ModelAdmin):
list_display = ('name', 'manager')
admin.site.register(Team, TeamAdmin)
</code></pre>
<p>Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.</p>
<p>I have a similar class with:</p>
<pre><code>class Meta:
ordering = ['name']
</code></pre>
<p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p>
<pre><code>class Meta:
ordering = ['username']
</code></pre>
<p>I get:</p>
<p><code>django.core.management.base.CommandError: One or more models did not validate:</code>
<code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p>
<p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
| 1,474,175 | 4 | 0 | null |
2009-09-24 21:01:23.547 UTC
| 10 |
2014-05-14 08:52:46.48 UTC
| null | null | null | null | 178,711 | null | 1 | 23 |
python|django|sorting|admin|user-profile
| 22,269 |
<p>One way would be to define a custom form to use for your Team model in the admin, and override the <code>manager</code> field to use a queryset with the correct ordering:</p>
<pre><code>from django import forms
class TeamForm(forms.ModelForm):
manager = forms.ModelChoiceField(queryset=User.objects.order_by('username'))
class Meta:
model = Team
class TeamAdmin(admin.ModelAdmin):
list_display = ('name', 'manager')
form = TeamForm
</code></pre>
|
2,284,703 |
Emacs: how to disable 'file changed on disk' checking?
|
<p>How to disable Emacs from checking the buffer file was changed outside the editor?</p>
| 2,284,921 | 4 | 0 | null |
2010-02-17 21:57:05.927 UTC
| 10 |
2016-11-26 03:52:40.157 UTC
| null | null | null | null | 137,122 | null | 1 | 24 |
emacs
| 9,503 |
<p>Emacs is really trying to help you here. Read the info page on <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Interlocking.html" rel="noreferrer">Protection against Simultaneous Editing</a>.</p>
<p>But, if you still want to avoid that message/prompt, you can redefine the function that is doing the prompting:</p>
<pre><code>(defun ask-user-about-supersession-threat (fn)
"blatantly ignore files that changed on disk"
)
(defun ask-user-about-lock (file opponent)
"always grab lock"
t)
</code></pre>
<p>The second function there is for when two people are using Emacs to edit the same file, and would provide a similar prompt (but not the one you seemed to refer to in the question).</p>
<p>I'd advise against overriding the two routines, but it's there if you want.</p>
<p><hr>
On the off chance <code>global-auto-revert-mode</code> is on, you could disable that. Add this to your .emacs:</p>
<pre><code>(global-auto-revert-mode -1)
</code></pre>
<p>You can tell if the mode is on by looking at the variable of the same name:</p>
<pre><code>C-h v global-auto-revert-mode RET
</code></pre>
<p>If the value is <code>t</code>, then the mode is on, otherwise it is off.</p>
|
1,763,071 |
Negate characters in Regular Expression
|
<p>How would I write a regular expression that matches the following criteria?</p>
<ul>
<li>No numbers</li>
<li>No special characters</li>
<li>No spaces</li>
</ul>
<p>in a string</p>
| 1,763,582 | 4 | 3 | null |
2009-11-19 12:48:49.847 UTC
| 3 |
2017-06-28 21:52:01.99 UTC
|
2017-06-28 21:52:01.99 UTC
| null | 6,943,394 | null | 192,923 | null | 1 | 62 |
regex|regex-negation
| 107,113 |
<p>The caret inside of a character class [^ ] is the negation operator common to most regular expression implementations (Perl, .NET, Ruby, Javascript, etc). So I'd do it like this:</p>
<pre><code>[^\W\s\d]
</code></pre>
<ul>
<li>^ - Matches anything NOT in the character class</li>
<li>\W - matches non-word characters (a word character would be defined as a-z, A-Z, 0-9, and underscore).</li>
<li>\s - matches whitespace (space, tab, carriage return, line feed)</li>
<li>\d - matches 0-9</li>
</ul>
<p>Or you can take another approach by simply including only what you want:</p>
<pre><code>[A-Za-z]
</code></pre>
<p>The main difference here is that the first one will include underscores. That, and it demonstrates a way of writing the expression in the same terms that you're thinking. But if you reverse you're thinking to include characters instead of excluding them, then that can sometimes result in an easier to read regular expression. </p>
<p>It's not completely clear to me which special characters you don't want. But I wrote out both solutions just in case one works better for you than the other.</p>
|
1,385,871 |
how to remove key+value from hash in javascript
|
<p>Given</p>
<pre><code>var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myHash['key2'] = { Name: 'Object 2' };
myHash['key3'] = { Name: 'Object 3' };
</code></pre>
<p>How do I remove <code>key2</code>, and <code>object 2</code> from the hash, so that it ends up in a state as if I did:</p>
<pre><code>var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myHash['key3'] = { Name: 'Object 3' };
</code></pre>
<p>delete doesn't do what I want;</p>
<pre><code>delete myHash['key2']
</code></pre>
<p>simply gives me this:</p>
<pre><code>var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myhash['key2'] = null;
myHash['key3'] = { Name: 'Object 3' };
</code></pre>
<p>the only docs I can find on <code>splice</code> and <code>slice</code> deal with integer indexers, which I don't have.</p>
<p>Edit: I also do not know that 'key2' is necessarily in position [1]</p>
<p><b>UPDATE</b></p>
<p>OK slight red herring, delete does seem to do what I want on the surface, however, I'm using json2.js to stringify my object to json for pushing back to the server,</p>
<p>after I've deleted, myHash gets serialized as:</p>
<pre><code>[ { Name: 'Object 1' }, null, { Name: 'Object 3' } ]
</code></pre>
<p>Is this a bug in json2.js? or is it something I'm doing wrong with delete?</p>
<p>Thanks</p>
| 1,385,889 | 4 | 2 | null |
2009-09-06 15:04:10.457 UTC
| 6 |
2018-05-30 18:05:40.963 UTC
|
2018-05-30 18:05:40.963 UTC
| null | 11,732,320 | null | 28,543 | null | 1 | 84 |
javascript|arrays
| 111,505 |
<p>You're looking for <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator" rel="noreferrer"><code>delete</code></a>:</p>
<pre><code>delete myhash['key2']
</code></pre>
<p>See the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide" rel="noreferrer">Core Javascript Guide</a></p>
|
1,715,681 |
Scala 2.8 breakOut
|
<p>In Scala <strong>2.8</strong>, there is an object in <code>scala.collection.package.scala</code>:</p>
<pre><code>def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
new CanBuildFrom[From, T, To] {
def apply(from: From) = b.apply() ; def apply() = b.apply()
}
</code></pre>
<p>I have been told that this results in:</p>
<pre><code>> import scala.collection.breakOut
> val map : Map[Int,String] = List("London", "Paris").map(x => (x.length, x))(breakOut)
map: Map[Int,String] = Map(6 -> London, 5 -> Paris)
</code></pre>
<p>What is going on here? Why is <code>breakOut</code> being called <em>as an argument</em> to my <code>List</code>?</p>
| 1,716,558 | 4 | 2 | null |
2009-11-11 14:53:23.257 UTC
| 168 |
2017-04-30 14:26:24.553 UTC
|
2015-05-08 21:50:41.59 UTC
| null | 699,224 | null | 16,853 | null | 1 | 230 |
scala|scala-2.8|scala-collections
| 37,610 |
<p>The answer is found on the definition of <code>map</code>:</p>
<pre><code>def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
</code></pre>
<p>Note that it has two parameters. The first is your function and the second is an implicit. If you do not provide that implicit, Scala will choose the most <em>specific</em> one available. </p>
<p><strong>About <code>breakOut</code></strong></p>
<p>So, what's the purpose of <code>breakOut</code>? Consider the example given for the question, You take a list of strings, transform each string into a tuple <code>(Int, String)</code>, and then produce a <code>Map</code> out of it. The most obvious way to do that would produce an intermediary <code>List[(Int, String)]</code> collection, and then convert it.</p>
<p>Given that <code>map</code> uses a <code>Builder</code> to produce the resulting collection, wouldn't it be possible to skip the intermediary <code>List</code> and collect the results directly into a <code>Map</code>? Evidently, yes, it is. To do so, however, we need to pass a proper <code>CanBuildFrom</code> to <code>map</code>, and that is exactly what <code>breakOut</code> does.</p>
<p>Let's look, then, at the definition of <code>breakOut</code>:</p>
<pre><code>def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
new CanBuildFrom[From, T, To] {
def apply(from: From) = b.apply() ; def apply() = b.apply()
}
</code></pre>
<p>Note that <code>breakOut</code> is parameterized, and that it returns an instance of <code>CanBuildFrom</code>. As it happens, the types <code>From</code>, <code>T</code> and <code>To</code> have already been inferred, because we know that <code>map</code> is expecting <code>CanBuildFrom[List[String], (Int, String), Map[Int, String]]</code>. Therefore:</p>
<pre><code>From = List[String]
T = (Int, String)
To = Map[Int, String]
</code></pre>
<p>To conclude let's examine the implicit received by <code>breakOut</code> itself. It is of type <code>CanBuildFrom[Nothing,T,To]</code>. We already know all these types, so we can determine that we need an implicit of type <code>CanBuildFrom[Nothing,(Int,String),Map[Int,String]]</code>. But is there such a definition?</p>
<p>Let's look at <code>CanBuildFrom</code>'s definition:</p>
<pre><code>trait CanBuildFrom[-From, -Elem, +To]
extends AnyRef
</code></pre>
<p>So <code>CanBuildFrom</code> is contra-variant on its first type parameter. Because <code>Nothing</code> is a bottom class (ie, it is a subclass of everything), that means <em>any</em> class can be used in place of <code>Nothing</code>.</p>
<p>Since such a builder exists, Scala can use it to produce the desired output.</p>
<p><strong>About Builders</strong></p>
<p>A lot of methods from Scala's collections library consists of taking the original collection, processing it somehow (in the case of <code>map</code>, transforming each element), and storing the results in a new collection.</p>
<p>To maximize code reuse, this storing of results is done through a <em>builder</em> (<code>scala.collection.mutable.Builder</code>), which basically supports two operations: appending elements, and returning the resulting collection. The type of this resulting collection will depend on the type of the builder. Thus, a <code>List</code> builder will return a <code>List</code>, a <code>Map</code> builder will return a <code>Map</code>, and so on. The implementation of the <code>map</code> method need not concern itself with the type of the result: the builder takes care of it.</p>
<p>On the other hand, that means that <code>map</code> needs to receive this builder somehow. The problem faced when designing Scala 2.8 Collections was how to choose the best builder possible. For example, if I were to write <code>Map('a' -> 1).map(_.swap)</code>, I'd like to get a <code>Map(1 -> 'a')</code> back. On the other hand, a <code>Map('a' -> 1).map(_._1)</code> can't return a <code>Map</code> (it returns an <code>Iterable</code>).</p>
<p>The magic of producing the best possible <code>Builder</code> from the known types of the expression is performed through this <code>CanBuildFrom</code> implicit.</p>
<p><strong>About <code>CanBuildFrom</code></strong></p>
<p>To better explain what's going on, I'll give an example where the collection being mapped is a <code>Map</code> instead of a <code>List</code>. I'll go back to <code>List</code> later. For now, consider these two expressions:</p>
<pre><code>Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)
Map(1 -> "one", 2 -> "two") map (_._2)
</code></pre>
<p>The first returns a <code>Map</code> and the second returns an <code>Iterable</code>. The magic of returning a fitting collection is the work of <code>CanBuildFrom</code>. Let's consider the definition of <code>map</code> again to understand it.</p>
<p>The method <code>map</code> is inherited from <code>TraversableLike</code>. It is parameterized on <code>B</code> and <code>That</code>, and makes use of the type parameters <code>A</code> and <code>Repr</code>, which parameterize the class. Let's see both definitions together:</p>
<p>The class <code>TraversableLike</code> is defined as:</p>
<pre><code>trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
</code></pre>
<p>To understand where <code>A</code> and <code>Repr</code> come from, let's consider the definition of <code>Map</code> itself:</p>
<pre><code>trait Map[A, +B]
extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]]
</code></pre>
<p>Because <code>TraversableLike</code> is inherited by all traits which extend <code>Map</code>, <code>A</code> and <code>Repr</code> could be inherited from any of them. The last one gets the preference, though. So, following the definition of the immutable <code>Map</code> and all the traits that connect it to <code>TraversableLike</code>, we have:</p>
<pre><code>trait Map[A, +B]
extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]]
trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
extends MapLike[A, B, This]
trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
extends PartialFunction[A, B] with IterableLike[(A, B), This] with Subtractable[A, This]
trait IterableLike[+A, +Repr]
extends Equals with TraversableLike[A, Repr]
trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
</code></pre>
<p>If you pass the type parameters of <code>Map[Int, String]</code> all the way down the chain, we find that the types passed to <code>TraversableLike</code>, and, thus, used by <code>map</code>, are:</p>
<pre><code>A = (Int,String)
Repr = Map[Int, String]
</code></pre>
<p>Going back to the example, the first map is receiving a function of type <code>((Int, String)) => (Int, Int)</code> and the second map is receiving a function of type <code>((Int, String)) => String</code>. I use the double parenthesis to emphasize it is a tuple being received, as that's the type of <code>A</code> as we saw.</p>
<p>With that information, let's consider the other types.</p>
<pre><code>map Function.tupled(_ -> _.length):
B = (Int, Int)
map (_._2):
B = String
</code></pre>
<p>We can see that the type returned by the first <code>map</code> is <code>Map[Int,Int]</code>, and the second is <code>Iterable[String]</code>. Looking at <code>map</code>'s definition, it is easy to see that these are the values of <code>That</code>. But where do they come from? </p>
<p>If we look inside the companion objects of the classes involved, we see some implicit declarations providing them. On object <code>Map</code>:</p>
<pre><code>implicit def canBuildFrom [A, B] : CanBuildFrom[Map, (A, B), Map[A, B]]
</code></pre>
<p>And on object <code>Iterable</code>, whose class is extended by <code>Map</code>:</p>
<pre><code>implicit def canBuildFrom [A] : CanBuildFrom[Iterable, A, Iterable[A]]
</code></pre>
<p>These definitions provide factories for parameterized <code>CanBuildFrom</code>.</p>
<p>Scala will choose the most specific implicit available. In the first case, it was the first <code>CanBuildFrom</code>. In the second case, as the first did not match, it chose the second <code>CanBuildFrom</code>.</p>
<p><strong>Back to the Question</strong></p>
<p>Let's see the code for the question, <code>List</code>'s and <code>map</code>'s definition (again) to see how the types are inferred:</p>
<pre><code>val map : Map[Int,String] = List("London", "Paris").map(x => (x.length, x))(breakOut)
sealed abstract class List[+A]
extends LinearSeq[A] with Product with GenericTraversableTemplate[A, List] with LinearSeqLike[A, List[A]]
trait LinearSeqLike[+A, +Repr <: LinearSeqLike[A, Repr]]
extends SeqLike[A, Repr]
trait SeqLike[+A, +Repr]
extends IterableLike[A, Repr]
trait IterableLike[+A, +Repr]
extends Equals with TraversableLike[A, Repr]
trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
</code></pre>
<p>The type of <code>List("London", "Paris")</code> is <code>List[String]</code>, so the types <code>A</code> and <code>Repr</code> defined on <code>TraversableLike</code> are:</p>
<pre><code>A = String
Repr = List[String]
</code></pre>
<p>The type for <code>(x => (x.length, x))</code> is <code>(String) => (Int, String)</code>, so the type of <code>B</code> is:</p>
<pre><code>B = (Int, String)
</code></pre>
<p>The last unknown type, <code>That</code> is the type of the result of <code>map</code>, and we already have that as well:</p>
<pre><code>val map : Map[Int,String] =
</code></pre>
<p>So,</p>
<pre><code>That = Map[Int, String]
</code></pre>
<p>That means <code>breakOut</code> must, necessarily, return a type or subtype of <code>CanBuildFrom[List[String], (Int, String), Map[Int, String]]</code>.</p>
|
36,612,596 |
Tuple to parameter pack
|
<p>This below code from user Faheem Mitha, is based on user Johannes Schaub - litb's answer in this <a href="https://stackoverflow.com/a/9288547/1655492">SO</a>. This code perfectly does what I seek, which is conversion of a <code>tuple</code> into parameter pack, but I don't understand this code well enough and therefore I thought I will create a new discussion that might help template metaprogramming newbies like me. So, please pardon the duplicate posting.</p>
<p>Now moving onto the code</p>
<pre><code>#include <tuple>
#include <iostream>
using std::cout;
using std::endl;
template<int ...> struct seq {};
template<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
double foo(int x, float y, double z)
{
return x + y + z;
}
template <typename ...Args>
struct save_it_for_later
{
std::tuple<Args...> params;
double(*func)(Args...);
double delayed_dispatch()
{
return callFunc(typename gens<sizeof...(Args)>::type()); // Item #1
}
template<int ...S>
double callFunc(seq<S...>)
{
return func(std::get<S>(params) ...);
}
};
int main(void)
{
std::tuple<int, float, double> t = std::make_tuple(1, (float)1.2, 5);
save_it_for_later<int, float, double> saved = { t, foo };
cout << saved.delayed_dispatch() << endl;
return 0;
}
</code></pre>
<p>I'm completely confounded by Item #1 above:</p>
<ul>
<li>What purpose does <code>typename</code> serve on that line?</li>
<li>I understand that <code>gens<sizeof...(Args)>::type()</code> will expand to <code>gens<3>::type()</code>, but that doesn't seem to match neither <code>template<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };</code> nor <code>template<int ...S> struct gens<0, S...></code>. I'm obviously missing the point and I'd be glad if someone can explain what is happening here.</li>
</ul>
<p>I do understand that <code>callFunc</code> gets invoked in this form <code>callFunc(seq<0,1,2>)</code> and the return statement of this method itself expands to <code>return func(std::get<0>(params), std::get<1>(params), std::get<2>(params)</code> and this is what makes this scheme work, but I cannot workout how this <code>seq<0,1,2></code> type is generated.</p>
<p>Note: Using <code>std::index_sequence_for</code> is not an option, my compiler doesn't support C++14 features.</p>
<p>PS: Can this technique be classified as template metaprogramming?</p>
| 36,612,797 | 2 | 5 | null |
2016-04-14 02:06:04.927 UTC
| 11 |
2019-02-10 19:12:14.353 UTC
|
2017-05-23 12:02:31.27 UTC
| null | -1 | null | 1,655,492 | null | 1 | 19 |
c++|templates|c++11|variadic-templates
| 16,366 |
<p>Let's look at what happens here:</p>
<pre><code>template<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
</code></pre>
<p>The first one is a generic template, the second one is a specialization that applies when the first template parameter is 0.</p>
<p>Now, take a piece of paper and pencil, and write down how</p>
<pre><code> gens<3>
</code></pre>
<p>gets defined by the above template. If your answer was:</p>
<pre><code> struct gens<3> : public gens<2, 2>
</code></pre>
<p>then you were right. That's how the first template gets expanded when <code>N</code> is "3", and <code>...S</code> is empty. <code>gens<N - 1, N - 1, S...></code>, therefore, becomes <code>gens<2, 2></code>.</p>
<p>Now, let's keep going, and see how <code>gens<2, 2></code> gets defined:</p>
<pre><code> struct gens<2, 2> : public gens<1, 1, 2>
</code></pre>
<p>Here, in the template expansion, <code>N</code> is 2, and <code>...S</code> is "2". Now, let's take the next step, and see how <code>gens<1, 1, 2></code> is defined:</p>
<pre><code> struct gens<1, 1, 2> : public gens<0, 0, 1, 2>
</code></pre>
<p>Ok, now how does <code>gens<0, 0, 1, 2></code> gets defined? It can now be defined by the specialization:</p>
<pre><code> template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
</code></pre>
<p>So, what happens with <code>struct gens<0, 0, 1, 2></code> here? Well, in the specialization, "S..." becomes "0, 1, 2", so this becomes, in a manner of speaking:</p>
<pre><code> struct gens<0, 0, 1, 2> {
typedef seq<0, 1, 2> type;
}
</code></pre>
<p>Now, keep in mind that all of these publicly inherit from each other, "elephant-style", so:</p>
<pre><code> gens<3>::type
</code></pre>
<p>ends up being a typedef declaration for</p>
<pre><code> struct seq<0, 1, 2>
</code></pre>
<p>And this is used, by the code that follows to convert the tuple into a parameter pack, using another template:</p>
<pre><code>double delayed_dispatch()
{
return callFunc(typename gens<sizeof...(Args)>::type()); // Item #1
}
</code></pre>
<p><code>...Args</code> are the tuple parameters. So, if there are three elements in the tuple, <code>sizeof(...Args)</code> is 3, and as I've explained above, <code>gens<sizeof...(Args)>::type()</code> becomes <code>gens<3>::type()</code>, a.k.a. <code>seq<0, 1, 2>()</code>.</p>
<p>So, now:</p>
<pre><code>template<int ...S>
double callFunc(seq<S...>)
{
return func(std::get<S>(params) ...);
}
</code></pre>
<p>The <code>S...</code> part becomes "0, 1, 2", so the</p>
<pre><code>std::get<S>(params)...
</code></pre>
<p>Becomes a parameter pack that gets expanded to:</p>
<pre><code>std::get<0>(params), std::get<1>(params), std::get<2>(params),
</code></pre>
<p>And that's how a tuple becomes a parameter pack.</p>
|
7,294,176 |
How to create global functions in Objective-C
|
<p>I'm developing an iphone app and I need to have some functions to use globally in my classes.</p>
<p>But how can I do this?</p>
<p>I just tried to create <code>functions.h</code> likes this</p>
<pre><code>#include <Foundation/Foundation.h>
- (void)printTest;
</code></pre>
<p>and in the <code>functions.m</code></p>
<pre><code>#import "functions.h"
- (void)prinTest {
NSLog(@"test");
}
</code></pre>
<p>but it doesn't work. Says me: "Method definition not in a @implementation context".</p>
| 7,294,359 | 5 | 0 | null |
2011-09-03 16:00:55.577 UTC
| 13 |
2021-09-07 20:34:03.773 UTC
| null | null | null | null | 719,127 | null | 1 | 35 |
iphone|objective-c
| 30,939 |
<p>First note that Objective-C language is a superset of C language (meaning there is absolutely nothing wrong with mixing them).</p>
<p>There are two approaches.</p>
<h2>#1 Real global function:</h2>
<p>Declare a global C-style function, which can have ObjC logic (in definetion instead of just C-style logic).</p>
<p>Header:</p>
<pre><code>void GSPrintTest();
</code></pre>
<p>Implementation:</p>
<pre><code>#import "functions.h"
#import <Foundation/Foundation.h>
void GSPrintTest() {
NSLog(@"test");
}
</code></pre>
<p>Call using:</p>
<pre><code>#import "functions.h"
...
GSPrintTest();
</code></pre>
<p>A third (bad, but possible) option would be adding a category to NSObject for your methods:</p>
<p>Header:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface NSObject(GlobalStuff)
- (void) printTest;
@end
</code></pre>
<p>Implementation:</p>
<pre><code>#import "functions.h"
@implementation NSObject(GlobalStuff)
- (void) printTest {
NSLog(@"test");
}
@end
</code></pre>
<p>Call using:</p>
<pre><code>#import "functions.h"
...
[self printTest];
</code></pre>
<h2>#2 class method:</h2>
<p>Create a class method with <code>+</code> sign, in helper class (instead of instance method with <code>-</code> sign).</p>
<p>Header:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface GlobalStuff : NSObject {}
+ (void)printTest;
@end
</code></pre>
<p>Implementation:</p>
<pre><code>#import "functions.h"
@implementation GlobalStuff
+ (void) printTest {
NSLog(@"test");
}
@end
</code></pre>
<p>Call using:</p>
<pre><code>#import "functions.h"
...
[GlobalStuff printTest];
</code></pre>
|
7,240,916 |
Android: Under what circumstances would a Dialog appearing cause onPause() to be called?
|
<p>A snippet from the Android <a href="http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle" rel="noreferrer">Activities</a> document(scroll down to the "<strong>foreground lifetime</strong>" line) says :</p>
<blockquote>
<p>An activity can frequently transition in and out of the foreground—for
example, <code>onPause()</code> is called when the device goes to sleep <strong><em>or when a
dialog appears</em></strong>.</p>
</blockquote>
<p>I don't quite understand this. Under what circumstances should this happen? Is <code>onPause()</code> called only if the context of the dialog in question is different from the activity on top of which the dialog is to be displayed?</p>
<h2>EDIT: Adding code sample to illustrate my doubt in detail</h2>
<p>Going by the above-mentioned quote from document, should my activity's <code>onPause()</code> method get called when the <code>AlertDialog</code> (or just the <code>Dialog</code>) in the following code gets displayed? Should I see the "onPause called" log entry when the dialog is displayed?</p>
<p>But I don't see that happen. And it shouldn't either, if I have understood the Android life cycle correctly! So, what's the document pointing at then?</p>
<pre><code>public class LifeCycleTestActivity extends Activity {
private static final String TAG = "LifeCycleTest";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick");
AlertDialog dialog = new AlertDialog.Builder(LifeCycleTestActivity.this).create();
dialog.setMessage("You Clicked on the button");
dialog.setTitle("Dialog!");
dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
/*
Dialog dialog = new Dialog(LifeCycleTestActivity.this);
dialog.setTitle("Dialog!");
dialog.setCancelable(true);
dialog.show();
*/
}
});
}
@Override
protected void onPause() {
Log.d(TAG, "onPause() called");
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
}
</code></pre>
| 7,384,782 | 7 | 0 | null |
2011-08-30 09:06:47.133 UTC
| 35 |
2018-07-05 20:44:30.963 UTC
|
2011-09-06 11:11:53.257 UTC
| null | 570,930 | null | 570,930 | null | 1 | 81 |
android|dialog|lifecycle|android-lifecycle|onpause
| 29,559 |
<p><code>onPause()</code> is called when your activity is no longer at the top of the activity stack. A Dialog by itself is not an Activity, so will not replace the current Activity at the top of the stack, so will not cause anything to pause.</p>
<p>A dialog (lower-case) does not need to be implemented by a Dialog class, however. For example, it is not uncommon to implement one with an Activity whose theme is set to that of a dialog. In this case, displaying the <strong>dialog-as-an-Activity</strong> will cause the new Activity to be on the top of the stack, pausing what previously was there.</p>
|
13,928,689 |
How to setup a maven project in Intellij IDEA 12
|
<p>I have problem importing a maven project which was created by Netbeans into the IDEA 12. The dependency artifacts writen in the pom doesn't work. It told me that "cannot resolve symbol 'springframework'" on "import org.springframework.xxx;". When I runs it, it says that org.springframework.xxx doesn't exist.
Here is the pom file</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.seu.cose.jellyjolly</groupId>
<artifactId>jellyjolly-openshift-dist</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>Jelly Jolly Openshift Distribution</name>
<organization>
<name>College of Software Engineering, Southeast University</name>
<url>http://cose.seu.edu.cn/</url>
</organization>
<repositories>
<repository>
<id>eap</id>
<url>http://maven.repository.redhat.com/techpreview/all</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>maven-restlet</id>
<name>Public online Restlet repository</name>
<url>http://maven.restlet.org</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>eap</id>
<url>http://maven.repository.redhat.com/techpreview/all</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<netbeans.hint.license>gpl30</netbeans.hint.license>
</properties>
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>3.0.0.Final-redhat-1</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.3.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.restlet.jee</groupId>
<artifactId>org.restlet</artifactId>
<version>2.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.restlet.jee</groupId>
<artifactId>org.restlet.ext.xml</artifactId>
<version>2.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.java.dev.rome</groupId>
<artifactId>rome</artifactId>
<version>1.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
</dependencies>
<profiles>
<profile>
<!-- When built in OpenShift the 'openshift' profile will be used when
invoking mvn. -->
<!-- Use this profile for any OpenShift specific customization your app
will need. -->
<!-- By default that is to put the resulting archive into the 'webapps'
folder. -->
<!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
<id>openshift</id>
<build>
<finalName>jellyjolly</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<outputDirectory>webapps</outputDirectory>
<warName>ROOT</warName>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</code></pre>
<p></p>
| 13,930,041 | 4 | 5 | null |
2012-12-18 08:03:17.603 UTC
| 5 |
2015-04-10 12:58:48.153 UTC
|
2015-04-10 12:58:48.153 UTC
| null | 617,450 | null | 1,122,665 | null | 1 | 8 |
java|maven|intellij-idea
| 42,203 |
<p>If the project runs on the command line (<code>mvn clean install</code>) the chance is like 100% it will work in IntelliJ 12 too :-)</p>
<p>After File -> Project Import -> From external Maven Model you should see the modules.</p>
<p>What I would check in the IntelliJ settings is the location of the maven home directory (File -> Settings -> Maven) and the settings.xml files it reads (or does not read).</p>
<p>The <code>mvn install</code> within the IDE should not differ from what happens on the command line. If it does it would compare <code>mvn help:effective-settings</code> output from the command line and from IntelliJ (maybe also from Netbeans).</p>
<p>If you just dont see all modules right click on the parent-pom.xml and choose maven -> reimport. To resolve the dependencies you have to execute an install once. It does not automatically resolve dependencies in all cases.</p>
|
14,198,942 |
Webapp file organization convention (development structure)
|
<p>For the webapps I'm developing, I usually use the following files organization, since I think it respects the convention:</p>
<pre class="lang-none prettyprint-override"><code>src
|-- main
|-- resources
| |-- *.properties
| |-- *.xml
| |-- spring
| |-- applicationContext.xml (main application context config file)
|-- webapp
|-- WEB-INF
|-- spring
| |-- spring-mvc.xml (web application context config file, delegated to manage only the web part)
| |-- spring-security-http.xml (web security config)
|-- static
| |-- *.css
| |-- *.js
|-- views
| |-- *.jsp
|-- web.xml (deployment configuration)
</code></pre>
<p>What I would like to try, is to organize my files according to the following structure:</p>
<pre class="lang-none prettyprint-override"><code>src
|-- main
|-- resources
| |-- *.properties
| |-- *.xml
| |-- web.xml
| |-- spring
| |-- applicationContext.xml
| |-- spring-mvc.xml
| |-- spring-security-http.xml
|-- webapp
|-- WEB-INF
|-- static
| |-- *.css
| |-- *.js
|-- views
|-- *.jsp
</code></pre>
<p>Of course, when packaging the webapp, the files will be relocated where they have to (e.g. the web.xml file within the WEB-INF folder). The reason why I would like to reorganize my webapps as above, is that I find it more convenient to have all the *.xml config files in the same location, instead of having some here and some there. Is it a bad idea in your opinion to break my initial structure? If yes why? Why is it so important to have all the web config files within the WEB-INF folder?</p>
<p>PS: technically, I know how to well link all the files within the classpath of the webapp. The question is more about convention and feedbacks from personal/professional experiences.</p>
| 14,200,520 | 2 | 0 | null |
2013-01-07 15:31:14.1 UTC
| 12 |
2018-10-13 19:43:55.17 UTC
|
2013-08-16 21:32:48.513 UTC
| null | 814,702 | null | 1,225,328 | null | 1 | 17 |
java|spring|jakarta-ee|web-applications|file-organization
| 29,761 |
<p>You can create the Java Web project is some popular IDE, like Eclipse, NetBeans, IntelliJ IDEA, to see the typical Java Web application structure.</p>
<p>And there is a difference between the <strong>development structure and packaging structure</strong>.<br>
While developing an app you can pretty much use whatever structure you like. But you <strong>must package</strong> Java EE web application according to the specific rules.</p>
<p>See the official Java EE tutorials for the details: </p>
<ul>
<li><a href="https://javaee.github.io/tutorial/packaging.html#GKJIQ4" rel="noreferrer">The Java EE 8 Tutorial:
Packaging</a></li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/packaging.htm" rel="noreferrer">The Java EE 7 Tutorial:
Packaging</a></li>
<li><a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnaby.html" rel="noreferrer">The Java EE 6 Tutorial: Packaging
Applications</a></li>
<li><a href="http://docs.oracle.com/javaee/6/tutorial/doc/gexap.html" rel="noreferrer">The Java EE 6 Tutorial: Example Directory
Structure</a>
(here just ignore info related to NetBeans)</li>
</ul>
<p>Also here is the recommended conventions for structuring applications developed using Java 2 Platform, Enterprise Edition (although dated but might be useful):<br>
<a href="http://web.archive.org/web/20081216004416/http://java.sun.com/blueprints/code/projectconventions.html#25692" rel="noreferrer">Java Blueprints Guidelines.
Project Conventions for Enterprise Applications</a></p>
<p>And here an example from the above Java BluePrints:
<img src="https://i.stack.imgur.com/aCmR6.jpg" alt="Web Applications: Recommended Directory Structure"></p>
<hr>
<p>UPDATE </p>
<p>Here is the example from one of my Java Web application project with Spring.
For instance I stored all Spring related configuration files in the specially created <em>spring</em> folder inside <em>WEB-INF</em>. And in the <em>spring</em> folder I created more folders to better organize my app. Again, it is just one of the possible variants, i.e. a <strong>matter of personal preferences</strong>. </p>
<p><img src="https://i.stack.imgur.com/HfUX0.png" alt="Spring project structure example"></p>
|
14,190,045 |
How do I convert datetime.timedelta to minutes, hours in Python?
|
<p>I get a start_date like this:</p>
<pre><code>from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
</code></pre>
<p>I get output like this:</p>
<pre><code>datetime.timedelta(0, 5, 41038)
</code></pre>
<p>How do I convert this into normal time like the following?</p>
<p>10 minutes, 1 hour like this</p>
| 14,190,143 | 10 | 2 | null |
2013-01-07 04:48:07.177 UTC
| 27 |
2021-06-14 20:14:07.247 UTC
|
2018-10-29 23:17:30.293 UTC
| null | 63,550 | null | 1,881,957 | null | 1 | 80 |
python|django
| 206,471 |
<p>There's no built-in formatter for <code>timedelta</code> objects, but it's pretty easy to do it yourself:</p>
<pre><code>days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
</code></pre>
<p>Or, equivalently, if you're in Python 2.7+ or 3.2+:</p>
<pre><code>seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
</code></pre>
<p>Now you can print it however you want:</p>
<pre><code>'{} minutes, {} hours'.format(minutes, hours)
</code></pre>
<p>For example:</p>
<pre><code>def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)
</code></pre>
<p>This will print:</p>
<pre><code>9 minutes, 50 hours
</code></pre>
<p>If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:</p>
<pre><code>print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
hours, 's' if minutes != 1 else '')
</code></pre>
<p>Or you may want to write an <code>english_plural</code> function to do the <code>'s'</code> bits for you, instead of repeating yourself.</p>
<p>From your comments, it sounds like you actually want to keep the days separate. That's even easier:</p>
<pre><code>def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return days, hours, minutes, seconds
</code></pre>
<p>If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:</p>
<pre><code>def dhms_to_seconds(days, hours, minutes, seconds):
return (((days * 24) + hours) * 60 + minutes) * 60 + seconds
def seconds_to_dhms(seconds):
days = seconds // (3600 * 24)
hours = (seconds // 3600) % 24
minutes = (seconds // 60) % 60
seconds = seconds % 60
return days, hours, minutes, seconds
</code></pre>
<p>So, putting it together:</p>
<pre><code>def store_timedelta_in_database(thingy, duration):
seconds = dhms_to_seconds(*convert_timedelta(duration))
db.execute('INSERT INTO foo (thingy, duration) VALUES (?, ?)',
thingy, seconds)
db.commit()
def print_timedelta_from_database(thingy):
cur = db.execute('SELECT duration FROM foo WHERE thingy = ?', thingy)
seconds = int(cur.fetchone()[0])
days, hours, minutes, seconds = seconds_to_dhms(seconds)
print '{} took {} minutes, {} hours, {} days'.format(thingy, minutes, hours, days)
</code></pre>
|
13,856,266 |
Class broken error with Joda Time using Scala
|
<p>I'm adding the Joda Time repository to SBT with</p>
<pre><code>libraryDependencies ++= Seq(
"joda-time" % "joda-time" % "2.1"
)
</code></pre>
<p>Then I merrily use it like this:</p>
<pre><code> val ymd = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd")
ymd.parseDateTime("20121212")
</code></pre>
<p>But, when I compile the project in SBT, I get a nasty:</p>
<pre><code>[warn] Class org.joda.convert.FromString not found - continuing with a stub.
[warn] Caught: java.lang.NullPointerException while parsing annotations in /home/jack/.ivy2/cache/joda-time/joda-time/jars/joda-time-2.1.jar(org/joda/time/DateTime.class)
[error] error while loading DateTime, class file '/home/jack/.ivy2/cache/joda-time/joda-time/jars/joda-time-2.1.jar(org/joda/time/DateTime.class)' is broken
[error] (class java.lang.RuntimeException/bad constant pool tag 10 at byte 42)
</code></pre>
<p>I tried the 2.0 version of joda-time, but get the same error.</p>
| 13,856,382 | 2 | 0 | null |
2012-12-13 09:00:43.637 UTC
| 9 |
2016-12-29 10:41:49.11 UTC
| null | null | null | null | 828,757 | null | 1 | 92 |
scala|sbt|jodatime
| 21,570 |
<p>Add this dependency: </p>
<blockquote>
<p>"org.joda" % "joda-convert" % "1.8.1"</p>
</blockquote>
<p>It's an optional dependency of joda-time.
I had to add it in my own project for the scala compiler to accept working with the joda-time jar.</p>
<p>Your issue seems to be the same.</p>
<p>Version is as at time of editing, latest versions can be found <a href="https://mvnrepository.com/artifact/org.joda/joda-convert" rel="noreferrer">here</a> </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.