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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52,415,943 |
Trying to git clone via SSH but getting broken pipe error
|
<p>I am having some strange issues trying to <code>git clone</code> one of my public GitHub repositories because of a weird issue. I know it's not an issue with my key, because I've taken the same key from another VM and just simply fixed its permissions. This is the error that I get when trying to use SSH:</p>
<pre><code>[root:kali:~/scripts]# ssh -T git@github.compacket_write_wait:
Connection to 192.30.253.112 port 22: Broken pipe
</code></pre>
<p><strong>Suggestion 1</strong></p>
<p>Reference: <a href="https://gitlab.com/gitlab-com/support-forum/issues/129" rel="noreferrer">https://gitlab.com/gitlab-com/support-forum/issues/129</a></p>
<p>Tried to add the following to an <code>/etc/ssh/ssh_config</code> file: </p>
<pre><code>Host *
ServerAliveInterval 120
TCPKeepAlive no
</code></pre>
<p>and no luck. I've even tried changing <code>TCPKeepAlive</code> to <code>yes</code>, and the same thing happens.</p>
<p>My DNS server is set to <code>8.8.8.8</code>, so not quite sure that's the issue. I can git clone the http URL, just not the SSH URL.</p>
<p><strong>Suggestion 2</strong></p>
<p>I also tried to run the <code>ssh</code> command with the verbose option, and according to the output, it looks like it actually authenticates successfully, as shown below:</p>
<pre><code>debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.253.113]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending environment.
debug1: Sending env LANG = C.UTF-8
debug1: Sending env LC_CTYPE = C.UTF-8
packet_write_wait: Connection to 192.30.253.113 port 22: Broken pipe
</code></pre>
<p>Any idea what else could be going wrong here?</p>
| 54,004,358 | 6 | 4 | null |
2018-09-20 00:44:46.967 UTC
| 13 |
2022-01-28 07:18:50.613 UTC
| null | null | null | null | 1,493,116 | null | 1 | 47 |
git
| 29,088 |
<p>I don't know who this guy is, but bless him! This worked for me: <a href="https://blog.bchoy.me/post/2018-09-11-vmware-ssh-bug/" rel="noreferrer">https://blog.bchoy.me/post/2018-09-11-vmware-ssh-bug/</a></p>
<p>Put this in your <code>~/.ssh/config</code></p>
<pre><code>Host *
ServerAliveInterval 600
TCPKeepAlive yes
IPQoS=throughput
</code></pre>
<p>He has a link to some discussion about the IPQoS parameter -- which fixed it for me.</p>
|
88,800 |
How do I restore from a drop database command using a mysql binary log?
|
<p>How can I restore a mysql database that was dropped using a "drop database" command? I have access to binary logs which should make this type of rollback possible.</p>
| 88,856 | 5 | 0 | null |
2008-09-17 23:59:56.667 UTC
| 1 |
2015-02-09 14:58:32.39 UTC
|
2008-09-24 15:56:06.167 UTC
|
Oli
| 12,870 | null | 17,002 | null | 1 | 8 |
mysql|database|recovery
| 39,980 |
<p>Documentation Sucks. It alludes to DROP DATABASE being recoverable, but only in odd conditions i'm not familiar with <a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/binary-log.html</a> </p>
<p>According to Docs, binlogs are just a sequence of commands executed based on a given reference point. So that when you did "DROP DATABASE", instead of going "Oh, hes droppping the database, we should back up now just in case" it merely wrote a "DROP DATABASE" to the last binlog. Recovery is not as simple as playing the tape backwards. </p>
<p>What you need to do is recover the database from a last-known-good, and apply the binlogs that happened between that recover point and the DROP command.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html</a></p>
<p>How one determines which binlogs to use tho, unclear. </p>
<p>There is nothing better than having full file system backups. And you should at least have these to fall back to.</p>
|
978,887 |
Why does WPF databinding swallow exceptions?
|
<p>I recently wasted a lot of time trying to debug a WPF datagrid (from the WPF Toolkit). I had a column bound to a linq query with a property that was throwing an exception (in a few rows). WPF seems to catch the exception and it just makes the cells blank. I have fixed the bug causing the exception, but I would like to change WPF's behavior. I always want to know if something is wrong. Why is swallowing the exception the default behavior and how can I change it?</p>
| 978,901 | 5 | 0 | null |
2009-06-11 01:23:40.9 UTC
| 9 |
2013-10-26 18:53:35.94 UTC
| null | null | null | null | 118,736 | null | 1 | 21 |
c#|.net|wpf|data-binding
| 4,832 |
<p>Databinding errors are swallowed natively, but they are displayed in the OUTPUT dialog in the visual studio interface. If you wish to be notified (and have as much control over it as possible), then you can use Trace Sources.</p>
<p>Bea Stollnitz provides a great writeup about this (and debuginng the bindings in general) here: <a href="http://www.beacosta.com/blog/?p=52" rel="nofollow noreferrer">http://www.beacosta.com/blog/?p=52</a></p>
<p>Apparently, this blog has departed, but we do have the WayBack Machine:
<a href="http://web.archive.org/web/20091103200557/http://www.beacosta.com/blog/?p=52" rel="nofollow noreferrer">http://web.archive.org/web/20091103200557/http://www.beacosta.com/blog/?p=52</a></p>
<p>I also added it to my Coding notebook for Evernote:
<a href="https://www.evernote.com/pub/view/sswrighton/coding/f9786746-94c3-41b5-bcd2-c12992d331a6?locale=en#st=p&n=f9786746-94c3-41b5-bcd2-c12992d331a6" rel="nofollow noreferrer">https://www.evernote.com/pub/view/sswrighton/coding/f9786746-94c3-41b5-bcd2-c12992d331a6?locale=en#st=p&n=f9786746-94c3-41b5-bcd2-c12992d331a6</a></p>
|
145,863 |
Best Java/Swing browser component?
|
<p>What's the best cross platform Java Swing browser component at least able to play nicely in a swing interface (lightweight component ?) and able to run on MacOSX and Windows ?</p>
<p>Things like : <a href="http://code.google.com/p/flying-saucer//" rel="noreferrer">FlyingSaucer</a>, <a href="https://jdic.dev.java.net/" rel="noreferrer">JDIC</a>, maybe others ?</p>
| 145,891 | 5 | 2 | null |
2008-09-28 13:45:56.92 UTC
| 11 |
2012-09-03 23:06:43.987 UTC
| null | null | null |
JeanLaurent
| 2,512 | null | 1 | 43 |
java|swing|browser
| 74,116 |
<p>i belive this could help:</p>
<p><a href="http://djproject.sourceforge.net/ns/index.html" rel="noreferrer">http://djproject.sourceforge.net/ns/index.html</a></p>
|
1,293,337 |
How can I test final and static methods of a utility project?
|
<p>I'm trying to implement unit testing for aproject, it uses a legacy "utility" project that is littered with static methods and many of the classes are final or their methods are final. I'm not able to update the legacy project at all.</p>
<p>JMock and EasyMock both choke on final methods, and I don't see a nice way to test the static calls. What techniques are there to test these?</p>
| 1,293,344 | 6 | 4 | null |
2009-08-18 11:41:56.037 UTC
| 5 |
2019-01-10 15:32:19.323 UTC
|
2009-08-18 11:56:06.163 UTC
| null | 148,419 | null | 148,419 | null | 1 | 27 |
java|junit
| 39,204 |
<p>If you're able to refactor your code, you can wrap your calls to the final/static methods in simple instance methods, for example:</p>
<pre><code>protected Foo doBar(String name) {
return Utility.doBar(name);
}
</code></pre>
<p>This allows you to override your wrapper method in the unit test to return a mock instance of Foo.</p>
<p>Alternatively you can use <a href="http://code.google.com/p/powermock/" rel="noreferrer">Powermock</a>, which extends Easymock (and Mockito) to allow mocking of final and static methods:</p>
<blockquote>
<p>PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.</p>
</blockquote>
<p>Here's an <a href="http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermock/junit4-test/src/test/java/samples/junit4/singleton/MockStaticTest.java" rel="noreferrer">example</a> test mocking a static final method, the example shows how to mock some other types too:</p>
<pre><code>@Test
public void testMockStaticFinal() throws Exception {
mockStatic(StaticService.class);
String expected = "Hello altered World";
expect(StaticService.sayFinal("hello")).andReturn("Hello altered World");
replay(StaticService.class);
String actual = StaticService.sayFinal("hello");
verify(StaticService.class);
assertEquals("Expected and actual did not match", expected, actual);
// Singleton still be mocked by now.
try {
StaticService.sayFinal("world");
fail("Should throw AssertionError!");
} catch (AssertionError e) {
assertEquals("\n Unexpected method call sayFinal(\"world\"):",
e.getMessage());
}
}
</code></pre>
|
1,209,469 |
storing android application data on SD Card
|
<p>Is there a way to store android application data on the SD card instead of in the internal memory?
I know how to transfer the application sqlite database from the internal memory to the SDCard, but what if the internal memory gets full in the first place? How does everyone handle this?</p>
| 1,209,573 | 6 | 0 | null |
2009-07-30 21:24:29.48 UTC
| 19 |
2013-03-07 00:28:15.023 UTC
|
2012-08-22 18:22:46.427 UTC
| null | 403,455 | null | 121,196 | null | 1 | 31 |
android|memory-management|android-sdcard
| 88,110 |
<p><strong>Warning:</strong> This answer is out-dated. You should use <a href="http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()" rel="nofollow noreferrer">Environment.getExternalStorageDirectory()</a> to get the root path of the SD card as mentioned in the answers below.</p>
<p>Old Answer so the comments on this make sense:</p>
<p>Adding <code>/sdcard/</code> to the root your path should direct your Android application to use the SD card (at least it works that way with the G1). Android's file system objects give you the ability to check file sizes... so it should be possible (if tricky) to write some fail-over code. This code would adjust your root path if the internal memory filled up.</p>
|
893,167 |
How to Remove ReadOnly Attribute on File Using PowerShell?
|
<p>How can I remove the ReadOnly attribute on a file, using a PowerShell (version 1.0) script?</p>
| 895,866 | 6 | 0 | null |
2009-05-21 14:20:31.59 UTC
| 13 |
2017-11-07 14:23:34.987 UTC
|
2013-10-15 08:51:27.767 UTC
| null | 206,730 | null | 35,483 | null | 1 | 102 |
powershell|powershell-1.0|scripting
| 79,521 |
<p>You can use <code>Set-ItemProperty</code>:</p>
<pre><code>Set-ItemProperty file.txt -name IsReadOnly -value $false
</code></pre>
<p>or shorter:</p>
<pre><code>sp file.txt IsReadOnly $false
</code></pre>
|
58,764,811 |
Object Oriented Programming - how to avoid duplication in processes that differ slightly depending on a variable
|
<p>Something that comes up quite a lot in my current work is that there is a generalised process that needs to happen, but then the odd part of that process needs to happen slightly differently depending on the value of a certain variable, and I'm not quite sure what's the most elegant way to handle this.</p>
<p>I'll use the example that we usually have, which is doing things slightly differently depending on the country we're dealing with.</p>
<p>So I have a class, let's call it <code>Processor</code>:</p>
<pre><code>public class Processor
{
public string Process(string country, string text)
{
text.Capitalise();
text.RemovePunctuation();
text.Replace("é", "e");
var split = text.Split(",");
string.Join("|", split);
}
}
</code></pre>
<p>Except that only some of those actions need to happen for certain countries. For example, only 6 countries require the capitalisation step. The character to split on might change depending on the country. Replacing the accented <code>'e'</code> might only be required depending on the country.</p>
<p>Obviously you could solve it by doing something like this:</p>
<pre><code>public string Process(string country, string text)
{
if (country == "USA" || country == "GBR")
{
text.Capitalise();
}
if (country == "DEU")
{
text.RemovePunctuation();
}
if (country != "FRA")
{
text.Replace("é", "e");
}
var separator = DetermineSeparator(country);
var split = text.Split(separator);
string.Join("|", split);
}
</code></pre>
<p>But when you're dealing with all the possible countries in the world, that becomes very cumbersome. And regardless, the <code>if</code> statements make the logic harder to read (at least, if you imagine a more complex method than the example), and the cyclomatic complexity starts to creep up pretty fast.</p>
<p>So at the moment I'm sort of doing something like this:</p>
<pre><code>public class Processor
{
CountrySpecificHandlerFactory handlerFactory;
public Processor(CountrySpecificHandlerFactory handlerFactory)
{
this.handlerFactory = handlerFactory;
}
public string Process(string country, string text)
{
var handlers = this.handlerFactory.CreateHandlers(country);
handlers.Capitalier.Capitalise(text);
handlers.PunctuationHandler.RemovePunctuation(text);
handlers.SpecialCharacterHandler.ReplaceSpecialCharacters(text);
var separator = handlers.SeparatorHandler.DetermineSeparator();
var split = text.Split(separator);
string.Join("|", split);
}
}
</code></pre>
<p>Handlers:</p>
<pre><code>public class CountrySpecificHandlerFactory
{
private static IDictionary<string, ICapitaliser> capitaliserDictionary
= new Dictionary<string, ICapitaliser>
{
{ "USA", new Capitaliser() },
{ "GBR", new Capitaliser() },
{ "FRA", new ThingThatDoesNotCapitaliseButImplementsICapitaliser() },
{ "DEU", new ThingThatDoesNotCapitaliseButImplementsICapitaliser() },
};
// Imagine the other dictionaries like this...
public CreateHandlers(string country)
{
return new CountrySpecificHandlers
{
Capitaliser = capitaliserDictionary[country],
PunctuationHanlder = punctuationDictionary[country],
// etc...
};
}
}
public class CountrySpecificHandlers
{
public ICapitaliser Capitaliser { get; private set; }
public IPunctuationHanlder PunctuationHanlder { get; private set; }
public ISpecialCharacterHandler SpecialCharacterHandler { get; private set; }
public ISeparatorHandler SeparatorHandler { get; private set; }
}
</code></pre>
<p>Which equally I'm not really sure I like. The logic is still somewhat obscured by all of the factory creation and you can't simply look at the original method and see what happens when a "GBR" process is executed, for example. You also end up creating a lot of classes (in more complex examples than this) in the style <code>GbrPunctuationHandler</code>, <code>UsaPunctuationHandler</code>, etc... which means that you have to look at several different classes to figure out all of the possible actions that could happen during punctuation handling. Obviously I don't want one giant class with a billion <code>if</code> statements, but equally 20 classes with slightly differing logic also feels clunky.</p>
<p>Basically I think I've got myself into some sort of OOP knot and don't quite know a good way of untangling it. I was wondering if there was a pattern out there that would help with this type of process?</p>
| 58,765,168 | 10 | 10 | null |
2019-11-08 10:30:41.943 UTC
| 9 |
2022-09-17 14:22:45.353 UTC
|
2022-09-17 14:22:45.353 UTC
| null | 7,132,550 | null | 2,257,227 | null | 1 | 64 |
c#|.net|oop
| 4,181 |
<p>I would suggest encapsulating all options in one class:</p>
<pre><code>public class ProcessOptions
{
public bool Capitalise { get; set; }
public bool RemovePunctuation { get; set; }
public bool Replace { get; set; }
public char ReplaceChar { get; set; }
public char ReplacementChar { get; set; }
public bool SplitAndJoin { get; set; }
public char JoinChar { get; set; }
public char SplitChar { get; set; }
}
</code></pre>
<p>and pass it into the <code>Process</code> method:</p>
<pre><code>public string Process(ProcessOptions options, string text)
{
if(options.Capitalise)
text.Capitalise();
if(options.RemovePunctuation)
text.RemovePunctuation();
if(options.Replace)
text.Replace(options.ReplaceChar, options.ReplacementChar);
if(options.SplitAndJoin)
{
var split = text.Split(options.SplitChar);
return string.Join(options.JoinChar, split);
}
return text;
}
</code></pre>
|
20,926,551 |
Recommended way of making React component/div draggable
|
<p>I want to make a draggable (that is, repositionable by mouse) React component, which seems to necessarily involve global state and scattered event handlers. I can do it the dirty way, with a global variable in my JS file, and could probably even wrap it in a nice closure interface, but I want to know if there's a way that meshes with React better.</p>
<p>Also, since I've never done this in raw JavaScript before, I'd like to see how an expert does it, to make sure I've got all the corner cases handled, especially as they relate to React.</p>
<p>Thanks.</p>
| 20,927,899 | 14 | 5 | null |
2014-01-04 20:46:40.397 UTC
| 84 |
2022-07-11 14:35:50.39 UTC
| null | null | null | null | 523,329 | null | 1 | 146 |
javascript|reactjs
| 211,824 |
<p>I should probably turn this into a blog post, but here's pretty solid example.</p>
<p>The comments should explain things pretty well, but let me know if you have questions.</p>
<p>And here's the fiddle to play with: <a href="http://jsfiddle.net/Af9Jt/2/" rel="noreferrer">http://jsfiddle.net/Af9Jt/2/</a></p>
<pre><code>var Draggable = React.createClass({
getDefaultProps: function () {
return {
// allow the initial position to be passed in as a prop
initialPos: {x: 0, y: 0}
}
},
getInitialState: function () {
return {
pos: this.props.initialPos,
dragging: false,
rel: null // position relative to the cursor
}
},
// we could get away with not having this (and just having the listeners on
// our div), but then the experience would be possibly be janky. If there's
// anything w/ a higher z-index that gets in the way, then you're toast,
// etc.
componentDidUpdate: function (props, state) {
if (this.state.dragging && !state.dragging) {
document.addEventListener('mousemove', this.onMouseMove)
document.addEventListener('mouseup', this.onMouseUp)
} else if (!this.state.dragging && state.dragging) {
document.removeEventListener('mousemove', this.onMouseMove)
document.removeEventListener('mouseup', this.onMouseUp)
}
},
// calculate relative position to the mouse and set dragging=true
onMouseDown: function (e) {
// only left mouse button
if (e.button !== 0) return
var pos = $(this.getDOMNode()).offset()
this.setState({
dragging: true,
rel: {
x: e.pageX - pos.left,
y: e.pageY - pos.top
}
})
e.stopPropagation()
e.preventDefault()
},
onMouseUp: function (e) {
this.setState({dragging: false})
e.stopPropagation()
e.preventDefault()
},
onMouseMove: function (e) {
if (!this.state.dragging) return
this.setState({
pos: {
x: e.pageX - this.state.rel.x,
y: e.pageY - this.state.rel.y
}
})
e.stopPropagation()
e.preventDefault()
},
render: function () {
// transferPropsTo will merge style & other props passed into our
// component to also be on the child DIV.
return this.transferPropsTo(React.DOM.div({
onMouseDown: this.onMouseDown,
style: {
left: this.state.pos.x + 'px',
top: this.state.pos.y + 'px'
}
}, this.props.children))
}
})
</code></pre>
<h2>Thoughts on state ownership, etc.</h2>
<p>"Who should own what state" is an important question to answer, right from the start. In the case of a "draggable" component, I could see a few different scenarios.</p>
<h3>Scenario 1</h3>
<p>the parent should own the current position of the draggable. In this case, the draggable would still own the "am I dragging" state, but would call <code>this.props.onChange(x, y)</code> whenever a mousemove event occurs. </p>
<h3>Scenario 2</h3>
<p>the parent only needs to own the "non-moving position", and so the draggable would own it's "dragging position" but onmouseup it would call <code>this.props.onChange(x, y)</code> and defer the final decision to the parent. If the parent doesn't like where the draggable ended up, it would just not update it's state, and the draggable would "snap back" to it's initial position before dragging.</p>
<h2>Mixin or component?</h2>
<p>@ssorallen pointed out that, because "draggable" is more an attribute than a thing in itself, it might serve better as a mixin. My experience with mixins is limited, so I haven't seen how they might help or get in the way in complicated situations. This might well be the best option.</p>
|
17,690,776 |
How to add pause to a Go program?
|
<p>When i ever execute a Go Console program it just executes in one second, I've been looking on Google, the Go website and Stackoverflow.</p>
<pre><code>import (
"fmt"
)
func main() {
fmt.Println()
}
</code></pre>
<p>It closes immediately when i execute it.</p>
<p>EDIT 2
actually i wanted the program to permanently stay paused untill the user presses a button</p>
| 17,690,896 | 4 | 0 | null |
2013-07-17 03:51:37.623 UTC
| 12 |
2020-10-26 03:23:26.457 UTC
|
2015-12-16 18:08:45.42 UTC
| null | 538,551 | null | 2,567,256 | null | 1 | 46 |
go
| 45,338 |
<p>You can pause the program for an arbitrarily long time by using <a href="http://golang.org/pkg/time/#example_Sleep"><code>time.Sleep()</code></a>. For example:</p>
<pre><code>package main
import ( "fmt"
"time"
)
func main() {
fmt.Println("Hello world!")
duration := time.Second
time.Sleep(duration)
}
</code></pre>
<p>To increase the duration arbitrarily you can do:</p>
<pre><code>duration := time.Duration(10)*time.Second // Pause for 10 seconds
</code></pre>
<p>EDIT: Since the OP added additional constraints to the question the answer above no longer fits the bill. You can pause until the <kbd>Enter</kbd> key is pressed by creating a new buffer reader which waits to read the newline (<code>\n</code>) character.</p>
<pre><code>package main
import ( "fmt"
"bufio"
"os"
)
func main() {
fmt.Println("Hello world!")
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
</code></pre>
|
21,104,702 |
Dereferencing a pointer to 0 in C
|
<p>Sometimes data at memory address 0x0 is quite valuable -- take x86 real mode IVT as a more known example: it starts at 0x0 and contains pointers to interrupt handlers: a dword at 0x00 is a pointer to division by zero error handler.</p>
<p>However, C11 language standard prohibits dereferencing null pointers <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">[WG14 N1570</a> 6.5.3.2], which are defined as pointers initialized with 0 or pointers initialized with a null pointer <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">[WG14 N1570</a> 6.3.2.3], effectively banning the very first byte.</p>
<p>How do people actually use 0x0 when it's needed?</p>
| 21,104,798 | 5 | 9 | null |
2014-01-14 01:42:53.12 UTC
| 10 |
2018-01-23 03:42:31.97 UTC
|
2014-01-14 06:14:04.223 UTC
| null | 527,702 | null | 3,192,369 | null | 1 | 55 |
c|pointers|memory|dereference
| 6,425 |
<p>C does not <em>prohibit</em> dereferencing the null pointer, it merely makes it undefined behavior.</p>
<p>If your environment is such that you're able to dereference a pointer containing the address <code>0x0</code>, then you should be able to do so. The C language standard says nothing about what will happen when you do so. (In most environments, the result will be a program crash.)</p>
<p>A concrete example (if I'm remembering this correctly): On the 68k-based Sun 3 computers, dereferencing a null pointer did not cause a trap; instead, the OS stored a zero value at memory address zero, and dereferencing a null pointer (which pointed to address zero) would yield that zero value. That meant, for example, that a C program could treat a null pointer as if it were a valid pointer to an empty string. Some software, intentionally or not, depended on this behavior. This required a great deal of cleanup when porting software to the SPARC-based Sun 4, which trapped on null pointer dereferences. (I distinctly remember reading about this, but I was unable to find a reference; I'll update this if I can find it.)</p>
<p>Note that the null pointer is <em>not</em> necessarily address zero. More precisely, the representation of a null may or may not be all-bits-zero. It very commonly is, but it's not guaranteed. (If it's not, then the integer-to-pointer conversion of <code>(void*)0</code> is non-trivial.)</p>
<p>Section 5 of the <a href="http://www.c-faq.com" rel="nofollow noreferrer">comp.lang.c FAQ</a> discusses null pointers.</p>
|
22,992,543 |
How do I git rebase the first commit?
|
<p>I used <code>git init</code> to create a fresh repo, then made three commits. Now I want to rebase to go back and amend my first commit, but if I do <code>git rebase -i HEAD~3</code> it complains! If I try the same with <code>HEAD~2</code> then it kinda works but only lets me rearrange the last two commits.</p>
<p>How do I refer to the 'commit before there were any commits' or go back and insert an empty commit?</p>
| 23,000,315 | 2 | 2 | null |
2014-04-10 15:35:09.797 UTC
| 68 |
2022-08-31 22:22:29.557 UTC
| null | null | null | null | 304,282 | null | 1 | 376 |
git|git-rebase
| 77,485 |
<p>The easy way, with a recent-enough Git (this has been out for a long time now so you should have this):</p>
<pre><code>git rebase -i --root
</code></pre>
<p>The other easy way, as <a href="https://stackoverflow.com/users/1253222/twalberg">twalberg</a> noted in a comment that has since been deleted but is now expanded in <a href="https://stackoverflow.com/a/68279810/1256452">https://stackoverflow.com/a/68279810/1256452's answer</a>, is to use <code>git checkout --orphan</code> to set up to make a new root commit, which you can copy the old commits on top of. (This is what <code>rebase -i --root</code> ends up doing internally anyway.) For some purposes, such as splitting what had been the initial commit, this initial blank commit is helpful.</p>
<p>Side note from the future (2022): It's often a good idea to make the very first commit contain just a few boilerplate files like a <code>README</code>. The very first commit in any new, empty repository is always a bit special. Note that if you use hosting sites like Bitbucket, GitHub, and GitLab, they will often make such an initial commit <em>for</em> you when you create a repository there, so that you can clone the repository thus created and have a starting point.</p>
|
2,208,926 |
How to speedup xcode builds without any project modifications?
|
<p>Last version or XCode (3.2.1) is running very slow on OS X 10.6.</p>
<p>What kinds of tweaks can you do to your Mac in order to <strong>speedup Xcode build</strong> process. </p>
<p>I'm not looking for general hints like how to restructure your projects, just tweaks that are related to environment. </p>
<p>For example I remember that on Windows for Visual Studio two significant speedups are to disable antivirus and NTFS last access time.</p>
<p>So I'm aiming at something <strong>else</strong> than: hardware upgrades, project structure modifications or configuring distributed builds.</p>
<p>Update #1 - maybe limiting the number of cc1plus processes could help speeding up. I think there is an environment variable that can be used for this but I wasn't able to relocate this info.</p>
| 2,209,790 | 5 | 0 | null |
2010-02-05 17:08:21.89 UTC
| 9 |
2011-11-16 15:24:54.217 UTC
|
2010-02-05 18:56:28.893 UTC
| null | 99,834 | null | 99,834 | null | 1 | 10 |
xcode|macos|performance|xcodebuild|xcode3.2
| 5,427 |
<p>I think I may got Xcode to build at decent speed with this command:</p>
<pre><code># Xcode 3.x
defaults write com.apple.Xcode PBXNumberOfParallelBuildSubtasks 4
# Xcode 4.x
defaults write com.apple.dt.Xcode IDEBuildOperationMaxNumberOfConcurrentCompileTasks 4
</code></pre>
<p>This will limit the number of processes executed when it does build. Before adding this to my machine (4 cores/3GB RAM) the build process was slower than on single core! </p>
<p>I think that XCode is not able to estimate the right limit of subtasks by itself because it does the estimate by looking only at your number of cores and ignoring the amount of RAM you have.</p>
|
1,714,761 |
Download a file programmatically on Android
|
<p>I am downloading files from web server programmatically. After download is completed, I checked the file. The size ,extension and all other parameters are correct but when I try to play that file in media player it is showing that it is corrupted.</p>
<p>Here is my code:</p>
<pre><code> byte[] b = null;
InputStream in = null;
b = new byte[Integer.parseInt(size)]; // size of the file.
in = OpenHttpConnection(URL);
in.read(b);
in.close();
File folder = new File("/sdcard", "folder");
boolean check = folder.mkdirs();
Log.d("HttpDownload", "check " + check);
File myFile = new File("/sdcard/folder/" + name);
myFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(myFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
</code></pre>
| 1,718,140 | 5 | 1 | null |
2009-11-11 12:00:19.873 UTC
| 23 |
2021-05-07 01:08:47.04 UTC
|
2017-07-03 18:07:50.013 UTC
| null | 1,033,581 | null | 152,867 | null | 1 | 34 |
android
| 93,658 |
<p>This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.</p>
<pre><code>private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
</code></pre>
|
1,349,740 |
Arguments in @selector
|
<p>Is there any way that I can pass arguments in selector?</p>
<p><strong>example:</strong>
I have this method</p>
<pre><code>- (void)myMethod:(NSString*)value1 setValue2:(NSString*)value2{
}
</code></pre>
<p>and I need to call this function through a selector passing two arguments.</p>
<pre><code>[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(/*my method*/) userInfo:nil repeats:YES];
</code></pre>
<p>How can I do this?</p>
| 1,349,800 | 5 | 0 | null |
2009-08-28 22:43:39.547 UTC
| 20 |
2013-07-19 14:34:45.793 UTC
|
2011-07-05 06:21:01.39 UTC
| null | 147,019 | null | 162,266 | null | 1 | 35 |
iphone|cocoa|cocoa-touch
| 30,703 |
<p>You could use the <code>NSTimer</code> method:</p>
<pre><code>+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
invocation:(NSInvocation *)invocation
repeats:(BOOL)repeats;
</code></pre>
<p>Instead, since an <code>NSInvocation</code> object will allow you to pass arguments; an <code>NSInvocation</code> object is, as the <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSInvocation_Class/Reference/Reference.html" rel="noreferrer">docs</a> define it:</p>
<blockquote>
<p>an Objective-C message rendered static, that is, it is an action turned into an object.</p>
</blockquote>
<p>Whilst creating an <code>NSTimer</code> object using a selector requires the format of the method being:</p>
<pre><code>- (void)timerFireMethod:(NSTimer*)theTimer
</code></pre>
<p>An <code>NSInvocation</code> allows you to set the target, the selector, and the arguments that you pass in:</p>
<pre><code>SEL selector = @selector(myMethod:setValue2:);
NSMethodSignature *signature = [MyObject instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
NSString *str1 = @"someString";
NSString *str2 = @"someOtherString";
//The invocation object must retain its arguments
[str1 retain];
[str2 retain];
//Set the arguments
[invocation setTarget:targetInstance];
[invocation setArgument:&str1 atIndex:2];
[invocation setArgument:&str2 atIndex:3];
[NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:YES];
</code></pre>
<p>Where <code>MyObject</code> is the class that <code>myMethod:setValue2:</code> is declared and implemented on – <code>instanceMethodSignatureForSelector:</code> is a convenience function declared on <code>NSObject</code> which returns an <code>NSMethodSignature</code> object for you, to be passed to <code>NSInvocation</code>.</p>
<p>Also, to note, with <code>setArgument:atIndex:</code>, the indices for arguments to be passed to the method set as the selector start at index 2. From the docs:</p>
<blockquote>
<p>Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message.</p>
</blockquote>
|
2,269,307 |
using jquery $.ajax to call a PHP function
|
<p>This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript. </p>
<pre><code><?php
if(isset($_POST['something'] {
//do something
}
?>
</code></pre>
<p>to this</p>
<pre><code><?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
</code></pre>
<p>How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed. </p>
| 2,269,397 | 6 | 5 | null |
2010-02-15 22:15:57.557 UTC
| 67 |
2018-05-20 15:04:08.613 UTC
|
2018-03-16 10:39:29.747 UTC
| null | 917,802 | null | 222,403 | null | 1 | 119 |
php|jquery|ajax
| 406,640 |
<p>Use <code>$.ajax</code> to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:</p>
<pre><code>$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</code></pre>
<p>On the server side, the <code>action</code> POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:</p>
<pre><code>if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
</code></pre>
<p>I believe that's a simple incarnation of the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="noreferrer">Command pattern</a>.</p>
|
1,410,172 |
Testing for multiple exceptions with JUnit 4 annotations
|
<p>Is it possible to test for multiple exceptions in a single JUnit unit test? I know for a single exception one can use, for example</p>
<pre><code> @Test(expected=IllegalStateException.class)
</code></pre>
<p>Now, if I want to test for another exception (say, NullPointerException), can this be done in the same annotation, a different annotation or do I need to write another unit test completely?</p>
| 1,410,254 | 7 | 1 | null |
2009-09-11 10:30:07.973 UTC
| 5 |
2021-02-26 04:24:26.327 UTC
| null | null | null | null | 171,993 | null | 1 | 27 |
java|junit|exception
| 55,782 |
<p>You really want the test to do <em>one</em> thing, and to test for that. If you're not sure as to which exception is going to be thrown, that doesn't sound like a good test to me.</p>
<p>e.g. (in pseudo-code)</p>
<pre><code>try {
badOperation();
/// looks like we succeeded. Not good! Fail the test
fail();
}
catch (ExpectedException e) {
// that's fine
}
catch (UnexpectedException e) {
// that's NOT fine. Fail the test
}
</code></pre>
<p>so if you want to test that your method throws 2 different exceptions (for 2 sets of inputs), then you'll need 2 tests.</p>
|
2,016,513 |
does continue work in a do while?
|
<p>I have a do while that looks like:</p>
<pre><code>User user = userDao.Get(1);
do
{
// processing
// get the next user
//
user = UserDao.GetNext(user.Id);
if(user == null)
continue; // will this work?????????????
}
while ( user != null)
</code></pre>
<p>If it does work, its going to go to the top of the do statement, and user is null so things are going to break?</p>
<p>Maybe I should rework the loop to a while statement?</p>
| 2,016,563 | 7 | 6 | null |
2010-01-06 21:47:27.913 UTC
| 3 |
2017-06-15 00:46:38.807 UTC
|
2010-01-06 21:50:15.003 UTC
| null | 65,295 | null | 68,183 | null | 1 | 29 |
java|loops|do-while
| 39,188 |
<p>The continue makes it jump to the evaluation at the botton so the program can evaluate if it has to continue with another iteration or exit. In this case it will exit.</p>
<p>This is the specification: <a href="http://java.sun.com/docs/books/jls/third_edition/html/statements.html#6045" rel="noreferrer">http://java.sun.com/docs/books/jls/third_edition/html/statements.html#6045</a></p>
<p>Such language questions you can search it in the Java Language Specification: <a href="http://java.sun.com/docs/books/jls/" rel="noreferrer">http://java.sun.com/docs/books/jls/</a></p>
|
1,490,821 |
What's the best way to get the current URL in Spring MVC?
|
<p>I'd like to create URLs based on the URL used by the client for the active request. Is there anything smarter than taking the current <code>HttpServletRequest</code> object and it's <code>getParameter...()</code> methods to rebuilt the complete URL including (and only) it's GET parameters.</p>
<p><strong>Clarification: If possible I want to resign from using a <code>HttpServletRequest</code> object.</strong></p>
| 1,490,991 | 7 | 0 | null |
2009-09-29 06:08:43.62 UTC
| 28 |
2021-05-26 01:34:46.693 UTC
|
2018-12-27 10:01:57.9 UTC
| null | 4,516,110 | null | 81,071 | null | 1 | 118 |
url|spring-mvc|httprequest
| 203,025 |
<p>Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:</p>
<pre><code>public static String makeUrl(HttpServletRequest request)
{
return request.getRequestURL().toString() + "?" + request.getQueryString();
}
</code></pre>
<p>I don't know about a way to do this with any Spring MVC facilities.</p>
<p>If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:</p>
<pre><code><listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</code></pre>
<p>And then use this to get the request bound to the current Thread:</p>
<pre><code>((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
</code></pre>
|
1,657,282 |
How to remove numbers from string using Regex.Replace?
|
<p>I need to use <code>Regex.Replace</code> to remove all numbers and signs from a string.</p>
<p>Example input: <code>123- abcd33</code><br>
Example output: <code>abcd</code></p>
| 1,657,288 | 8 | 1 | null |
2009-11-01 14:21:31.503 UTC
| 5 |
2022-01-09 02:32:08.223 UTC
|
2019-03-19 08:55:21.327 UTC
| null | 3,885,376 | null | 43,907 | null | 1 | 82 |
c#|regex
| 147,626 |
<p>Try the following:</p>
<pre><code>var output = Regex.Replace(input, @"[\d-]", string.Empty);
</code></pre>
<p>The <code>\d</code> identifier simply matches any digit character.</p>
|
2,310,498 |
Why doesn't String's hashCode() cache 0?
|
<p>I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet:</p>
<pre><code>public class Main{
static void test(String s) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
s.hashCode();
}
System.out.format("Took %d ms.%n", System.currentTimeMillis() - start);
}
public static void main(String[] args) {
String z = "Allocator redistricts; strict allocator redistricts strictly.";
test(z);
test(z.toUpperCase());
}
}
</code></pre>
<p><a href="https://web.archive.org/web/20000000000000/http://www.ideone.com/Ho9lfOKy" rel="noreferrer">Running this in ideone.com</a> gives the following output:</p>
<pre><code>Took 1470 ms.
Took 58 ms.
</code></pre>
<p>So my questions are:</p>
<ul>
<li>Why doesn't String's hashCode() cache 0?</li>
<li>What is the probability that a Java string hashes to 0?</li>
<li>What's the best way to avoid the performance penalty of recomputing the hash value every time for strings that hash to 0?</li>
<li>Is this the best-practice way of caching values? (i.e. cache all except one?)</li>
</ul>
<hr>
<p>For your amusement, each line here is a string that hash to 0:</p>
<pre><code>pollinating sandboxes
amusement & hemophilias
schoolworks = perversive
electrolysissweeteners.net
constitutionalunstableness.net
grinnerslaphappier.org
BLEACHINGFEMININELY.NET
WWW.BUMRACEGOERS.ORG
WWW.RACCOONPRUDENTIALS.NET
Microcomputers: the unredeemed lollipop...
Incentively, my dear, I don't tessellate a derangement.
A person who never yodelled an apology, never preened vocalizing transsexuals.
</code></pre>
| 2,313,224 | 9 | 2 | null |
2010-02-22 11:20:12.76 UTC
| 22 |
2020-09-26 22:11:03.19 UTC
|
2018-10-08 17:11:27.243 UTC
| null | 1,033,581 | null | 276,101 | null | 1 | 77 |
java|string|hashcode
| 12,360 |
<p>You're worrying about nothing. Here's a way to think about this issue.</p>
<p>Suppose you have an application that does nothing but sit around hashing Strings all year long. Let's say it takes a thousand strings, all in memory, calls hashCode() on them repeatedly in round-robin fashion, a million times through, then gets another thousand new strings and does it again.</p>
<p>And suppose that the likelihood of a string's hash code being zero were, in fact, much greater than 1/2^32. I'm sure it is <em>somewhat</em> greater than 1/2^32, but let's say it's a lot worse than that, like 1/2^16 (the square root! now that's a lot worse!).</p>
<p>In this situation, you have more to benefit from Oracle's engineers improving how these strings' hash codes are cached than anyone else alive. So you write to them and ask them to fix it. And they work their magic so that whenever s.hashCode() is zero, it returns <em>instantaneously</em> (even the first time! a 100% improvement!). And let's say that they do this without degrading the performance at all for any other case.</p>
<p>Hooray! Now your app is... let's see... 0.0015% faster!</p>
<p>What used to take an entire day now takes only 23 hours, 57 minutes and 48 seconds!</p>
<p>And remember, we set up the scenario to give every possible benefit of the doubt, often to a ludicrous degree.</p>
<p>Does this seem worth it to you?</p>
<p><strong>EDIT:</strong> since posting this a couple hours ago, I've let one of my processors run wild looking for two-word phrases with zero hash codes. So far it's come up with: bequirtle zorillo, chronogrammic schtoff, contusive cloisterlike, creashaks organzine, drumwood boulderhead, electroanalytic exercisable, and favosely nonconstruable. This is out of about 2^35 possibilities, so with perfect distribution we'd expect to see only 8. Clearly by the time it's done we'll have a few times that many, but not outlandishly more. What's more significant is that I've now come up with a few interesting band names/album names! No fair stealing!</p>
|
1,693,041 |
How to stop a java application?
|
<p>I have made a java application and have packed it into an executable jar file. Now a user can start that program from either of the following two ways:</p>
<ol>
<li><p>Start if from command prompt by executing the following command on the command prompt:</p>
<p>java -jar "MyJar.jar"</p></li>
<li><p>By double clicking on that jar file.</p></li>
</ol>
<p>I want that my client would adopt second approach as it is much easier than the first approach. But the problem with second approach is how to stop application before it has finished?</p>
<p>It is a command-line application.</p>
<p>And no command prompt window appears when a user double clicks on the jar file. So in this case, Will Ctrl + c work?</p>
| 1,693,193 | 10 | 0 | null |
2009-11-07 13:35:40.573 UTC
| 4 |
2013-07-29 06:58:31.487 UTC
|
2009-11-07 13:46:37.93 UTC
| null | 157,027 | null | 157,027 | null | 1 | 4 |
java
| 59,352 |
<p>Stopping (exiting) the application should be inside the application. Whether it is command line or GUI based, the application developer should write code to exit it (For eg., in a command line application you might have something like <code>Press 5 to exit</code>, <code>Press Esc to Exit</code> etc) and in an application with a GUI, you will have to write code to exit when the window is closed, or an <code>EXIT</code> button (or others, depending on your application)</p>
<p><code>Ctrl + C</code> is KILL the application. This is <em>not</em> a Normal exit. For apps with a GUI, the user would typically (in Windows) go to task manager and end the process (similar ways in other operating systems)</p>
<p>But these are abnormal exits - when the user wants to kill the app when, for instance, the application is no longer responding. Normal exits should be provided by the application (and therefore by the programmer - you)</p>
|
1,857,822 |
Unique model field in Django and case sensitivity (postgres)
|
<p>Consider the following situation: -</p>
<p>Suppose my app allows users to create the states / provinces in their
country. Just for clarity, we are considering only ASCII characters
here.</p>
<p>In the US, a user could create the state called "Texas". If this app
is being used internally, let's say the user doesn't care if it is
spelled "texas" or "Texas" or "teXas"</p>
<p>But importantly, the system should prevent creation of "texas" if
"Texas" is already in the database.</p>
<p>If the model is like the following:</p>
<pre><code>class State(models.Model):
name = models.CharField(max_length=50, unique=True)
</code></pre>
<p>The uniqueness would be case-sensitive in postgres; that is, postgres
would allow the user to create both "texas" and "Texas" as they are
considered unique.</p>
<p>What can be done in this situation to prevent such behavior. How does
one go about providing case-<strong>insenstitive</strong> uniqueness with Django and
Postgres </p>
<p>Right now I'm doing the following to prevent creation of case-
insensitive duplicates.</p>
<pre><code>class CreateStateForm(forms.ModelForm):
def clean_name(self):
name = self.cleaned_data['name']
try:
State.objects.get(name__iexact=name)
except ObjectDoesNotExist:
return name
raise forms.ValidationError('State already exists.')
class Meta:
model = State
</code></pre>
<p>There are a number of cases where I will have to do this check and I'm not keen on having to write similar iexact checks everywhere.</p>
<p>Just wondering if there is a built-in or
better way? Perhaps db_type would help? Maybe some other solution exists?</p>
| 1,905,928 | 10 | 4 | null |
2009-12-07 04:31:16.217 UTC
| 11 |
2018-10-27 16:03:16.127 UTC
| null | null | null | null | 46,928 | null | 1 | 31 |
django|postgresql|django-models|unique
| 13,489 |
<p>You could define a custom model field derived from <code>models.CharField</code>.
This field could check for duplicate values, ignoring the case.</p>
<p>Custom fields documentation is here <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/" rel="noreferrer">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/</a></p>
<p>Look at <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py</a> for an example of how to create a custom field by subclassing an existing field.</p>
<p>You could use the citext module of PostgreSQL <a href="https://www.postgresql.org/docs/current/static/citext.html" rel="noreferrer">https://www.postgresql.org/docs/current/static/citext.html</a></p>
<p>If you use this module, the the custom field could define "db_type" as CITEXT for PostgreSQL databases.</p>
<p>This would lead to case insensitive comparison for unique values in the custom field.</p>
|
1,369,361 |
How can I programmatically create, read, write an excel without having office installed?
|
<p>I'm confused as hell with all the bazillion ways to read/write/create excel files. VSTO, OLEDB, etc, but they all <em>seem</em> to have the requirement that office must be installed.</p>
<p>Here is my situation: I need to develop an app which will take an excel file as input, do some calculations and create a new excel file which will basically be a modification of the first excel file. All with the constraint that the machine that runs this may not have office installed. (Don't ask why...)</p>
<p>I need to support <em>all</em> excel formats. The only saving grace is that the formats spreadsheets themselves are really simple. Just a bunch of columns and values, nothing fancy. And unfortunately no CSV as the end user might not even know what a CSV file is.</p>
| 1,369,413 | 11 | 7 | null |
2009-09-02 18:24:54.093 UTC
| 9 |
2017-08-18 17:09:41.343 UTC
|
2017-04-15 18:48:45.617 UTC
| null | 1,033,581 | null | 750 | null | 1 | 31 |
c#|excel
| 16,461 |
<p>write your excel in HTML table format:</p>
<pre><code><html>
<body>
<table>
<tr>
<td style="background-color:#acc3ff">Cell1</td>
<td style="font-weight:bold">Cell2</td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>and give your file an xls extension. Excel will convert it automatically</p>
|
2,323,292 |
Assign output of a program to a variable using a MS batch file
|
<p>I need to assign the output of a program to a variable using a MS batch file.</p>
<p>So in GNU Bash shell I would use <code>VAR=$(application arg0 arg1)</code>. I need a similar behavior in Windows using a batch file.</p>
<p>Something like <code>set VAR=application arg0 arg1</code>.</p>
<h3>Similar Questions</h3>
<ul>
<li><a href="https://stackoverflow.com/q/6359820/">How to set commands output as a variable in a batch file</a></li>
<li><a href="https://stackoverflow.com/q/108439/">How do I get the result of a command in a variable in windows?</a></li>
<li><a href="https://stackoverflow.com/q/889518/">Set the value of a variable with the result of a command in a Windows batch file</a></li>
<li><a href="https://stackoverflow.com/q/14952295/">Set output of a command as a variable (with pipes)</a></li>
<li><a href="https://stackoverflow.com/q/16203629/">Assign command output to variable in batch file</a></li>
</ul>
| 2,340,018 | 11 | 0 | null |
2010-02-24 02:33:31.61 UTC
| 93 |
2022-08-28 17:59:18.727 UTC
|
2022-05-24 16:09:41.987 UTC
| null | 1,366,033 | null | 193,315 | null | 1 | 341 |
batch-file|cmd|variable-assignment|windows-console
| 383,829 |
<p>One way is:</p>
<pre><code>application arg0 arg1 > temp.txt
set /p VAR=<temp.txt
</code></pre>
<p>Another is:</p>
<pre><code>for /f %%i in ('application arg0 arg1') do set VAR=%%i
</code></pre>
<p>Note that the first <code>%</code> in <code>%%i</code> is used to escape the <code>%</code> after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your <code>test.bat</code> has something like:</p>
<pre><code>for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%
</code></pre>
|
1,568,057 |
ASCII strings and endianness
|
<p>An intern who works with me showed me an exam he had taken in computer science about endianness issues. There was a question that showed an ASCII string "My-Pizza", and the student had to show how that string would be represented in memory on a little endian computer. Of course, this sounds like a trick question because ASCII strings are not affected by endian issues.</p>
<p>But shockingly, the intern claims his professor insists that the string would be represented as:</p>
<pre><code>P-yM azzi
</code></pre>
<p>I know this can't be right. There is no way an ASCII string would be represented like that on any machine. But apparently, the professor is insisting on this. So, I wrote up a small C program and told the intern to give it to his professor.</p>
<pre><code>#include <string.h>
#include <stdio.h>
int main()
{
const char* s = "My-Pizza";
size_t length = strlen(s);
for (const char* it = s; it < s + length; ++it) {
printf("%p : %c\n", it, *it);
}
}
</code></pre>
<p>This clearly demonstrates that the string is stored as "My-Pizza" in memory. A day later, the intern gets back to me and tells me the professor is now claiming that C is automagically converting the addresses to display the string in proper order.</p>
<p>I told him his professor is insane, and this is clearly wrong. But just to check my own sanity here, I decided to post this on stackoverflow so I could get others to confirm what I'm saying. </p>
<p>So, I ask : who is right here?</p>
| 1,568,113 | 12 | 16 | null |
2009-10-14 18:12:50.657 UTC
| 23 |
2019-08-24 00:36:32.833 UTC
|
2009-10-15 05:13:06.417 UTC
| null | 57,428 | null | 168,288 | null | 1 | 50 |
c|ascii|endianness
| 30,955 |
<p>Without a doubt, you are correct.</p>
<p>ANSI C standard 6.1.4 specifies that string literals are stored in memory by "concatenating" the characters in the literal.</p>
<p>ANSI standard 6.3.6 also specifies the effect of addition on a pointer value:</p>
<blockquote>
<p>When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression.</p>
</blockquote>
<p>If the idea attributed to this person were correct, then the compiler would also have to monkey around with integer math when the integers are used as array indices. Many other fallacies would also result which are left to the imagination.</p>
<p>The person may be confused, because (unlike a string initializer), multi-byte chacter constants such as 'ABCD' <em>are</em> stored in endian order.</p>
<p>There are many reasons a person might be confused about this. As others have suggested here, he may be misreading what he sees in a debugger window, where the contents have been byte-swapped for readability of int values.</p>
|
2,169,732 |
Most efficient solution for reading CLOB to String, and String to CLOB in Java?
|
<p>I have a big CLOB (more than 32kB) that I want to read to a String, using StringBuilder. How do I do this in the most efficient way? I can not use the "int length" constructor for StringBuilder since the lenght of my CLOB is longer than a "int" and needs a "long" value.</p>
<p>I am not that confortable with the Java I/O classes, and would like to get some guidance.</p>
<p><b>Edit</b> - <i>I have tried with this code for clobToString():</i></p>
<pre><code>private String clobToString(Clob data) {
StringBuilder sb = new StringBuilder();
try {
Reader reader = data.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String line;
while(null != (line = br.readLine())) {
sb.append(line);
}
br.close();
} catch (SQLException e) {
// handle this exception
} catch (IOException e) {
// handle this exception
}
return sb.toString();
}
</code></pre>
| 2,171,455 | 12 | 9 | null |
2010-01-30 22:36:54.59 UTC
| 12 |
2021-01-12 17:57:06.157 UTC
|
2010-01-30 22:58:35.617 UTC
| null | 213,269 | null | 213,269 | null | 1 | 54 |
java|stringbuilder|clob
| 178,592 |
<blockquote>
<p>I can not use the "int length" constructor for <code>StringBuilder</code> since the length of my CLOB is longer than a <code>int</code> and needs a <code>long</code> value.</p>
</blockquote>
<p>If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.</p>
<p>If the actual length of the CLOB is smaller than <code>Integer.MAX_VALUE</code>, just force the <code>long</code> to <code>int</code> by putting <code>(int)</code> in front of it.</p>
|
1,561,554 |
Cocoa-Touch: How do I see if two NSDates are in the same day?
|
<p>I need to know if two NSDate instances are both from the same day.</p>
<p>Is there an easier/better way to do it than getting the NSDateComponents and comparing day/month/year?</p>
| 1,561,593 | 12 | 1 | null |
2009-10-13 16:59:12.277 UTC
| 9 |
2017-03-17 20:05:13.48 UTC
|
2015-04-26 00:48:34.703 UTC
| null | 1,693,173 | null | 21,240 | null | 1 | 67 |
ios|objective-c|macos|cocoa-touch
| 22,044 |
<p>NSDateComponents sounds like the best bet to me. Another tactic to try is toll-free-bridging it to a CFDate, then using CFDateGetAbsoluteTime and doing a subtraction to get the amount of time between the two dates. You'll have to do some additional math to figure out if the time difference lands the dates on the same day, however.</p>
|
1,899,072 |
Getting a list of folders in a directory
|
<p>How do I get a list of the folders that exist in a certain directory with ruby?</p>
<p><code>Dir.entries()</code> looks close but I don't know how to limit to folders only.</p>
| 1,899,164 | 13 | 0 | null |
2009-12-14 05:26:06.323 UTC
| 12 |
2020-05-14 07:31:27.557 UTC
|
2009-12-14 06:11:46.62 UTC
| null | 39,892 | null | 126,163 | null | 1 | 95 |
ruby|directory|directory-listing
| 68,329 |
<p>Jordan is close, but <code>Dir.entries</code> doesn't return the full path that <code>File.directory?</code> expects. Try this:</p>
<pre><code> Dir.entries('/your_dir').select {|entry| File.directory? File.join('/your_dir',entry) and !(entry =='.' || entry == '..') }
</code></pre>
|
1,976,007 |
What characters are forbidden in Windows and Linux directory names?
|
<p>I know that <code>/</code> is illegal in Linux, and the following are illegal in Windows
(I think) <code>*</code> <code>.</code> <code>"</code> <code>/</code> <code>\</code> <code>[</code> <code>]</code> <code>:</code> <code>;</code> <code>|</code> <code>,</code></p>
<p>What else am I missing?</p>
<p>I need a comprehensive guide, however, and one that takes into account
double-byte characters. Linking to outside resources is fine with me.</p>
<p>I need to first create a directory on the filesystem using a name that may
contain forbidden characters, so I plan to replace those characters with
underscores. I then need to write this directory and its contents to a zip file
(using Java), so any additional advice concerning the names of zip directories
would be appreciated.</p>
| 1,976,050 | 19 | 13 | null |
2009-12-29 18:11:36.49 UTC
| 170 |
2022-07-03 01:28:00.653 UTC
|
2021-04-29 02:28:58.807 UTC
| null | 1,832,568 | null | 33,775 | null | 1 | 538 |
windows|linux|directory|zip|filenames
| 587,684 |
<p>A “comprehensive guide” of forbidden filename characters is not going to work on Windows because it reserves filenames as well as characters. Yes, characters like
<code>*</code> <code>"</code> <code>?</code> and others are forbidden, but there are a infinite number of names composed only of valid characters that are forbidden. For example, spaces and dots are valid filename characters, but names composed only of those characters are forbidden.</p>
<p>Windows does not distinguish between upper-case and lower-case characters, so you cannot create a folder named <code>A</code> if one named <code>a</code> already exists. Worse, seemingly-allowed names like <code>PRN</code> and <code>CON</code>, and many others, are reserved and not allowed. Windows also has several length restrictions; a filename valid in one folder may become invalid if moved to another folder. The rules for
<a href="https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file" rel="noreferrer">naming files and folders</a>
are on the Microsoft docs.</p>
<p>You cannot, in general, use user-generated text to create Windows directory names. If you want to allow users to name anything they want, you have to create safe names like <code>A</code>, <code>AB</code>, <code>A2</code> et al., store user-generated names and their path equivalents in an application data file, and perform path mapping in your application.</p>
<p>If you absolutely must allow user-generated folder names, the only way to tell if they are invalid is to catch exceptions and assume the name is invalid. Even that is fraught with peril, as the exceptions thrown for denied access, offline drives, and out of drive space overlap with those that can be thrown for invalid names. You are opening up one huge can of hurt.</p>
|
33,811,041 |
Javascript: Zoom in on mouseover WITHOUT Jquery or plugins
|
<p>I've looked for this everywhere for weeks, and I simply cannot find something to tell me what I'm doing wrong or how to even proceed. The goal is to create a function similar to Amazon's zoom in on mouseover for products with small images.</p>
<p>I'm currently at a loss for how to proceed, though I am aware that I will require two images- one in the "zoomed in" size and one in the "zoomed out" size. <strong>I'm not using Jquery</strong>- I cannot install it or any plugins to the website via my employer's request. I'm basically asking for the harder answer, and I apologize for that in advance. I must do this from moderate scratch. <strong>Warning</strong>: I am a programming Student. Take that as you will.</p>
<p>I've got HTML and CSS script, and because we don't actually have an IDE here I'm doing this on codecademy's project section, otherwise I'd have to program this completely live. You can find my code <a href="https://www.codecademy.com/kitfoxpup/codebits/9RPoQ1" rel="noreferrer">here</a>, but I'll also post the code below, as that link is bound to have changing code since it uses procedural saving.</p>
<p>Note: I originally had it so that the gray box was following my mouse at relative center. It was flickering as it moved, but it was working. Currently though it's decided not to, at least on my work computer. I've not tested it on my personal computer.</p>
<p>Edit: The code is working on my Surface Pro 3, though it does follow the mouse off of the image (which is temporary and something random I grabbed). I'm not sure why the code isn't working on my work computer, though it's probable because it's a Macintosh OSX version 10.6.8...</p>
<p><strong>HTML Code</strong>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src='script.js'></script>
</head>
<body>
<img id="imgZoom" onmousemove="zoomIn()" onmouseout="zoomOut()" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg">
<div id="overlay" onmousemove="zoomIn()"></div>
</body>
</html>
</code></pre>
<p><strong>CSS Code</strong>:</p>
<pre><code>#imgZoom {
height: 300;
}
#overlay {
visibility: hidden;
position: absolute;
left: 0px;
top: 0px;
width:20%;
height:20%;
padding: 25px;
border: 5px solid gray;
background-color: white;
opacity:0.4;
text-align:center;
z-index: 1000;
}
</code></pre>
<p><strong>Javascript code</strong>:</p>
<pre><code>function zoomIn()
{
var element = document.getElementById("overlay");
element.style.visibility = "visible";
var x = event.clientX; // Get the horizontal coordinate
var y = event.clientY; // Get the vertical coordinate
element.style.top = y - 80;
element.style.left = x - 80;
}
function zoomOut()
{
var element = document.getElementById("overlay");
element.style.visibility = "hidden";
}
</code></pre>
| 33,811,884 | 4 | 4 | null |
2015-11-19 17:56:05.413 UTC
| 9 |
2021-03-31 19:19:03.17 UTC
|
2015-11-19 18:04:00.68 UTC
| null | 5,162,489 | null | 5,162,489 | null | 1 | 21 |
javascript|html|css|zooming|mouseover
| 59,779 |
<p>you can just do it by playing background-position on mouse-over just moving background-position on mouseover <a href="http://codepen.io/anon/pen/NGJJeB" rel="nofollow noreferrer">DEMO</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function zoomIn(event) {
var element = document.getElementById("overlay");
element.style.display = "inline-block";
var img = document.getElementById("imgZoom");
var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
element.style.backgroundPosition = (-posX * 4) + "px " + (-posY * 4) + "px";
}
function zoomOut() {
var element = document.getElementById("overlay");
element.style.display = "none";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#overlay {
border: 1px solid black;
width: 200px;
height: 200px;
display: inline-block;
background-image: url('https://via.placeholder.com/400.png');
background-repeat: no-repeat;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="https://via.placeholder.com/200.png">
<div id="overlay" onmousemove="zoomIn(event)"></div></code></pre>
</div>
</div>
</p>
|
8,486,165 |
What can cause a persistent "Reload the page to get source for" error in firebug?
|
<p>I'm trying to debug the javascript of a specific page, and I keep seeing</p>
<p><code>Reload the page to get source for page.htm</code> in Firebug.</p>
<p>On Chrome, I'm mostly able to debug the js, but sometimes I also get a blank page. What can cause such issues? </p>
<p>I believe I always see a blank page in Chrome if I reload while the JS console is open. If I open a new Chrome tab, load the page, and then open the JS console, everything is ok.</p>
<p>The page I'm debugging is on a localhost server (Play Framework server), although I have seen this on other pages occasionally. This only happens with inline javascript ... js that is linked from the page is displayed fine.</p>
| 11,252,883 | 10 | 2 | null |
2011-12-13 08:23:31.657 UTC
| 3 |
2014-02-06 07:20:31.453 UTC
| null | null | null | null | 11,236 | null | 1 | 24 |
javascript|firefox|firebug
| 44,900 |
<p>With firebug icon, you'll see a dropdown arrow. Click that arrow to open up the drop down menu.</p>
<p><img src="https://i.stack.imgur.com/fbdNu.png" alt="enter image description here"></p>
<p>Click <strong>Clear Activation List.</strong></p>
<p>Refresh the page now.</p>
<p>Now under script tab you'd see the Reload link. Click that to reload the page again.
This time when the page reloads, you'd see the script.</p>
|
6,736,189 |
How to Add "Write a Review" / "Rate Us" Feature to My App?
|
<p>I wish to add some sort of a "Write a Review" or "Rate Us" feature to my app so my customers can easily rate and review my app.</p>
<p>Best practice I can think of is to have some sort of pop-up or open a UIWebView within my app so the user is not kicked off of my app while opening the App Store application as done in:</p>
<p><strong>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.com/apps/myAppName"]];</strong> </p>
<p>Does anyone knows of a way to do that?</p>
| 10,263,602 | 3 | 2 | null |
2011-07-18 16:33:20.327 UTC
| 29 |
2022-04-07 12:29:32.433 UTC
|
2022-04-07 12:29:32.433 UTC
| null | 1,839,439 | null | 1,143,060 | null | 1 | 39 |
ios|uiwebview|popup|review
| 41,312 |
<h1>StoreKit API (iOS 10.3 and up)</h1>
<p>As of iOS 10.3, the StoreKit API provides a way to request a review on the App Store without leaving your app. When called, the system may present the user with an alert that requests a review. The user may provide a star rating directly inside the alert, continue on to write a review, or dismiss the alert. StoreKit handles just about everything for you. To present the review request, make the following call where it is appropriate in your app:</p>
<pre><code>// Objective-C
[SKStoreReviewController requestReview]
// Swift
SKStoreReviewController.requestReview()
</code></pre>
<p>As per Apple's instructions, you should not call these in response to a direct user-interaction (i.e. tapping a button that says "Write a Review") because it may not always display the alert. Indeed, the alert may only be displayed three times every 365 days.</p>
<blockquote>
<p><strong>Important Note</strong>: Although this seems fairly simple, you'll still need to write some kind of logic in order to space out your prompts. For example, to present the prompt only after X number of launches, days, or significant events. </p>
<p>If you fail to do this and just stick the review prompt anywhere (a <code>viewDidAppear</code> call, for example), your users will be rather annoyed because they'll see it pretty quickly and repeatedly. Then, either they leave a bad review (because they're annoyed) or aren't asked to review again for a whole year.</p>
</blockquote>
<p>Below is an example of what the alert looks like. For more information, see <a href="https://developer.apple.com/app-store/ratings-and-reviews/" rel="nofollow noreferrer">Apple's documentation</a>.</p>
<p><a href="https://i.stack.imgur.com/1WLuk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1WLuk.png" alt="StoreKit rating / review prompt."></a></p>
<hr>
<h1>iRate (iOS 7.0 and up)</h1>
<p>If your app runs on versions of iOS earlier than 10.3 <em>or</em> you need more robust control over requesting ratings from users, iRate is a good solution.</p>
<p>For devices with iOS 10.3 or greater, iRate uses the aforementioned StoreKit API. For devices running iOS 7.0 to 10.2, iRate uses a <a href="/questions/tagged/uialertview" class="post-tag" title="show questions tagged 'uialertview'" rel="tag">uialertview</a> and <a href="/questions/tagged/storekit" class="post-tag" title="show questions tagged 'storekit'" rel="tag">storekit</a> to ask the user for a rating (or to remind them later). Everything is customizable, from the title of the Cancel button to the interval at which it reminds the user.</p>
<p>By default, iRate automatically opens when certain requirements are met (e.g. app launched X number of times, user passed X number of levels), but you can also use a variety of methods and your own logic (with the help of iRate methods) to manually display an iRate popup.</p>
<h3>Setup</h3>
<p>To install, just drag the header file, the implementation file, and the <code>.bundle</code> (for localization) into your project.</p>
<ol>
<li>Import the header in your AppDelegate: <code>#import "iRate.h"</code></li>
<li>Add the <strong>StoreKit</strong> Framework to your project - More on <a href="http://developer.apple.com/library/ios/#documentation/StoreKit/Reference/StoreKit_Collection/_index.html" rel="nofollow noreferrer">StoreKit from Apple Documentation</a></li>
<li><p>In your <code>application: didFinishLaunchingWithOptions:</code> method, set the following: </p>
<pre><code>// Configure iRate
[iRate sharedInstance].daysUntilPrompt = 5;
[iRate sharedInstance].usesUntilPrompt = 15;
</code></pre></li>
</ol>
<h3>Properties</h3>
<p>The property below is useful for testing purposes. Set it to <code>YES</code> during testing to make sure the dialog appears properly. When set to <code>YES</code> it will appear immediately on startup, disregarding other display settings. Set this to <code>NO</code> for release versions of your app.</p>
<pre><code> [iRate sharedInstance].previewMode = NO;
</code></pre>
<p>The <code>appStoreID</code> property allows you to set the ID of your app. This is <em>only required if you have both Mac and iOS apps with the same Bundle Identifier</em>. The App ID set here must also match the Bundle ID set in Xcode and iTunes Connect:</p>
<pre><code>[iRate sharedInstance].appStoreID = 555555555;
</code></pre>
<p><a href="https://github.com/nicklockwood/iRate" rel="nofollow noreferrer">More Details</a> are available on the iRate GitHub page.</p>
|
35,207,515 |
What is the purpose of a single pound/hash sign (#) on its own line in the C/C++ preprocessor?
|
<p>I have been looking at the <a href="http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29">Boost</a> libraries source code, and I have noticed that often there are single pound signs without any preprocessor directives attached to them. I read through the GCC preprocessor manual and specification guide and can't find anything about it.</p>
<pre><code>(1) #ifndef BOOST_CONFIG_HPP
(2) # include <boost/config.hpp>
(3) #endif
(4) #
(5) #if defined(BOOST_HAS_PRAGMA_ONCE)
(6) # pragma once
(7) #endif
</code></pre>
<p>On line 4, there is nothing after the pound sign. What effect does this have? Is it defined in the C preprocessor (CPP) specification?</p>
<p>As Boost is a cross-platform library, I would assume that any CPP should parse it correctly. What would the effect/side-effects be of having random pound/hash signs throughout the code?</p>
| 35,207,652 | 3 | 8 | null |
2016-02-04 17:20:57.113 UTC
| 12 |
2018-11-19 12:20:42.223 UTC
|
2016-02-06 20:54:05.94 UTC
| null | 63,550 | null | 4,975,646 | null | 1 | 147 |
c++|c|boost|c-preprocessor
| 16,127 |
<p>A <code>#</code> on its own on a line has no effect at all. I assume it's being used for aesthetic value.</p>
<p>The C standard says:</p>
<blockquote>
<p><strong>6.10.7 Null directive</strong></p>
<p><strong>Semantics</strong></p>
<p>A preprocessing directive of the form</p>
<p><code># new-line</code></p>
<p>has no effect.</p>
</blockquote>
<p>The C++ standard says the same thing:</p>
<blockquote>
<p><strong>16.7 Null directive [cpp.null]</strong></p>
<p>A preprocessing directive of the form</p>
<p><code># new-line</code></p>
<p>has no effect.</p>
</blockquote>
|
40,273,463 |
Angular 2 - Global CSS file
|
<p>Is it possible to add a global CSS file to Angular 2?
At the moment I have many different components that have the same button styling - but each of the components have their own CSS file with the styling. This is frustrating for changes.</p>
<p>I read somewhere on Stack Overflow to add:</p>
<pre><code>import { ViewEncapsulation } from '@angular/core'; //add this
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None //add this
})
</code></pre>
<p>So I added the ViewEncapsulation lines in the root component, then added the CSS styling to the root app CSS (app.component.css) and removed the CSS styling from individual component CSS files, and it did not work.</p>
<p>Surely there is a way to add a global CSS file? Do I need to add something to the individual components to make them access the global CSS file?</p>
| 40,273,782 | 3 | 4 | null |
2016-10-26 22:59:27.107 UTC
| 5 |
2019-05-04 19:20:52.13 UTC
| null | null | null | null | 5,338,991 | null | 1 | 58 |
css|angular|angular-cli
| 65,984 |
<p>You can simply import the css in the main html file.</p>
|
1,128,305 |
Regex for PascalCased words (aka camelCased with leading uppercase letter)
|
<p>How do I find all <a href="http://wiki.c2.com/?PascalCase" rel="noreferrer">PascalCased</a> words in a document with a regular expression? </p>
<p>If you don't know the word Pascal cased, I'm only concerned with leading <strong>Upper camel case</strong> (i.e., camel cased words in which the first letter is capitalized).</p>
| 1,128,326 | 9 | 2 | null |
2009-07-14 21:59:56.233 UTC
| 14 |
2022-08-13 15:40:27.81 UTC
|
2019-08-22 07:59:46.14 UTC
| null | 7,059,810 | null | 25,068 | null | 1 | 46 |
regex|search|camelcasing|pascalcasing
| 51,533 |
<pre><code>([A-Z][a-z0-9]+)+
</code></pre>
<p>Assuming English. Use appropriate character classes if you want it internationalizable. This will match words such as "This". If you want to only match words with at least two capitals, just use</p>
<pre><code>([A-Z][a-z0-9]+){2,}
</code></pre>
<p>UPDATE:
As I mentioned in a comment, a better version is:</p>
<pre><code>[A-Z]([A-Z0-9]*[a-z][a-z0-9]*[A-Z]|[a-z0-9]*[A-Z][A-Z0-9]*[a-z])[A-Za-z0-9]*
</code></pre>
<p>It matches strings that start with an uppercase letter, contain only letters and numbers, and contain at least one lowercase letter and at least one other uppercase letter.</p>
|
586,284 |
Finding prime numbers with the Sieve of Eratosthenes (Originally: Is there a better way to prepare this array?)
|
<p><strong>Note:</strong> Version 2, below, uses the Sieve of Eratosthenes. There are several answers that helped with what I originally asked. I have chosen the Sieve of Eratosthenes method, implemented it, and changed the question title and tags appropriately. Thanks to everyone who helped!</p>
<h2>Introduction</h2>
<p>I wrote this fancy little method that generates an array of int containing the prime numbers less than the specified upper bound. It works very well, but I have a concern.</p>
<h2>The Method</h2>
<pre><code>private static int [] generatePrimes(int max) {
int [] temp = new int [max];
temp [0] = 2;
int index = 1;
int prime = 1;
boolean isPrime = false;
while((prime += 2) <= max) {
isPrime = true;
for(int i = 0; i < index; i++) {
if(prime % temp [i] == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
temp [index++] = prime;
}
}
int [] primes = new int [index];
while(--index >= 0) {
primes [index] = temp [index];
}
return primes;
}
</code></pre>
<h2>My Concern</h2>
<p>My concern is that I am creating an array that is far too large for the final number of elements the method will return. The trouble is that I don't know of a good way to correctly guess the number of prime numbers less than a specified number.</p>
<h2>Focus</h2>
<p>This is how the program uses the arrays. This is what I want to improve upon.</p>
<ol>
<li>I create a temporary array that is
large enough to hold every number
less than the limit.</li>
<li>I generate the prime numbers, while
keeping count of how many I have
generated.</li>
<li>I make a new array that is the right
dimension to hold just the prime
numbers.</li>
<li>I copy each prime number from the
huge array to the array of the
correct dimension.</li>
<li>I return the array of the correct
dimension that holds just the prime
numbers I generated.</li>
</ol>
<h2>Questions</h2>
<ol>
<li>Can I copy the whole chunk (at once) of
<code>temp[]</code> that has nonzero
elements to <code>primes[]</code>
without having to iterate through
both arrays and copy the elements
one by one?</li>
<li>Are there any data structures that
behave like an array of primitives
that can grow as elements are added,
rather than requiring a dimension
upon instantiation? What is the
performance penalty compared to
using an array of primitives?</li>
</ol>
<hr>
<p>Version 2 (thanks to <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>):</p>
<pre><code>private static int [] generatePrimes(int max) {
int [] temp = new int [max];
temp [0] = 2;
int index = 1;
int prime = 1;
boolean isPrime = false;
while((prime += 2) <= max) {
isPrime = true;
for(int i = 0; i < index; i++) {
if(prime % temp [i] == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
temp [index++] = prime;
}
}
return Arrays.copyOfRange(temp, 0, index);
}
</code></pre>
<hr>
<p>Version 3 (thanks to <a href="https://stackoverflow.com/users/3333/paul-tomblin">Paul Tomblin</a>) which uses the <a href="http://en.wikipedia.org/wiki/Sieve%5Fof%5FErastosthenes" rel="nofollow noreferrer">Sieve of Erastosthenes</a>:</p>
<pre><code>private static int [] generatePrimes(int max) {
boolean[] isComposite = new boolean[max + 1];
for (int i = 2; i * i <= max; i++) {
if (!isComposite [i]) {
for (int j = i; i * j <= max; j++) {
isComposite [i*j] = true;
}
}
}
int numPrimes = 0;
for (int i = 2; i <= max; i++) {
if (!isComposite [i]) numPrimes++;
}
int [] primes = new int [numPrimes];
int index = 0;
for (int i = 2; i <= max; i++) {
if (!isComposite [i]) primes [index++] = i;
}
return primes;
}
</code></pre>
| 586,302 | 13 | 7 | null |
2009-02-25 14:54:13.983 UTC
| 9 |
2019-04-23 09:14:58.073 UTC
|
2017-05-23 11:55:06.673 UTC
|
eleven81
| -1 |
eleven81
| 43,263 | null | 1 | 22 |
java|arrays|primes|sieve-of-eratosthenes
| 42,495 |
<p>Your method of finding primes, by comparing every single element of the array with every possible factor is hideously inefficient. You can improve it immensely by doing a <a href="http://en.wikipedia.org/wiki/Sieve_of_Erastosthenes" rel="noreferrer">Sieve of Eratosthenes</a> over the entire array at once. Besides doing far fewer comparisons, it also uses addition rather than division. Division is way slower.</p>
|
703,948 |
What is the difference between a data flow diagram and a flow chart?
|
<p>I want to know why we use Data Flow Diagrams instead of flow charts.</p>
| 703,960 | 14 | 1 | null |
2009-04-01 03:28:41.187 UTC
| 1 |
2017-05-05 09:35:13.587 UTC
|
2014-02-25 18:57:45.4 UTC
| null | 321,731 |
Rahul Vyas
| 83,905 | null | 1 | 14 |
flowchart
| 129,689 |
<p>You should use whatever you like. The diagram is just a tool. Use whatever tool fits you and your problem best. I usually just use boxes and arrows and squiggles and circles and little stick figures and whatever else I think gets the point across to the viewer. In short it doesn't matter if you even use a standard diagraming standard. People are usually pretty good at understanding pictures.</p>
|
85,992 |
How do I enumerate the properties of a JavaScript object?
|
<p>How do I enumerate the properties of a JavaScript object?</p>
<p>I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.</p>
| 86,014 | 14 | 0 | null |
2008-09-17 18:10:18.38 UTC
| 136 |
2018-08-25 12:03:24.387 UTC
|
2015-06-01 22:50:09.06 UTC
| null | 63,550 |
davenpcj
| 4,777 | null | 1 | 719 |
javascript|properties
| 612,589 |
<p>Simple enough:</p>
<pre><code>for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}
</code></pre>
<p>Now, you will not get private variables this way because they are not available.</p>
<hr>
<p>EDIT: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> is correct that unless you use the <code>hasOwnProperty()</code> method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.</p>
<p>Now, that said, <code>hasOwnProperty()</code> <em>is</em> useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.</p>
<p>EDIT 2: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use <code>hasOwnProperty()</code>. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via <code>jQuery.extend</code> and <code>jQuery.fn.extend</code>).</p>
|
1,332,778 |
What are your most common sql optimizations?
|
<p>What are your most common SQL optimization that you used?</p>
| 1,332,805 | 17 | 0 |
2009-08-26 11:10:14.107 UTC
|
2009-08-26 06:48:49.173 UTC
| 25 |
2022-08-18 17:57:51.697 UTC
|
2018-02-27 08:02:28.107 UTC
| null | 680,068 | null | 153,621 | null | 1 | 33 |
sql|optimization
| 14,336 |
<p>Reducing the amount of data that is returned, by only returning the fields required and only returning the rows required. This is the most common, as you do it for every query that returns data.</p>
<p>With ENGINE=InnoDB, the above advice especially applies to avoiding unnecessary fetching of <code>TEXT</code> and <code>BLOB</code> columns since they may be stored in a different location (thereby costing extra I/O).</p>
<p>Adding indexes. This is not done as frequently, as some tables doesn't need any other index than the one created for the primary key.</p>
|
1,032,914 |
How to make a div fill a remaining horizontal space?
|
<p><strong>I have 2 divs:</strong> one in the left side and one in the right side of my page. The one in the left side has fixed width and I want the one of the right side to fill the remaining space.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#search {
width: 160px;
height: 25px;
float: left;
background-color: #ffffff;
}
#navigation {
width: 780px;
float: left;
background-color: #A53030;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="search">Text</div>
<div id="navigation">Navigation</div></code></pre>
</div>
</div>
</p>
| 1,032,952 | 26 | 6 | null |
2009-06-23 14:29:30.553 UTC
| 101 |
2021-07-27 14:34:19.35 UTC
|
2020-03-10 02:14:33.463 UTC
| null | 6,904,888 | null | 122,536 | null | 1 | 492 |
html|css|width|responsive
| 617,623 |
<p>This seems to accomplish what you're going for.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#left {
float:left;
width:180px;
background-color:#ff0000;
}
#right {
width: 100%;
background-color:#00FF00;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div id="left">
left
</div>
<div id="right">
right
</div>
</div></code></pre>
</div>
</div>
</p>
|
854,128 |
Find duplicate records in MySQL
|
<p>I want to pull out duplicate records in a MySQL Database. This can be done with:</p>
<pre><code>SELECT address, count(id) as cnt FROM list
GROUP BY address HAVING cnt > 1
</code></pre>
<p>Which results in:</p>
<pre><code>100 MAIN ST 2
</code></pre>
<p>I would like to pull it so that it shows each row that is a duplicate. Something like:</p>
<pre><code>JIM JONES 100 MAIN ST
JOHN SMITH 100 MAIN ST
</code></pre>
<p>Any thoughts on how this can be done? I'm trying to avoid doing the first one then looking up the duplicates with a second query in the code.</p>
| 854,177 | 28 | 0 | null |
2009-05-12 18:24:21.757 UTC
| 244 |
2022-07-28 01:09:59.52 UTC
| null | null | null | null | 497 | null | 1 | 725 |
mysql|duplicates
| 881,451 |
<p>The key is to rewrite this query so that it can be used as a subquery.</p>
<pre><code>SELECT firstname,
lastname,
list.address
FROM list
INNER JOIN (SELECT address
FROM list
GROUP BY address
HAVING COUNT(id) > 1) dup
ON list.address = dup.address;
</code></pre>
|
6,800,509 |
Are there APIs for text analysis/mining in Java?
|
<p>I want to know if there is an API to do text analysis in Java. Something that can extract all words in a text, separate words, expressions, etc. Something that can inform if a word found is a number, date, year, name, currency, etc.</p>
<p>I'm starting the text analysis now, so I only need an API to kickoff. I made a web-crawler, now I need something to analyze the downloaded data. Need methods to count the number of words in a page, similar words, data type and another resources related to the text.</p>
<p>Are there APIs for text analysis in Java?</p>
<p>EDIT: Text-mining, I want to mining the text. An API for Java that provides this.</p>
| 6,800,681 | 5 | 7 | null |
2011-07-23 12:56:34.703 UTC
| 10 |
2012-12-14 18:39:38.947 UTC
|
2011-07-25 18:41:56.737 UTC
| null | 734,984 | null | 734,984 | null | 1 | 25 |
java|api|nlp|analysis|text-mining
| 16,385 |
<p>For example - you might use some classes from standard library <code>java.text</code>, or use <code>StreamTokenizer</code> (you might customize it according to your requirements). But as you know - <strong>text data from internet sources is usually has many orthographical mistakes</strong> and for better performance you have to use something like <strong>fuzzy tokenizer</strong> - <em>java.text and other standart utils has too limited capabilities in such context</em>.</p>
<p><em>So, I'd advice you to use <strong>regular expressions</strong> (java.util.regex) and create own kind of tokenizer according to your needs.</em></p>
<p><strong>P.S.</strong>
According to your needs - you might create state-machine parser for recognizing templated parts in raw texts. You might see simple state-machine recognizer on the picture below (you can construct more advanced parser, which could recognize much more complex templates in text).</p>
<p><img src="https://i.stack.imgur.com/VifsP.png" alt="enter image description here"></p>
|
6,323,296 |
Python remove anything that is not a letter or number
|
<p>I'm having a little trouble with Python regular expressions.</p>
<p>What is a good way to remove all characters in a string that are not letters or numbers?</p>
<p>Thanks!</p>
| 6,325,804 | 7 | 1 | null |
2011-06-12 17:09:48.13 UTC
| 11 |
2012-09-02 05:09:23.287 UTC
| null | null | null | null | 84,131 | null | 1 | 37 |
python|regex|string
| 55,874 |
<p><code>[\w]</code> matches (alphanumeric or underscore).</p>
<p><code>[\W]</code> matches (not (alphanumeric or underscore)), which is equivalent to (not alphanumeric and not underscore)</p>
<p>You need <code>[\W_]</code> to remove ALL non-alphanumerics.</p>
<p>When using re.sub(), it will be much more efficient if you reduce the number of substitutions (expensive) by matching using <code>[\W_]+</code> instead of doing it one at a time.</p>
<p>Now all you need is to define alphanumerics:</p>
<p><code>str</code> object, only ASCII A-Za-z0-9:</p>
<pre><code> re.sub(r'[\W_]+', '', s)
</code></pre>
<p><code>str</code> object, only locale-defined alphanumerics:</p>
<pre><code> re.sub(r'[\W_]+', '', s, flags=re.LOCALE)
</code></pre>
<p><code>unicode</code> object, all alphanumerics:</p>
<pre><code> re.sub(ur'[\W_]+', u'', s, flags=re.UNICODE)
</code></pre>
<p>Examples for <code>str</code> object:</p>
<pre><code>>>> import re, locale
>>> sall = ''.join(chr(i) for i in xrange(256))
>>> len(sall)
256
>>> re.sub('[\W_]+', '', sall)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> re.sub('[\W_]+', '', sall, flags=re.LOCALE)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> locale.setlocale(locale.LC_ALL, '')
'English_Australia.1252'
>>> re.sub('[\W_]+', '', sall, flags=re.LOCALE)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\
x9a\x9c\x9e\x9f\xaa\xb2\xb3\xb5\xb9\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\
xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\
xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\
xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
# above output wrapped at column 80
</code></pre>
<p>Unicode example:</p>
<pre><code>>>> re.sub(ur'[\W_]+', u'', u'a_b A_Z \x80\xFF \u0404', flags=re.UNICODE)
u'abAZ\xff\u0404'
</code></pre>
|
6,334,830 |
PHP: Possible to automatically get all POSTed data?
|
<p>Simple question: Is it possible to get all the data POSTed to a page, even if you don't know all the fields?</p>
<p>For example, I want to write a simple script that collects any POSTed data and emails it. I can foresee that the fields in the form are likely to change a lot over time, and so to save myself some time in the long run, I was wondering if I could write something that automatically gathered everything?</p>
<p>Is it possible?</p>
| 6,334,857 | 9 | 2 | null |
2011-06-13 18:52:32.347 UTC
| 19 |
2022-09-24 18:33:56.073 UTC
|
2015-11-09 04:57:47.927 UTC
| null | 408,262 | null | 199,700 | null | 1 | 65 |
php|forms|post
| 145,474 |
<p>Sure. Just walk through the <code>$_POST</code> array:</p>
<pre><code>foreach ($_POST as $key => $value) {
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
</code></pre>
|
6,711,295 |
How to check if Facebook is installed Android
|
<p>I am modifying my app to be able to catch if a user tries to publish without having the facebook app installed (required for SSO). Here is the code I am using:</p>
<pre><code>try{
ApplicationInfo info = getPackageManager().
getApplicationInfo("com.facebook.android", 0 );
return true;
} catch( PackageManager.NameNotFoundException e ){
return false;
}
</code></pre>
<p>The problem is, it is always catching an error. According to the question <a href="https://stackoverflow.com/questions/4323553/way-to-know-if-my-application-is-installed">here</a>, I need to request the appropriate permission but I don't know what permissions I need to request.</p>
<p>Is my problem a permission one or something else?</p>
| 6,711,348 | 9 | 0 | null |
2011-07-15 18:01:44.06 UTC
| 16 |
2021-12-07 06:00:00.007 UTC
|
2017-05-23 12:08:54.16 UTC
| null | -1 | null | 796,231 | null | 1 | 68 |
android|facebook|package
| 57,891 |
<p><code>com.facebook.android</code> is the package name for the Facebook SDK. The Facebook app's package is <code>com.facebook.katana</code>.</p>
|
6,332,577 |
Send Outlook Email Via Python?
|
<p>I am using <code>Outlook 2003</code>.</p>
<p>What is the best way to send email (through <code>Outlook 2003</code>) using <code>Python</code>?</p>
| 6,332,639 | 9 | 2 | null |
2011-06-13 15:31:43.81 UTC
| 63 |
2022-05-16 00:30:14.213 UTC
| null | null | null | null | 540,009 | null | 1 | 94 |
python|outlook
| 321,522 |
<p>For a solution that uses outlook see <a href="https://stackoverflow.com/a/17887528/5211833">TheoretiCAL's answer</a>.</p>
<p>Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.</p>
<pre><code>SERVER = "smtp.example.com"
FROM = "yourEmail@example.com"
TO = ["listOfEmails"] # must be a list
SUBJECT = "Subject"
TEXT = "Your Text"
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
</code></pre>
<p><strong>EDIT:</strong> this example uses reserved domains like described in <a href="https://www.rfc-editor.org/rfc/rfc2606" rel="nofollow noreferrer">RFC2606</a></p>
<pre><code>SERVER = "smtp.example.com"
FROM = "johnDoe@example.com"
TO = ["JaneDoe@example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()
</code></pre>
<p><sub>For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.</sub></p>
<p>Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.</p>
|
6,556,522 |
Authentication versus Authorization
|
<p>What's the difference in context of web applications? I see the abbreviation "auth" a lot. Does it stand for <strong>auth</strong>-entication or <strong>auth</strong>-orization? Or is it both?</p>
| 6,556,548 | 17 | 4 | null |
2011-07-02 10:44:19.63 UTC
| 197 |
2022-03-27 13:54:08.44 UTC
|
2018-09-26 17:00:48.873 UTC
| null | 458,610 | null | 458,610 | null | 1 | 699 |
security|authorization|authentication
| 253,636 |
<blockquote>
<p><strong>Authentication</strong> is the process of ascertaining that somebody really is who they claim to be.</p>
<p><strong>Authorization</strong> refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases,
while Usama is only authorised to read.</p>
</blockquote>
<p>The two concepts are completely orthogonal and independent, but <em>both</em> are central to security design, and the failure to get either one correct opens up the avenue to compromise.</p>
<p>In terms of web apps, very crudely speaking, authentication is when you check login credentials to see if you recognize a user as logged in, and authorization is when you look up in your access control whether you allow the user to view, edit, delete or create content.</p>
|
41,459,657 |
How to create dynamic plots to display on Flask?
|
<p>I wish to create dynamic plots based on user input on a flask app. However I am getting the following error:
string argument expected, got 'bytes'</p>
<p>If I use io.BytesIO(), I am not getting this error, but I am not getting the plot on test.html</p>
<pre><code>from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import io
import base64
app = Flask(__name__)
@app.route('/plot')
def build_plot():
img = io.StringIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue())
return render_template('test.html', plot_url=plot_url)
if __name__ == '__main__':
app.debug = True
app.run()
</code></pre>
<p>Test.html</p>
<pre><code><!DOCTYPE html>
<html>
<title> Plot</title>
<body>
<img src="data:image/png;base64, {{ plot_url }}">
</body>
</html>
</code></pre>
| 41,460,112 | 1 | 1 | null |
2017-01-04 08:51:36.053 UTC
| 13 |
2017-01-04 09:17:41.22 UTC
| null | null | null | null | 4,059,923 | null | 1 | 14 |
python|flask|io
| 20,923 |
<p>Use <code>BytesIO</code> and later <code>decode()</code></p>
<p>Working example</p>
<pre><code>from flask import Flask
#from flask import render_template
import matplotlib.pyplot as plt
import io
import base64
app = Flask(__name__)
@app.route('/plot')
def build_plot():
img = io.BytesIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return '<img src="data:image/png;base64,{}">'.format(plot_url)
if __name__ == '__main__':
app.debug = True
app.run()
</code></pre>
|
15,571,022 |
How to find reason for Generic GDI+ error when saving an image?
|
<p>Having a code that works for ages when loading and storing images, I discovered that I have <em>one single image</em> that breaks this code:</p>
<pre><code>const string i1Path = @"c:\my\i1.jpg";
const string i2Path = @"c:\my\i2.jpg";
var i = Image.FromFile(i1Path);
i.Save(i2Path, ImageFormat.Jpeg);
</code></pre>
<p>The exception is:</p>
<blockquote>
<p>System.Runtime.InteropServices.ExternalException occurred</p>
<p><strong>A generic error occurred in GDI+.</strong></p>
<p>at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)<br />
at System.Drawing.Image.Save(String filename, ImageFormat format)<br />
at ...</p>
</blockquote>
<p>As far as I can see, there is nothing special about the image. It is approx 250 pixels in size and can be opened in e.g. Windows Image Viewer or Paint.NET:</p>
<p><img src="https://i.stack.imgur.com/qm3l3.jpg" alt="enter image description here" /></p>
<p><em>(Since the image above, after being uploaded to Stack Overflow does not produce the error anymore, I've put <a href="https://www.magerquark.de/misc/i1.jpg" rel="noreferrer">the original image here</a>)</em></p>
<p>What I discovered is that upon calling the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.save?view=dotnet-plat-ext-3.1#System_Drawing_Image_Save_System_String_System_Drawing_Imaging_ImageFormat_" rel="noreferrer"><code>Save</code> method</a>, the destination image file is being created with zero bytes.</p>
<p>I am really clueless on what causes the error.</p>
<p><strong>My questions:</strong></p>
<ul>
<li>Can you think of any special thing that would hinder .NET from saving the image?</li>
<li>Is there any way (beside panicing) to narrow down these kind of errors?</li>
</ul>
| 15,595,846 | 10 | 2 | null |
2013-03-22 13:02:40.26 UTC
| 9 |
2020-09-18 04:59:44.637 UTC
|
2020-09-18 04:59:44.637 UTC
| null | 107,625 | null | 107,625 | null | 1 | 43 |
c#|.net|image|gdi+|system.drawing
| 113,868 |
<p>While I still did not find out the reason what exactly caused the error when saving the image, I found a workaround to apply:</p>
<pre><code>const string i1Path = @"c:\my\i1.jpg";
const string i2Path = @"c:\my\i2.jpg";
var i = Image.FromFile(i1Path);
var i2 = new Bitmap(i);
i2.Save(i2Path, ImageFormat.Jpeg);
</code></pre>
<p>I.e. by copying the image internally into a <a href="http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx" rel="noreferrer"><code>Bitmap</code></a> instance and saving this image instead of the original image, the error disappeared.</p>
<p>I'm assuming that by copying it, the erroneous parts the caused the original <code>Save</code> call to fail are being removed an/or normalized, thus enabling the save operation to succeed.</p>
<p><img src="https://i.stack.imgur.com/23ZmS.jpg" alt="saved image i2.jpg"></p>
<p>Interestingly, the so stored image has a smaller file on disk (16 kB) than its original source (26 kB).</p>
|
10,413,704 |
How to select value of input onClick?
|
<p>I have a <code><input type="text"></code> and if user clicks inside it I want to make the content (value) of that box selected. How would I do that?</p>
| 10,413,799 | 4 | 3 | null |
2012-05-02 12:25:19.63 UTC
| 7 |
2017-10-27 10:32:05.063 UTC
|
2012-10-29 15:42:53.613 UTC
| null | -1 | null | 1,368,173 | null | 1 | 27 |
javascript
| 59,188 |
<pre><code><input type="text" onclick="select()"/>
</code></pre>
|
10,803,296 |
Modifying replace string in xargs
|
<p>When I am using <code>xargs</code> sometimes I do not need to explicitly use the replacing string:</p>
<pre><code>find . -name "*.txt" | xargs rm -rf
</code></pre>
<p>In other cases, I want to specify the replacing string in order to do things like:</p>
<pre><code>find . -name "*.txt" | xargs -I '{}' mv '{}' /foo/'{}'.bar
</code></pre>
<p>The previous command would move all the text files under the current directory into <code>/foo</code> and it will append the extension <code>bar</code> to all the files.</p>
<p>If instead of appending some text to the replace string, I wanted to modify that string such that I could insert some text between the name and extension of the files, how could I do that? For instance, let's say I want to do the same as in the previous example, but the files should be renamed/moved from <code><name>.txt</code> to <code>/foo/<name>.bar.txt</code> (instead of <code>/foo/<name>.txt.bar</code>).</p>
<p><strong>UPDATE</strong>: I manage to find a solution:</p>
<pre><code>find . -name "*.txt" | xargs -I{} \
sh -c 'base=$(basename $1) ; name=${base%.*} ; ext=${base##*.} ; \
mv "$1" "foo/${name}.bar.${ext}"' -- {}
</code></pre>
<p>But I wonder if there is a shorter/better solution.</p>
| 10,805,692 | 8 | 4 | null |
2012-05-29 16:41:51.147 UTC
| 31 |
2022-02-22 10:31:31.063 UTC
|
2012-05-29 20:05:35.06 UTC
| null | 1,135,819 | null | 1,135,819 | null | 1 | 74 |
bash|xargs
| 74,210 |
<p>In cases like this, a <code>while</code> loop would be more readable:</p>
<pre><code>find . -name "*.txt" | while IFS= read -r pathname; do
base=$(basename "$pathname"); name=${base%.*}; ext=${base##*.}
mv "$pathname" "foo/${name}.bar.${ext}"
done
</code></pre>
<p>Note that you may find files with the same name in different subdirectories. Are you OK with duplicates being over-written by <code>mv</code>?</p>
|
13,309,103 |
AUGraph Record and Play with RemoteIO and MultiChannelMixer
|
<p>i have a Problem ;)</p>
<p>i want to record Audio from the Mic and Write it to the Filesystem with Extended Audio File Services and also play the recorded Stuff.
if i only use the remoteIO with two callbacks one for read one for write it works.</p>
<p>For the Volumen Control i want to use the MultiChannelMixer and the AUGraph.
is it possible that you realize playback <strong>and</strong> recording with the same mixer and the RemoteIO?</p>
<p>i think it must look like this:</p>
<pre><code>RemotIO Input -> -> Write Callback
Mixer
RemoteIO Output <- <- Read Callback
</code></pre>
<p>i create two AUNodes (RemoteIO and MultiChannelMixer), how must i set the Callbacks and the Connections that one Callback deliver the AudioData from the mic and an other reads the Data from a File and both paths go through the mixer?</p>
<p>The reading and writing is not the Problem, only the configuration of the Nodes! </p>
<p>…and the output of CAShow:</p>
<pre><code>AudioUnitGraph 0x8AEE000:
Member Nodes:
node 1: 'aumx' 'mcmx' 'appl', instance 0x865a510 O I
node 2: 'auou' 'rioc' 'appl', instance 0x865d0a0 O I
Connections:
node 1 bus 0 => node 2 bus 0 [ 2 ch, 44100 Hz, 'lpcm' (0x0000000C) 16-bit little-endian signed integer]
node 2 bus 1 => node 1 bus 1 [ 2 ch, 44100 Hz, 'lpcm' (0x0000000C) 16-bit little-endian signed integer]
Input Callbacks:
{0x4150, 0x7573340} => node 2 bus 1 [2 ch, 44100 Hz]
{0x4330, 0x7573340} => node 1 bus 0 [2 ch, 44100 Hz]
CurrentState:
mLastUpdateError=0, eventsToProcess=F, isRunning=F
</code></pre>
<p>here is the setup code:</p>
<pre><code> OSStatus setupErr = noErr;
AudioComponentDescription mixerDescription;
AudioComponentDescription ioDescription;
// the AUNodes
AUNode mixerNode;
AUNode ioNode;
// the graph
setupErr = NewAUGraph(&_graph);
NSAssert(setupErr == noErr, @"Couldn't create graph");
// the mixer
mixerDescription.componentFlags = 0;
mixerDescription.componentFlagsMask = 0;
mixerDescription.componentType = kAudioUnitType_Mixer;
mixerDescription.componentSubType = kAudioUnitSubType_MultiChannelMixer;
mixerDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
// the io
ioDescription.componentFlags = 0;
ioDescription.componentFlagsMask = 0;
ioDescription.componentType = kAudioUnitType_Output;
ioDescription.componentSubType = kAudioUnitSubType_RemoteIO;
ioDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
// add mixer Node
setupErr = AUGraphAddNode(self.graph, &mixerDescription, &mixerNode);
NSAssert(setupErr == noErr, @"Couldn't create master mixer");
// add io Node
setupErr = AUGraphAddNode(self.graph, &ioDescription, &ioNode);
NSAssert(setupErr == noErr, @"Couldn't create io node");
// open Graph
setupErr = AUGraphOpen(self.graph);
NSAssert(setupErr == noErr, @"Couldn't open graph");
// get the mixer info
setupErr = AUGraphNodeInfo(self.graph, mixerNode, &mixerDescription, &_mixer);
NSAssert(setupErr == noErr, @"Couldn't get master mixer info");
// get the io info
setupErr = AUGraphNodeInfo(self.graph, ioNode, &ioDescription, &_io);
NSAssert(setupErr == noErr, @"Couldn't get io Node info");
// enable io input
UInt32 enableFlag = 1;
setupErr = AudioUnitSetProperty(self.io, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &enableFlag, sizeof(enableFlag));
NSAssert(setupErr == noErr, @"Couldn't enable io input");
// set up the mixers input callbacks
AURenderCallbackStruct outputCallbackStruct;
outputCallbackStruct.inputProc = outputCallback;
outputCallbackStruct.inputProcRefCon = self;
AURenderCallbackStruct inputCallbackStruct;
inputCallbackStruct.inputProc = inputCallback;
inputCallbackStruct.inputProcRefCon = self;
setupErr = AUGraphConnectNodeInput(self.graph, mixerNode, 0, ioNode, 0);
NSAssert(setupErr == noErr, @"Couldn't connect mixer output to io output");
setupErr = AUGraphConnectNodeInput(self.graph, ioNode, 1, mixerNode, 1);
NSAssert(setupErr == noErr, @"Couldn't connect io input to mixer input");
// set output Callback
setupErr = AUGraphSetNodeInputCallback(self.graph, ioNode, 1, &outputCallbackStruct);
NSAssert(setupErr == noErr, @"Error setting io output callback");
// set input Callback
setupErr = AUGraphSetNodeInputCallback(self.graph, mixerNode, 0, &inputCallbackStruct);
NSAssert(setupErr == noErr, @"Error setting mixer input callback");
// describe format
AudioStreamBasicDescription audioFormat = {0};
audioFormat.mSampleRate = 44100.00;
audioFormat.mFormatID = kAudioFormatLinearPCM;
audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
audioFormat.mFramesPerPacket = 1;
audioFormat.mChannelsPerFrame = 2;
audioFormat.mBitsPerChannel = 16;
audioFormat.mBytesPerPacket = 4;
audioFormat.mBytesPerFrame = 4;
// set the rio input properties
setupErr = AudioUnitSetProperty(self.io, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, kOutputBus, &audioFormat, sizeof(audioFormat));
NSAssert(setupErr == noErr, @"Error setting RIO input property");
// set the rio output properties
setupErr = AudioUnitSetProperty(self.io, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &audioFormat, sizeof(audioFormat));
NSAssert(setupErr == noErr, @"Error setting RIO output property");
// set the master fader output properties
setupErr = AudioUnitSetProperty(self.mixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Global, kOutputBus, &audioFormat, sizeof(audioFormat));
NSAssert(setupErr == noErr, @"Error setting master output property");
// set the master fader input properties
setupErr = AudioUnitSetProperty(self.mixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Global, kOutputBus, &audioFormat, sizeof(audioFormat));
NSAssert(setupErr == noErr, @"Error setting master input1 property");
// initialize Graph
setupErr = AUGraphInitialize(self.graph);
NSAssert(setupErr == noErr, @"Error initializing graph - error code");
CAShow(self.graph);
// start Graph
setupErr = AUGraphStart(self.graph);
NSAssert(setupErr == noErr, @"Error starting graph. - error code");
</code></pre>
<p>i hope you understand my problem :)
Thanks..</p>
<p><strong>Update:</strong>
Some more Stuff to describe my Problem!</p>
<p>Recording: RemoteIO InputScope Bus 0 -> Mixer Input Bus 0 -> Mixer Output Bus 0 -> Write Callback -> File
Playback: File -> Read Callback -> Mixer Input Bus 1 -> Mixer Output Bus 0 -> RemoteIO OutputScope Bus 1</p>
<p><img src="https://i.stack.imgur.com/kVcLY.jpg" alt="Connection Plan"></p>
| 13,444,724 | 1 | 0 | null |
2012-11-09 13:34:43.843 UTC
| 8 |
2012-11-18 21:21:20.06 UTC
|
2012-11-14 14:19:58.743 UTC
| null | 318,272 | null | 318,272 | null | 1 | 8 |
objective-c|audio|core-audio|record|playback
| 3,117 |
<p>You need create AUGraph with three nodes (units):</p>
<ol>
<li>File Player (kAudioUnitSubType_AudioFilePlayer)</li>
<li>RemoteIO</li>
<li>Mixer</li>
</ol>
<p>Connect them like this:</p>
<pre><code>AUGraphConnectNodeInput(m_graph, m_player, 0, m_mixerNode, 0); // player -> mixer
AUGraphConnectNodeInput(m_graph, m_mixerNode, 0, m_rioNode, 0); // mixer -> output
AUGraphConnectNodeInput(m_graph, m_rioNode, 1, m_mixerNode, 1); // input -> mixer
</code></pre>
<p>Enable input on RIO:</p>
<pre><code>UInt32 enable = 1;
AudioUnitSetProperty(m_rioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enable, sizeof(UInt32));
</code></pre>
<p>Get mixer output format and set it as client format for Extended Audio File:</p>
<pre><code>AudioStreamBasicDescription mixerASBD;
UInt32 prop = sizeof(mixerASBD);
AudioUnitGetProperty(m_mixerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &mixerASBD, &prop);
ExtAudioFileSetProperty(extAudioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(mixerASBD), &mixerASBD);
</code></pre>
<p>Define render callback:</p>
<pre><code>static OSStatus mixerCallBack(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp * inTimeStamp, UInt32 inBusNumber,UInt32 inNumberFrames, AudioBufferList *ioData) {
if ((*ioActionFlags) & kAudioUnitRenderAction_PostRender)
return (ExtAudioFileWrite(extAudioFile, inNumberFrames, ioData));
return noErr;
}
</code></pre>
<p>Add callback for output data from mixer:</p>
<pre><code>AudioUnitAddRenderNotify(m_mixerUnit, mixerCallBack, NULL);
</code></pre>
<p>That's all. You need to schedule audio files to FilePlayer unit to play.</p>
|
13,750,953 |
Is it possible to configure user.name and user.email per wildcard domains in .gitconfig?
|
<p>I have a work computer, and it's configured globally to use my work email and name when committing. This is good. However, I'd like to make some sort of rule that says, "if the repo origin is github, use user X and email Y"</p>
<p>I realize you can make a config entry per repository, but I'd like it to be more automatic: if the clone is github, it should use github user details. If I clone from work, it should use work details.</p>
<p>Is there any way to configure this globally based on the remote domain? Or another way?</p>
<p>EDIT/UPDATE</p>
<p>I have accepted the answer below, but modified the script just a bit:</p>
<pre><code>#!/usr/bin/env bash
# "Real" git is the second one returned by 'which'
REAL_GIT=$(which -a git | sed -n 2p)
# Does the remote "origin" point to GitHub?
if ("$REAL_GIT" remote -v 2>/dev/null | grep '^origin\b.*github.com.*(push)$' >/dev/null 2>&1); then
# Yes. Set username and email that you use on GitHub.
export GIT_AUTHOR_NAME=$("$REAL_GIT" config --global user.ghname)
export GIT_AUTHOR_EMAIL=$("$REAL_GIT" config --global user.ghemail)
fi
"$REAL_GIT" "$@"
</code></pre>
<p>The primary addition is the requirement for two <code>git config</code> values.</p>
<pre><code>git config --global user.ghname "Your Name"
git config --global user.ghemail "you@yourmail.com"
</code></pre>
<p>This avoids hard coding the values in the script, allowing it to be more portable. Maybe?</p>
| 46,239,540 | 5 | 2 | null |
2012-12-06 19:21:05.013 UTC
| 12 |
2018-01-16 08:16:50.36 UTC
|
2015-01-07 12:20:57.74 UTC
| null | 895,245 | null | 169,491 | null | 1 | 49 |
git|github
| 14,204 |
<p>Git <a href="https://github.com/blog/2360-git-2-13-has-been-released" rel="noreferrer">2.13 adds</a> support for conditional config includes. If you organize your checkouts into directories for each domain of work, then you can add custom settings based on where the checkouts are. In your global git config:</p>
<pre><code>[includeIf "gitdir:code/work/"]
path = /Users/self/code/work/.gitconfig
</code></pre>
<p>And then in ~/code/work/.gitconfig:</p>
<pre><code>[user]
email = self@work.com
</code></pre>
<p>And of course you can do that for as many domains of work as you like.</p>
|
24,301,235 |
Tint menu icons
|
<p>I'm building an Android app and I use the icons from the Action Bar Icon Pack to use in the action bar. I define them through the xml files in the <code>menu</code> folder.
Is there a way to "tint" these icons so that they are all the same color?
So far, I have to do it manually with an image editing software but if I decide to change the color, I have to do it all over again.</p>
<p>I know there is a <code>android:tint</code> attribute for <code>ImageView</code> but I haven't found a way to use it for the menu's icons.</p>
<p>Thanks</p>
| 24,333,131 | 4 | 2 | null |
2014-06-19 07:40:33.827 UTC
| 12 |
2018-01-24 14:35:44.397 UTC
| null | null | null | null | 1,644,052 | null | 1 | 19 |
android|xml|menu
| 19,312 |
<p>There may be a better way to do this, but one option is to redraw the icon in code.</p>
<p>Suppose you have a menu item for favorites and want to tint it gray:</p>
<pre class="lang-java prettyprint-override"><code>MenuItem favoriteItem = menu.findItem(R.id.action_favorite);
Drawable newIcon = (Drawable)favoriteItem.getIcon();
newIcon.mutate().setColorFilter(Color.argb(255, 200, 200, 200), PorterDuff.Mode.SRC_IN);
favoriteItem.setIcon(newIcon);
</code></pre>
<p>You can also use a color resource like</p>
<pre class="lang-java prettyprint-override"><code>newIcon.mutate().setColorFilter(getResources().getColor(R.color.myCustomTint), PorterDuff.Mode.SRC_IN);
</code></pre>
|
24,043,688 |
postgresql using json sub-element in where clause
|
<p>This might be a very basic question but I am not able to find anything on this online.</p>
<p>If I create a sample table :</p>
<pre><code> create table dummy ( id int not null, data json );
</code></pre>
<p>Then, if I query the table using the following query:</p>
<pre><code>select * from dummy where data->'x' = 10;
</code></pre>
<p>Now since there are no records in the table yet and there is no such property as 'x' in any record, it should return zero results.</p>
<p>But I get the following error:</p>
<pre><code>postgres=# select * from dummy where data->'x' = 10;
ERROR: operator does not exist: json = integer
LINE 1: select * from dummy where data->'x' = 10;
</code></pre>
<p>However following query works:</p>
<pre><code>select * from dummy where cast(data->>'x' as integer) = 10;
</code></pre>
<p>Am I missing something here or typecasting is the only way I can get an integer value from a json field ? If that's the case, does it not affect the performance when data becomes extremely large ?</p>
| 24,044,453 | 2 | 2 | null |
2014-06-04 17:20:02.323 UTC
| 9 |
2014-06-04 18:13:33.417 UTC
| null | null | null | null | 3,097,807 | null | 1 | 27 |
sql|json|database|postgresql|postgresql-9.3
| 26,508 |
<blockquote>
<p>Am I missing something here or typecasting is the only way I can get
an integer value from a json field ? </p>
</blockquote>
<p>You're correct, typecasting is the only way to read an integer value from a json field.</p>
<blockquote>
<p>If that's the case, does it not affect the performance when data
becomes extremely large ?</p>
</blockquote>
<p>Postgres allows you to index functions including casts, so the index below will allow you to quickly retrieve all rows where data->>x has some integer value</p>
<pre><code>CREATE INDEX dummy_x_idx ON dummy(cast("data"->>'x' AS int))
</code></pre>
|
29,711,728 |
How to Sort Geo-points according to the distance from current location in Android
|
<p>I have a "Place" object with a LatLng coordinate for each:</p>
<pre><code>import com.google.android.gms.maps.model.LatLng;
public class Place{
public String name;
public LatLng latlng;
public Restaurant(String name, LatLng latlng) {
this.name = name;
this.latlng = latlng;
}
}
</code></pre>
<p>and I have an ArrayList of these Places, something like this:</p>
<pre><code> ArrayList<Place> places = new ArrayList<Place>();
places.add("Place 1", LatLng(90.0,90.0));
places.add("Place 2", LatLng(93.0,93.0));
places.add("Place 3", LatLng(83.0,92.0));
places.add("Place 4", LatLng(93.0,91.0));
</code></pre>
<p>and I have "my" LatLng:</p>
<pre><code> LatLng myLocation = new LatLng(10.0,10.0);
</code></pre>
<p>How can I sort these objects according to closest to me? Thanks for the help</p>
| 29,713,656 | 4 | 3 | null |
2015-04-18 01:08:01.877 UTC
| 14 |
2018-03-04 04:48:14.413 UTC
|
2015-04-18 06:43:04.977 UTC
| null | 2,126,077 | null | 1,282,637 | null | 1 | 8 |
android|geolocation|latitude-longitude
| 16,504 |
<p>Taking the algorithm from <a href="https://stackoverflow.com/questions/5396286/sort-list-of-lon-lat-points-start-with-nearest/5396425#5396425">this answer</a> from the question posted by @shieldstroy, that uses the <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="noreferrer">Great Circle Distance</a>, I got this example working.</p>
<p>Here is the <code>Comparator</code>:</p>
<pre><code>public class SortPlaces implements Comparator<Place> {
LatLng currentLoc;
public SortPlaces(LatLng current){
currentLoc = current;
}
@Override
public int compare(final Place place1, final Place place2) {
double lat1 = place1.latlng.latitude;
double lon1 = place1.latlng.longitude;
double lat2 = place2.latlng.latitude;
double lon2 = place2.latlng.longitude;
double distanceToPlace1 = distance(currentLoc.latitude, currentLoc.longitude, lat1, lon1);
double distanceToPlace2 = distance(currentLoc.latitude, currentLoc.longitude, lat2, lon2);
return (int) (distanceToPlace1 - distanceToPlace2);
}
public double distance(double fromLat, double fromLon, double toLat, double toLon) {
double radius = 6378137; // approximate Earth radius, *in meters*
double deltaLat = toLat - fromLat;
double deltaLon = toLon - fromLon;
double angle = 2 * Math.asin( Math.sqrt(
Math.pow(Math.sin(deltaLat/2), 2) +
Math.cos(fromLat) * Math.cos(toLat) *
Math.pow(Math.sin(deltaLon/2), 2) ) );
return radius * angle;
}
}
</code></pre>
<p>Here is the high level code, I just put this in <code>onCreate()</code>:</p>
<pre><code> //My location, San Francisco
double lat = 37.77657;
double lng = -122.417506;
LatLng latLng = new LatLng(lat, lng);
//set up list
ArrayList<Place> places = new ArrayList<Place>();
places.add(new Place("New York", new LatLng(40.571256,73.98369)));
places.add(new Place("Colorado", new LatLng(39.260658,-105.101615)));
places.add(new Place("Los Angeles", new LatLng(33.986816,118.473819)));
for (Place p: places){
Log.i("Places before sorting", "Place: " + p.name);
}
//sort the list, give the Comparator the current location
Collections.sort(places, new SortPlaces(latLng));
for (Place p: places){
Log.i("Places after sorting", "Place: " + p.name);
}
</code></pre>
<p>Here is the log output:</p>
<pre><code>04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places before sorting﹕ Place: New York
04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places before sorting﹕ Place: Colorado
04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places before sorting﹕ Place: Los Angeles
04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places after sorting﹕ Place: Los Angeles
04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places after sorting﹕ Place: Colorado
04-17 23:04:16.074 12963-12963/com.maptest.daniel.maptest I/Places after sorting﹕ Place: New York
</code></pre>
|
16,372,593 |
How to get facebook profile picture of user in facebook SDK 3.0 Android
|
<p>i am using facebook SDK 3.0 i have to get profile picture of user login.
Here is the code I use: </p>
<pre><code>URL image_value = new URL("http://graph.facebook.com/"+id+"/picture" );
profPict=BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
</code></pre>
<p>But I don't get the desired result.</p>
| 17,794,658 | 8 | 1 | null |
2013-05-04 09:09:41.23 UTC
| 9 |
2016-09-23 13:00:10.96 UTC
|
2013-05-04 15:16:17.44 UTC
| null | 1,677,125 | null | 2,349,436 | null | 1 | 15 |
android|facebook|facebook-android-sdk
| 28,091 |
<p>You should change your code following:</p>
<pre><code>URL image_value = new URL("http://graph.facebook.com/"+id+"/picture" );
</code></pre>
<p>Possible GET parameters for the URL can be found here:
<a href="https://developers.facebook.com/docs/graph-api/reference/user/picture/" rel="noreferrer">https://developers.facebook.com/docs/graph-api/reference/user/picture/</a></p>
|
16,105,718 |
DataGridView changing cell background color
|
<p>I have the following code :</p>
<pre><code>private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dgvStatus.Rows)
{
row.Cells[color.Index].Style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
}
}
</code></pre>
<p>I am trying to set the background color of each cell from the background color column. this doesn't work the color never change. Any idea of why?</p>
<p>I've been looking around but didn't found anything usefull</p>
| 16,106,585 | 10 | 0 | null |
2013-04-19 13:25:36.653 UTC
| 4 |
2020-05-25 12:27:44.753 UTC
|
2018-12-21 18:13:28.267 UTC
| null | 3,998,265 | null | 2,145,522 | null | 1 | 20 |
c#|winforms|datagridview
| 164,096 |
<p>I finally managed to get it working. Here the code :</p>
<pre><code>private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex != color.Index)
return;
e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));
}
</code></pre>
<p>if anyone know a better to do this please don't hesitate to post it. I'm open to suggestion</p>
|
16,432,265 |
What's the difference between runghc and runhaskell?
|
<p>RWH suddenly started using runhaskell instead of runghc. What's the difference? As far as I can tell, they work the same.</p>
| 16,432,345 | 1 | 0 | null |
2013-05-08 03:40:53.13 UTC
| 2 |
2015-05-14 01:56:09.68 UTC
| null | null | null | null | 926,143 | null | 1 | 38 |
haskell
| 8,281 |
<p><code>runhaskell</code> can run whatever Haskell interpreter you're using on your system—it does not necessarily have to be GHCi. For example, <code>runhaskell</code> could instead point to <code>runhugs</code> or <code>runjhc</code> or whatever, if appropriate.</p>
<p>Essentially, it's just a nice alias. By using it, you make it much easier to change which compiler you're using in the future. After all, having <code>runghc</code> run <code>jhc</code> instead would be confusing!</p>
|
16,557,071 |
Git: error: RPC failed; result=22, HTTP code = 411
|
<p><strong>Symptoms:</strong></p>
<p>Git suddenly refused to push a repository (to github in my case):</p>
<pre><code>$ git push
Counting objects: 9292, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (2136/2136), done.
error: RPC failed; result=22, HTTP code = 411
fatal: The remote end hung up unexpectedly
Writing objects: 100% (8222/8222), 1.27 MiB | 837 KiB/s, done.
Total 8222 (delta 6060), reused 8181 (delta 6033)
fatal: The remote end hung up unexpectedly
Everything up-to-date
</code></pre>
| 16,557,072 | 1 | 1 | null |
2013-05-15 04:47:41.163 UTC
| 28 |
2014-01-22 07:29:19.17 UTC
| null | null | null | null | 166,484 | null | 1 | 68 |
git|github|runtime-error
| 28,319 |
<p>Here is what helped, the following command increases git buffer to 500mb:</p>
<pre><code>git config http.postBuffer 524288000
</code></pre>
|
16,296,622 |
Rename column SQL Server 2008
|
<p>I am using SQL Server 2008 and Navicat. I need to rename a column in a table using SQL.</p>
<pre><code>ALTER TABLE table_name RENAME COLUMN old_name to new_name;
</code></pre>
<p>This statement doesn't work.</p>
| 16,296,669 | 11 | 2 | null |
2013-04-30 09:34:48.44 UTC
| 104 |
2020-11-22 16:06:17.847 UTC
|
2018-01-15 10:10:59.84 UTC
| null | 133 | null | 1,303,193 | null | 1 | 763 |
sql|sql-server|sql-server-2008|alter-table
| 1,393,235 |
<p>Use <code>sp_rename</code></p>
<pre><code>EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'
</code></pre>
<p>See: <a href="http://blog.sqlauthority.com/2008/08/26/sql-server-how-to-rename-a-column-name-or-table-name/" rel="noreferrer">SQL SERVER – How to Rename a Column Name or Table Name</a></p>
<p>Documentation: <a href="https://docs.microsoft.com/de-de/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql" rel="noreferrer"><strong>sp_rename</strong> (Transact-SQL)</a></p>
<p>For your case it would be:</p>
<pre><code>EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN'
</code></pre>
<p>Remember to use single quotes to enclose your values. </p>
|
16,335,729 |
how to convert image to matrix
|
<p>i am interested how to convert given image into matrix form with just numbers?for example let take following picture</p>
<p><img src="https://i.stack.imgur.com/8rbvI.jpg" alt="enter image description here"></p>
<p>as i know there exist in matlab special functions,which decompose given image into colors and numbers,for example i have seen this code on this website</p>
<pre><code>I = imread('test.jpg');
b = dec2bin(I); % b becomes vector
% some actions with binary vector
du = bin2dec(b);
du = reshape(du,size(I)); % converting vector du to 3d Image array
imwrite(uint8(du), 'du.jpg'); %save our du to file du.jpg
I = imread('du.jpg'); %test if it saved correctly
imshow(du)
</code></pre>
<p>and converted to my picture,like this</p>
<pre><code>I=imread('tensor_in.jpg');
b=dec2bin(I)
</code></pre>
<p>and get the following array,in fact only with zero and one</p>
<pre><code>00001110
00001111
00010000
00010000
00010001
00010010
00010011
00010101
00010110
00011000
00011001
00011000
00010101
00010101
00010101
00010101
00010101
00010101
00010101
00010101
00011000
00011000
00011000
00011000
00011000
00011000
00011000
00011000
00011011
00011011
00011011
00011011
00011011
00011011
00011011
00011011
00011100
00011100
00011100
00011101
00011101
00011110
00011110
00011101
00011110
00011011
00011011
00011011
00100000
00100011
00101001
00101011
00101111
</code></pre>
<p>clearly i have not continued,because it's size is </p>
<pre><code><151074x8 char>
</code></pre>
<p>and follows same rule as for example</p>
<pre><code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code></pre>
<p>but i am interested if instead of getting digital array,how to get array with some another numbers,like for example</p>
<pre><code>2 1 3
4 21 23
67 89 100
</code></pre>
<p>let's say like this.could i do in matlab?please help me</p>
| 16,338,816 | 1 | 9 | null |
2013-05-02 10:28:14.863 UTC
| 2 |
2020-08-23 20:49:11.527 UTC
|
2013-05-02 11:01:07.757 UTC
| null | 466,534 | null | 466,534 | null | 1 | -2 |
matlab|image-processing|matrix
| 44,646 |
<p>Dato, when you use</p>
<pre><code>I = imread('test.jpg');
</code></pre>
<p>your image is already in an array form of numbers. Each "number" tells you part of the color information. </p>
<p>If the image file is in an indexed form you will get a NxM array (for an image of the size NxM).</p>
<p>If the image is not indexed, you will get an NxMx3 array, where each of the three NxM arrays corresponds, respectively to the red, green and blue channel.</p>
<p>i suggest you to study how matlab handles images: <a href="http://www.mathworks.de/de/help/matlab/creating_plots/working-with-images-in-matlab-graphics.html" rel="noreferrer">http://www.mathworks.de/de/help/matlab/creating_plots/working-with-images-in-matlab-graphics.html</a></p>
|
53,335,950 |
Performance penalty of creating handlers on every render with react-hooks
|
<p>I'm currently very amazed about the use cases of the new react <a href="https://reactjs.org/docs/hooks-intro.html" rel="noreferrer">hooks</a> API and what you can possibly do with it.</p>
<p>A question that came up while experimenting was how expensive it is to always create a new handler function just to throw it away when using <code>useCallback</code>.</p>
<p>Considering this example:</p>
<pre><code>const MyCounter = ({initial}) => {
const [count, setCount] = useState(initial);
const increase = useCallback(() => setCount(count => count + 1), [setCount]);
const decrease = useCallback(() => setCount(count => count > 0 ? count - 1 : 0), [setCount]);
return (
<div className="counter">
<p>The count is {count}.</p>
<button onClick={decrease} disabled={count === 0}> - </button>
<button onClick={increase}> + </button>
</div>
);
};
</code></pre>
<p>Although I'm wrapping the handler into a <code>useCallback</code> to avoid passing down a new handler every time it renders the inline arrow function still has to be created only to be thrown away in the majority of times. </p>
<p>Probably not a big deal if I only render a few components. But how big is the impact on performance if I do that 1000s of times? Is there a noticeable performance penalty? And what would be a way to avoid it? Probably a static handler factory that only gets called when a new handler has to be created?</p>
| 53,336,060 | 5 | 10 | null |
2018-11-16 10:28:36.217 UTC
| 3 |
2020-03-21 16:05:56.083 UTC
|
2019-04-05 05:55:10.067 UTC
| null | 5,928,186 | null | 5,005,177 | null | 1 | 36 |
javascript|reactjs|arrow-functions|react-hooks
| 7,747 |
<p>The <strong><a href="https://reactjs.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render" rel="noreferrer">React FAQs</a></strong> provide an explanation to it </p>
<blockquote>
<p><strong>Are Hooks slow because of creating functions in render?</strong></p>
<p>No. In modern browsers, the raw performance of closures compared to
classes doesn’t differ significantly except in extreme scenarios.</p>
<p>In addition, consider that the design of Hooks is more efficient in a
couple ways:</p>
<p>Hooks avoid a lot of the overhead that classes require, like the cost
of creating class instances and binding event handlers in the
constructor.</p>
<p>Idiomatic code using Hooks doesn’t need the deep component tree
nesting that is prevalent in codebases that use higher-order
components, render props, and context. With smaller component trees,
React has less work to do.</p>
<p>Traditionally, performance concerns around inline functions in React
have been related to how passing new callbacks on each render breaks
shouldComponentUpdate optimizations in child components. Hooks
approach this problem from three sides.</p>
</blockquote>
<p>So overall benefits that hooks provide are much greater than the penalty of creating new functions</p>
<p>Moreover for functional components, you can optimize by making use of <code>useMemo</code> so that the components are re-rendering when there is not change in their props. </p>
|
41,932,635 |
Scanning classpath/modulepath in runtime in Java 9
|
<p>I can't seem to find any info on whether scanning all available classes (for interfaces, annotations etc) is still possible in runtime, the way Spring, Reflections and many other frameworks and libraries currently do, in the face of Jigsaw related changes to the way classes are loaded.</p>
<p><strong><em>EDIT</em></strong>:
This question is about <em>scanning</em> the real physical file paths looking for classes. <a href="https://stackoverflow.com/questions/45166757/loading-classes-and-resources-in-java-9">The other question</a> is about dynamically <em>loading</em> classes and resources. It's related but very much <strong>not a duplicate</strong>.</p>
<p><strong><em>UPDATE</em></strong>: Jetty project has made a <a href="https://github.com/jetty-project/annotation-discovery" rel="noreferrer">JEP proposal</a> for a standardized API for this. If you have a way to help make this reality, please do. Otherwise, wait and hope.</p>
<p><strong><em>UPDATE 2</em></strong>: Found <a href="http://mail.openjdk.java.net/pipermail/jigsaw-dev/2017-September/013182.html" rel="noreferrer">this</a> relevant sounding post. Quoting the code snippet for posterity:</p>
<blockquote>
<p>If you are really just looking to get at the contents of the modules in
the boot layer (the modules that are resolved at startup) then you'll do
something like this:</p>
</blockquote>
<pre><code> ModuleLayer.boot().configuration().modules().stream()
.map(ResolvedModule::reference)
.forEach(mref -> {
System.out.println(mref.descriptor().name());
try (ModuleReader reader = mref.open()) {
reader.list().forEach(System.out::println);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
});
</code></pre>
| 45,612,376 | 2 | 6 | null |
2017-01-30 09:36:19.177 UTC
| 12 |
2022-07-20 11:54:25.88 UTC
|
2018-06-14 14:24:28.31 UTC
| null | 294,657 | null | 294,657 | null | 1 | 24 |
java|classpath|java-9|java-platform-module-system|java-module
| 9,879 |
<p>The following code achieves module path scanning in Java 9+ (Jigsaw / JPMS). It finds all classes on the callstack, then for each class reference, calls <code>classRef.getModule().getLayer().getConfiguration().modules()</code>, which returns a a <code>List<ResolvedModule></code>, rather than just a <code>List<Module></code>. (<code>ResolvedModule</code> gives you access to the module resources, whereas <code>Module</code> does not.) Given a <code>ResolvedModule</code> reference for each module, you can call the <code>.reference()</code> method to get the <code>ModuleReference</code> for a module. <code>ModuleReference#open()</code> gives you a <code>ModuleReader</code>, which allows you to list the resources in a module, using <code>ModuleReader#list()</code>, or to open a resource using <code>Optional<InputStream> ModuleReader#open(resourcePath)</code> or <code>Optional<ByteBuffer> ModuleReader#read(resourcePath)</code>. You then close the <code>ModuleReader</code> when you're done with the module. This is not documented anywhere that I have seen. It was very difficult to figure all this out. But here is the code, in the hope that someone else will benefit from this.</p>
<p>Note that even in JDK9+, you can still utilize traditional classpath elements along with module path elements, so for a complete module path + classpath scan, you should probably use a proper classpath scanning solution, such as <a href="https://github.com/classgraph/classgraph" rel="noreferrer">ClassGraph</a>, which supports module scanning using the below mechanism (disclaimer, I am the author). You can find a reflection-based version of the following code <a href="https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/classpath/ModuleFinder.java" rel="noreferrer">here</a>.</p>
<p>Also note that there was a <a href="https://bugs.openjdk.java.net/browse/JDK-8210457" rel="noreferrer">bug</a> in StackWalker in several JDK releases after JDK 9 that has to be worked around, see the above reflection-based code for details.</p>
<pre><code>package main;
import java.lang.StackWalker;
import java.lang.StackWalker.Option;
import java.lang.StackWalker.StackFrame;
import java.lang.module.ModuleReader;
import java.lang.module.ModuleReference;
import java.lang.module.ResolvedModule;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
public class Java9Scanner {
/** Recursively find the topological sort order of ancestral layers. */
private static void findLayerOrder(ModuleLayer layer,
Set<ModuleLayer> visited, Deque<ModuleLayer> layersOut) {
if (visited.add(layer)) {
List<ModuleLayer> parents = layer.parents();
for (int i = 0; i < parents.size(); i++) {
findLayerOrder(parents.get(i), visited, layersOut);
}
layersOut.push(layer);
}
}
/** Get ModuleReferences from a Class reference. */
private static List<Entry<ModuleReference, ModuleLayer>> findModuleRefs(
Class<?>[] callStack) {
Deque<ModuleLayer> layerOrder = new ArrayDeque<>();
Set<ModuleLayer> visited = new HashSet<>();
for (int i = 0; i < callStack.length; i++) {
ModuleLayer layer = callStack[i].getModule().getLayer();
findLayerOrder(layer, visited, layerOrder);
}
Set<ModuleReference> addedModules = new HashSet<>();
List<Entry<ModuleReference, ModuleLayer>> moduleRefs = new ArrayList<>();
for (ModuleLayer layer : layerOrder) {
Set<ResolvedModule> modulesInLayerSet = layer.configuration()
.modules();
final List<Entry<ModuleReference, ModuleLayer>> modulesInLayer =
new ArrayList<>();
for (ResolvedModule module : modulesInLayerSet) {
modulesInLayer
.add(new SimpleEntry<>(module.reference(), layer));
}
// Sort modules in layer by name for consistency
Collections.sort(modulesInLayer,
(e1, e2) -> e1.getKey().descriptor().name()
.compareTo(e2.getKey().descriptor().name()));
// To be safe, dedup ModuleReferences, in case a module occurs in multiple
// layers and reuses its ModuleReference (no idea if this can happen)
for (Entry<ModuleReference, ModuleLayer> m : modulesInLayer) {
if (addedModules.add(m.getKey())) {
moduleRefs.add(m);
}
}
}
return moduleRefs;
}
/** Get the classes in the call stack. */
private static Class<?>[] getCallStack() {
// Try StackWalker (JDK 9+)
PrivilegedAction<Class<?>[]> stackWalkerAction =
(PrivilegedAction<Class<?>[]>) () ->
StackWalker.getInstance(
Option.RETAIN_CLASS_REFERENCE)
.walk(s -> s.map(
StackFrame::getDeclaringClass)
.toArray(Class[]::new));
try {
// Try with doPrivileged()
return AccessController
.doPrivileged(stackWalkerAction);
} catch (Exception e) {
}
try {
// Try without doPrivileged()
return stackWalkerAction.run();
} catch (Exception e) {
}
// Try SecurityManager
PrivilegedAction<Class<?>[]> callerResolverAction =
(PrivilegedAction<Class<?>[]>) () ->
new SecurityManager() {
@Override
public Class<?>[] getClassContext() {
return super.getClassContext();
}
}.getClassContext();
try {
// Try with doPrivileged()
return AccessController
.doPrivileged(callerResolverAction);
} catch (Exception e) {
}
try {
// Try without doPrivileged()
return callerResolverAction.run();
} catch (Exception e) {
}
// As a fallback, use getStackTrace() to try to get the call stack
try {
throw new Exception();
} catch (final Exception e) {
final List<Class<?>> classes = new ArrayList<>();
for (final StackTraceElement elt : e.getStackTrace()) {
try {
classes.add(Class.forName(elt.getClassName()));
} catch (final Throwable e2) {
// Ignore
}
}
if (classes.size() > 0) {
return classes.toArray(new Class<?>[0]);
} else {
// Last-ditch effort -- include just this class
return new Class<?>[] { Java9Scanner.class };
}
}
}
/**
* Return true if the given module name is a system module.
* There can be system modules in layers above the boot layer.
*/
private static boolean isSystemModule(
final ModuleReference moduleReference) {
String name = moduleReference.descriptor().name();
if (name == null) {
return false;
}
return name.startsWith("java.") || name.startsWith("jdk.")
|| name.startsWith("javafx.") || name.startsWith("oracle.");
}
public static void main(String[] args) throws Exception {
// Get ModuleReferences for modules of all classes in call stack,
List<Entry<ModuleReference, ModuleLayer>> systemModuleRefs = new ArrayList<>();
List<Entry<ModuleReference, ModuleLayer>> nonSystemModuleRefs = new ArrayList<>();
Class<?>[] callStack = getCallStack();
List<Entry<ModuleReference, ModuleLayer>> moduleRefs = findModuleRefs(
callStack);
// Split module refs into system and non-system modules based on module name
for (Entry<ModuleReference, ModuleLayer> m : moduleRefs) {
(isSystemModule(m.getKey()) ? systemModuleRefs
: nonSystemModuleRefs).add(m);
}
// List system modules
System.out.println("\nSYSTEM MODULES:\n");
for (Entry<ModuleReference, ModuleLayer> e : systemModuleRefs) {
ModuleReference ref = e.getKey();
System.out.println(" " + ref.descriptor().name());
}
// Show info for non-system modules
System.out.println("\nNON-SYSTEM MODULES:");
for (Entry<ModuleReference, ModuleLayer> e : nonSystemModuleRefs) {
ModuleReference ref = e.getKey();
ModuleLayer layer = e.getValue();
System.out.println("\n " + ref.descriptor().name());
System.out.println(
" Version: " + ref.descriptor().toNameAndVersion());
System.out.println(
" Packages: " + ref.descriptor().packages());
System.out.println(" ClassLoader: "
+ layer.findLoader(ref.descriptor().name()));
Optional<URI> location = ref.location();
if (location.isPresent()) {
System.out.println(" Location: " + location.get());
}
try (ModuleReader moduleReader = ref.open()) {
Stream<String> stream = moduleReader.list();
stream.forEach(s -> System.out.println(" File: " + s));
}
}
}
}
</code></pre>
|
15,158,811 |
Use of 1=2 in a SQL query
|
<p>Someone please explain the meaning of <strong><em>'1=2'</em></strong> in the below SQL query.</p>
<pre><code>SELECT E.EmpID,
E.EmpName,
Country = CASE
WHEN T.Active = 'N'
AND 1 = 2 THEN 'Not Working Anymore'
ELSE C.Country_Name
END,
T.Contract_No
FROM Employees E (nolock)
INNER JOIN Contract T
ON T.Contract_No = E.Contract_No
LEFT JOIN Country C (nolock)
ON E.Country_ID = C.Country_ID
</code></pre>
<p>thanks</p>
<p>EDIT:- Corrected the slight mistake existed in the example SQL query given by me.
@ ALL :- The query mentioned here is an example version of a big working query on which I have to reoslve something. I have created a sample scenario of SQL query for the sake of simplicity of question.</p>
| 15,158,931 | 10 | 7 | null |
2013-03-01 13:22:27.53 UTC
| 2 |
2020-02-03 16:20:53.213 UTC
|
2013-03-01 14:02:34.903 UTC
| null | 73,226 | null | 609,736 | null | 1 | 7 |
sql
| 42,396 |
<pre><code>when T.Active = 'N' and 1=2 then 'Not Working Anymore'
</code></pre>
<p>Simple, the above condition will never become <code>true</code>.
So the result will always be <code>C.Country_Name</code></p>
|
24,727,428 |
Eclipse Error: java.lang.CharSequence cannot be resolved
|
<p>I'm getting a error trying to compile a simple code in Eclipse. I'm using jre8.</p>
<p>For example, when I try to compile this code:</p>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyProject {
public static void main (String args[])
{
List<String> myList = new ArrayList<String>();
myList.add("test");
myList.add("test2");
Collections.sort(myList);
}
}
</code></pre>
<p>I get a error in the <code>Collections.sort(myList);</code> line.</p>
<p>The error is:</p>
<pre><code>Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
at project.Principal.main(Principal.java:14)
</code></pre>
<p>I have already opened eclipse Build Path, removed JRE System Library [jre8] and added it again. But didn't work! What can I do? Thanks!</p>
<p>PS.: In the <code>Collections.sort(myList);</code> line eclipse shows this error:</p>
<p><strong>The type java.lang.CharSequence cannot be resolved. It is inderectly referenced from required .class files.</strong></p>
| 28,989,940 | 2 | 6 | null |
2014-07-13 22:22:00.637 UTC
| 4 |
2018-01-14 14:25:27.11 UTC
| null | null | null | null | 3,513,453 | null | 1 | 10 |
java|eclipse
| 53,863 |
<h1>Ensure that your Eclipse IDE supports Java 8:</h1>
<p>The first Eclipse version supporting Java 8 was Eclipse Kepler SR2 (4.3.2) with an additional patch. (See: <a href="https://waynebeaton.wordpress.com/2014/03/26/add-java-8-support-to-eclipse-kepler/" rel="nofollow noreferrer">Installing Java™ 8 Support in Eclipse Kepler SR2</a>, and the corresponding Marketplace Item that needs to be installed: <a href="http://marketplace.eclipse.org/content/java-8-support-eclipse-kepler-sr2" rel="nofollow noreferrer">Java 8 support for Eclipse Kepler SR2</a>).</p>
<p>In my opinion you should udpate to the <a href="http://www.eclipse.org/downloads/" rel="nofollow noreferrer">latest Eclipse Version</a>.</p>
<p>With Luna SR2 (4.4.2) no additional patch is necessary.</p>
<hr>
<h1>Ensure the 1.8 JRE is available in your Workspace:</h1>
<p>Windows > Preferences: Java > Installed JREs</p>
<p><img src="https://i.stack.imgur.com/VbzY1.png" alt="Installed JREs"></p>
<p>If this is not the case you can add a new JRE with the add button.</p>
<hr>
<h1>Ensure that <code>JRE System Library</code> == <code>JavaSE-1.8</code> for your Project</h1>
<p>In the Package Explorer, you should see the Java version:</p>
<p><img src="https://i.stack.imgur.com/0BLdA.png" alt="Package Explorer"></p>
<p>If this is not correct you should open the context menu the <code>JRE System Library</code> item and select the <code>Properties</code> menu entry.</p>
<p><img src="https://i.stack.imgur.com/2XSuc.png" alt="JRE System Library - Properties"></p>
<p>In your project you have a <code>.classpath</code> file (Use the <code>Navigator View</code> if you do not see the file), that should looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="output" path="bin"/>
</classpath>
</code></pre>
<hr>
<h1>Rebuild your project</h1>
<p>Project Menu > Clean...</p>
<p>Select your project from the list or "Clean all projects" and "Start a build immediately"</p>
<hr>
<p>See also:</p>
<ul>
<li>Explaination from @mkrakhin in his answer: <a href="https://stackoverflow.com/a/24302496/91497">The type java.lang.CharSequence cannot be resolved in package declaration</a></li>
</ul>
|
12,005,993 |
Java/Eclipse: How to configure Run Configuration's Classpath for JUnit test?
|
<p>I have an Eclipse project with the following directory structure:</p>
<pre><code>MyProj/
src/main/java/
com.me.myproject.widgets
Widget.java
src/main/config
widget-config.xml
src/test/java
com.me.myproject.widgets
WidgetTest.java
src/test/config
widget-test-config.xml
</code></pre>
<p>The <code>Widget</code> class reads its config (XML) file in from anywhere on the classpath and uses it to configure its properties.</p>
<p>I am trying to just get <code>WidgetTest</code>'s test cases (all written with JUnit) to run inside Eclipse when I right-click the file and go to <code>Run As >> JUnit Test</code>. I assume I'll have to actually run it as a customized <em>Run Configuration</em> with its own configured classpath, but I'm not sure about that as I've never done this before.</p>
<p>Does anybody know how I can get a custom Run Configuration to run <code>WidgetTest.java</code> as a JUnit test, and successfully place <code>src/test/config/widget-test-config.xml</code> on the classpath? Thanks in advance!</p>
<p>Please note, this question is <strong>not</strong> about how to read a resource from the runtime classpath, its about how to get it on Eclipse's JUnit Run Config classpath in the first place!</p>
| 12,006,195 | 2 | 0 | null |
2012-08-17 12:38:38.22 UTC
| 5 |
2012-08-17 13:39:34.773 UTC
| null | null | null | null | 892,029 | null | 1 | 3 |
java|eclipse|junit|classpath
| 59,052 |
<p>I was under the impression that as long as you have <code>src/test/config/widget-test-config.xml</code> inside what Eclipse considers to be a source folder, it should already be on the classpath.</p>
<p>Is src/test a source folder for Eclipse ? If it is and you still get the problem, try out the following experiment : </p>
<p>If you copy widget-test-config.xml to the src root can Widget class read it ?</p>
<h2>If Yes </h2>
<p>then it's a problem of the test folder not being on the classpath and you may wanna try adding it manually like so. </p>
<p>Right click WidgetTest and select <code>Run As -> Junit Test</code>. This should automatically create a Junit Run Configuration accessible at <code>Run -> Run Configurations</code>. You modify it's Classpath entry to add the project containing the .xml file like so :</p>
<p><img src="https://i.stack.imgur.com/0Sy5s.png" alt="enter image description here"></p>
<h2>If No</h2>
<p>If, even after moving the .xml file to the src root (i.e. default package), your widget class cannot read it then there is something else wrong. In that case, it would be great if you could furnish the snippet of code in WidgetTest which is trying to read the .xml file.</p>
<h1> Working Code </h1>
<p>Here is a bit of working code :</p>
<pre><code>public class A {
@Test
public void test() {
InputStream stream = A.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
</code></pre>
<p>The above works for me in a simple JAVA project and runs fine. (Running fine means getting
'true' printed on the console)</p>
<p>I am in the process of creating a GITHub repo for you to try out this code painlessly.</p>
<h2> GIT Hub Repo with Test project</h2>
<p>You should be able to import the project in <strong><a href="https://github.com/ajorpheus/stack-overflow/zipball/master" rel="noreferrer">this</a></strong> zip and see the code working. Right click on the Test class <code>A</code> and click <code>Run As -> Junit Test</code>, and you should see two <code>true</code> in the Console.</p>
|
19,589,231 |
Can I iterate through a NodeList using for-each in Java?
|
<p>I want to iterate through a <code>NodeList</code> using a for-each loop in Java. I have it working with a for loop and a do-while loop but not for-each.</p>
<pre><code>NodeList nList = dom.getElementsByTagName("year");
do {
Element ele = (Element) nList.item(i);
list.add(ele.getElementsByTagName("MonthId").item(0).getTextContent());
i++;
} while (i < nList.getLength());
NodeList nList = dom.getElementsByTagName("year");
for (int i = 0; i < nList.getLength(); i++) {
Element ele = (Element) nList.item(i);
list.add(ele.getElementsByTagName("MonthId").item(0).getTextContent());
}
</code></pre>
| 19,591,302 | 12 | 3 | null |
2013-10-25 11:58:24.017 UTC
| 6 |
2022-08-28 13:16:19.95 UTC
|
2018-01-08 16:19:06.95 UTC
| null | 7,248,342 | null | 2,919,834 | null | 1 | 53 |
java|xml|dom
| 69,626 |
<p>The workaround for this problem is straight-forward, and, thankfully you have to implements it only once.</p>
<pre><code>import java.util.*;
import org.w3c.dom.*;
public final class XmlUtil {
private XmlUtil(){}
public static List<Node> asList(NodeList n) {
return n.getLength()==0?
Collections.<Node>emptyList(): new NodeListWrapper(n);
}
static final class NodeListWrapper extends AbstractList<Node>
implements RandomAccess {
private final NodeList list;
NodeListWrapper(NodeList l) {
list=l;
}
public Node get(int index) {
return list.item(index);
}
public int size() {
return list.getLength();
}
}
}
</code></pre>
<p>Once you have added this utility class to your project and added a <code>static</code> <code>import</code> for the <code>XmlUtil.asList</code> method to your source code you can use it like this:</p>
<pre><code>for(Node n: asList(dom.getElementsByTagName("year"))) {
…
}
</code></pre>
|
17,656,320 |
Using Python in vimscript: How to export a value from a python script back to vim?
|
<p>I'm struggling with Python in vim.<br>
I still haven't found out how I can import a value from a python script (in a vim function) back to vim p.e.</p>
<pre><code>function! myvimscript()
python << endpython
import vim, random, sys
s = vim.eval("mylist")
# do operation with variable "s" in python
endpython
" import variable "s" from above
" do operation with "s" in vimscript
endfunction
</code></pre>
<p>1) How can I use <code>"s"</code> again in vim (how can I import <code>"s"</code> from the python code back to vim)? </p>
<p>I can't find out as well how to use vim.current.buffer with a selection. </p>
<pre><code>function! myvimscript()
let startline = line("'<")
let endline = line("'>")
python << endpython
start = vim.eval("startline")
end = vim.eval("endline")
cb = vim.current.buffer
l = cb[start:end]
endpython
endfunction
</code></pre>
<p>2) How can I assign the dynamic value <code>"start"</code> and <code>"end"</code> to <code>"l"</code> </p>
| 17,657,288 | 3 | 3 | null |
2013-07-15 14:11:31.803 UTC
| 9 |
2019-12-12 05:53:37.583 UTC
|
2015-02-15 17:04:44.43 UTC
| null | 660,921 | null | 662,967 | null | 1 | 21 |
python|variables|vim
| 7,939 |
<p>First of all, please define your function name starting with uppercase.</p>
<p>Here is an example for your two questions. I hope it helps:</p>
<pre><code>function! TestPy() range
let startline = line("'<")
let endline = line("'>")
echo "vim-start:".startline . " vim-endline:".endline
python << EOF
import vim
s = "I was set in python"
vim.command("let sInVim = '%s'"% s)
start = vim.eval("startline")
end = vim.eval("endline")
print "start, end in python:%s,%s"% (start, end)
EOF
echo sInVim
endfunction
</code></pre>
<p>first I paste the output of a small test: I visual selected 3,4,5, three lines, and <code>:call TestPy()</code></p>
<p>The output I had:</p>
<pre><code>vim-start:3 vim-endline:5
start, end in python:3,5
I was set in python
</code></pre>
<p>So I explain the output a bit, you may need to read the example function codes a little for understanding the comment below.</p>
<pre><code>vim-start:3 vim-endline:5 #this line was printed in vim, by vim's echo.
start, end in python:3,5 # this line was prrinted in py, using the vim var startline and endline. this answered your question two.
I was set in python # this line was printed in vim, the variable value was set in python. it answered your question one.
</code></pre>
<p>I added a <code>range</code> for your function. because, if you don't have it, for each visual-selected line, vim will call your function once. in my example, the function will be executed 3 times (3,4,5). with range, it will handle visualselection as a range. It is sufficient for this example. If your real function will do something else, you could remove the <code>range</code>.</p>
<p>With <code>range</code>, better with <code>a:firstline and a:lastline</code>. I used the <code>line("'<")</code> just for keep it same as your codes.</p>
<p><strong>EDIT</strong> with list variable:</p>
<p>check this function:</p>
<pre><code>function! TestPy2()
python << EOF
import vim
s = range(10)
vim.command("let sInVim = %s"% s)
EOF
echo type(sInVim)
echo sInVim
endfunction
</code></pre>
<p>if you call it, the output is:</p>
<pre><code>3
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>the "3" means type list (check type() function). and one line below is the string representation of list.</p>
|
17,364,951 |
Remove all lines before a match with sed
|
<p>I'm using sed to filter a list of files. I have a sorted list of folders and I want to get all lines after a specific one. To do this task I'm using the solution described <a href="https://stackoverflow.com/a/5935779/518204">here</a> which works pretty well with any input I tried but it doesn't work when the match is on the first line. In that case sed will remove all lines of the input</p>
<p>Here it's an example:</p>
<pre><code>$ ls -1 /
bin
boot
...
sys
tmp
usr
var
vmlinuz
$ ls -1 / | sed '1,/tmp/d'
usr
var
vmlinuz
$ ls -1 / | sed '1,/^bin$/d'
# sed will delete all lines from the input stream
</code></pre>
<p>How should I change the command to consider also the limit case when first line is matched by regexp?</p>
<p>BTW <code>sed '1,1d'</code> correctly works and remove the first line only.</p>
| 17,365,103 | 4 | 3 | null |
2013-06-28 12:40:11.303 UTC
| 14 |
2021-01-16 15:14:14.237 UTC
|
2021-01-16 09:29:50.52 UTC
| null | 10,248,678 | null | 518,204 | null | 1 | 62 |
sed
| 59,057 |
<p>try this (GNU sed only):</p>
<pre><code>sed '0,/^bin$/d'
</code></pre>
<p>..output is:</p>
<pre>
$sed '0,/^bin$/d' file
boot
...
sys
tmp
usr
var
vmlinuz
</pre>
|
30,391,939 |
Synchronization of data with video using WebRTC
|
<p>I'm using <code>WebRTC</code> to send video from a server to client browser (using the native <code>WebRTC API</code> and an <code>MCU WebRTC</code> server like Kurento).</p>
<p>Before sending it to clients each frame of the video contained metadata (like subtitles or any other applicative content). I'm looking for a way to send this metadata to the client such that it remains synchronized (to the time it is actually <em>presented</em>). In addition I would like to be able to access this data from the client side (by Javascript).</p>
<p>Some options I thought about:</p>
<ul>
<li>Sending the data by WebRTC DataChannel. But I don't know how to ensure the data is synchronized on a per-frame basis. But I couldn't find a way to ensure the data sent by the data channel and the video channel is synchronize (again, I hope to get precision level of single frame).</li>
<li>Sending the data manually to the client in some way (WebRTC DataChannel, websockets, etc.) with timestamps that match the video's timestamps. However, even if Kurento or other middle servers preserve the timestamp information in the video, according to the following answer there is no applicative way to get the video timestamps from the javascript:
<a href="https://stackoverflow.com/questions/15009887/how-can-use-the-webrtc-javascript-api-to-access-the-outgoing-audio-rtp-timestamp">How can use the webRTC Javascript API to access the outgoing audio RTP timestamp at the sender and the incoming audio RTP timestamp at the receiver?</a>. I thought about using the standard video element's <code>timeupdate</code> event, but I don't konw if it will work for precision level of frame, and I'm not sure what it means in a live video as in WebRTC.</li>
<li>Sending the data manually and attach it to the video applicatively as another <code>TextTrack</code>. Then use the <code>onenter</code> and <code>onexit</code> to read it synchronizely: <a href="http://www.html5rocks.com/en/tutorials/track/basics/" rel="noreferrer">http://www.html5rocks.com/en/tutorials/track/basics/</a>. It still requires precise timestamps, and I'm not sure how to know what are the timestamps and if Kurento pass them as-is.</li>
<li>Using the statistics API of WebRTC to manually count frames (using <code>getstats</code>), and hope that the information provided by this API is precise.</li>
</ul>
<p>What is the best way to do that, and how to solve the problems I mentioned in either way?</p>
<p><strong>EDIT:</strong> Precise synchronization (in resolution of no more than a single frame ) of metadata with the appropriate frame is required.</p>
| 35,572,224 | 2 | 4 | null |
2015-05-22 08:32:25.823 UTC
| 9 |
2016-02-23 08:17:20.383 UTC
|
2017-05-23 11:54:27.7 UTC
| null | -1 | null | 2,463,642 | null | 1 | 22 |
javascript|html|video|video-streaming|webrtc
| 11,552 |
<p>I suspect the amount of data per frame is fairly small. I would look at encoding it into a 2D barcode image and place it in each frame in a way so it is not removed by compression. Alternatively just encode timestamp like this. </p>
<p>Then on the player side you look at the image in a particular frame and get the data out or if it.</p>
|
36,916,093 |
Convert ipynb to pdf in Jupyter
|
<p>I am new to ipython notebook, and I would like to convert my ipynb to pdf. But I get the following error when I try to Download as PDF via LaTex.</p>
<pre><code>nbconvert failed: pdflatex not found on PATH
</code></pre>
<p>There is no documentation anywhere how to add pdflatex to my PATH. I use windows. Thank you!</p>
| 38,928,026 | 9 | 5 | null |
2016-04-28 13:24:55.04 UTC
| 11 |
2022-03-06 13:13:38.14 UTC
|
2016-04-29 13:41:42.827 UTC
| null | 434,217 | null | 4,770,682 | null | 1 | 37 |
jupyter|jupyter-notebook
| 103,897 |
<p>As said by <a href="https://stackoverflow.com/users/434217/thomas-k">Thomas K</a> in the comments, you need to have Latex installed, and after add the path to the directory containing <code>pdflatex.exe</code> file to the <code>PATH</code> variable of your system.</p>
<p>I have looked for a lightweight distribution and tried installing <a href="https://www.tug.org/texworks/" rel="nofollow noreferrer">TeXworks</a>, but I didn't find any <code>pdflatex.exe</code> file.<br>
So I have tried <a href="https://www.tug.org/texlive/" rel="nofollow noreferrer">TeX Live</a>, which worked fine creating the <code>pdflatex.exe</code> file under the target installation directory. This path should be like <code>C:\...\texlive\2016\bin\win32</code>.<br>
Finally, you should just add this path to the <code>PATH</code> environment variable of your system (you can use the link shared by <a href="https://stackoverflow.com/users/434217/thomas-k">Thomas K</a>).</p>
<p>As said <a href="https://github.com/jupyter/nbconvert/issues/799#issuecomment-539905612" rel="nofollow noreferrer">here</a>, you need to quit jupyter notebook and open a new command prompt after making any path changes, in order for jupyter to find the newly added item to the <code>PATH</code>.</p>
<p>Then, in Jupyter, you can check your environment variables by running the following (refer to this <a href="https://stackoverflow.com/questions/4906977/access-environment-variables-from-python#4907053">link</a> for details):</p>
<pre>
import os
os.environ['PATH'].split(';')
</pre>
<p>and check if it contains the path to <code>pdflatex.exe</code> file.</p>
<p>If you get some trouble when exporting your notebook to pdf due to missing files/packages (this happened to me), refer to this <a href="https://tex.stackexchange.com/questions/274536/find-the-right-package-for-missing-files-in-texlive">link</a> to search and install them under TeX Live.</p>
|
18,708,428 |
How to do Authentication with Node.js and MEAN stack?
|
<p>I am currently working on a text based game with a small team of developers. The game requires login and we are using the MEAN (MongoDB, Express, Angular, Node) Stack for the application codebase, however i am stuck on authentication, as a rails developer i am used to being able to drop in a gem and use the helpers available.</p>
<p>has anybody has any experience with MEAN and Authentication?</p>
| 20,713,765 | 4 | 1 | null |
2013-09-09 23:08:39.837 UTC
| 19 |
2018-02-16 19:43:54.94 UTC
|
2014-08-07 19:17:58.333 UTC
| null | 3,842,582 |
user2693845
| null | null | 1 | 17 |
node.js|mean-stack
| 21,265 |
<p>the MEAN stack by linnovate uses <a href="http://passportjs.org" rel="nofollow noreferrer">Passport.js</a> for its authentication. Passport uses different strategies for authentication. One of these strategies is a username and password pair, which they call <em>LocalStrategy</em>. </p>
<p>Here is one of the samples from the Passportjs-Local Github <a href="https://github.com/jaredhanson/passport-local/wiki/Examples" rel="nofollow noreferrer">Examples Page</a></p>
<p><strong>Step 1: Require Passport</strong></p>
<p>First you require the module after doing npm install passport</p>
<pre><code>var passport = require('passport');
</code></pre>
<p><strong>Step 2: Configure 'Verify' Function</strong></p>
<p>Use the LocalStrategy within Passport. Strategies in passport require a <code>verify</code> function, which accept credentials (in this case, a username and password), and invoke a callback with a user object. In the real world, this would query a database; however, in this example we are using a baked-in set of users.</p>
<pre><code>passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
})
});
}
));
</code></pre>
<p><strong>Step 3: Initialize Passport on app</strong></p>
<p>You need to tell Express that you will be using passport and that it will be managing sessions for you. This is done by using the app.use() during app configuration. </p>
<pre><code>app.use(passport.initialize());
app.use(passport.session());
</code></pre>
<p><strong>Step 4: Configure Middleware on the login URI</strong></p>
<p>Next we need to create a method that will accept when a user tries to login to the app using by POST-ing to a specific URI. It will look like this. </p>
<pre><code>// POST /login
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
//
// curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res) {
res.redirect('/');
});
</code></pre>
<p><strong>Step 5: Set up Sessions</strong>
You may have to create your own serialization for User objects that are being stored in the sessions. That is done with the following </p>
<pre><code>// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
</code></pre>
|
25,932,730 |
HashMap with Null Key and Null Value
|
<p>Consider the following Code :</p>
<pre><code>import java.util.*;
class Employee {
String name;
public Employee(String nm) {
this.name=nm;
}
}
public class HashMapKeyNullValue {
Employee e1;
public void display(){
Employee e2=null;
Map map=new HashMap();
map.put(e2, "25");
System.out.println("Getting the Value When e2 is set as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(e1, "");
System.out.println("Getting the Value when e1 is set as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(null, null); // null as key and null as value
System.out.println("Getting the Value when setting null as KEY and null as value");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
map.put(null, "30");
System.out.println("Getting the Value when setting only null as KEY");
System.out.println("e2 : "+map.get(e2));
System.out.println("e1 : "+map.get(e1));
System.out.println("null : "+map.get(null));
}
public static void main(String[] args) {
new HashMapKeyNullValue().display();
}
}
</code></pre>
<p>The Output of program is :</p>
<pre><code>Getting the Value When e2 is set as KEY
e2 : 25
e1 : 25
null : 25
Getting the Value when e1 is set as KEY
e2 :
e1 :
null :
Getting the Value when setting null as KEY and null as value
e2 : null
e1 : null
null : null
Getting the Value when setting only null as KEY
e2 : 30
e1 : 30
null : 30
</code></pre>
<p>Here how <code>e1, e2, and null</code> as keys are related to each other. Are all three assigned to same hashcode? If yes, WHY?</p>
<p>Since all three look different, the change in one value changes the other. Does it mean, only one entry for key is being made into <code>HashMap</code> either <code>e1, e2 or null</code>? Because all are treated to be same key.</p>
| 25,933,619 | 5 | 2 | null |
2014-09-19 11:19:02.903 UTC
| 11 |
2022-03-21 18:21:18.683 UTC
|
2022-03-21 18:21:18.683 UTC
| null | 1,852,693 | null | 3,287,010 | null | 1 | 36 |
java|collections|null|hashmap|hashcode
| 130,227 |
<p><strong><em><code>HashMap</code></em></strong> does not call hashcode when <em>null</em> is passed as key and null Key is handled as special case.</p>
<h2><strong>Put Method</strong></h2>
<p><strong><em><code>HashMap</code></em></strong> puts <em>null</em> key in bucket <em>0</em> and maps <em>null</em> as key to passed value. HashMap does it by linked list data structure. HashMap uses linked list data structure internally.</p>
<p>Linked list data structure used by <strong><em><code>HashMap</code></em></strong> (a static class in <code>HashMap.java</code>)</p>
<pre><code>static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
}
</code></pre>
<p>In Entry class the <em>K</em> is set to <em>null</em> and value mapped to value passed in put method.</p>
<h2><strong>Get Method</strong></h2>
<p>While in <strong><em><code>Hashmap</code></em></strong> get method the checks if key is passed as <em>null</em>. Search Value for <em>null</em> key in bucket <em>0</em>.</p>
<p><strong>Hence there can only be one null key in one <em></strong><code>hashmap</code><strong></em> object.</strong></p>
|
18,377,268 |
Checkbox value is always 'on'
|
<p>this is my checkbox</p>
<p><strong>HTML</strong></p>
<pre><code><label class="checkbox">
<input id="eu_want_team" name="eu_want_team" type="checkbox">
</label>
</code></pre>
<p><strong>JQuery</strong></p>
<pre><code>var eu_want_team = $('#eu_want_team').val();
alert(eu_want_team);
</code></pre>
<p>Its always displaying ON, is it checked or not. Whats the problem with it?</p>
| 18,377,378 | 6 | 2 | null |
2013-08-22 09:59:25.197 UTC
| 3 |
2013-08-22 10:24:50.237 UTC
|
2013-08-22 10:10:08.393 UTC
| null | 2,353,403 |
user2705406
| null | null | 1 | 88 |
javascript|jquery|html|dom|checkbox
| 37,574 |
<p>Use <code>.is(':checked')</code> instead: <strong><a href="http://jsfiddle.net/AB3eb/" rel="noreferrer">Working jsFiddle</a></strong></p>
<pre><code>var eu_want_team = $('#eu_want_team').is(':checked');
alert(eu_want_team);
</code></pre>
<p>or as @Itay said in comments you can use jQuery's <code>.prop()</code> to get the checked property value:</p>
<pre><code>alert($("#eu_want_team").prop("checked"));
</code></pre>
|
18,731,603 |
How to tar certain file types in all subdirectories?
|
<p>I want to tar and all .php and .html files in a directory and its subdirectories. If I use </p>
<p><code>tar -cf my_archive *</code></p>
<p>it tars all the files, which I don't want. If I use </p>
<p><code>tar -cf my_archive *.php *.html</code></p>
<p>it ignores subdirectories. How can I make it tar recursively but include only two types of files?</p>
| 18,731,818 | 8 | 0 | null |
2013-09-11 02:11:12.873 UTC
| 29 |
2022-07-02 19:22:31.45 UTC
|
2013-09-11 02:30:48.083 UTC
| null | 1,566,515 | null | 1,566,515 | null | 1 | 108 |
linux|tar
| 124,637 |
<p><code>find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -</code></p>
|
18,365,049 |
Is there a way to make UITableView cells in iOS 7 not have a line break in the separator?
|
<p>I noticed that in iOS 7, UITableViewCells have a line break in the separator of the cell that iOS 6 does not have. Is there a way to get rid of this line break? Changing the separator to none and then making UIViews with the color of the separator still causes the white separator to occur regardless.</p>
| 18,749,172 | 17 | 0 | null |
2013-08-21 18:29:58.59 UTC
| 29 |
2015-11-21 21:09:38.39 UTC
| null | null | null | null | 75,350 | null | 1 | 68 |
uitableview|ios7
| 36,176 |
<p><strong>For iOS7:</strong></p>
<pre><code>if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
</code></pre>
<p><strong>For iOS8:</strong></p>
<p>First configure your table view as follows:</p>
<pre><code>if ([self.tableView respondsToSelector:@selector(layoutMargins)]) {
self.tableView.layoutMargins = UIEdgeInsetsZero;
}
</code></pre>
<p>Then in your <em>cellForRowAtIndexPath:</em> method, configure the cell as follows:</p>
<pre><code>if ([cell respondsToSelector:@selector(layoutMargins)]) {
cell.layoutMargins = UIEdgeInsetsZero;
}
</code></pre>
<p>Note: Include both <em>layoutMargins</em> and <em>separatorInset</em>, to support both iOS versions</p>
|
18,392,741 |
Apache2: 'AH01630: client denied by server configuration'
|
<p>I get this error when trying to access localhost via a browser.</p>
<pre><code>AH01630: client denied by server configuration
</code></pre>
<p>I checked my site folder permissions using:</p>
<pre><code>sudo chmod 777 -R *
</code></pre>
<p>Here is my configuration file:</p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /home/user-name/www/myproject
<Directory />
Options FollowSymLinks
AllowOverride all
Allow from all
</Directory>
<Location />
Allow from all
Order Deny,Allow
</Location>
<Directory /home/user-name/www/myproject/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride all
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride all
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</code></pre>
<p></p>
| 19,588,786 | 32 | 10 | null |
2013-08-23 00:13:34.773 UTC
| 99 |
2022-09-16 17:18:36.853 UTC
|
2015-11-10 22:42:27.61 UTC
| null | 1,063,706 | null | 1,063,706 | null | 1 | 488 |
server|apache2|apache2.4
| 786,076 |
<p>If you are using Apache 2.4</p>
<p>You have to check allow and deny rules</p>
<p>Check out <a href="http://httpd.apache.org/docs/2.4/upgrading.html#access">http://httpd.apache.org/docs/2.4/upgrading.html#access</a></p>
<blockquote>
<p>In 2.2, access control based on client hostname, IP address, and other
characteristics of client requests was done using the directives
Order, Allow, Deny, and Satisfy.</p>
<p>In 2.4, such access control is done in the same way as other
authorization checks, using the new module mod_authz_host.</p>
</blockquote>
<p>The new directive is <a href="http://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require">Require</a>:</p>
<p>2.2 configuration:</p>
<pre><code>Order allow,deny
Allow from all
</code></pre>
<p>2.4 configuration:</p>
<pre><code>Require all granted
</code></pre>
<p>Also don't forget to restart the apache server after these changes (<code># service httpd restart</code>)</p>
|
15,430,016 |
Non character argument in R string split function (strsplit)
|
<p>This works</p>
<pre><code>x <- "0.466:1.187:2.216:1.196"
y <- as.numeric(unlist(strsplit(x, ":")))
</code></pre>
<p>Values of <code>blat$LRwAvg</code> all look like <code>X</code> above but this doesn't work</p>
<pre><code>for (i in 1:50){
y <- as.numeric(unlist(strsplit(blat$LRwAvg[i], "\\:")))
blat$meanLRwAvg[i]=mean(y)
}
</code></pre>
<p>Because of: </p>
<blockquote>
<p>Error in strsplit(blat$LRwAvg[i], "\:") : non-character argument</p>
</blockquote>
<p>It doesn't matter if I have one, two or null backslashes.</p>
<p>What's my problem? (Not generally, I mean in this special task, technically)</p>
| 15,430,792 | 1 | 7 | null |
2013-03-15 10:31:04.147 UTC
| 2 |
2019-10-29 12:10:12.107 UTC
|
2013-03-15 10:37:58.087 UTC
| null | 1,385,941 | null | 1,045,523 | null | 1 | 33 |
string|r|for-loop|strsplit
| 84,913 |
<p>As agstudy implied <code>blat$LRwAvg <- as.character(blat$LRwAvg)</code> before loop fixed it</p>
<pre><code>blat$meanLRwAvg <- blat$gtFrqAvg #or some other variable in data frame with equal length
blat$LRwAvg <- as.character(blat$LRwAvg)
for (i in 1:50){
y <- as.numeric(unlist(strsplit(blat$LRwAvg[i], "\\:")))
blat$meanLRwAvg[i]=mean(y)
}
</code></pre>
|
15,267,034 |
Is there an AddRange equivalent for a HashSet in C#
|
<p>With a list you can do:</p>
<pre><code>list.AddRange(otherCollection);
</code></pre>
<p>There is no add range method in a <code>HashSet</code>.
What is the best way to add another <code>ICollection</code> to a <code>HashSet</code>?</p>
| 15,267,088 | 3 | 0 | null |
2013-03-07 09:09:33.76 UTC
| 16 |
2021-06-23 18:53:55.397 UTC
|
2020-08-13 18:19:42.73 UTC
| null | 4,298,200 | null | 350,061 | null | 1 | 416 |
c#|collections|hashset|addrange
| 109,926 |
<p>For <code>HashSet<T></code>, the name is <a href="http://msdn.microsoft.com/en-us/library/bb342097.aspx" rel="noreferrer"><code>UnionWith</code></a>.</p>
<p>This is to indicate the distinct way the <code>HashSet</code> works. You cannot safely <code>Add</code> a set of random elements to it like in <code>Collections</code>, some elements may naturally evaporate.</p>
<p>I think that <code>UnionWith</code> takes its name after "merging with another <code>HashSet</code>", however, there's an overload for <code>IEnumerable<T></code> too.</p>
|
48,147,356 |
Install Qt on Ubuntu
|
<p>Need to build simple GUI application. For this reason I decided to install Qt on my Ubuntu 16. I have downloaded open source Qt edition <a href="https://www.qt.io/download-qt-installer?hsCtaTracking=9f6a2170-a938-42df-a8e2-a9f0b1d6cdce%7C6cb0de4f-9bb5-4778-ab02-bfb62735f3e5" rel="noreferrer">from theirs site</a>. Got error while run:</p>
<pre><code>g@ubuntu:~/Downloads$ ./qt-unified-linux-x86-2.0.5-2-online.run
./qt-unified-linux-x86-2.0.5-2-online.run: error while loading shared libraries: libX11.so.6: cannot open shared object file: No such file or directory
</code></pre>
<p>How to fix that?</p>
| 48,147,619 | 4 | 4 | null |
2018-01-08 09:25:30.287 UTC
| 26 |
2021-10-12 22:05:11.107 UTC
| null | null | null | null | 1,501,700 | null | 1 | 67 |
c++|linux|qt|ubuntu
| 186,697 |
<p>The ubuntu package name is <code>qt5-default</code>, not <code>qt</code>.</p>
|
9,181,782 |
Why are the terms "automatic" and "dynamic" preferred over the terms "stack" and "heap" in C++ memory management?
|
<p>Related to a lot of questions and answers on SO, I've learned that it's better to refer to objects whose lifetime is managed as residing in automatic storage rather than the stack. </p>
<p>Also, dynamically allocated objects shouldn't be referred to as residing on the heap, but in dynamic storage.</p>
<p>I get that there is automatic, dynamic and static storage, but never really understood the difference between automatic-stack and dynamic-heap. Why are the former preferred?</p>
<p><strong>I'm not asking what stack/heap mean or how memory management works. I'm asking why the terms automatic/dynamic storage are preferred over the terms stack/heap.</strong></p>
| 9,182,244 | 6 | 6 | null |
2012-02-07 18:31:51.183 UTC
| 12 |
2021-07-02 21:28:53.78 UTC
|
2021-07-02 21:28:53.78 UTC
| null | 5,459,839 | null | 673,730 | null | 1 | 46 |
c++|heap-memory|stack-memory|automatic-storage
| 10,572 |
<p><strong>Automatic</strong> tells me something about the lifetime of an object: specifically that it is bound <em>automatically</em> to the enclosing scope, and will be destroyed <em>automatically</em> when that scope exits.</p>
<p><strong>Dynamic</strong> tells me that the lifetime of an object is not controlled <em>automatically</em> by the compiler, but is under my direct control.</p>
<p><strong>Stack</strong> is an overloaded name for a type of container, and for the related popular instruction pointer protocol supported by common <code>call</code> and <code>ret</code> instructions. It doesn't tell me anything about the lifetime of an object, except through a historical association to object lifetimes in C, due to popular stack frame conventions.
Note also that in some implementations, thread-local storage is <em>on the stack</em> of a thread, but is not limited to the scope of any single function.</p>
<p><strong>Heap</strong> is again an overloaded name, indicating either a type of sorted container or a free-store management system. This is <em>not the only</em> free store available on all systems, and nor does it tell me anything concrete about the lifetime of an object allocated with <code>new</code>.</p>
|
9,611,061 |
How to support both iPad and iPhone retina graphics in universal apps
|
<p>Apple presented new iPad that support retina graphics.</p>
<p>I saw <a href="http://9to5mac.com/2011/06/14/ios-5-sdk-includes-retina-display-graphics-for-next-generation-ipad/" rel="noreferrer">this link retina graphic in apple apps</a>. As you can see apple just use "@2x" suffix for retina iPad display.</p>
<p>I have an universal app. So how to support retina in new iPad <em>and</em> iPhone? Will iPad retina use suffix "@2x" similar to iPad?</p>
| 9,611,572 | 2 | 10 | null |
2012-03-07 23:59:27.247 UTC
| 60 |
2016-07-29 12:03:37.83 UTC
|
2012-03-08 00:17:34.96 UTC
|
user166390
| null | null | 558,824 | null | 1 | 71 |
iphone|ios|ipad|retina-display
| 46,239 |
<p>I just created a test app and tested.<br/></p>
<p><strong>So for devices without retina:</strong><br/>
<code>ImageName.png</code> - For iPhone/iPod<br/>
<code>ImageName~ipad.png</code> -- For iPad<br/></p>
<p><strong>For devices with retina display:</strong><br/>
<code>ImageName@2x.png</code> - For iPhone/iPod<br/>
<code>ImageName@2x~ipad.png</code> -- For iPad<br/></p>
<p>And you can still use @2x if your iPhone high resolution image and iPad high resolution image have the same size.<br/>
To load the image just use <code>[UIImage imageNamed:@"ImageName.png"];</code><br/>
I just tested it on iOS simulator for iOS 5.1, 5.0 and 4.3.<br/>
By the way why you should use @2x and nothing more.<br/></p>
<p>The main thing because you shouldn't use the same graphics on iPhone and iPad, because iPhone and iPad has different size. And if you will use the same size the graphics will already done for you iPad retina display (if you previously use iPhone retina display). If you will images with different size, so you will use different image names for iPhone and iPad. So in this side you need just add @2x suffix.
That's why you should use just @2x suffix. - these are my thoughts.</p>
|
67,065,119 |
Why don't instance fields need to be final or effectively final to be used in lambda expressions?
|
<p>I'm practicing lambda expressions in Java. I know local variables need to be final or effectively final according to the Oracle documentation for Java SE 16 <a href="https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.27.2" rel="noreferrer">Lambda Body </a>:</p>
<blockquote>
<p>Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be final or effectively final (§4.12.4), as specified in §6.5.6.1.</p>
</blockquote>
<p>It doesn't say why though. Searching I found this similar question <a href="https://stackoverflow.com/questions/50456920/why-does-variables-in-lambdas-have-to-be-final-or-effectively-final">Why do variables in lambdas have to be final or effectively final?</a>, where StackOverflow user "snr" responded with the next quote:</p>
<blockquote>
<p>Local variables in Java have until now been immune to race conditions and visibility problems because they are accessible only to the thread executing the method in which they are declared. But a lambda can be passed from the thread that created it to a different thread, and that immunity would therefore be lost if the lambda, evaluated by the second thread, were given the ability to mutate local variables.</p>
</blockquote>
<ul>
<li>Source: <a href="http://www.lambdafaq.org/what-are-the-reasons-for-the-restriction-to-effective-immutability/" rel="noreferrer">Why the restriction on local variable capture?</a></li>
</ul>
<p>This is what I understand: a method can only be executed by one thread (let's say thread_1) at a time. This ensures the local variables of that particular method are modified only by thread_1. On the other hand, a lambda can be passed to a different thread (thread_2), so... if thread_1 finishes with the lambda expression and keeps executing the rest of the method it could change the values of the local variables, and, at the same time, thread_2 could be changing the same variables within the lambda expression. Then, that's why this restriction exists (local variables need to be final or effectively final).</p>
<p>Sorry for the long explanation. Am I getting this right?</p>
<p>But the next questions would be:</p>
<ul>
<li>Why isn't this case applicable to instance variables?</li>
<li>What could happen if thread_1 changes instance variables at the same time as thread_2 (even if they are not executing a lambda expression)?</li>
<li>Are instance variables protected in another way?</li>
</ul>
<p>I don't have much experience with Java. Sorry if my questions have obvious answers.</p>
| 67,065,633 | 3 | 3 | null |
2021-04-12 20:15:12.577 UTC
| 9 |
2021-04-13 12:07:24.27 UTC
|
2021-04-13 04:43:16.12 UTC
| null | 1,746,118 | null | 15,596,616 | null | 1 | 30 |
java|lambda|instance-variables|local-variables
| 3,119 |
<p>Instance variables are stored in the heap space whereas local variables are stored in the stack space. Each thread maintains its own stack and hence the local variables are not shared across the threads. On the other hand, the heap space is shared by all threads and therefore, multiple threads can modify an instance variable. There are various mechanisms to make the data thread-safe and you can find many related discussions on this platform. Just for the sake of completeness, I've quoted below an excerpt from <a href="http://web.mit.edu/6.005/www/fa14/classes/18-thread-safety/" rel="noreferrer">http://web.mit.edu/6.005/www/fa14/classes/18-thread-safety/</a></p>
<blockquote>
<p>There are basically four ways to make variable access safe in
shared-memory concurrency:</p>
<ul>
<li><strong>Confinement</strong>. Don’t share the variable between threads. This idea is called confinement, and we’ll explore it today.</li>
<li><strong>Immutability</strong>. Make the shared data immutable. We’ve talked a lot about immutability already, but there are some additional constraints
for concurrent programming that we’ll talk about in this reading.</li>
<li><strong>Threadsafe data type</strong>. Encapsulate the shared data in an existing threadsafe data type that does the coordination for you. We’ll talk
about that today.</li>
<li><strong>Synchronization</strong>. Use synchronization to keep the threads from accessing the variable at the same time. Synchronization is what you
need to build your own threadsafe data type.</li>
</ul>
</blockquote>
|
5,436,951 |
Rails 3: validates :presence => true vs validates_presence_of
|
<p>What is the difference between <code>validates :presence</code> and <code>validates_presence_of</code>? Looking through <code>ActiveModel</code> it looks like they setup the validation the same way. However, given the following model definition:</p>
<pre><code>class Account < ActiveRecord::Base
has_one :owner_permission, :class_name => 'AccountPermission', :conditions => { :owner => true, :admin => true }
has_one :owner, :class_name => 'User', :through => :owner_permission, :source => :user
validate :owner, :presence => true
validates_associated :owner
end
</code></pre>
<p>Calling save on an instance of <code>Account</code> does not validate the presence of owner. Though, if I use <code>validates_presence_of</code> it will.</p>
| 5,436,994 | 4 | 0 | null |
2011-03-25 19:04:09.137 UTC
| 4 |
2018-02-08 19:28:31.313 UTC
|
2018-02-08 19:28:31.313 UTC
| null | 2,252,927 | null | 633,219 | null | 1 | 31 |
ruby-on-rails-3
| 21,932 |
<p>All those <code>validates_whatever_of :attr</code> macros do is call <code>validates :attr, :whatever => true</code>. </p>
<p><strong>The problem is you are using <a href="http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate" rel="noreferrer"><code>validate</code></a> and not <a href="http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates" rel="noreferrer"><code>validates</code></a>.</strong></p>
|
5,126,892 |
In TSQL, how to evaluate an expression and assign it to a BIT field?
|
<p>I'm struggling on something very simple. I'm trying to assign the results of a boolean expression to a <code>BIT</code> variable.</p>
<p>Basically I would like to do something like: </p>
<pre><code>DECLARE @is_search_term_empty BIT
SET @is_search_term_empty = (@search_term = '')
</code></pre>
<p>where <code>@search_term</code> is a <code>NVARCHAR(128)</code> declared somewhere else in the code.</p>
<p>I cannot work out the syntax to evaluate something and assign it to a <code>BIT</code> variable, ie:</p>
<pre><code>SET @is_search_term_empty = (1 > 2)
</code></pre>
<p>Thanks.</p>
| 5,126,909 | 4 | 0 | null |
2011-02-26 12:27:12.903 UTC
| 0 |
2017-07-03 20:55:18.637 UTC
| null | null | null | null | 144,607 | null | 1 | 37 |
sql|tsql|sql-server-2008
| 15,768 |
<p>You can do this with a <code>CASE</code> statement:</p>
<pre><code>DECLARE @bitvar BIT
DECLARE @search_term varchar(128)
set @search_term = 'abc'
SET @bitvar = CASE
WHEN (@search_term = 'abc') THEN 1
ELSE 0
END
select @bitvar
</code></pre>
|
5,153,986 |
CSS selector to select an id with a slash in the id name?
|
<p>I've got <code><span id="/about-us"></code> being generated by this CMS I'm using. </p>
<p>I'd like to select this element with jQuery but it doesn't seem to like selecting elements with a slash in them.</p>
<p>Is this possible?</p>
| 5,154,155 | 5 | 4 | null |
2011-03-01 11:38:59.713 UTC
| 7 |
2019-07-01 17:26:15.283 UTC
|
2014-05-21 01:20:55.723 UTC
| null | 775,283 | null | 15,441 | null | 1 | 43 |
jquery|jquery-selectors
| 25,988 |
<p>you can do </p>
<pre><code>$("#\\/about-us")
</code></pre>
<p> </p>
|
5,549,781 |
Generate Upper and Lowercase Alphanumeric Random String in Oracle
|
<p>How does one generate an upper and lowercase alphanumeric random string from oracle?</p>
<p>I have used <code>select DBMS_RANDOM.STRING('x', 10) from dual</code> to generate uppercase alphanumeric characters</p>
<p>and <code>select DBMS_RANDOM.STRING('a', 10) from dual</code> to generate uppercase and lowercase alpha characters</p>
<p>...but I'd like a function that does both upper and lower case, and alpha and numeric characters.</p>
<p>Also, bonus points (or just upvotes) if you can think of good reasons why Oracle didn't implement this?</p>
| 5,550,448 | 6 | 0 | null |
2011-04-05 09:25:23.003 UTC
| 5 |
2013-11-10 19:00:41.367 UTC
| null | null | null | null | 110,545 | null | 1 | 15 |
oracle
| 39,647 |
<p>You can make your own function. This is one option:</p>
<pre><code>create or replace function random_str(v_length number) return varchar2 is
my_str varchar2(4000);
begin
for i in 1..v_length loop
my_str := my_str || dbms_random.string(
case when dbms_random.value(0, 1) < 0.5 then 'l' else 'x' end, 1);
end loop;
return my_str;
end;
/
select random_str(30) from dual;
RANDOM_STR(30)
--------------------------------------------------------------------------------
pAAHjlh49oZ2xuRqVatd0m1Pv8XuGs
</code></pre>
<p>You might want to adjust the <code>0.5</code> to take into account the different pool sizes - 26 for <code>l</code> vs. 36 for <code>x</code>. (<code>.419354839?</code>). You could also use value() and pass in the start and end range of the character values, but that would be character-set specific.</p>
<p>As to why... do Oracle need a reason? The use of <code>x</code> might suggest that it was originally hexadecimal and was expanded to include all upper-case, without it occurring to them to add a mixed-case version at the same time.</p>
|
5,522,337 |
C# Picturebox transparent background doesn't seem to work
|
<p>For a project of mine I need images to display with a transparent background. I made some .png images that have a transparent background(to check this I opened them in Photoshop). Now I have a class that extends PictureBox:</p>
<pre><code>class Foo : PictureBox
{
public Foo(int argument)
: base()
{
Console.WriteLine(argument);//different in the real application of course.
//MyProject.Properties.Resources.TRANSPARENCYTEST.MakeTransparent(MyProject.Properties.Resources.TRANSPARENCYTEST.GetPixel(1,1)); //<-- also tried this
this.Image = MyProject.Properties.Resources.TRANSPARENCYTEST;
((Bitmap)this.Image).MakeTransparent(((Bitmap)this.Image).GetPixel(1, 1));
this.SizeMode = PictureBoxSizeMode.StretchImage;
this.BackColor = System.Drawing.Color.Transparent;
}
}
</code></pre>
<p>this however just displays the picturebox with a white background, I just can't seem to make it work with a transparent background.</p>
| 5,523,359 | 6 | 6 | null |
2011-04-02 09:24:02.307 UTC
| 5 |
2016-09-04 18:41:57.77 UTC
| null | null | null | null | 618,702 | null | 1 | 23 |
c#|transparency|picturebox
| 102,228 |
<p>It probably works perfectly. You are seeing what's behind the picture box control. Which is the form. Whose BackColor is probably white. You can set the form's BackgroundImage property to be sure, you should see the image through the picture box. Like this:</p>
<p><img src="https://i.stack.imgur.com/ZpjtL.png" alt="enter image description here"></p>
<p>Punching a hole through <em>both</em> the picture box <em>and</em> the form requires a bigger weapon, Form.TransparencyKey</p>
|
4,954,140 |
How to redirect qDebug, qWarning, qCritical etc output?
|
<p>I'm using a lot of <code>qDebug() <<</code> statements for debug output. Is there any cross-platform way I can redirect that debug output to a file, without resorting to shell scripts? I'm guessing that <a href="http://opennet.ru/man.shtml?topic=open&category=2&russian=0" rel="noreferrer">open()</a> and <a href="http://opennet.ru/man.shtml?topic=dup2&category=2&russian=0" rel="noreferrer">dup2()</a> will do the job in Linux, but will it work compiled with MinGW in Windows?</p>
<p>And maybe there is a Qt way to do it?</p>
| 4,954,188 | 6 | 0 | null |
2011-02-10 06:42:29.95 UTC
| 35 |
2022-01-14 12:37:10.347 UTC
|
2011-03-16 06:42:52.703 UTC
| null | 415,784 | null | 521,032 | null | 1 | 97 |
c++|debugging|qt|mingw|qdebug
| 87,037 |
<p>You've to install a message handler using <code>qInstallMsgHandler</code> function, and then, you can use <code>QTextStream</code> to write the <em>debug</em> message to a file. Here is a sample example:</p>
<pre><code>#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
}
}
int main(int argc, char **argv)
{
qInstallMessageHandler(myMessageOutput); // Install the handler
QApplication app(argc, argv);
...
return app.exec();
}
</code></pre>
<p>Taken from the doc of <code>qInstallMsgHandler</code> (I only added the comments):</p>
<ul>
<li><a href="http://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler" rel="noreferrer">QtMsgHandler qInstallMessageHandler ( QtMsgHandler handler )</a></li>
</ul>
<p>In the above example, the function <code>myMessageOutput</code> uses <code>stderr</code> which you might want to replace with some other file stream, or completely re-write the function!</p>
<p>Once you write and install this function, all your <code>qDebug</code> (as well as <code>qWarning</code>, <code>qCritical</code> etc) messages would be redirected to the file you're writing to in the handler.</p>
|
4,851,234 |
Difference between int* and int[] in C++
|
<p>Context: C++
Consider the example below</p>
<pre><code>class TestClass
{
private:
int A[];
int *B;
public:
TestClass();
};
TestClass::TestClass()
{
A = 0; // Fails due to error: incompatible types in assignment of `int' to `int[0u]'
B = 0; // Passes
}
</code></pre>
<p>A = 0 fails but B = 0 succeeds. What's the catch? What exactly is A? A constant pointer? How do I initialize it then?</p>
| 4,851,326 | 7 | 5 | null |
2011-01-31 13:12:46.51 UTC
| 3 |
2016-08-24 07:27:13.45 UTC
| null | null | null | null | 197,928 | null | 1 | 11 |
c++
| 51,133 |
<p>The only difference between them is that <code>int A[]</code> <em>in a class</em> would not compile, and should not compile!</p>
<h1>Comeau C++ compiler gives this error:</h1>
<blockquote>
<pre>"ComeauTest.c", line 4: error:
incomplete type is not allowed
int A[];
^ </pre>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Comeau_C/C%2B%2B" rel="nofollow noreferrer">Wikipedia</a> says,</p>
<blockquote>
<p><strong>Comeau C/C++ has been regarded as the
most standards-conformant C++
compiler.</strong></p>
</blockquote>
<p><strong>I therefore would suggest : Don't write such code even if your compiler compiles it.</strong></p>
|
5,523,135 |
.htaccess produces 500 Internal Server Error
|
<p>The content of .htaccess is:</p>
<pre><code>php_value upload_max_filesize 64M
</code></pre>
<p>Works on localhost, screws up every hosting server I upload it to.
The error.log says: Invalid command 'php_value', perhaps misspelled or defined by a module not included in the server configuration</p>
<p>Is there another way to change the upload_max_filesize?</p>
| 5,686,596 | 7 | 7 | null |
2011-04-02 12:29:30.053 UTC
| 1 |
2022-03-10 04:33:13.477 UTC
|
2011-04-02 12:36:41.743 UTC
| null | 493,991 | null | 493,991 | null | 1 | 20 |
apache
| 49,861 |
<p>The problem was the hosting provider, they only allow changing this via php.ini</p>
|
4,852,767 |
How can I check if a file exists on a remote server using PHP?
|
<p>How can I check if a specific file exists on a remote server using PHP via FTP connections?</p>
| 9,568,577 | 7 | 0 | null |
2011-01-31 15:43:41.097 UTC
| 10 |
2022-02-11 23:10:44.553 UTC
|
2011-01-31 15:50:53.403 UTC
| null | 218,196 | null | 498,504 | null | 1 | 33 |
php
| 54,974 |
<p>I used this, a bit easier:</p>
<pre><code>// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
$ftp_server = "ftp.example.com";
// set up a connection to the server we chose or die and show an error
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
ftp_login($conn_id,"ftpserver_username","ftpserver_password");
// check if a file exist
$path = "/SERVER_FOLDER/"; //the path where the file is located
$file = "file.html"; //the file you are looking for
$check_file_exist = $path.$file; //combine string for easy use
$contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error.
// Test if file is in the ftp_nlist array
if (in_array($check_file_exist, $contents_on_server))
{
echo "<br>";
echo "I found ".$check_file_exist." in directory : ".$path;
}
else
{
echo "<br>";
echo $check_file_exist." not found in directory : ".$path;
};
// output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
var_dump($contents_on_server);
// remember to always close your ftp connection
ftp_close($conn_id);
</code></pre>
<p>Functions used: (thanks to middaparka)</p>
<ol>
<li><p>Login using <a href="http://www.php.net/manual/en/function.ftp-connect.php">ftp_connect</a></p></li>
<li><p>Get the remote file list via <a href="http://www.php.net/manual/en/function.ftp-nlist.php">ftp_nlist</a></p></li>
<li><p>Use <a href="http://www.php.net/manual/en/function.in-array.php">in_array</a> to see if the file was present in the array</p></li>
</ol>
|
5,346,926 |
How to specify database name in Code First?
|
<p>How do I tell EF what to name the database and where to put it?</p>
<p>If there is no connection string in the Web.Config, it tries to put it in the local SQLEXPRESS Server, but I want to put it out on a known SQL Server and name it what I want. Any suggestions?</p>
| 5,346,966 | 8 | 1 | null |
2011-03-18 00:52:01.913 UTC
| 12 |
2022-01-17 23:08:27.883 UTC
|
2014-05-12 19:33:21.6 UTC
| null | 2,864,740 | null | 587,920 | null | 1 | 60 |
entity-framework-4|ef-code-first
| 52,846 |
<p>Create a connection string in the app.config/web.config with the same name as the context and the EF will use that DB.</p>
|
5,461,468 |
How to debug Spring MVC url mapping?
|
<p>I am using Spring MVC 3 and am having an issue with a URL mapping. I have a method</p>
<pre><code> @Controller
public class DocumentController {
@RequestMapping( value="/docs/pupil/classes/{courseCategoryType}", method=RequestMethod.GET )
public ModelAndView listClassesForPupil( @PathVariable("courseCategoryType") final String courseCategoryType ){
System.err.print( "\n\n\n\t\t--- XXXXX ---\n\n\n" );
}
}
</code></pre>
<p>I am trying to use the <a href="http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates" rel="noreferrer" title="Spring URI Template Syntax">Spring URI template syntax</a>, and I know that is getting mapped because in console I see:</p>
<pre><code> 11:22:12,108 INFO DefaultAnnotationHandlerMapping:411 - Mapped URL path [/docs/pupil/classes/{courseCategoryType}] onto handler 'documentController'
11:22:12,108 INFO DefaultAnnotationHandlerMapping:411 - Mapped URL path [/docs/pupil/classes/{courseCategoryType}.*] onto handler 'documentController'
11:22:12,108 INFO DefaultAnnotationHandlerMapping:411 - Mapped URL path [/docs/pupil/classes/{courseCategoryType}/] onto handler 'documentController'
</code></pre>
<p>However, when I enter the URL<code>https://localhost/docs/pupil/classes/ACADEMIC</code> in browser I get a 404 error and I do not see anything printed out in the console. I replaced the print out code that just throws an exception, and it didn't seem to get thrown either. A coworker suggested there should be a way of viewing how the URL resolution is being done but a <a href="http://www.google.ca/search?q=spring%20url%20resolver%20debug%20enable" rel="noreferrer">Google search</a> didn't seem to turn up anything.</p>
<p>Any suggestions as how to debug this?</p>
| 42,279,116 | 11 | 2 | null |
2011-03-28 15:39:50.023 UTC
| 13 |
2020-11-26 07:08:58.373 UTC
|
2013-01-16 21:39:15.957 UTC
| null | 254,477 | null | 254,477 | null | 1 | 42 |
java|spring|spring-mvc
| 61,745 |
<p>For problems like this I feel like the best "entrypoint" to start debugging is the method <code>getHandler(HttpServletRequest request)</code> of the <code>DispatcherServlet</code>. </p>
<p>Inside this method every configured <code>HandlerMapping</code> is inspected if it responsible for handling your specific request. If your request makes it this far, you can be quite sure that it is a configuration problem inside the spring context.</p>
<p>Watch out for handlers of the type <code>RequestMappingHandlerMapping</code> (or <code>DefaultAnnotationHandlerMapping</code>, if you are using an older version of Spring), these are normally the <code>HandlerMapping</code> used by annotation based Controller configuration.</p>
<p>In the other case, make sure there is nothing "in front" of the <code>DispatcherServlet</code> filtering your requests (like in your case)</p>
|
5,034,580 |
Comparing chars in Java
|
<p>I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?</p>
<p>For example:</p>
<pre><code>if(symbol == ('A'|'B'|'C')){}
</code></pre>
<p>Doesn't seem to be working. Do I need to write it like:</p>
<pre><code>if(symbol == 'A' || symbol == 'B' etc.)
</code></pre>
| 5,034,600 | 13 | 1 | null |
2011-02-17 20:59:15.373 UTC
| 20 |
2021-12-28 21:08:42.673 UTC
|
2019-08-19 08:09:32.577 UTC
| null | 313,528 | null | 313,528 | null | 1 | 73 |
java|comparison|char
| 551,520 |
<p>If your input is a character and the characters you are checking against are mostly consecutive you could try this:</p>
<pre><code>if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
// ...
}
</code></pre>
<hr>
<p>However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:</p>
<pre><code>if (symbol.matches("[A-Z?]")) {
// ...
}
</code></pre>
<p>If you have a character you'll first need to convert it to a string before you can use a regular expression:</p>
<pre><code>if (Character.toString(symbol).matches("[A-Z?]")) {
// ...
}
</code></pre>
|
5,542,680 |
How to get a UITableview to go to the top of page on reload?
|
<p>I am trying to get a UITableview to go to the top of the page when I reload the table data when I call the following from </p>
<pre><code>- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
// A bunch of code...
[TableView reloadData];
}
</code></pre>
<p>Along those same lines, I would also like to be able to go to a specific section when I reload the table data.</p>
<p>I tried placing the following, which seems applicable only to the row, before and after the reload, but nothing happens:</p>
<pre><code>[TableView scrollToRowAtIndexPath:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
</code></pre>
| 5,544,007 | 14 | 0 | null |
2011-04-04 18:30:03.797 UTC
| 10 |
2022-03-04 10:49:03.183 UTC
|
2020-02-02 10:43:32.697 UTC
| null | 1,265,393 | null | 688,315 | null | 1 | 39 |
iphone|cocoa-touch|tableview
| 31,182 |
<p>Here's another way you could do it:</p>
<p><strong>Objective-C</strong></p>
<pre><code>[tableView setContentOffset:CGPointZero animated:YES];
</code></pre>
<p><strong>Swift 3 and higher</strong></p>
<pre><code>tableView.setContentOffset(.zero, animated: true)
</code></pre>
<p>Probably the easiest and most straight forward way to do it.</p>
|
5,269,713 |
css ellipsis on second line
|
<p>CSS <code>text-overflow: ellipsis</code> on second line, is this possible? I can't find it on the net.</p>
<p>example:</p>
<p>what I want is like this:</p>
<pre><code>I hope someone could help me. I need
an ellipsis on the second line of...
</code></pre>
<p>but what's happening is this:</p>
<pre><code>I hope someone could help me. I ...
</code></pre>
| 7,680,712 | 21 | 4 | null |
2011-03-11 06:30:55.613 UTC
| 66 |
2021-12-14 15:28:16.66 UTC
|
2015-12-18 01:29:46.74 UTC
| null | 251,986 | null | 251,986 | null | 1 | 317 |
html|css
| 361,007 |
<p>A requirement for <code>text-overflow: ellipsis;</code> to work is a one-line version of <code>white-space</code> (<code>pre</code>, <code>nowrap</code> etc). Which means the text will never reach the second line.</p>
<p>Ergo. Not possible in pure CSS.</p>
<p>My source when I was looking for the exact same thing just now: <a href="http://www.quirksmode.org/css/textoverflow.html" rel="noreferrer">http://www.quirksmode.org/css/textoverflow.html</a> (Quirksmode ftw!)</p>
<p><strong>EDIT</strong> If the good CSS gods will implement <a href="http://www.w3.org/TR/css-overflow-3/#max-lines" rel="noreferrer">http://www.w3.org/TR/css-overflow-3/#max-lines</a> we can haz this in pure CSS using <code>fragments</code> (new) and <code>max-lines</code> (new). Also some more info on <a href="http://css-tricks.com/line-clampin/" rel="noreferrer">http://css-tricks.com/line-clampin/</a></p>
<p><strong>EDIT 2</strong> WebKit/Blink has <a href="http://caniuse.com/#search=line-clamp" rel="noreferrer"><code>line-clamp</code></a>: <code>-webkit-line-clamp: 2</code> will put ellipsis on 2nd line.</p>
|
12,142,350 |
CMD: How do I recursively remove the "Hidden"-Attribute of files and directories
|
<p>I can't find a command or simple batch of commands to recursively remove the "Hidden"-Attribute from files and directories. All commands like "attrib" and "for" seem to skip hidden files. E.g.:</p>
<pre><code>attrib -H /S /D /L mydir
</code></pre>
<p>doesn't do anything at all, because it skips all hidden stuff. Does someone know how to do this with standard Windows tools?</p>
| 12,150,188 | 7 | 0 | null |
2012-08-27 12:51:00.107 UTC
| 8 |
2017-12-19 07:52:00.113 UTC
|
2017-01-15 18:31:22.657 UTC
| null | 3,826,372 | null | 434,268 | null | 1 | 20 |
windows|batch-file|cmd
| 175,131 |
<p>Move the -h and specify that mydir is a directory</p>
<pre><code>attrib /S /D /L -H mydir\*.*
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.