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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43,790,137 |
Why can't type parameter in Kotlin have any other bounds if it's bounded by another type parameter?
|
<p>Here is the minimal demo code that shows this problem:</p>
<pre><code>interface A
fun <T1, T2> test() where T2 : T1, T2 : A {}
</code></pre>
<p>When I try to compile it, compiler will complain:</p>
<blockquote>
<p>Error:(81, 25) Kotlin: Type parameter cannot have any other bounds if it's bounded by another type parameter</p>
</blockquote>
<p>I read <a href="http://jetbrains.github.io/kotlin-spec/#_bounds" rel="noreferrer">Kotlin Language Specification</a>, but only find the following bound restriction:</p>
<blockquote>
<p>A type-parameter cannot specify itself as its own bound, and several type-parameters cannot specify each other as a bound in a cyclic manner.</p>
</blockquote>
<p>It doesn't explain the restriction I meet.</p>
<p>I explore Kotlin's issue tracker, and I find an issue about this restriction: <a href="https://youtrack.jetbrains.com/issue/KT-13768" rel="noreferrer">Allow to inherit a type parameter from another type parameter and a class : KT-13768</a>. However, this issue has been rejected by the following reason (update on May 6th, 2017: this issue has been reopened by Stanislav Erokhin):</p>
<blockquote>
<p>I don't think we can compile the code correctly to JVM if we remove this restriction.</p>
<p>By Andrey Breslav</p>
</blockquote>
<p>So the question is: why can't we compile the code correctly to JVM if we remove this restriction?</p>
<p>The same demo works in Scala:</p>
<pre><code>trait A
def test[T1, T2 <: T1 with A](): Unit = {}
</code></pre>
<p>It indicates that Scala can compile the code correctly to JVM. Why can't Kotlin? Is it a restriction to guarantee a decidable subtyping in Kotlin (I guess. Subtyping is undecidable for Scala (Scala has a Turing-complete type system). Kotlin may want decidable subtyping like C#.)?</p>
<p>Update after answered by @erokhins (<a href="https://stackoverflow.com/a/43807444/7964561">https://stackoverflow.com/a/43807444/7964561</a>):</p>
<p>There are some subtle issues when supporting something forbidden by Java but allowed by JVM, especially in Java interoperability. I find an interesting issue when digging into bytecode generated by scalac. I modify Scala code in demo as follow:</p>
<pre><code>trait A
trait B
def test[T1 <: B, T2 <: T1 with A](t1: T1, t2: T2): Unit = {}
class AB extends A with B
</code></pre>
<p>Scalac will generate the following signature:</p>
<pre><code>// signature <T1::LB;T2:TT1;:LA;>(TT1;TT2;)V
// descriptor: (LB;LB;)V
public <T1 extends B, T2 extends T1 & A> void test(T1, T2);
</code></pre>
<p>Invoke <code>test</code> with <code>test(new AB, new AB)</code> in Scala will succeed, since Scalas invoke signature <code>(LB;LB;)V</code>; but invoke with <code>test(new AB(), new AB());</code> in Java will fail, since Java invokes signature <code>(LB;Ljava/lang/Object;)V</code>, causing <code>java.lang.NoSuchMethodError</code> in runtime. It means scalac generates something cannot be invoked in Java after relaxing this restriction. Kotlin may meet the same issue after relaxing it.</p>
| 43,807,444 | 2 | 0 | null |
2017-05-04 18:19:31.26 UTC
| 7 |
2022-06-20 07:26:53.713 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 7,964,561 | null | 1 | 35 |
types|kotlin
| 2,468 |
<p>This restrictions was made because java(language) has it:</p>
<pre><code> interface A {}
// Error:(7, 26) java: a type variable may not be followed by other bounds
<T1, T2 extends T1 & A> void test() {}
</code></pre>
<p>And we suppose that this forbidden also in bytecode level.
I dig into it and seems like it is allowed, and scalac generate the following signature:</p>
<pre><code> // access flags 0x1
// signature <T1:Ljava/lang/Object;T2:TT1;:LA;>()V
// declaration: void test<T1, T2T1 extends A>()
public test()V
</code></pre>
<p>So, we probably can support such cases it in the future versions of kotlin.</p>
<p>P.S. As far as I know Kotlin has decidable subtyping, and decidability isn't affected by this.</p>
|
204,140 |
Moving items in Dual Listboxes
|
<p>How can I move items from one list box control to another listbox control using JavaScript in ASP.NET?</p>
| 204,429 | 3 | 2 | null |
2008-10-15 09:20:18.74 UTC
| 9 |
2009-11-18 20:53:23.803 UTC
|
2009-07-28 02:03:12.18 UTC
|
keparo
| 16,587 |
balaweblog
| 22,162 | null | 1 | 18 |
asp.net|javascript|listbox|listbox-control
| 19,252 |
<p>This code assumes that you have an anchor or that will trigger to movement when it is clicked:</p>
<pre><code>document.getElementById('moveTrigger').onclick = function() {
var listTwo = document.getElementById('secondList');
var options = document.getElementById('firstList').getElementsByTagName('option');
while(options.length != 0) {
listTwo.appendChild(options[0]);
}
}
</code></pre>
|
550,703 |
C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'
|
<p>Take the below code:</p>
<pre><code>private void anEvent(object sender, EventArgs e) {
//some code
}
</code></pre>
<hr>
<p>What is the difference between the following ?</p>
<pre><code>[object].[event] += anEvent;
//and
[object].[event] += new EventHandler(anEvent);
</code></pre>
<p><strong>[UPDATE]</strong></p>
<p>Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.</p>
| 550,708 | 3 | 4 | null |
2009-02-15 10:55:46.573 UTC
| 16 |
2015-07-03 13:28:32.283 UTC
|
2013-12-14 22:24:40.707 UTC
|
Dreas Grech
| 1,243,762 |
Dreas Grech
| 44,084 | null | 1 | 78 |
c#|delegates|event-handling
| 11,986 |
<p>There is no difference. In your first example, the compiler will automatically infer the delegate you would like to instantiate. In the second example, you explicitly define the delegate. </p>
<p>Delegate inference was added in C# 2.0. So for C# 1.0 projects, second example was your only option. For 2.0 projects, the first example using inference is what I would prefer to use and see in the codebase - since it is more concise.</p>
|
652,186 |
Why do Objective-C files use the .m extension?
|
<p>Since I started learning Objective-C and Cocoa, I've been wondering why they have chosen the extension .m for the implementation files - was it supposed to mean something, or was it just a random letter?</p>
| 652,266 | 3 | 3 | null |
2009-03-16 21:17:51.89 UTC
| 42 |
2019-06-26 12:48:41.657 UTC
|
2019-06-26 12:48:41.657 UTC
|
epatel
| 1,033,581 |
Psionides
| 78,255 | null | 1 | 231 |
objective-c|file-extension
| 78,045 |
<p>Today most people would refer to them as "method files", but</p>
<blockquote>
<p>"The .m extension originally stood for
"<strong>m</strong>essages" when Objective-C was first
introduced, referring to a central
feature of Objective-C [...]"</p>
</blockquote>
<p>(from the book "<a href="https://rads.stackoverflow.com/amzn/click/com/1430218150" rel="noreferrer" rel="nofollow noreferrer">Learn Objective-C on the Mac</a>" by Mark Dalrymple and Scott Knaster, page 9)</p>
<p><strong>EDIT:</strong> To satisfy an itch I emailed <a href="http://www.virtualschool.edu/cox/" rel="noreferrer">Brad Cox</a>, the inventor of Objective-C, about the question and he answered with this single line: </p>
<blockquote>
<p>"Because .o and .c were taken. Simple
as that."</p>
</blockquote>
<p>Here's the email as visual proof:</p>
<p><img src="https://i.stack.imgur.com/O7pPJ.png" alt="Visual Proof"></p>
|
28,856,326 |
Crontab - simple echo not running
|
<p>I've got such situation:
I want to schedule a job with crontab on a linux server. I'm not super-user, so I'm editing (with crontab -l, editor vim) only my crontab file. For testing, I put there:</p>
<pre><code>* * * * * echo asdf
</code></pre>
<p>And the job is not running. Is the restart of the server needed? Or maybe some administrator move?</p>
| 28,856,563 | 3 | 1 | null |
2015-03-04 13:57:42.463 UTC
| 4 |
2022-02-09 13:51:06.977 UTC
|
2015-03-04 17:09:24.69 UTC
| null | 827,263 | null | 3,117,006 | null | 1 | 33 |
linux|cron|scheduling
| 56,166 |
<p>May be it is, cron jobs will run in their own shell. So you can't expect to see <code>asdf</code> on your console.</p>
<p>What you should try is </p>
<pre><code>* * * * * echo asdf > somefile_in_your_home_directory_with_complete_path.log
</code></pre>
<p>Next check the file by doing a tail:</p>
<pre><code>tail -f somefile_in_your_home_directory_with_complete_path.log
</code></pre>
<p>And if it's not, check if the cron daemon itself is running or is down:</p>
<pre><code># pgrep crond
</code></pre>
<p>OR</p>
<pre><code># service crond status
</code></pre>
|
20,883,868 |
WPF Caliburn.Micro and TabControl with UserControls issue
|
<p>I'm pretty sure this has been answered somewhere, but I can't seem to find it for the life of me.</p>
<p>I'm trying to use a TabControl to switch between UserControls (each tab is different, so not using Items)</p>
<p>Here's the breakdown:
I have my mainview, and 3 usercontrols. Mainview has a tab control - each tab should display a different user control.</p>
<p>I could easily just set the tabcontrol contect to the usercontrol using
But then it isn't bound to the viewmodel, only the view.</p>
<p>So I'm using Conductor in my VM, and ActivateItem. Here's where it starts to get weird / frustrating. Application starts with Tab0 selected, but Tab2 (last tab) content. Click on any other tab, loads the correct ViewModel for that tab. Click back to Tab0, loads the correct content there as well.</p>
<p>How do I get this to stop? Also, I'd really like it if switching tabs doesn't re-initialize the viewmodel again, clearing out fields that have already been entered.</p>
<p>Anyways, here's some of my source, I'm going to just drop this here and work on something else before I break my mouse.</p>
<p>View:</p>
<pre><code><TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row ="1">
<TabItem Header="PC Information">
<Grid>
<ContentControl x:Name="LoadRemoteInfo" cal:View.Model="{Binding ActiveItem}"/>
</Grid>
</TabItem>
<TabItem Header="Remote Tools">
<Grid>
<ContentControl x:Name="LoadRemoteTools" cal:View.Model="{Binding ActiveItem}"/>
</Grid>
</TabItem>
<TabItem Header="CHRemote">
<Grid>
<ContentControl x:Name="LoadCHRemote" cal:View.Model="{Binding ActiveItem}"/>
</Grid>
</TabItem>
</TabControl>
</code></pre>
<p>and the ViewModel:</p>
<pre><code>class MainViewModel : Conductor<object>
{
RemoteInfoViewModel remoteInfo = new RemoteInfoViewModel();
RemoteToolsViewModel remoteTools = new RemoteToolsViewModel();
CHRemoteViewModel chRemote = new CHRemoteViewModel();
public MainViewModel()
{
ActivateItem(remoteInfo);
}
public void LoadRemoteInfo()
{
ActivateItem(remoteInfo);
}
public void LoadRemoteTools()
{
ActivateItem(remoteTools);
}
public void LoadCHRemote()
{
ActivateItem(chRemote);
}
}
</code></pre>
| 20,885,027 | 2 | 0 | null |
2014-01-02 13:16:39.077 UTC
| 13 |
2021-10-27 17:50:57.653 UTC
| null | null | null | null | 773,165 | null | 1 | 14 |
c#|wpf|mvvm|tabcontrol|caliburn.micro
| 9,421 |
<p>May I suggest a tad different route?</p>
<p>It's something that I have been successfully doing in master-details scenarios. Let's say you have a collection of child view models. I'll prepare a marker interface for all those items, of course you can add properties/methods you see fit if there are such methods that span all child view models:</p>
<pre><code>public interface IMainScreenTabItem : IScreen
{
}
</code></pre>
<p>You can be quite sure that you want all your child models to be <code>Screen</code>s (or, in case of nested scenarios, <code>Conductor</code>s). It makes them have the full initialization/activation/deactivation cycle available.</p>
<p>Then, the child view models:</p>
<pre><code>public sealed class ChRemoteViewModel : Screen, IMainScreenTabItem
{
public ChRemoteViewModel()
{
DisplayName = "CH Remote";
}
}
public sealed class PcInfoViewModel : Screen, IMainScreenTabItem
{
public PcInfoViewModel()
{
DisplayName = "PC Info";
}
}
public sealed class RemoteToolsViewModel : Screen, IMainScreenTabItem
{
public RemoteToolsViewModel()
{
DisplayName = "Remote Tools";
}
}
</code></pre>
<p><code>DisplayName</code> will be displayed as a header text. It's a good practice to make those classes sealed, because <code>DisplayName</code> is a virtual property, and it's a big no-no to call virtual methods in a constructor of a class that's not sealed.</p>
<p>Then, you can add corresponding views and set your IoC container of choice registrations - you have to register your all child view models as classes implementing the <code>IMainScreenTabItem</code> and then:</p>
<pre><code>public class MainViewModel : Conductor<IMainScreenTabItem>.Collection.OneActive
{
public MainViewModel(IEnumerable<IMainScreenTabItem> tabs)
{
Items.AddRange(tabs);
}
}
</code></pre>
<p>Where the <code>MainView.xaml</code> is just:</p>
<pre><code><TabControl Name="Items"/>
</code></pre>
<p>And it just works. It's also <em>very</em> nice and convenient solution if your child view models take multiple dependencies (e.g. database access, logger, validation mechanism etc), now you can have the IoC do all the heavy lifting instead of instantiating them by hand.</p>
<p>One thing here though: the tabs will be placed in the same order the classes are injected. If you want to have a control over the ordering, you can order them in <code>MainViewModel</code> constructor by either passing a custom <code>IComparer<IMainScreenTabItem></code> or adding some property you can <code>OrderBy</code> or select to the <code>IMainScreenTabItem</code> interface. The default selected item will be the first one in the <code>Items</code> list.</p>
<p>Other option is to make the <code>MainViewModel</code> take three parameters:</p>
<pre><code>public MainViewModel(ChRemoteViewModel chRemoteViewModel, PcInfoViewModel pcInfo, RemoteToolsViewModel remoteTools)
{
// Add the view models above to the `Items` collection in any order you see fit
}
</code></pre>
<p>Although when you have more than 2 - 3 child view models (and you can easily get more), it's going to get messy quick.</p>
<p>About the 'clearing' part. The view models created by IoC confrom to the regular life-cycle: they're initialized at most once (<code>OnInitialize</code>), then deactivated each time they are navigated away from <code>OnDeactivate(bool)</code> and activated when they're navigated to (<code>OnActivate</code>). The <code>bool</code> parameter in <code>OnDeactivate</code> indicates whether the view model is just deactivated or completely 'closed' (e.g. when you close the dialog window and navigate away). If you completely close the view model, it will be re-initialized next time it's shown.</p>
<p>That means that any bound data will be retained between <code>OnActivate</code> calls and you'd have to explicitly clear it in <code>OnDeactivate</code>. What's more, if you keep the strong reference to your child view models, then even after you call <code>OnDeactivate(true)</code>, the data will still be there on next initialization - that's because IoC injected view models are created <em>once</em> (unless you inject the factory function in a form of <code>Func<YourViewModel></code>), and then initialized/activated/deactivated on demand.</p>
<hr />
<h3>EDIT</h3>
<p>About the bootstrapper, I'm not quite sure what kind of IoC container you're using. My sample uses <a href="http://simpleinjector.codeplex.com/" rel="noreferrer">SimpleInjector</a>, but you can do the same just as easily with e.g. Autofac:</p>
<pre><code>public class AppBootstrapper : Bootstrapper<MainViewModel>
{
private Container container;
/// <summary>
/// Override to configure the framework and setup your IoC container.
/// </summary>
protected override void Configure()
{
container = new Container();
container.Register<IWindowManager, WindowManager>();
container.Register<IEventAggregator, EventAggregator>();
var viewModels =
Assembly.GetExecutingAssembly()
.DefinedTypes.Where(x => x.GetInterface(typeof(IMainScreenTabItem).Name) != null && !x.IsAbstract && x.IsClass);
container.RegisterAll(typeof(IMainScreenTabItem), viewModels);
container.Verify();
}
/// <summary>
/// Override this to provide an IoC specific implementation.
/// </summary>
/// <param name="service">The service to locate.</param><param name="key">The key to locate.</param>
/// <returns>
/// The located service.
/// </returns>
protected override object GetInstance(Type service, string key)
{
if (service == null)
{
var typeName = Assembly.GetExecutingAssembly().DefinedTypes.Where(x => x.Name.Contains(key)).Select(x => x.AssemblyQualifiedName).Single();
service = Type.GetType(typeName);
}
return container.GetInstance(service);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.InjectProperties(instance);
}
}
</code></pre>
<p>Note the <code>viewModels</code> registration in <code>Configure</code>.</p>
|
56,130,792 |
Will consteval functions allow template parameters dependent on function arguments?
|
<p>In C++17, this code is illegal:</p>
<pre><code>constexpr int foo(int i) {
return std::integral_constant<int, i>::value;
}
</code></pre>
<p>That's because even if <code>foo</code> can be evaluated at compile-time, the compiler still needs to produce the instructions to execute it at runtime, thus making the template instantiation impossible.</p>
<p>In C++20 we will have <code>consteval</code> functions, which are required to be evaluated at compile-time, so the runtime constraint should be removed. Does it mean this code will be legal?</p>
<pre><code>consteval int foo(int i) {
return std::integral_constant<int, i>::value;
}
</code></pre>
| 56,131,418 | 3 | 3 | null |
2019-05-14 12:43:05.583 UTC
| 11 |
2019-06-03 14:55:45.743 UTC
|
2019-05-14 16:40:35.427 UTC
| null | 963,864 | null | 9,987,834 | null | 1 | 87 |
c++|language-lawyer|constexpr|c++20|class-template
| 4,107 |
<p>No. </p>
<p>Whatever changes the paper will entail, which is little <a href="http://wg21.link/p1073" rel="noreferrer">at this point</a>, it cannot change the fact that a non-template function definition is only typed once. Moreover, if your proposed code would be legal, we could presumably find a way to declare a variable of type <code>std::integral_constant<int, i></code>, which feels very prohibitive in terms of the ODR. </p>
<p>The paper also indicates that parameters are not intended to be treated as core constant expressions in one of its examples;</p>
<pre><code>consteval int sqrsqr(int n) {
return sqr(sqr(n)); // Not a constant-expression at this point,
} // but that's okay.
</code></pre>
<p>In short, function parameters will never be constant expressions, due to possible typing discrepancy.</p>
|
19,855,426 |
Can Visual Studio 2013 generate CSS files from .less files?
|
<p>Visual Studio 2013 is awesome, now with syntax highlight and autocomplete for <code>.less</code> files. But does it also generate the respective CSS files? Do I need to install other extensions for that?</p>
| 19,855,623 | 6 | 0 | null |
2013-11-08 09:21:04.563 UTC
| 6 |
2021-07-26 20:34:28.06 UTC
|
2013-11-08 09:48:41.193 UTC
| null | 158,246 | null | 158,246 | null | 1 | 64 |
css|less|visual-studio-2013
| 40,067 |
<p>Yes. While Visual Studio 2013 doesn't come with a LESS compiler built-in (so you'll need to bring your own), you can either use an external compiler, or install an extension so you can compile your LESS files from within the IDE.</p>
|
5,719,538 |
Realtime Audio/Video Streaming FROM iPhone to another device (Browser, or iPhone)
|
<p>I'd like to get real-time video from the iPhone to another device (either desktop browser or another iPhone, e.g. point-to-point). </p>
<p>NOTE: It's not one-to-many, just one-to-one at the moment. Audio can be part of stream or via telephone call on iphone. </p>
<p>There are four ways I can think of...</p>
<ol>
<li><p>Capture frames on iPhone, send
frames to mediaserver, have
mediaserver publish realtime video
using host webserver.</p></li>
<li><p>Capture frames on iPhone, convert to
images, send to httpserver, have
javascript/AJAX in browser reload
images from server as fast as
possible.</p></li>
<li><p>Run httpServer on iPhone, Capture 1 second duration movies on
iPhone, create M3U8 files on iPhone, have the other
user connect directly to httpServer on iPhone for
liveStreaming.</p></li>
<li><p>Capture 1 second duration movies on
iPhone, create M3U8 files on iPhone,
send to httpServer, have the other
user connected to the httpServer
for liveStreaming. <a href="https://stackoverflow.com/questions/3444791/streaming-video-from-an-iphone">This is a good answer</a>, has anyone gotten it to work?</p></li>
</ol>
<p>Is there a better, more efficient option?
What's the fastest way to get data off the iPhone? Is it ASIHTTPRequest?</p>
<p>Thanks, everyone.</p>
| 5,723,955 | 3 | 1 | null |
2011-04-19 16:23:23.97 UTC
| 17 |
2017-03-03 13:38:46.053 UTC
|
2017-05-23 12:00:10.983 UTC
| null | -1 | null | 79,856 | null | 1 | 16 |
iphone|video-streaming|audio-streaming|http-live-streaming
| 11,367 |
<p>Sending raw frames or individual images will never work well enough for you (because of the amount of data and number of frames). Nor can you reasonably serve anything from the phone (WWAN networks have all sorts of firewalls). You'll need to encode the video, and stream it to a server, most likely over a standard streaming format (RTSP, RTMP). There is an H.264 encoder chip on the iPhone >= 3GS. The problem is that it is not stream oriented. That is, it outputs the metadata required to parse the video last. This leaves you with a few options. </p>
<ol>
<li>Get the raw data and use FFmpeg to encode on the phone (will use a ton of CPU and battery). </li>
<li>Write your own parser for the H.264/AAC output (very hard)</li>
<li>Record and process in chunks (will add latency equal to the length of the chunks, and drop around 1/4 second of video between each chunk as you start and stop the sessions).</li>
</ol>
|
6,165,449 |
c++ error: invalid types 'int[int]' for array subscript
|
<p>Trying to learn C++ and working through a simple exercise on arrays. </p>
<p>Basically, I've created a multidimensional array and I want to create a function that prints out the values.</p>
<p>The commented for-loop within Main() works fine, but when I try to turn that for-loop into a function, it doesn't work and for the life of me, I cannot see why.</p>
<pre><code>#include <iostream>
using namespace std;
void printArray(int theArray[], int numberOfRows, int numberOfColumns);
int main()
{
int sally[2][3] = {{2,3,4},{8,9,10}};
printArray(sally,2,3);
// for(int rows = 0; rows < 2; rows++){
// for(int columns = 0; columns < 3; columns++){
// cout << sally[rows][columns] << " ";
// }
// cout << endl;
// }
}
void printArray(int theArray[], int numberOfRows, int numberOfColumns){
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << " ";
}
cout << endl;
}
}
</code></pre>
| 6,165,546 | 4 | 1 | null |
2011-05-29 01:38:46.46 UTC
| null |
2020-02-23 17:15:34.243 UTC
|
2017-09-18 09:28:46.543 UTC
| null | 2,350,638 | null | 774,799 | null | 1 | 8 |
c++
| 74,139 |
<p>C++ inherits its syntax from C, and tries hard to maintain backward compatibility where the syntax matches. So passing arrays works just like C: the length information is lost.</p>
<p>However, C++ does provide a way to automatically pass the length information, using a reference (no backward compatibility concerns, C has no references):</p>
<pre><code>template<int numberOfRows, int numberOfColumns>
void printArray(int (&theArray)[numberOfRows][numberOfColumns])
{
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << " ";
}
cout << endl;
}
}
</code></pre>
<p>Demonstration: <a href="http://ideone.com/MrYKz" rel="noreferrer">http://ideone.com/MrYKz</a></p>
<p>Here's a variation that avoids the complicated array reference syntax: <a href="http://ideone.com/GVkxk" rel="noreferrer">http://ideone.com/GVkxk</a></p>
<p>If the size is dynamic, you can't use either template version. You just need to know that C and C++ store array content in row-major order.</p>
<p>Code which works with variable size: <a href="http://ideone.com/kjHiR" rel="noreferrer">http://ideone.com/kjHiR</a></p>
|
5,830,549 |
MVC: Iterating a Viewbag array in javascript
|
<p>The goal is to get the data from the <code>ViewBag.Array</code> to a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:</p>
<pre><code>for(i = 0; i < @ViewBag.Array.Length; i++)
{
jScriptArray[i] = @ViewBag.Array[i];
}
</code></pre>
<p>The problem is "'i' does not exist in the current context" in the <code>@ViewBag.Array[i]</code> but has no problems in the <code>jScriptArray[i]</code>. Any help is appreciated.</p>
| 5,830,594 | 4 | 0 | null |
2011-04-29 09:50:03.733 UTC
| 7 |
2020-01-27 14:00:53.15 UTC
|
2013-11-01 09:04:09.15 UTC
| null | 779,549 | null | 730,805 | null | 1 | 17 |
javascript|asp.net-mvc|arrays|razor|viewbag
| 40,106 |
<p>You may try the following:</p>
<pre><code>var array = @Html.Raw(Json.Encode(@ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}
</code></pre>
|
5,914,040 |
onBackPressed to hide Not destroy activity
|
<p>i know how to cancel back keypress, so that the activity / main window stays visible:</p>
<pre><code>public void onBackPressed() {
return;
}
</code></pre>
<p>my aim is to hide the activity, however, without finishing it, how do you do that in the onBackPressed event? </p>
<p>i.e. I would like to get as far as onPause(), but not evoke the onBackPressed() default behaviour that essentially calls finish(). another way to put it is that i would like to mimic onUserLeaveHint() ?</p>
<p>any help appreciated!</p>
| 5,914,566 | 4 | 0 | null |
2011-05-06 16:06:38.477 UTC
| 5 |
2016-02-24 10:11:09.477 UTC
| null | null | null | null | 742,084 | null | 1 | 28 |
android
| 34,243 |
<p>If you want to mimic the "Home" button on specific Activities just do this:</p>
<p><strong>Below API 5</strong>:</p>
<pre><code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
</code></pre>
<p><strong>Above and on API 5</strong>:</p>
<pre><code>@Override
public void onBackPressed() {
moveTaskToBack(true);
}
</code></pre>
<p>It will move the Task to background.. when you return, it will be as it was.</p>
<p>You can see more information about this here: <a href="https://stackoverflow.com/questions/2000102/android-override-back-button-to-act-like-home-button">Override back button to act like home button</a></p>
|
34,531,748 |
How to get the smallest in lexicographical order?
|
<p>I am doing a leetcode exercise</p>
<p><a href="https://leetcode.com/problems/remove-duplicate-letters/" rel="noreferrer">https://leetcode.com/problems/remove-duplicate-letters/</a></p>
<p>The question is:</p>
<pre><code># Given a string which contains only lowercase letters, remove duplicate
# letters so that every letter appear once and only once. You must make
# sure your result is the smallest in lexicographical order among all possible results.
#
# Example:
# Given "bcabc"
# Return "abc"
#
# Given "cbacdcbc"
# Return "acdb"
</code></pre>
<p>I am not quite sure about <code>what is the smallest in lexicographical order</code> and why Given "cbacdcbc" then the answer would be "acdb"</p>
<p>Thanks for the answer in advance :)</p>
| 34,531,894 | 6 | 1 | null |
2015-12-30 14:50:21.29 UTC
| 9 |
2016-05-29 12:20:41.187 UTC
|
2015-12-30 23:38:28.597 UTC
| null | 5,119,700 | null | 5,119,700 | null | 1 | 36 |
algorithm
| 67,273 |
<p>The smallest lexicographical order is an order relation where string <em>s</em> is smaller than <em>t</em>, given the first character of <em>s</em> (<em>s<sub>1</sub></em>) is smaller than the first character of <em>t</em> (<em>t<sub>1</sub></em>), or in case they are equivalent, the second character, etc.</p>
<p>So <code>aaabbb</code> is smaller than <code>aaac</code> because although the first three characters are equal, the fourth character <code>b</code> is smaller than the fourth character <code>c</code>.</p>
<p>For <code>cbacdcbc</code>, there are several options, since <code>b</code> and <code>c</code> are duplicates, you can decided which duplicates to remove. This results in:</p>
<pre>
<s>c</s><s>b</s>a<s>c</s>d<s>c</s>bc = adbc
<s>c</s><s>b</s>a<s>c</s>dcb<s>c</s> = adcb
<s>c</s>ba<s>c</s>d<s>c</s><s>b</s>c = badc
<s>c</s>ba<s>c</s>dc<s>b</s><s>c</s> = badc
...
</pre>
<p>since <code>adbc</code> < <code>adcb</code>, you cannot thus simply answer with the first answer that pops into your mind.</p>
|
29,790,070 |
Upgraded to AppCompat v22.1.0 and now getting IllegalArgumentException: AppCompat does not support the current theme features
|
<p>I've just upgraded my app to use the newly released v22.1.0 AppCompat and I'm now getting the following exception when I open my app.</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
</code></pre>
<p>How do I fix it?</p>
| 29,790,071 | 4 | 0 | null |
2015-04-22 07:01:41.917 UTC
| 94 |
2020-08-10 12:37:13.253 UTC
|
2020-08-10 12:37:13.253 UTC
| null | 8,035,260 | null | 474,997 | null | 1 | 340 |
android|android-appcompat|illegalargumentexception
| 66,491 |
<p>AppCompat is now more strict on what it expect in theme window flags, more closely matching what you would get from the framework.</p>
<p>The main reason behind this is to support <a href="https://developer.android.com/reference/android/support/v7/app/AppCompatDialog.html">AppCompatDialogs</a> which we were also adding in this release. They make heavy use of the <code>windowNoTitle</code> flag, which AppCompat previously didn't pay much attention to.</p>
<p>So to fix your issue you have two options:</p>
<p>The easy way is to just use <code>Theme.AppCompat.NoActionBar</code> as your parent theme. This will always do the right thing.</p>
<p>If you can't do that though (maybe you need to support action bar and no action bar), you should do the following:</p>
<pre><code><style name="MyTheme" parent="Theme.AppCompat">
...
</style>
<style name="MyTheme.NoActionBar">
<!-- Both of these are needed -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</code></pre>
<p>You should be back on track now.</p>
|
32,364,579 |
Upstream / downstream terminology used backwards? (E.g. nginx)
|
<p>I've always thought of upstream and downstream along the lines of an actual stream, where the flow of information is like water. So upstream is where water/data comes from (e.g. an HTTP request) and downstream is where it goes (e.g. the underlying system that services the request).</p>
<p>I've been looking at API gateways recently and noticed that some of them used the inverse of this definition. I shrugged it off as an oddity at the time. I then discovered that nginx, which some API gateways are based on, also uses the terminology in the opposite way to what I expected. nginx calls the servers that it sends requests to "upstream servers", and presumably the incoming requests would therefore be "downstream clients".</p>
<p>Conceptually it seems like nginx would be pushing the requests "uphill" if going to an "upstream server", which is totally counter-intuitive... Gravity is reversed in the land of reverse proxies and API gateways, apparently!</p>
<p>I've seen other discussions talking about upstream / downstream representing dependencies between systems but for middleware or infrastructure components that sit between systems the idea of dependencies is a little looser, and I find it more helpful to think in terms of flow of information still - because THAT'S usually the source of your dependencies anyway.</p>
<p>Have I got my understanding of the stream analogy fundamentally wrong or are these software components getting the concepts backwards? </p>
| 32,365,658 | 2 | 1 | null |
2015-09-02 23:06:21.82 UTC
| 41 |
2022-07-13 01:28:20.813 UTC
| null | null | null | null | 705,288 | null | 1 | 123 |
nginx|definition
| 29,860 |
<p>In HTTP world, the "upstream server" term was introduced in the HTTP/1.0 specification, <a href="https://www.rfc-editor.org/rfc/rfc1945#section-9.5" rel="noreferrer">RFC 1945</a>:</p>
<blockquote>
<p>502 Bad Gateway</p>
<p>The server, while acting as a gateway or proxy, received an invalid
response from <strong>the upstream server</strong> it accessed in attempting to
fulfill the request.</p>
</blockquote>
<p>Formal definition was added later, in <a href="https://www.rfc-editor.org/rfc/rfc2616#section-1.3" rel="noreferrer">RFC 2616</a>:</p>
<blockquote>
<p>upstream/downstream</p>
<p>Upstream and downstream describe the flow of a message: all
messages flow from upstream to downstream.</p>
</blockquote>
<p>According to this definition:</p>
<ul>
<li>if you are looking at a request, then the client is upstream, and the server is downstream;</li>
<li>in contrast, if you are looking at a response, then the client is downstream, and the server is upstream.</li>
</ul>
<p>At the same time, in HTTP most of the data flow is not for requests, but for <em>responses</em>. So, if you'll consider flow of responses, then the "upstream server" term sounds pretty reasonable and logical. And the term is again used in the 502 response code description (it is identical to HTTP/1.0 one), as well as some other places.</p>
<p>The same logic can be also seen in terms "downloading" and "uploading" in natural language. Most of the data flow is from servers to clients, and that's why "downloading" means loading something from a server to a client, and "uploading" - from a client to a server.</p>
|
32,296,209 |
Dependency Injection Unity - Conditional Resolving
|
<p>Conditional resolving is the last thing I don't understand at the moment.</p>
<p>Lets say we have an interface <code>IAuthenticate</code>:</p>
<pre><code>public interface IAuthenticate{
bool Login(string user, string pass);
}
</code></pre>
<p>Now I have two types of authentication.</p>
<p><strong>Twitter auth</strong></p>
<pre><code>public class TwitterAuth : IAuthenticate
{
bool Login(string user, string pass)
{
//connect to twitter api
}
}
</code></pre>
<p><strong>Facebook Auth</strong></p>
<pre><code>public class FacebookAuth: IAuthenticate
{
bool Login(string user, string pass)
{
//connect to fb api
}
}
</code></pre>
<p>Registering types in unity config:</p>
<pre><code>unityContainer.RegisterType<IAuthenticate, TwitterAuth>();
unityContainer.RegisterType<IAuthenticate, FacebookAuth>();
</code></pre>
<p>inject objects via DI in our controller:</p>
<pre><code>private readonly IAuthenticate _authenticate;
public AuthenticateController(IAuthenticate authenticate)
{
_authenticate = authenticate;
}
// login with twitter
public virtual ActionResult Twitter(string user, string pass)
{
bool success =
_authenticate.Login(user, pass);
}
// login with fb
public virtual ActionResult Facebook(string user, string pass)
{
bool success =
_authenticate.Login(user, pass);
}
// login with google
public virtual ActionResult Google(string user, string pass)
{
bool success =
_authenticate.Login(user, pass);
}
</code></pre>
<p>How exactly will unity know which object does it have to resolve for different types of authentication? How do I do conditional resolving in this case?</p>
<p>I spoke with friend of mine, and he explained if this situation appears it is wrong design, but this is just factory pattern used.</p>
| 32,415,954 | 2 | 2 | null |
2015-08-30 11:45:41.757 UTC
| 17 |
2020-11-25 10:30:59.653 UTC
|
2018-01-30 21:30:26.257 UTC
| null | 181,087 | null | 1,395,676 | null | 1 | 20 |
c#|dependency-injection|inversion-of-control|unity-container
| 13,058 |
<p>A simple way to solve this is with the <a href="https://sourcemaking.com/design_patterns/strategy" rel="nofollow noreferrer">strategy pattern</a>. Note that you can add or remove login providers without changing the design - you simply need to change the DI configuration.</p>
<h1>Interfaces</h1>
<pre><code>public interface IAuthenticate{
bool Login(string user, string pass);
bool AppliesTo(string providerName);
}
public interface IAuthenticateStrategy
{
bool Login(string providerName, string user, string pass);
}
</code></pre>
<h1>Authenticate Providers</h1>
<pre><code>public class TwitterAuth : IAuthenticate
{
bool Login(string user, string pass)
{
//connect to twitter api
}
bool AppliesTo(string providerName)
{
// I used the type name for this example, but
// note that you could use any string or other
// datatype to select the correct provider.
return this.GetType().Name.Equals(providerName);
}
}
public class FacebookAuth: IAuthenticate
{
bool Login(string user, string pass)
{
//connect to fb api
}
bool AppliesTo(string providerName)
{
return this.GetType().Name.Equals(providerName);
}
}
</code></pre>
<h1>Strategy</h1>
<pre><code>public class AuthenticateStrategy: IAuthenticateStrategy
{
private readonly IAuthenticate[] authenticateProviders;
public AuthenticateStrategy(IAuthenticate[] authenticateProviders)
{
if (authenticateProviders == null)
throw new ArgumentNullException("authenticateProviders");
this.authenticateProviders = authenticateProviders;
}
public bool Login(string providerName, string user, string pass)
{
var provider = this.authenticateProviders
.FirstOrDefault(x => x.AppliesTo(providerName));
if (provider == null)
{
throw new Exception("Login provider not registered");
}
return provider.Login(user, pass);
}
}
</code></pre>
<h1>Unity Registration</h1>
<pre><code>// Note that the strings used here for instance names have nothing
// to do with the strings used to select the instance in the strategy pattern
unityContainer.RegisterType<IAuthenticate, TwitterAuth>("twitterAuth");
unityContainer.RegisterType<IAuthenticate, FacebookAuth>("facebookAuth");
unityContainer.RegisterType<IAuthenticateStrategy, AuthenticateStrategy>(
new InjectionConstructor(
new ResolvedArrayParameter<IAuthenticate>(
new ResolvedParameter<IAuthenticate>("twitterAuth"),
new ResolvedParameter<IAuthenticate>("facebookAuth")
)
));
</code></pre>
<h1>Usage</h1>
<pre><code>private readonly IAuthenticateStrategy _authenticateStrategy;
public AuthenticateController(IAuthenticateStrategy authenticateStrategy)
{
if (authenticateStrategy == null)
throw new ArgumentNullException("authenticateStrategy");
_authenticateStrategy = authenticateStrategy;
}
// login with twitter
public virtual ActionResult Twitter(string user, string pass)
{
bool success =
_authenticateStrategy.Login("TwitterAuth", user, pass);
}
// login with fb
public virtual ActionResult Facebook(string user, string pass)
{
bool success =
_authenticateStrategy.Login("FacebookAuth", user, pass);
}
</code></pre>
<h1>unity.config</h1>
<blockquote>
<p>Instead of "Unity Registration" you could do this on your unity.config</p>
</blockquote>
<pre><code><register type="IAuthenticate" mapTo="TwitterAuth" name="twitterAuth" />
<register type="IAuthenticate" mapTo="FacebookAuth" name="facebookAuth" />
<register type="IAuthenticateStrategy" mapTo="AuthenticateStrategy" />
</code></pre>
|
5,978,519 |
How can I use setInterval and clearInterval?
|
<p>Consider:</p>
<pre><code>function doKeyDown(event) {
switch (event.keyCode) {
case 32:
/* Space bar was pressed */
if (x == 4) {
setInterval(drawAll, 20);
}
else {
setInterval(drawAll, 20);
x += dx;
}
break;
}
}
</code></pre>
<p>I want to call <strong><code>drawAll()</code> once</strong>, not creating a <strong>loop</strong> that call <code>drawAll</code> again and again. Should I use a recursive method for that or should I use <strong><code>clearInterval</code></strong>?</p>
<p>How can I use <code>clearInterval</code>?</p>
| 5,978,560 | 5 | 0 | null |
2011-05-12 13:14:10.887 UTC
| 38 |
2022-08-12 21:59:43.96 UTC
|
2022-08-12 21:52:26.457 UTC
| null | 63,550 | null | 715,573 | null | 1 | 177 |
javascript|jquery
| 304,899 |
<p><code>setInterval</code> sets up a <em>recurring</em> timer. It returns a handle that you can pass into <code>clearInterval</code> to stop it from firing:</p>
<pre><code>var handle = setInterval(drawAll, 20);
// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval
</code></pre>
<p>On browsers, the handle is guaranteed to be a number that isn't equal to <code>0</code>; therefore, <code>0</code> makes a handy flag value for "no timer set". (Other platforms may return other values; Node.js's timer functions return an object, for instance.)</p>
<p>To schedule a function to <em>only</em> fire once, use <code>setTimeout</code> instead. It won't keep firing. (It also returns a handle you can use to cancel it via <code>clearTimeout</code> before it fires that one time if appropriate.)</p>
<pre><code>setTimeout(drawAll, 20);
</code></pre>
|
6,081,307 |
How to connect NetBeans to MySQL database?
|
<p>I have just installed NetBeans 7.0 and I am a newbie in NetBeans' world. can any one tell me how to connect my application to MySQl / Postgres ? I work on Windows XP.</p>
| 6,081,579 | 6 | 1 | null |
2011-05-21 11:10:41.077 UTC
| 3 |
2016-08-20 12:00:03.317 UTC
|
2015-07-20 04:36:04.16 UTC
| null | 720,176 | null | 720,176 | null | 1 | 6 |
java|mysql|postgresql|netbeans|jdbc
| 102,420 |
<p>In the <strong>Services</strong> window you can right click on the <strong>Databases</strong> tab and select <strong>New Connection</strong>.
<img src="https://i.stack.imgur.com/6EJsq.png" alt="New Connection"></p>
<p>Select <strong>MySQL(Connector/J Driver)</strong> from the drop down list. The driver file should be listed in the window. If not, you can download the file, then click add and select it from your hard drive.
<img src="https://i.stack.imgur.com/OSFKB.png" alt="Driver Information"></p>
<p>Finally enter your database details such as servername, username and password and click finish.
<img src="https://i.stack.imgur.com/IB5Sm.png" alt="Database Details"></p>
|
5,901,153 |
Compress large Integers into smallest possible string
|
<p>I have a bunch of 10 digit integers that I'm passing in a URL. Something like:
"4294965286", "2292964213". They will always be positive and always be 10 digits. </p>
<p>I'd like to compress those integers into the smallest possible form that can still be used in in a URL (aka letters and numbers are perfectly fine) and then uncompress them later. I've looked at using gzipstream but it creates larger strings, not shorter. </p>
<p>I'm currently using asp.net so a vb.net or c# solution would be best. </p>
<p>Thanks</p>
| 5,901,201 | 6 | 1 | null |
2011-05-05 16:31:41.187 UTC
| 8 |
2020-06-24 17:16:22.257 UTC
| null | null | null | null | 44,336 | null | 1 | 30 |
c#|asp.net|vb.net|compression
| 24,747 |
<p>Yes. GZIP is a <em>compression</em> algorithm which both requires compressible data and has an overhead (framing and dictionaries, etc). An <em>encoding</em> algorithm should be used instead.</p>
<p><strong>The "simple" method is to use <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">base-64 encoding</a>.</strong></p>
<p>That is, convert the number (which is represented as base 10 in the string) to the actual series of bytes that represent the number (5 bytes will cover a 10 digit decimal number) and then base-64 that result. Each base-64 character stores 6 bits of information (to the decimals ~3.3 bits/character) and will thus result in a size of approximately just over half (in this case, 6* base-64 output characters are required).</p>
<p>Additionally, since the input/output lengths are obtainable from the data itself, "123" might be originally (before being base-64 encoded) converted as 1 byte, "30000" as 2 bytes, etc. This would be advantageous if not all the numbers are approximately the same length.</p>
<p>Happy coding.</p>
<hr>
<p>* <strong>Using base-64 requires 6 output characters</strong>.</p>
<p>Edit: <em>I was wrong initially</em> where I said "2.3 bits/char" for decimal and proposed that less than half the characters were required. I have updated the answer above and show the (should be correct) math here, where <code>lg(n)</code> is log to the base 2.</p>
<p>The number of input bits required to represent the input number is <code>bits/char * chars</code> -> <code>lg(10) * 10</code> (or just <code>lg(9999999999)</code>) -> <code>~33.2 bits</code>. Using jball's manipulation to shift the number first, the number of bits required is <code>lg(8999999999)</code> -> <code>~33.06 bits</code>. However this transformation isn't able to increase the efficiency <em>in this particular case</em> (the number of input bits would need to be reduced to 30 or below to make a difference here).</p>
<p>So we try to find an x (number of characters in base-64 encoding) such that:</p>
<p><code>lg(64) * x = 33.2</code> -> <code>6 * x = 33.2</code> -> <code>x ~ 5.53</code>. Of course five and a half characters is nonsensical so we choose 6 as the <em>maximum</em> number of characters required to encode a value up to 999999999 in base-64 encoding. This is slightly more than half of the original 10 characters.</p>
<p>However, it should be noted that to obtain only 6 characters in base-64 output requires a non-standard base-64 encoder or a little bit of manipulation (most base-64 encoders only work on whole bytes). This works because out of the original 5 "required bytes" only 34 of the 40 bits are used (the top 6 bits are always 0). It would require 7 base-64 characters to encode all 40 bits.</p>
<p>Here is a modification of the code that Guffa posted in his answer (if you like it, go give him an up-vote) that only requires 6 base-64 characters. Please see other notes in Guffa's answer and <a href="http://en.wikipedia.org/wiki/Base64#URL_applications" rel="noreferrer">Base64 for URL applications</a> as the method below does <em>not</em> use a URL-friendly mapping.</p>
<pre><code>byte[] data = BitConverter.GetBytes(value);
// make data big-endian if needed
if (BitConverter.IsLittleEndian) {
Array.Reverse(data);
}
// first 5 base-64 character always "A" (as first 30 bits always zero)
// only need to keep the 6 characters (36 bits) at the end
string base64 = Convert.ToBase64String(data, 0, 8).Substring(5,6);
byte[] data2 = new byte[8];
// add back in all the characters removed during encoding
Convert.FromBase64String("AAAAA" + base64 + "=").CopyTo(data2, 0);
// reverse again from big to little-endian
if (BitConverter.IsLittleEndian) {
Array.Reverse(data2);
}
long decoded = BitConverter.ToInt64(data2, 0);
</code></pre>
<hr>
<p><strong>Making it "prettier"</strong></p>
<p>Since base-64 has been determined to use 6 characters then any encoding variant that still encodes the input bits into 6 characters will create just as small an output. Using a <a href="http://en.wikipedia.org/wiki/Base32" rel="noreferrer">base-32 encoding</a> won't quite make the cut, as in base-32 encoding 6 character can only store 30 bits of information (<code>lg(32) * 6</code>).</p>
<p>However, the same output size could be achieved with a custom base-48 (or 52/62) encoding. (The advantage of a base 48-62 is that they only requires a subset of alpha-numeric characters and do not need symbols; optionally "ambiguous" symbols like 1 and "I" can be avoided for variants). With a base-48 system the 6 characters can encode ~33.5 bits (<code>lg(48) * 6</code>) of information which is just above the ~33.2 (or ~33.06) bits (<code>lg(10) * 10</code>) required.</p>
<p>Here is a proof-of-concept:</p>
<pre><code>// This does not "pad" values
string Encode(long inp, IEnumerable<char> map) {
Debug.Assert(inp >= 0, "not implemented for negative numbers");
var b = map.Count();
// value -> character
var toChar = map.Select((v, i) => new {Value = v, Index = i}).ToDictionary(i => i.Index, i => i.Value);
var res = "";
if (inp == 0) {
return "" + toChar[0];
}
while (inp > 0) {
// encoded least-to-most significant
var val = (int)(inp % b);
inp = inp / b;
res += toChar[val];
}
return res;
}
long Decode(string encoded, IEnumerable<char> map) {
var b = map.Count();
// character -> value
var toVal = map.Select((v, i) => new {Value = v, Index = i}).ToDictionary(i => i.Value, i => i.Index);
long res = 0;
// go in reverse to mirror encoding
for (var i = encoded.Length - 1; i >= 0; i--) {
var ch = encoded[i];
var val = toVal[ch];
res = (res * b) + val;
}
return res;
}
void Main()
{
// for a 48-bit base, omits l/L, 1, i/I, o/O, 0
var map = new char [] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't',
'u', 'v', 'x', 'y', 'z', '2', '3', '4',
};
var test = new long[] {0, 1, 9999999999, 4294965286, 2292964213, 1000000000};
foreach (var t in test) {
var encoded = Encode(t, map);
var decoded = Decode(encoded, map);
Console.WriteLine(string.Format("value: {0} encoded: {1}", t, encoded));
if (t != decoded) {
throw new Exception("failed for " + t);
}
}
}
</code></pre>
<p>The result is:</p>
<pre>value: 0 encoded: A
value: 1 encoded: B
value: 9999999999 encoded: SrYsNt
value: 4294965286 encoded: ZNGEvT
value: 2292964213 encoded: rHd24J
value: 1000000000 encoded: TrNVzD</pre>
<hr>
<p>The above considers the case where the numbers are "random and opaque"; that is, there is nothing that can be determined about the internals of the number. However, if there is a defined structure (e.g. 7th, 8th, and 9th bits are always zero and 2nd and 15th bits are always the same) then -- if and only if 4 or more bits of information can be <em>eliminated</em> from the input -- only 5 base-64 characters would be required. The added complexities and reliance upon the structure very likely outweigh any marginal gain.</p>
|
5,908,581 |
Is hash_map part of the STL?
|
<p>Quick question...Is hash_map part of the STL?</p>
| 5,908,859 | 6 | 3 | null |
2011-05-06 08:10:45.84 UTC
| 18 |
2019-03-11 23:41:00.003 UTC
|
2011-05-06 08:15:43.613 UTC
| null | 27,615 | null | 501,600 | null | 1 | 62 |
c++|stl|hashmap
| 95,967 |
<p><a href="http://www.sgi.com/tech/stl/" rel="noreferrer">The STL</a> has <a href="http://en.wikipedia.org/wiki/Hash_map_%28C++%29" rel="noreferrer"><code>hash_map</code></a>, but the C++ Standard Library <a href="http://jcatki.no-ip.org/fncpp/Resources" rel="noreferrer">does not</a>.</p>
<p>Due to <a href="https://stackoverflow.com/questions/5205491/whats-this-stl-vs-c-standard-library-fight-all-about/5205571#5205571">a common misconception</a>, you may think of the C++ Standard Library as "the STL", or of parts of your toolchain's implementation of the C++ Standard Library as "an STL implementation".</p>
<p>It is not.</p>
<p>It is also a great shame that both MSVC++ and GCC (which implement <code>hash_map</code> as a compiler-specific extension), <a href="http://en.wikipedia.org/wiki/Hash_map_%28C++%29" rel="noreferrer">place it in the <code>std</code> namespace</a>, which is not only highly misleading, but also illegal per the standard. *sigh*</p>
<p>C++11 has introduced <a href="http://en.cppreference.com/w/cpp/container/unordered_map" rel="noreferrer"><code>std::unordered_map</code></a>, which is not dissimilar.</p>
|
5,857,386 |
How to avoid SQL injection in CodeIgniter?
|
<p>Is there any method to set in config file to avoid SQL injection? I am using this code for selecting values:</p>
<pre><code>$this->db->query("SELECT * FROM tablename WHERE var='$val1'");
</code></pre>
<p>And this for inserting values:</p>
<pre><code>$this->db->query("INSERT INTO tablename (`var1`,`var2`) VALUES ('$val1','$val2')");
</code></pre>
<p>Another method used to insert and select values from the database is CodeIgniter's <code>insert()</code> and <code>get()</code> methods. Is any chance to SQL injection while using CodeIgniter's bulit-in functions</p>
| 5,857,481 | 7 | 2 | null |
2011-05-02 12:55:26.367 UTC
| 25 |
2022-09-14 23:22:52.243 UTC
|
2022-09-14 23:22:52.243 UTC
| null | 1,839,439 | null | 667,030 | null | 1 | 42 |
function|codeigniter|sql-injection|built-in|data-security
| 57,283 |
<p>CodeIgniter's <a href="https://www.codeigniter.com/userguide2/database/active_record.html" rel="noreferrer">Active Record</a> methods automatically escape queries for you, to prevent sql injection.</p>
<pre><code>$this->db->select('*')->from('tablename')->where('var', $val1);
$this->db->get();
</code></pre>
<p>or</p>
<pre><code>$this->db->insert('tablename', array('var1'=>$val1, 'var2'=>$val2));
</code></pre>
<p>If you don't want to use Active Records, you can use <a href="https://www.codeigniter.com/userguide2/database/queries.html" rel="noreferrer">query bindings</a> to prevent against injection.</p>
<pre><code>$sql = 'SELECT * FROM tablename WHERE var = ?';
$this->db->query($sql, array($val1));
</code></pre>
<p>Or for inserting you can use the <a href="https://www.codeigniter.com/userguide2/database/helpers.html" rel="noreferrer"><code>insert_string()</code></a> method.</p>
<pre><code>$sql = $this->db->insert_string('tablename', array('var1'=>$val1, 'var2'=>$val2));
$this->db->query($sql);
</code></pre>
<p>There is also the <a href="https://www.codeigniter.com/userguide2/database/queries.html" rel="noreferrer"><code>escape()</code></a> method if you prefer to run your own queries.</p>
<pre><code>$val1 = $this->db->escape($val1);
$this->db->query("SELECT * FROM tablename WHERE var=$val1");
</code></pre>
|
6,137,224 |
Immutable Object with ArrayList member variable - why can this variable be changed?
|
<p>I have got one class with various member variables. There is a constructor and there are getter-methods, but no setter-methods. In fact, this object should be immutable.</p>
<pre><code>public class Example {
private ArrayList<String> list;
}
</code></pre>
<p>Now I noticed the following: when I get the variable list with a getter-method, I can add new values and so on - I can change the <code>ArrayList</code>. When I call the next time <code>get()</code> for this variable, the changed <code>ArrayList</code> is returned. How can this be? I didn't set it again, I just worked on it!
With a <code>String</code> this behaviour isn't possible. So what is the difference here?</p>
| 6,137,270 | 10 | 0 | null |
2011-05-26 10:39:30.87 UTC
| 16 |
2021-11-16 19:31:48.677 UTC
|
2015-05-11 11:46:56.373 UTC
| null | 4,554,061 | null | 669,356 | null | 1 | 23 |
java|object|immutability|member|getter-setter
| 43,796 |
<p>Just because <em>the reference</em> to the list is immutable doesn't mean that the list <em>it refers</em> to is immutable.</p>
<p>Even if <code>list</code> was made <code>final</code> this would be allowed</p>
<pre><code>// changing the object which list refers to
example.getList().add("stuff");
</code></pre>
<p>but this would <em>not</em> allowed:</p>
<pre><code>// changing list
example.list = new ArrayList<String>(); // assuming list is public
</code></pre>
<hr>
<p>In order to make the list immutable (prevent also the first line), I suggest you use <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29" rel="noreferrer"><code>Collections.unmodifiableList</code></a>:</p>
<pre><code>public class Example {
final private ArrayList<String> list;
Example(ArrayList<String> listArg) {
list = Collections.unmodifiableList(listArg);
}
}
</code></pre>
<p>(Note that this creates an unmodifiable view of the list. If someone is holding on to the original reference, then the list can still be modified through that.)</p>
<hr>
<blockquote>
<p><strong><em>With a String this behaviour isnt possible. So what is the difference here?</em></strong></p>
</blockquote>
<p>That is because a <code>String</code> is already immutable (unmodifiable) just as the list would be if you turned it into an unmodifiableList.</p>
<p>Comparison:</p>
<pre><code> String data structure | List data structure
.-------------------------+------------------------------------.
Immutable | String | Collection.unmodifiableList(...) |
-----------+-------------------------+------------------------------------|
Mutable | StringBuffer | ArrayList |
'-------------------------+------------------------------------'
</code></pre>
|
5,741,101 |
Easy way to print Perl array? (with a little formatting)
|
<p>Is there an <strong>easy</strong> way to print out a Perl array with commas in between each element?</p>
<p>Writing a for loop to do it is pretty easy but not quite elegant....if that makes sense.</p>
| 5,741,144 | 11 | 0 | null |
2011-04-21 07:48:32.977 UTC
| 16 |
2017-10-28 07:58:51.98 UTC
|
2017-02-05 20:21:38.62 UTC
| null | 6,862,601 | null | 455,612 | null | 1 | 103 |
perl
| 273,784 |
<p>Just use <a href="http://perldoc.perl.org/functions/join.html" rel="noreferrer"><code>join()</code></a>:</p>
<pre><code># assuming @array is your array:
print join(", ", @array);
</code></pre>
|
5,784,652 |
Eclipse "Invalid Project Description" when creating new project from existing source
|
<p>I am trying to create a new project from existing source code. I keep getting the following error: "Invalid Project Description", project path "overlaps the location of another project" with the same name. The reason is that I created that project from the source code before, but then I deleted that project and deleted its whole directory, before adding the source code directory again. I tried everything like cleaning and restarting, but nothing worked. I looked in my workspace directory, but there are no traces for the old project.
There are several questions around this problem such as this <a href="https://stackoverflow.com/q/5044151/724195">Attempting Android Notepad Tutorial - Exercise 1 - More problems</a>, but none of the answers worked for me!</p>
| 5,784,712 | 22 | 10 | null |
2011-04-26 00:17:56.077 UTC
| 44 |
2021-03-04 06:45:58.403 UTC
|
2017-05-23 11:54:44.17 UTC
| null | -1 | null | 724,195 | null | 1 | 252 |
android|eclipse
| 186,921 |
<p>Go into your workspace, and move your project source code folder to another area outside of your workspace (like the desktop). Make sure the project is deleted in eclipse, then create a new project from source from that directory.</p>
<p>Another thing you could do is try creating a project of a different name (from the first project's source), so that the workspace will contain the new project as a functional project. Then, go into your workspace directory and absolutely delete the folder that contained the original project, or move it. Try loading the project from source again, this time using the second project, by naming it with the correct name. Or, you could try refactoring the second project back to the first's name.</p>
|
39,032,333 |
Get a value inside a Promise Typescript
|
<p>One of function inside a typescript class returns a <code>Promise<string></code>. How do I unwrap/yield the value inside that promise.</p>
<pre><code>functionA(): Promise<string> {
// api call returns Promise<string>
}
functionB(): string {
return this.functionA() // how to unwrap the value inside this promise
}
</code></pre>
| 39,034,776 | 2 | 2 | null |
2016-08-19 06:22:09.053 UTC
| 1 |
2020-05-10 01:02:36.133 UTC
| null | null | null | null | 3,513,857 | null | 1 | 25 |
javascript|typescript|promise|es6-promise
| 59,240 |
<blockquote>
<p>How do I unwrap/yield the value inside that promise</p>
</blockquote>
<p>You can do it with <code>async</code>/<code>await</code>.Don't be fooled into thinking that you just went from async to sync, async await it is just a wrapper around <code>.then</code>. </p>
<pre><code>functionA(): Promise<string> {
// api call returns Promise<string>
}
async functionB(): Promise<string> {
const value = await this.functionA() // how to unwrap the value inside this promise
return value;
}
</code></pre>
<h1>Further</h1>
<ul>
<li><a href="https://basarat.gitbook.io/typescript/future-javascript/async-await#async-await-support-in-typescript" rel="noreferrer">TypeScript Deep Dive docs</a></li>
</ul>
|
44,714 |
How to have two remote origins for Git?
|
<p>Our git server will be local, but we want an server where our local repo is also kept online but only used in a <code>push</code> to fashion.</p>
<p>How can one do that?</p>
| 44,738 | 1 | 0 | null |
2008-09-04 20:36:15.597 UTC
| 9 |
2021-10-09 14:16:37.387 UTC
|
2021-10-09 14:16:37.387 UTC
|
Ravi Chhabra
| 285,795 |
Ravi Chhabra
| 370,899 | null | 1 | 19 |
git
| 7,044 |
<p>You can add remotes with <code>git remote add <name> <url></code></p>
<p>You can then push to a remote with <code>git push <name> master:master</code> to push your local master branch to the remote master branch.</p>
<p>When you create a repo with <code>git clone</code> the remote is named <code>origin</code> but you can create a <code>public</code> repository for your online server and push to it with <code>git push public master:master</code></p>
|
41,567,196 |
Ansible: How to add variables to "command" or "shell"
|
<p>Is it possible to use variables on <code>command</code> or <code>shell</code> modules?
I have the following code, and I would like to use variable file to provide some configurations:</p>
<p>I would like to read the Hadoop version from my variables file. On other modules of ansible I could use <code>{{ansible_version}}</code>, but with command or shell it doesn't works.</p>
<pre><code>- name: start ZooKeeper HA
command: hadoop-2.7.1/bin/hdfs zkfc -formatZK -nonInteractive
- name: start zkfc
shell: hadoop-2.7.1/sbin/hadoop-daemon.sh start zkfc
</code></pre>
<p>I would like to convert to the following:</p>
<pre><code>- name: Iniciar zkfc
command: {{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc
</code></pre>
<p>Because if I run the with this syntax it throws this error:</p>
<pre><code>- name: inicializar estado ZooKeeper HA
command: {{hadoop_version}}/bin/hdfs zkfc -formatZK -nonInteractive
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
</code></pre>
<p>I have try using, but same problem:</p>
<pre><code>- name: Iniciar zkfc
command: "{{ hadoop_version }}"/sbin/hadoop-daemon.sh start zkfc
</code></pre>
<p>What is the correct syntax?</p>
| 41,567,971 | 3 | 0 | null |
2017-01-10 10:59:36.597 UTC
| null |
2020-02-13 09:09:45.367 UTC
|
2019-07-23 17:28:10.49 UTC
| null | 1,245,190 | null | 5,621,509 | null | 1 | 16 |
ansible|ansible-2.x
| 47,702 |
<p>Quote the full string in the <code>command</code> argument:</p>
<pre><code>- name: Iniciar zkfc
command: "{{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc"
</code></pre>
|
47,239,332 |
Take the sum of every N rows in a pandas series
|
<p>Suppose </p>
<p><code>s = pd.Series(range(50))</code></p>
<pre><code>0 0
1 1
2 2
3 3
...
48 48
49 49
</code></pre>
<p>How can I get the new series that consists of sum of every n rows?</p>
<p>Expected result is like below, when n = 5;</p>
<pre><code>0 10
1 35
2 60
3 85
...
8 210
9 235
</code></pre>
<p>If using loc or iloc and loop by python, of course it can be accomplished, however I believe it could be done simply in Pandas way.</p>
<p>Also, this is a very simplified example, I don't expect the explanation of the sequences:). Actual data series I'm trying has the time index and the the number of events occurred in every second as the values.</p>
| 47,239,367 | 2 | 0 | null |
2017-11-11 15:05:07.933 UTC
| 4 |
2021-02-04 15:53:09.94 UTC
|
2018-12-05 09:31:29.24 UTC
| null | 4,909,087 | null | 869,074 | null | 1 | 32 |
python|pandas
| 28,687 |
<h3><code>GroupBy.sum</code></h3>
<pre><code>N = 5
s.groupby(s.index // N).sum()
0 10
1 35
2 60
3 85
4 110
5 135
6 160
7 185
8 210
9 235
dtype: int64
</code></pre>
<p>Chunk the index into groups of 5 and group accordingly.</p>
<hr />
<h3><code>numpy.reshape</code> + <code>sum</code></h3>
<p>If the size is a multiple of N (or 5), you can reshape and add:</p>
<pre><code>s.values.reshape(-1, N).sum(1)
# array([ 10, 35, 60, 85, 110, 135, 160, 185, 210, 235])
</code></pre>
<hr />
<h3><code>numpy.add.at</code></h3>
<pre><code>b = np.zeros(len(s) // N)
np.add.at(b, s.index // N, s.values)
b
# array([ 10., 35., 60., 85., 110., 135., 160., 185., 210., 235.])
</code></pre>
|
30,081,491 |
Google Sheets ArrayFormula with Sumifs
|
<p>Usually don't need help with sheets but I think my brain is imploding from thinking on this too much.</p>
<p>Trying to fill an entire column with an array formula that sums values from a separate column based on conditions from two other columns. If that sounds strange just check out <a href="https://docs.google.com/spreadsheets/d/1MPM-yLccOudcAJWji5MBllEPJyCPfJNwvEgPjBT930k/edit#gid=0" rel="nofollow noreferrer">this example sheet</a>.</p>
<p><a href="https://i.stack.imgur.com/cD8oE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cD8oE.png" alt="screenshot" /></a></p>
<p>Invoices have numbers. Customer payments have "Into" bank accounts and also invoice numbers associated with them so I know which payment corresponds to which invoice. Sometimes payments are made in pieces. I would like to sum all payments for each invoice and on separate accounts. I know how to do this using sumifs. The trick I want to pull is doing this with one array formula in the first cell. Appreciate all help.</p>
| 30,105,877 | 3 | 0 | null |
2015-05-06 15:42:04.927 UTC
| 3 |
2022-05-14 12:27:07.29 UTC
|
2020-12-03 12:15:31.553 UTC
| null | 12,188,861 | null | 3,689,610 | null | 1 | 16 |
google-sheets|sumifs|array-formulas
| 39,342 |
<p>The solution that I ended up using was this:</p>
<p>Credit due to 2n9 from google forums. Here is the <a href="https://productforums.google.com/forum/?utm_medium=email&utm_source=footer#!msg/docs/OrriYjusT6k/2XSeq1FhH3oJ" rel="noreferrer">link</a></p>
<p><code>=arrayformula(sumif(B3:B8&C3:C8,F3:F8&"A",A3:A8))</code></p>
<p>There were some other very good answers there using queries from Jean-Pierre Verhulst:</p>
<p><code>=query(A2:C8, "select B, sum(A) group by B pivot C")</code></p>
<p><code>=query(query(A2:C8, "select B, sum(A) group by B pivot C"), "select Col2, Col3")</code></p>
<p><code>=ArrayFormula(query(query(A2:C8, "select B, sum(A) group by B pivot C"), "select Col2, Col3 offset 1",0)+0)</code></p>
<p>Each of these solutions solves the problem but in a different way. They have different attributes such as removing headers or choosing only a certain column. Use the link to the google forum for more information.</p>
<p>Hope this helps someone.</p>
|
9,445,489 |
performing HTTP requests with cURL (using PROXY)
|
<p>I have this proxy address: <code>125.119.175.48:8909</code></p>
<p>How can I perform a HTTP request using cURL like <code>curl http://www.example.com</code>, but specifying the proxy address of my network? </p>
| 9,447,493 | 17 | 0 | null |
2012-02-25 15:47:56.51 UTC
| 147 |
2022-06-23 21:51:30.283 UTC
|
2017-08-22 20:27:13.393 UTC
| null | 5,780,109 | null | 873,286 | null | 1 | 559 |
linux|curl|proxy
| 1,256,420 |
<p>General way:</p>
<pre><code>export http_proxy=http://your.proxy.server:port/
</code></pre>
<p>Then you can connect through proxy from (many) application.</p>
<p>And, as per comment below, for https:</p>
<pre><code>export https_proxy=https://your.proxy.server:port/
</code></pre>
|
31,109,514 |
Making GCM work for iOS device in the background
|
<p>I'm trying to use GCM for IOS and Android clients. It seems to work fine with IOS when app is in the foreground, however, when the app is in the background, the notification center doesn't receive the message and <code>didReceiveRemoteNotification with completionHandler</code> doesn't get called.</p>
<p>I identified a problem as a wrongly formatted message from GCM to APNS. Namely, that's how it looks: <pre>
[message: New message, collapse_key: do_not_collapse, from: **************]</pre>
While, the IOS push notifications should have <code>aps</code> key in the notification, am I right ? As well as content-available set to 1. For example:</p>
<p>{
"aps" : {
"content-available" : 1
},
"data-id" : 345
}</p>
<p>By the way, in the foreground app receives the message anyway, the problem is only with the background. Any advice on how should I approach a problem, to make GCM work for both ios and android?</p>
<p><strong>UPDATE</strong>:
That is what I found on the net:</p>
<blockquote>
<p>Regarding actual communication, as long as the application is in the background on an iOS device, GCM uses APNS to send messages, the application behaving similarly as using Apple’s notification system. But when the app is active, GCM communicates directly with the app</p>
</blockquote>
<p>So the message I received in the foreground mode:</p>
<blockquote>
<p>[message: New message, collapse_key: do_not_collapse, from: **************]</p>
</blockquote>
<p>Was the direct message from GCM(APNS did not participate in this affair at all). So the question is: does APNS reformat what GCM sends to it to adhere to ios notifications format? If so how do I know that APNS actually does something and whether it sends me a notification in different format ? Is there any way to view logs of incoming data from APNS ?</p>
<p><strong>UPDATE:</strong>
Okay, I managed to change the structure of the message and now in the foreground mode I receive the following message:</p>
<blockquote>
<p>Notification received: ["aps": {"alert":"Simple message","content-available":1}, collapse_key: do_not_collapse, from: **************]</p>
</blockquote>
<p>Now it seems to be well formatted, but there is still no reaction when the app is in the background. didReceiveRemoteNotifification completionHandler doesn't get called! What should I look for and where can a problem be ? Can the square bracket be a problem for push notification ? To be even more precise, ios doesn't post any alerts/badges/banners from that incoming notification.</p>
| 31,176,165 | 5 | 1 | null |
2015-06-29 06:56:27.937 UTC
| 18 |
2016-11-25 14:17:04.83 UTC
|
2016-11-25 14:17:04.83 UTC
| null | 1,678,420 | null | 4,665,643 | null | 1 | 26 |
ios|push-notification|apple-push-notifications|google-cloud-messaging
| 27,014 |
<p>For every poor soul wondering in quest for an answer to GCM background mystery. I solved it and the problem was in the format. I'm posting the right format as well as Java code needed to send Http request to GCM with some message.
So the Http request should have two field in the header, namely:</p>
<pre><code>Authorization:key="here goes your GCM api key"
Content-Type:application/json for JSON data type
</code></pre>
<p>then the message body should be a json dictionary with keys "to" and "notification". For example:</p>
<pre><code>{
"to": "gcm_token_of_the_device",
"notification": {
"sound": "default",
"badge": "2",
"title": "default",
"body": "Test Push!"
}
}
</code></pre>
<p>Here is the simple java program (using only java libraries) that sends push to a specified device, using GCM:</p>
<pre><code>public class SendMessage {
//config
static String apiKey = ""; // Put here your API key
static String GCM_Token = ""; // put the GCM Token you want to send to here
static String notification = "{\"sound\":\"default\",\"badge\":\"2\",\"title\":\"default\",\"body\":\"Test Push!\"}"; // put the message you want to send here
static String messageToSend = "{\"to\":\"" + GCM_Token + "\",\"notification\":" + notification + "}"; // Construct the message.
public static void main(String[] args) throws IOException {
try {
// URL
URL url = new URL("https://android.googleapis.com/gcm/send");
System.out.println(messageToSend);
// Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Specify POST method
conn.setRequestMethod("POST");
//Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
//Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
byte[] data = messageToSend.getBytes("UTF-8");
wr.write(data);
//Send the request and close
wr.flush();
wr.close();
//Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Print result
System.out.println(response.toString()); //this is a good place to check for errors using the codes in http://androidcommunitydocs.com/reference/com/google/android/gcm/server/Constants.html
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
|
47,302,607 |
Meaning of H/5 in cron Jenkins
|
<p>I have a job with as cron:</p>
<pre><code>5 3,21 * * 1-5
</code></pre>
<p>This will run my job at 03:05AM and 09:05PM. Now I read it's a best practice to use <code>H</code>.</p>
<p>I try:</p>
<pre><code>H/5 3,21 * * 1-5
</code></pre>
<p>What is the meaning now? Will this schedule a build in a range of 5 minutes or 5 minutes after 3AM and 21PM?</p>
| 47,302,727 | 1 | 1 | null |
2017-11-15 08:28:22.683 UTC
| 3 |
2022-04-15 14:29:19.09 UTC
| null | null | null | null | 6,077,803 | null | 1 | 31 |
jenkins|cron
| 64,766 |
<p>The <code>H</code> will take a numeric hash of the Job name and use this to ensure that different jobs with the same cron settings do not all trigger at the same time. This is a form of <a href="https://stackoverflow.com/questions/1336454/what-is-scheduling-jitter">Scheduling Jitter</a></p>
<p><code>H/5</code> in the first field means <strong>Every five minutes starting at some time between 0 and 4 minutes past the hour</strong></p>
<p>So <code>H/5 3,21 * * 1-5</code></p>
<p>is <strong>Every five minutes between 03:00 and 03:59 and then between 21:00 and 21:59 on Mon -> Fri</strong> but starting at some 'random' time between 03:00 and 03:04 and then the same number of minutes after 21:00</p>
<p>If you want to run once per hour between 03:00-03:59 and 21:00-21:59 on Mon -> Fri, you can use <code>H 3,21 * * 1-5</code> where <code>H</code> will be replaced by some number between 0-59 depending on job name.</p>
<p>The user interface will tell you when the job will last have triggered and will next trigger</p>
|
10,539,836 |
Access: Using query in VBA for recordset
|
<p>I have been accustomed to do recordssets in the following format:</p>
<pre><code>Dim rs As DAO.Recordset
Dim strSQL As String
strSQL = "Select field1, field2 from myTable where field1 > 30"
Set rs = CurrentDb.OpenRecordset(strSQL)
'... Do wahtever using rs.
</code></pre>
<p>Is it possible to use an already created query instead of text and giving it the where clause?</p>
<p>This is a linked table to a SQL Server 2008 Database. I like to save simple queries in Access.</p>
| 10,539,987 | 1 | 1 | null |
2012-05-10 18:09:35.107 UTC
| 7 |
2012-05-10 19:07:44.58 UTC
|
2012-05-10 18:31:36.827 UTC
| null | 317,589 | null | 317,589 | null | 1 | 6 |
ms-access|vba
| 80,444 |
<p>You can either</p>
<ul>
<li><p>Use a query that has parameters and specify values for parameters provided that the query uses parameters.</p>
<pre><code>Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Dim rst As DAO.Recordset
Set qdf = CurrentDb.QueryDefs("qry_SomeQueryWithParameters")
qdf.Parameters("SomeParam").Value = "whatever"
Set rst = qdf.OpenRecordset
</code></pre></li>
</ul>
<p>or </p>
<ul>
<li>Specify a query name as the command and use the <a href="http://msdn.microsoft.com/en-us/library/ff837300.aspx">Filter property</a> on the recordset</li>
</ul>
<pre>
<code>
Dim rs As DAO.Recordset
Dim rsFiltered As DAO.Recordset
Set rs = CurrentDb.OpenRecordset(qry_SomeQueryWithoutParameters)
rs.Filter = "field1 > 30"
set rsFiltered = rs.OpenRecordset
</code>
</pre>
|
10,776,539 |
Comparing dates in MySQL ignoring time portion of a DateTime field
|
<p>I need to compare dates in MySQL ignoring the time portion in a <code>DateTime</code> column. I have tried the following SQL.</p>
<pre><code>SELECT * FROM order_table where order_date=date_format('2012-05-03', '%Y-%m-%d');
</code></pre>
<p>It doesn't retrieve any row even though there is a date <code>2012-05-03 10:16:46</code> in MySQL table. How can the time portion in the <code>DateTime</code> field be ignored while comparing dates in MySQL?</p>
| 10,776,557 | 8 | 1 | null |
2012-05-27 19:10:22.787 UTC
| 9 |
2018-02-21 16:54:30.907 UTC
|
2013-11-27 21:40:00.01 UTC
| null | 1,391,249 | null | 1,391,249 | null | 1 | 50 |
mysql|date|datetime|date-comparison
| 60,575 |
<p>You could use the <a href="http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date" rel="noreferrer"><code>DATE</code></a> function:</p>
<pre><code>SELECT col1, col2, ..., coln
FROM order_table
WHERE date(order_date) = '2012-05-03'
</code></pre>
<p>But this is more efficient, if your table is large and you have an index on <code>order date</code>:</p>
<pre><code>SELECT col1, col2, ..., coln
FROM order_table
WHERE order_date >= '2012-05-03'
AND order_date < '2012-05-04'
</code></pre>
|
7,446,301 |
Autowire reference beans into list by type
|
<p>I have one class that has a list of objects of <code>Daemon</code> type.</p>
<pre><code>class Xyz {
List<Daemon> daemons;
}
</code></pre>
<p>My spring configuration looks like this.</p>
<pre><code><bean id="xyz" class="package1.Xyz">
<property name="daemons" ref="daemonsList">
</bean>
<bean id="daemon1" class="package1.DaemonImpl1"/>
<bean id="daemon2" class="package1.DaemonImpl2"/>
<bean id="daemonsList" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="daemon1" />
<ref bean="daemon2" />
</list>
</constructor-arg>
</bean>
</code></pre>
<p>Now instead of explicitly wiring each daemon implementation in list, is it possible to autowire all beans of type <code>Daemon</code> automatically in list. Problem I am trying to solve is, If someone creates a bean of new implementation of <code>Daemon</code> class and forgets to wire it into list.</p>
<p>I have seen this question somewhere on stackoverflow but not able to find that again. Apologies for it.</p>
| 7,446,351 | 2 | 2 | null |
2011-09-16 14:36:06.187 UTC
| 13 |
2019-07-18 16:36:26.607 UTC
|
2017-06-19 07:07:55.647 UTC
| null | 5,091,346 | null | 372,887 | null | 1 | 85 |
java|spring
| 77,535 |
<p>It should work like this (remove the ArrayList bean from your XML):</p>
<pre><code>public Class Xyz {
private List<Daemon> daemons;
@Autowired
public void setDaemons(List<Daemon> daemons){
this.daemons = daemons;
}
}
</code></pre>
<p>I don't think there's a way to do this in XML.</p>
<hr>
<p>See:
<a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation" rel="noreferrer">3.9.2. <code>@Autowired</code> and <code>@Inject</code></a>:</p>
<blockquote>
<p>It is also possible to provide all beans of a particular type from the
ApplicationContext by adding the annotation to a field or method that
expects an array of that type:</p>
</blockquote>
<pre><code>public class MovieRecommender {
@Autowired
private MovieCatalog[] movieCatalogs;
// ...
}
</code></pre>
<blockquote>
<p>The same applies for typed collections:</p>
</blockquote>
<pre><code>public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
@Autowired
// or if you don't want a setter, annotate the field
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
</code></pre>
<p>BTW, as of Spring 4.x, <a href="https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/htmlsingle/#_core_container_improvements" rel="noreferrer">these lists can be ordered automatically using the <code>@Ordered</code> mechanism</a>.</p>
|
18,998,671 |
Set Height and Width of Stage and Scene in javafx
|
<ul>
<li>I develop one javafx application.</li>
<li>In my application there are two scenes and one stage.</li>
<li>In application the height and width for both scenes are same or constant.</li>
<li>so as per my research the height and width for scene remain constant which mention in the constructor but the scene adjust itself with height and width of stage.</li>
<li>when i lunch application with the height and width of stage which is different than the constant height and width of scene then scene adjust with stage.</li>
<li><p>but when at the run time when i apply the 2nd scene then scene is not adjust with height and width of stage.the height and width of scene remain constant. </p></li>
<li><p>so any solution? </p></li>
</ul>
| 19,589,004 | 3 | 1 | null |
2013-09-25 07:23:18.84 UTC
| 5 |
2016-12-20 11:55:13.91 UTC
| null | null | null | null | 2,732,483 | null | 1 | 18 |
java|javafx|stage|scene
| 100,951 |
<p>As I understand the problem above posted. I think the stage is good enough to set the preferred height and width as per the listener get the newer request to apply on the windows size. But it has some limitations, if you maximize or minimize the javaFX screen and will try to navigate to other screen then other screen will be having same window size but the scene content will distorted into the default height and width of it, e.g take a login and home scene in javafx (all scene is screated with fxml). Login.fxml is initialized by its controller. As you have mentioned that scene is initialized in constructor, so it must be the controller of the related fxml(as of now FXML is tight coupled with controller). You are going to set the scene size(height & width) in constructor itself.</p>
<p>1.) LoginController for login.fxml</p>
<pre><code> import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
class LoginController {
private Stage stage;
private Scene scene;
private Parent parent;
@FXML
private Button gotoHomeButton;
public LoginController() throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/login.fxml"));
fxmlLoader.setController(this);
try {
parent = (Parent) fxmlLoader.load();
// set height and width here for this login scene
scene = new Scene(parent, 1000, 800);
} catch (IOException ex) {
System.out.println("Error displaying login window");
throw new RuntimeException(ex);
}
}
// create a launcher method for this. Here I am going to take like below--
public void launchLoginScene(Stage stage) {
this.stage = stage;
stage.setScene(scene);
stage.setResizable(true);
stage.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
setCurrentWidthToStage(number2);
}
});
stage.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
setCurrentHeightToStage(number2);
}
});
//Don't forget to add below code in every controller
stage.hide();
stage.show();
}
@FXML
public void authenticateUser(ActionEvent actionEvent) {
// write your logic to authenticate user
//
new HomeController().displayHomeScreen(stage);
}
private void setCurrentWidthToStage(Number number2) {
stage.setWidth((double) number2);
}
private void setCurrentHeightToStage(Number number2) {
stage.setHeight((double) number2);
}
}
</code></pre>
<p>2.) Same for HomeController --</p>
<pre><code>public class HomeController {
private Parent parent;
private Stage stage;
private Scene scene;
public HomeController (){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/home.fxml"));
fxmlLoader.setController(this);
try {
parent = (Parent) fxmlLoader.load();
// set height and width here for this home scene
scene = new Scene(parent, 1000, 800);
} catch (IOException e) {
// manage the exception
}
}
public void displayHomeScreen(Stage stage){
this.stage = stage;
stage.setScene(scene);
// Must write
stage.hide()
stage.show();
}
}
</code></pre>
<p>3.) Main class </p>
<pre><code>import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
new LoginController().launchLoginScene(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p>Just try to put Stage.hide() before Stage.show() in every controller. I hope this will help you out.</p>
|
35,735,762 |
What's the difference between `def` and `defp`
|
<p>I'm going through the Programming Phoenix book and I am wondering what the difference between <code>def</code> and <code>defp</code> is.</p>
<p>There are several functions in my controller - most of them are actions like this:</p>
<pre><code>def new (conn, _params) do
...
end
</code></pre>
<p>The book had me create another function in this controller that is not a typical controller action like this:</p>
<pre><code>defp user_videos(user) do
...
end
</code></pre>
<p>So my question is how do I know when to use <code>defp</code> and when to use <code>def</code> when defining a function in Elixir?</p>
| 35,735,871 | 2 | 1 | null |
2016-03-01 23:35:33.153 UTC
| 6 |
2021-08-14 21:45:11.577 UTC
|
2021-08-14 21:45:11.577 UTC
| null | 9,935,916 | null | 1,863,692 | null | 1 | 91 |
elixir
| 21,934 |
<p>From <a href="http://elixir-lang.org/getting-started/modules.html#named-functions" rel="noreferrer">Elixir’s documentation on functions within modules</a>:</p>
<blockquote>
<p>Inside a module, we can define functions with <code>def/2</code> and private functions with <code>defp/2</code>. A function defined with <code>def/2</code> can be invoked from other modules while a private function can only be invoked locally.</p>
</blockquote>
<p>So <code>defp</code> defines a private function.</p>
|
21,141,817 |
Why are callbacks more "tightly coupled" than promises?
|
<p>Can you explain me the following phrase (taken from <a href="https://stackoverflow.com/a/6824836/196210">an answer to Stack Overflow question <em>What are the differences between Deferred, Promise and Future in Javascript?</em></a>)?</p>
<p>What are the pros of using <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> promises against using the previous jQuery callbacks?</p>
<blockquote>
<p>Rather than directly passing callbacks to functions, something which
can lead to tightly coupled interfaces, using promises allows one to
separate concerns for code that is synchronous or asynchronous.</p>
</blockquote>
| 22,254,599 | 5 | 2 | null |
2014-01-15 15:43:28.623 UTC
| 18 |
2016-01-19 11:33:44.333 UTC
|
2017-05-23 11:53:24.403 UTC
| null | -1 | null | 196,210 | null | 1 | 36 |
javascript|jquery|callback|promise
| 15,716 |
<p>I don't think promises are more or less coupled than callbacks, just about the same. </p>
<p>Promises however have other benefits: </p>
<ul>
<li><p>If you expose a callback, you have to document whether it will be called once (like in jQuery.ajax) or more than once (like in Array.map). Promises are called always once. </p></li>
<li><p>There's no way to call a callback throwing and exception on it, so you have to provide another callback for the error case.</p></li>
<li><p>Just one callback can be registered, more than one for promises, and you can register them AFTER the event and you will get called anyway. </p></li>
<li><p>In a typed declaration (Typescript), Promise make easier to read the signature. </p></li>
<li><p>In the future, you can take advantage of an async / yield syntax. </p></li>
<li><p>Because they are standard, you can make reusable components like this one: </p>
<pre><code> disableScreen<T>(promiseGenerator: () => Promise<T>) : Promise<T>
{
//create transparent div
return promiseGenerator.then(val=>
{
//remove transparent div
return val;
}, error=>{
//remove transparent div
throw error;
});
}
disableScreen(()=>$.ajax(....));
</code></pre></li>
</ul>
<p>More on that: <a href="http://www.html5rocks.com/en/tutorials/es6/promises/" rel="nofollow">http://www.html5rocks.com/en/tutorials/es6/promises/</a></p>
<p><strong>EDIT:</strong> </p>
<ul>
<li>Another benefit is writing a sequence of N async calls without N levels of indentation. </li>
</ul>
<p>Also, while I still don't think it's the main point, now I think they are a little bit more loosely coupled for this reasons: </p>
<ul>
<li><p>They are standard (or at least try): code in C# or Java that uses strings are more lousy coupled than similar code in C++, because the different implementations of strings there, making it more reusable. Having an standard promise, the caller and the implementation are less coupled to each other because they don't have to agree on a (pair) of custom callbacks with custom parameters orders, names, etc... The fact that there are many different flavors on promises doesn't help thought. </p></li>
<li><p>They promote a more expression-based programming, easier to compose, cache, etc..:</p>
<pre><code> var cache: { [key: string] : Promise<any> };
function getData(key: string): Promise<any> {
return cache[key] || (cache[key] = getFromServer(key));
}
</code></pre></li>
</ul>
<p>you can argue that expression based programming is more loosely coupled than imperative/callback based programming, or at least they pursue the same goal: composability. </p>
|
2,001,920 |
Calling a class prototype method by a setInterval event
|
<p>I have a simple javascript class. </p>
<p>One method of this class sets up a timer using setInterval function. The method that I want to call every time the event fires is defined inside the same class. </p>
<p>The question is, how can I pass this method as a parameter to the setInterval function?</p>
<p>One attempt was setInterval('this.showLoading(), 100). But doesn't work. This method access class properties, so I need the 'this' reference.</p>
<p>This is the sample code:</p>
<pre><code> function LoadingPicture(Id)
{
this.imgArray = null;
this.currentImg = 0;
this.elementId = Id;
this.loadingTimer = null;
}
LoadingPicture.prototype.showLoading = function()
{
if(this.currentImg == imgArray.length)
currentImg = 0;
document.getElementById(this.elementId).src = imgArray[this.currentImg++].src;
}
LoadingPicture.prototype.StartLoading = function()
{
document.getElementById(this.elementId).style.visibility = "visible";
loadingTimer = setInterval("showLoading()", 100);
}
</code></pre>
| 2,001,955 | 3 | 0 | null |
2010-01-04 20:16:03.017 UTC
| 8 |
2019-09-11 03:03:12.82 UTC
| null | null | null | null | 93,955 | null | 1 | 29 |
javascript
| 26,090 |
<p>setInterval can take a function directly, not just a string.
<a href="https://developer.mozilla.org/en/DOM/window.setInterval" rel="noreferrer">https://developer.mozilla.org/en/DOM/window.setInterval</a></p>
<p>i.e.</p>
<pre><code>loadingTimer = setInterval(showLoading, 100);
</code></pre>
<p>But, for optimal browser compatibility, you should use a closure with an explicit reference:</p>
<pre><code> var t = this;
loadingTimer = setInterval(function(){t.showLoading();}, 100);
</code></pre>
|
1,649,102 |
What is a sequence (Database)? When would we need it?
|
<p>Why would we create a sequence even if there is a primary key?</p>
| 1,649,126 | 3 | 0 | null |
2009-10-30 10:46:34.83 UTC
| 14 |
2020-09-10 14:59:01.377 UTC
|
2015-07-16 13:50:47.33 UTC
| null | 4,801,314 | null | 128,647 | null | 1 | 47 |
database
| 54,327 |
<p>The primary key is a column in a table.</p>
<p>The primary key needs a unique value, which needs to come from somewhere.</p>
<p>The sequence is a feature by some database products which just creates unique values. It just increments a value and returns it. The special thing about it is: there is no transaction isolation, so several transactions can not get the same value, the incrementation is also not rolled back. Without a database sequence it is very hard to generate unique incrementing numbers.</p>
<p>Other database products support columns that are automatically initialized with a incrementing number.</p>
<p>There are other means to create unique values for the primary keys, for instance Guids.</p>
|
8,452,586 |
Display a ul class when the mouse hovers over a li class css only
|
<p>I am currently looking into developing a CSS only drop down menu. The idea is when the mouse hovers over a ul tag it will make another ul class appear. </p>
<p>Below is the code that I currently have. </p>
<p><strong>HTML</strong></p>
<pre><code><head>
<link href="nav.css" rel="stylesheet" type="text/css">
</head>
<ul class="nav">
<li class="topMenu"><a href="#">Home</a></li>
<ul class="subMenu" id="home">
<li><a href="#">Hello</a></li>
<li><a href="#">World</a></li>
</ul>
</ul>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.nav, .topMenu, .subMenu
{
position: relative;
list-style: none;
}
.topMenu
{
position: relative;
float: left;
}
.subMenu
{
display: none;
}
.topMenu a:hover + li
{
display: block;
background-color: blue;
}
</code></pre>
<p>The idea is that when the mouse hovers over the li class="topMenu" then the ul class="subMenu" id="home" should appear underneath. </p>
<p>Ideally this should be only in a CSS format without requiring any javascript etc. </p>
<p>Thanks for any help you can provide. </p>
| 8,453,171 | 2 | 1 | null |
2011-12-09 22:36:59.78 UTC
| 1 |
2011-12-10 02:05:47.223 UTC
| null | null | null | null | 499,448 | null | 1 | 1 |
html|css
| 48,089 |
<p>All you really need to do is nest the <code><ul></code> within your <code><li></code> element.</p>
<pre><code><nav>
<ul>
<li><a href="#">Link</a></li>
<li>
<a href="#">Link</a>
<ul>
<li><a href="#">Submenu</a></li>
<li><a href="#">Submenu</a></li>
</ul>
</li>
<li><a href="#">Link</a></li>
</ul>
</nav>
</code></pre>
<p>Here's some CSS that will help you get started:</p>
<pre><code>/* Resets */
nav a {
text-decoration: none;
font: 12px/1 Verdana;
color: #000;
display: block; }
nav a:hover { text-decoration: underline; }
nav ul {
list-style: none;
margin: 0;
padding: 0; }
nav ul li { margin: 0; padding: 0; }
/* Top-level menu */
nav > ul > li {
float: left;
position: relative; }
nav > ul > li > a {
padding: 10px 30px;
border-left: 1px solid #000;
display: block;}
nav > ul > li:first-child { margin: 0; }
nav > ul > li:first-child a { border: 0; }
/* Dropdown Menu */
nav ul li ul {
position: absolute;
background: #ccc;
width: 100%;
margin: 0;
padding: 0;
display: none; }
nav ul li ul li {
text-align: center;
width: 100%; }
nav ul li ul a { padding: 10px 0; }
nav ul li:hover ul { display: block; }
</code></pre>
<p>Preview: <a href="http://jsfiddle.net/Wexcode/BEhvQ/" rel="nofollow">http://jsfiddle.net/Wexcode/BEhvQ/</a></p>
|
8,753,286 |
Nerd tree: enter does not open sub dirs
|
<p>I installed NERDTree via Pathogen on Mac OSX 10.6.8. </p>
<p>When I vim a dir, I cannot enter into sub dirs with enter key. Furthermore, the dirs look like this:</p>
<pre><code>?~V? doc/
</code></pre>
<p>What's going on?</p>
| 8,758,710 | 7 | 1 | null |
2012-01-06 04:14:09.34 UTC
| 12 |
2018-05-15 22:04:25.717 UTC
| null | null | null | null | 586,706 | null | 1 | 24 |
vim|nerdtree
| 12,635 |
<p>Putting this in my .vimrc solved the problem: <code>let g:NERDTreeDirArrows=0</code></p>
<p>The creator gave me the fix: <a href="https://github.com/scrooloose/nerdtree/issues/108" rel="noreferrer">https://github.com/scrooloose/nerdtree/issues/108</a></p>
|
8,763,451 |
How to handle urllib's timeout in Python 3?
|
<p>First off, my problem is quite similar to <a href="https://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python">this one</a>. I would like a timeout of urllib.urlopen() to generate an exception that I can handle.</p>
<p>Doesn't this fall under URLError?</p>
<pre><code>try:
response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
except (HTTPError, URLError) as error:
logging.error(
'Data of %s not retrieved because %s\nURL: %s', name, error, url)
else:
logging.info('Access successful.')
</code></pre>
<p>The error message:</p>
<blockquote>
<p>resp = urllib.request.urlopen(req, timeout=10).read().decode('utf-8')<br>
File "/usr/lib/python3.2/urllib/request.py", line 138, in urlopen<br>
return opener.open(url, data, timeout)<br>
File "/usr/lib/python3.2/urllib/request.py", line 369, in open<br>
response = self._open(req, data)<br>
File "/usr/lib/python3.2/urllib/request.py", line 387, in _open<br>
'_open', req)<br>
File "/usr/lib/python3.2/urllib/request.py", line 347, in _call_chain<br>
result = func(*args)<br>
File "/usr/lib/python3.2/urllib/request.py", line 1156, in http_open<br>
return self.do_open(http.client.HTTPConnection, req)<br>
File "/usr/lib/python3.2/urllib/request.py", line 1141, in do_open<br>
r = h.getresponse()<br>
File "/usr/lib/python3.2/http/client.py", line 1046, in getresponse<br>
response.begin()<br>
File "/usr/lib/python3.2/http/client.py", line 346, in begin<br>
version, status, reason = self._read_status()<br>
File "/usr/lib/python3.2/http/client.py", line 308, in _read_status<br>
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")<br>
File "/usr/lib/python3.2/socket.py", line 276, in readinto<br>
return self._sock.recv_into(b)<br>
socket.timeout: timed out </p>
</blockquote>
<p>There was a major change from in Python 3 when they re-organised the <code>urllib</code> and <code>urllib2</code> modules into <code>urllib</code>. Is it possible that there was a change then that causes this?</p>
| 8,763,542 | 3 | 1 | null |
2012-01-06 19:36:45.01 UTC
| 11 |
2022-05-03 15:30:48.663 UTC
|
2017-05-23 12:34:04.717 UTC
| null | -1 | null | 1,109,785 | null | 1 | 30 |
python|exception|urllib
| 76,491 |
<p>Catch the different exceptions with explicit clauses, and check the reason for the exception with URLError (thank you <a href="https://stackoverflow.com/users/356528/r%C3%A9gis-b">Régis B.</a>)</p>
<pre class="lang-py prettyprint-override"><code>from socket import timeout
try:
response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
except HTTPError as error:
logging.error('HTTP Error: Data of %s not retrieved because %s\nURL: %s', name, error, url)
except URLError as error:
if isinstance(error.reason, timeout):
logging.error('Timeout Error: Data of %s not retrieved because %s\nURL: %s', name, error, url)
else:
logging.error('URL Error: Data of %s not retrieved because %s\nURL: %s', name, error, url)
else:
logging.info('Access successful.')
</code></pre>
<p>NB For recent comments, the original post referenced python 3.2 where you needed to catch timeout errors explicitly with <code>socket.timeout</code>. For example</p>
<pre class="lang-py prettyprint-override"><code>
# Warning - python 3.2 code
from socket import timeout
try:
response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
except timeout:
logging.error('socket timed out - URL %s', url)
</code></pre>
|
8,785,624 |
How to safely wrap `console.log`?
|
<p>Suppose I want to include some calls to <code>console.log</code> for some legitimate production reason, say for something like a unit test harness. Obviously I would not want this to throw a premature exception if the browser doesn't have a <code>console</code>, or if <a href="https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function">no console is present</a>.</p>
<p>What's the best way to create a simple <code>log</code> function to log stuff to the console, or silently fail without error if no console is present?</p>
<p>The accepted answer to the question linked above:</p>
<blockquote>
<pre><code>var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
</code></pre>
</blockquote>
<p>Can this <code>log</code> function be called normally on IE, and the use of <code>apply</code> here is just to show it's possible? And, I assume from the linked question that this will fail if IE's console is closed when it runs, so <code>log</code> won't work even after the console opens, correct? If that's wrong, can someone explain how it works? </p>
<p>This <a href="http://news.ycombinator.com/item?id=2787083" rel="nofollow noreferrer">ycombinator article</a> seems relevant. Are they are talking about the same IE behavior as the question linked above?</p>
<blockquote>
<pre><code>Function.prototype.apply.apply(console.log, [console, arguments]);
</code></pre>
<p>Works both on IE9 broken console.log, and regular console.log from other vendors.
Same hack as using Array.prototype.slice to convert arguments into a real array.</p>
</blockquote>
<p>This works nicely in my chrome console.</p>
<pre><code>function echo(){
Function.prototype.apply.apply(console.log, [console, arguments]);
}
</code></pre>
<p>Simplified:</p>
<pre><code>function echo(){
Function.apply.call(console.log, console, arguments);
}
</code></pre>
<p>Add a check and return:</p>
<pre><code>function echo(){
return window.console && console.log &&
Function.apply.call(console.log, console, arguments);
}
</code></pre>
<p>The example above looks adequate to me. I don't have IE on hand to test it, though. Is this a reasonable approach for safely wrapping <code>console.log</code>?</p>
<hr>
<p><strong>More questions</strong></p>
<p>Following the link in nav's answer below, we see the code:</p>
<pre><code>Function.prototype.call.call(console.log, console,
Array.prototype.slice.call(arguments));
</code></pre>
<p>What is the purpose of converting <code>arguments</code> to an array in this case? I guess it must fail in some browser if you don't do this? And, opera weird behavior and console-less browsers aside, shouldn't something like this pretty much work for every other browser as well? And does <code>prototype</code> serve a purpose in the above examples, or are we just being pedantic... <code>Function.call.call</code> or <code>Object.call.call</code> or for that matter <code>isNaN.call.call</code> seem to work just as well as <code>Function.prototype.call.call</code>. </p>
| 8,794,378 | 10 | 1 | null |
2012-01-09 08:32:32.31 UTC
| 10 |
2017-01-22 12:15:36.6 UTC
|
2017-05-23 12:17:28.077 UTC
| null | -1 | null | 886,931 | null | 1 | 48 |
javascript|internet-explorer|console|logging|wrapper
| 28,123 |
<blockquote>
<p>Can this log function be called normally on IE, and the use of apply here is just to show it's possible?</p>
</blockquote>
<p>Yes, and yes. That particular example was aimed squarely at the <em>"is it a real function"</em> part of the linked question.</p>
<blockquote>
<p>And, I assume from the linked question that this will fail if IE's console is closed when it runs, so log won't work even after the console opens, correct?</p>
</blockquote>
<p>Correct. As explained in my answer on that question, the <code>console</code> object is not exposed until the first time the developer tools are opened for a particular tab. Most developers use a console shim, in which case the <code>Function#bind</code> approach becomes a little obsolete because you may as well use the <code>Function#apply.apply</code> method.</p>
<blockquote>
<p>What is the purpose of converting arguments to an array in this case? </p>
</blockquote>
<p>There isn't one, it's redundant. Unless it's a custom <em>log</em> implementation, in which case the developer may have a reason to convert an arguments object to an array.</p>
<blockquote>
<p>And does prototype serve a purpose in the above examples, or are we just being pedantic... </p>
</blockquote>
<p>Well, yes and no. Some developer may have unwittingly changed <code>Function.call</code> to a custom function or value. Of course, they could break <code>Function.prototype.call</code> too, but this is far less likely to happen by accident.</p>
|
8,605,122 |
How do I resolve configuration errors with Nant 0.91?
|
<p>After downloading Nant 0.91, I'm getting some rather cryptic configuration errors relating to configuration or security (see below). </p>
<p>I'm trying to simply upgrade my Nant executables from 0.86 to 0.91.</p>
<p>How can I resolve the issues below when building on a Windows 7 machine?</p>
<blockquote>
<p>log4net:ERROR XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.AppDomainSetup.VerifyDir(String dir, Boolean normalize)
at log4net.Util.SystemInfo.get_ConfigurationFileLocation()
at log4net.Config.XmlConfiguratorAttribute.ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository)</p>
<p>The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.FileIOPermission
The Zone of the assembly that failed was:
Internet</p>
<p>Unhandled Exception: System.Security.SecurityException: Request for ConfigurationPermission failed while attempting to access configuration section 'nant'. To allow all callers to access the data for this section, set section attribute 'requirePermission' equal 'false' in the configuration file where this section is declared. ---> System.Security.SecurityException: Request for the permission of type 'System.Configuration.ConfigurationPermission, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.Configuration.BaseConfigurationRecord.CheckPermissionAllowed(String configKey, Boolean requirePermission, Boolean isTrustedWithoutAptca)
--- End of inner exception stack trace ---
at System.Configuration.BaseConfigurationRecord.CheckPermissionAllowed(String configKey, Boolean requirePermission, Boolean isTrustedWithoutAptca)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NAnt.Console.ConsoleStub.Framework.GetRuntimeFramework()
at NAnt.Console.ConsoleStub.Main(String[] args</p>
</blockquote>
<p>(Answer is forthcoming, posting as a question for reference....)</p>
| 8,605,149 | 4 | 1 | null |
2011-12-22 14:13:55.537 UTC
| 14 |
2021-03-05 06:09:40.47 UTC
|
2011-12-22 14:27:09.12 UTC
| null | 6,112 | null | 6,112 | null | 1 | 106 |
windows-7|build|log4net|nant
| 21,071 |
<p>Oddly enough, this is related to how the executables are extracted from the Nant 0.91 archive. (This made no sense to me until I actually tried it, but it does actually work...)</p>
<p>Source : <a href="http://surfjungle.blogspot.com/2011/11/tip-running-nant-091-on-windows-7.html">http://surfjungle.blogspot.com/2011/11/tip-running-nant-091-on-windows-7.html</a></p>
<blockquote>
<p>I found that the problem was Windows 7 security related in that the downloaded NAnt 0.91 zip file needed additional security related configuration to be performed: before extracting, <strong>one must right click on the zip file, select Properties and under the General tab, click the button labelled Unblock, then click OK on the Properties window. Now, extract the file to your desired location</strong>, ensure it is on the system path, open a new command line and NAnt should run successfully.</p>
</blockquote>
|
8,839,958 |
How does origin/HEAD get set?
|
<p>I have a branch set up to track a ref in origin. <code>git checkout <branchname></code> switches to that branch, and a <code>git status</code> will show me how far ahead or behind my branch is from origin, but I'm surprised that <code>origin/HEAD</code> still points at <code>origin/master</code>, and not <code>origin/<branchname></code></p>
<p>So my question is, under what circumstances does origin/HEAD get moved?</p>
<p>EDIT:</p>
<p>I appreciate the answers about <em>how</em> to move origin/HEAD, but I'm interested in what "organically" moves it, outside of me explicitly telling it to do so.</p>
<p>For example, when I switch branches, git makes HEAD point at the branch I'm checking out, so I'm surprised that origin/HEAD doesn't move in the same manner.</p>
| 8,841,024 | 7 | 1 | null |
2012-01-12 18:03:15.96 UTC
| 83 |
2021-05-17 21:01:16.303 UTC
|
2012-01-12 18:48:06.02 UTC
| null | 37,838 | null | 37,838 | null | 1 | 187 |
git
| 234,086 |
<p>Note first that your question shows a bit of misunderstanding. <strong>origin/HEAD represents the default branch on the remote</strong>, i.e. the HEAD that's in that remote repository you're calling origin. When you switch branches in your repo, you're not affecting that. The same is true for remote branches; you might have <code>master</code> and <code>origin/master</code> in your repo, where <code>origin/master</code> represents a local copy of the <code>master</code> branch in the remote repository. </p>
<p><strong>origin's HEAD will only change if you or someone else actually changes it in the remote repository</strong>, which should basically never happen - you want the default branch a public repo to stay constant, on the stable branch (probably master). <strong>origin/HEAD is a local ref representing a local copy of the HEAD in the remote repository.</strong> (Its full name is refs/remotes/origin/HEAD.)</p>
<p>I think the above answers what you actually wanted to know, but to go ahead and answer the question you explicitly asked... origin/HEAD is set automatically when you clone a repository, and that's about it. Bizarrely, that it's <em>not</em> set by commands like <code>git remote update</code> - I believe the only way it will change is if you manually change it. (By change I mean point to a different branch; obviously the commit it points to changes if that branch changes, which might happen on fetch/pull/remote update.)</p>
<hr>
<p><strong>Edit</strong>: The problem discussed below was corrected in <strong>Git 1.8.4.3</strong>; see <a href="https://stackoverflow.com/a/25430727/2541573">this update</a>.</p>
<hr>
<p>There is a tiny caveat, though. HEAD is a symbolic ref, pointing to a branch instead of directly to a commit, but the git remote transfer protocols only report commits for refs. So Git knows the SHA1 of the commit pointed to by HEAD and all other refs; it then has to deduce the value of HEAD by finding a branch that points to the same commit. This means that if two branches happen to point there, it's ambiguous. (I believe it picks master if possible, then falls back to first alphabetically.) You'll see this reported in the output of <code>git remote show origin</code>:</p>
<pre><code>$ git remote show origin
* remote origin
Fetch URL: ...
Push URL: ...
HEAD branch (remote HEAD is ambiguous, may be one of the following):
foo
master
</code></pre>
<p>Oddly, although the notion of HEAD printed this way will change if things change on the remote (e.g. if foo is removed), it doesn't actually update <code>refs/remotes/origin/HEAD</code>. This can lead to really odd situations. Say that in the above example origin/HEAD actually pointed to foo, and origin's foo branch was then removed. We can then do this:</p>
<pre><code>$ git remote show origin
...
HEAD branch: master
$ git symbolic-ref refs/remotes/origin/HEAD
refs/remotes/origin/foo
$ git remote update --prune origin
Fetching origin
x [deleted] (none) -> origin/foo
(refs/remotes/origin/HEAD has become dangling)
</code></pre>
<p>So even though remote show knows HEAD is master, it doesn't update anything. The stale foo branch is correctly pruned, and HEAD becomes dangling (pointing to a nonexistent branch), and it <em>still</em> doesn't update it to point to master. If you want to fix this, use <code>git remote set-head origin -a</code>, which automatically determines origin's HEAD as above, and then actually sets origin/HEAD to point to the appropriate remote branch.</p>
|
27,221,795 |
Disable automatic doubling of quotes in Notepad++
|
<p>Notepad++ automatically places another quote if I type a single quote or double quote. How can I disable this?</p>
| 27,221,822 | 2 | 3 | null |
2014-12-01 04:39:07.497 UTC
| 1 |
2019-12-05 13:21:44.733 UTC
|
2019-12-05 13:21:44.733 UTC
| null | 2,932,052 | null | 1,165,493 | null | 1 | 31 |
notepad++|quotes
| 19,074 |
<p>Notepad++ has a setting that controls the auto-completion behavior. </p>
<pre><code>Settings -> Preferences -> Auto-Completion ->Auto-Insert
</code></pre>
<p><strong>Edit:</strong> </p>
<p>Your requirement:</p>
<blockquote>
<p>We need to type quotes twice for them to appear and when they do appear, there are two of them.</p>
</blockquote>
<p>This behavior is controlled by Keyboard language settings in Control Panel. Go to </p>
<pre><code>Control Panel -> Regional and Language -> Keyboards and Languages
</code></pre>
<p>and select a keyboard language which requires typing twice before quotes appear.</p>
|
19,619,425 |
What is the true difference between a real mode program and a protected mode program?
|
<p>I know the difference between a real mode and protected mode from the OS and hardware perspective. </p>
<p>But I am trying to figure out What does a program 'knows' about real mode or protected mode? how can you say while looking at an source code/object code that it is a real mode program or not?</p>
<p>Looking for an answer, All I could come up with is that a 'real mode' program uses BIOS subroutines along with OS subroutines whereas a 'protected mode' program uses only OS subroutines. instruction code differs since opcodes for registers are different and offset addresses are of different length. Is there any other feature that differentiates a real and protected mode program?</p>
| 19,630,884 | 3 | 1 | null |
2013-10-27 14:54:02.877 UTC
| 8 |
2013-10-28 10:06:29.7 UTC
|
2013-10-27 16:53:02.753 UTC
| null | 597,858 | null | 597,858 | null | 1 | 12 |
operating-system|protected-mode|real-mode
| 24,503 |
<p>a 'real mode' program uses BIOS subroutines along with OS subroutines whereas a 'protected mode' program uses only OS subroutines. </p>
<p>instruction code differs since opcodes for registers are different and offset addresses are of different length.</p>
|
436,169 |
IIS7: Setup Integrated Windows Authentication like in IIS6
|
<p>This is for IIS 7 on a Windows Server 2008 that is not part of an AD domain. I would like to password protect a website, where people have to enter a username/password (a windows account for example) to view the website. The website would then use its own authentication method (forms) to handle user accounts and decide whether or not to show member specific pages, etc. </p>
<p>With IIS6, we just disabled anonymous access and enabled integrated windows authentication. IIS7 behaves differently and when I enter the windows username/password to view the site, the site comes up fine but redirects to the login page. Once I log in, the site behaves naturally. I need to be able to navigate the site without logging in with the website credentials.</p>
<p>I don't think enabling anonymous access would make sense here since I want access to the website to be password protected (popup username/password dialog when you first navigate to the url).</p>
<p>Any help is appreciated!</p>
| 437,758 | 4 | 0 | null |
2009-01-12 17:15:11.68 UTC
| 12 |
2013-05-22 13:28:31.92 UTC
| null | null | null |
Jim Geurts
| 3,085 | null | 1 | 52 |
authentication|iis-7|windows-authentication
| 150,751 |
<p>Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.</p>
<p>You can either:</p>
<ol>
<li>Change the app domain to be in IIS6 classic mode... </li>
<li>Follow <a href="http://mvolo.com/iis-70-twolevel-authentication-with-forms-authentication-and-windows-authentication/" rel="nofollow noreferrer">this example</a> (<a href="http://mvolo.com/blogs/serverside/archive/2008/02/11/IIS-7.0-Two_2D00_Level-Authentication-with-Forms-Authentication-and-Windows-Authentication.aspx" rel="nofollow noreferrer">old link</a>) of how to fake two-stage authentication with IIS7 integrated mode.</li>
<li>Use <a href="http://www.helicontech.com/ape/" rel="nofollow noreferrer">Helicon Ape</a> and <a href="http://www.helicontech.com/articles/site-authentication-not-using-windows-users/" rel="nofollow noreferrer">mod_auth to provide basic authentication</a></li>
</ol>
|
37,357,605 |
Android Firebase Analytics Custom Events Reporting in Console
|
<p>Accept my apologies in advance if this is the incorrect place to post this question as I am unsure what would be.</p>
<p>What I am trying to accomplish is to record a custom even using Firebase analytics that produces a similar report in the Firebase console to their example of the <code>select_content</code> event. It is triggered as follows:</p>
<pre><code> FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "ID");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "NAME");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
</code></pre>
<p>and more specifically the string after <code>FirebaseAnalytics.Param.CONTENT_TYPE</code> can be any value and will produce a report in the console as shown below:</p>
<p><a href="https://i.stack.imgur.com/zQ9s0.jpg"><img src="https://i.stack.imgur.com/zQ9s0.jpg" alt=""></a></p>
<p>I create my own custom events as:</p>
<pre><code>Bundle params2 = new Bundle();
params2.putString(FirebaseAnalytics.Param.VALUE, "Google Play Games Sign out Button");
mFirebaseAnalytics.logEvent("Main_Activity_Button_Pressed", params2);
</code></pre>
<p>and the report produced for this event shown below does not appear to take into account the value I have added.</p>
<p><a href="https://i.stack.imgur.com/txDzi.jpg"><img src="https://i.stack.imgur.com/txDzi.jpg" alt="enter image description here"></a></p>
<p>Is it possible to accomplish what I am trying to do, and if so what is the correct way to implement this?</p>
<p><strong>Update</strong>: Seems this is not possible for testing purposes as I recently discovered this:<a href="https://i.stack.imgur.com/83k67.jpg"><img src="https://i.stack.imgur.com/83k67.jpg" alt="enter image description here"></a></p>
<p>which explains why my custom parameters do not appear in the console. </p>
| 37,369,326 | 4 | 2 | null |
2016-05-21 00:16:49.363 UTC
| 3 |
2020-09-13 09:34:31.6 UTC
|
2016-05-22 00:12:33.63 UTC
| null | 1,489,990 | null | 1,489,990 | null | 1 | 36 |
android|firebase|firebase-analytics
| 29,389 |
<p>First, credit to <a href="https://stackoverflow.com/users/268156/adamk">AdamK</a> for adding this:</p>
<blockquote>
<p>Custom parameters: Custom parameters are not represented directly in your Analytics reports, but they can be used as filters in audience definitions that can be applied to every report. Custom parameters are also included in data exported to BigQuery if your app is linked to a BigQuery project.</p>
</blockquote>
<p>But, something I discovered is:</p>
<p><a href="https://i.stack.imgur.com/oLsHh.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/oLsHh.jpg" alt="enter image description here"></a></p>
<p>which would explain why my custom parameters do not appear as I am the only tester. </p>
|
30,373,343 |
ReactJS component names must begin with capital letters?
|
<p>I am playing around with the ReactJS framework on <a href="https://jsbin.com/" rel="noreferrer">JSBin</a>.</p>
<p>I have noticed that if my component name starts with a lowercase letter it does not work.</p>
<p>For instance the following does not render:</p>
<pre><code>var fml = React.createClass({
render: function () {
return <a href='google.com'>Go</a>
}
});
React.render(<fml />, document.body);
</code></pre>
<p>But as soon as I replace the <code>fml</code> with <code>Fml</code> it does render. </p>
<p>Is there a reason I cannot begin tags with small letters?</p>
| 30,373,505 | 6 | 1 | null |
2015-05-21 12:09:50.923 UTC
| 35 |
2021-06-27 09:15:39.89 UTC
|
2019-12-09 20:26:16.117 UTC
| null | 1,218,980 | null | 894,903 | null | 1 | 176 |
javascript|reactjs
| 68,432 |
<p>In JSX, lower-case tag names are considered to be HTML tags. However, lower-case tag names with a dot (property accessor) aren't.</p>
<p>See <a href="https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components" rel="noreferrer">HTML tags vs React Components</a>.</p>
<ul>
<li><code><component /></code> compiles to <code>React.createElement('component')</code> (html tag)</li>
<li><code><Component /></code> compiles to <code>React.createElement(Component)</code></li>
<li><code><obj.component /></code> compiles to <code>React.createElement(obj.component)</code></li>
</ul>
|
46,844,263 |
Writing json to file in s3 bucket
|
<p>This code writes json to a file in s3,
what i wanted to achieve is instead of opening data.json file and writing to s3 (sample.json) file, </p>
<p>how do i pass the json directly and write to a file in s3 ?</p>
<pre><code>import boto3
s3 = boto3.resource('s3', aws_access_key_id='aws_key', aws_secret_access_key='aws_sec_key')
s3.Object('mybucket', 'sample.json').put(Body=open('data.json', 'rb'))
</code></pre>
| 46,844,646 | 4 | 2 | null |
2017-10-20 07:28:48.72 UTC
| 11 |
2022-07-19 22:04:17.637 UTC
|
2017-10-20 15:12:48.32 UTC
| null | 400,617 | null | 8,782,508 | null | 1 | 47 |
python|boto3
| 95,635 |
<p>Amazon S3 is an object store (File store in reality). The primary operations are PUT and GET. You can not add data into an existing object in S3. You can only replace the entire object itself.</p>
<p>For a list of available operations you can perform on s3 see this link
<a href="http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectOps.html" rel="noreferrer">http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectOps.html</a></p>
|
47,039,812 |
How to install popper.js with Bootstrap 4?
|
<p>From what I've read so far, popper.js is a big pain with Bootstrap 4. I can't get it to work. I keep getting this error:</p>
<blockquote>
<p>Error: Bootstrap dropdown require Popper.js (<a href="https://popper.js.org" rel="noreferrer">https://popper.js.org</a>)</p>
</blockquote>
<p>I've tried the CDN and NPM install. Same result. At the bottom of my HTML file, I have this for the NPM install:</p>
<pre><code><script src="js/jquery.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</code></pre>
<p>Then tried this for the CDN:</p>
<pre><code><script src="/js/jquery.min.js"></script>
<script src="/js/tether.min.js"></script>
<script src="https://cdnjs.com/libraries/popper.js"></script>
<script src="/js/bootstrap.min.js"></script>
</code></pre>
<p>Any ideas what I'm doing wrong?</p>
| 47,041,690 | 11 | 3 | null |
2017-10-31 16:07:21.753 UTC
| 18 |
2021-03-19 16:06:54.02 UTC
| null | null | null | null | 40,106 | null | 1 | 66 |
twitter-bootstrap|popper.js
| 171,320 |
<p><a href="https://cdnjs.com/libraries/popper.js" rel="noreferrer">https://cdnjs.com/libraries/popper.js</a> does not look like a right src for popper, it does not specify the file </p>
<p>with bootstrap 4 I am using this </p>
<pre><code><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
</code></pre>
<p>and it is working perfectly fine, give it a try</p>
|
36,631,762 |
Returning HTML With fetch()
|
<p>I'm trying to fetch a file and return it's HTML. However it's not as simple as I'd have imagined.</p>
<pre><code> fetch('/path/to/file')
.then(function (response) {
return response.body;
})
.then(function (body) {
console.log(body);
});
</code></pre>
<p>This returns an object called <code>ReadableByteStream</code>. How do I use this to grab the HTML file content?</p>
<p>If I change the contents of <code>/path/to/file</code> to be a JSON string, and change the above to:</p>
<pre><code> fetch('/path/to/file')
.then(function (response) {
return response.json();
})
.then(function (json) {
console.log(json);
});
</code></pre>
<p>... it returns the JSON correctly. How do I do fetch HTML?</p>
| 36,632,271 | 7 | 5 | null |
2016-04-14 19:01:03.097 UTC
| 38 |
2022-05-10 15:29:44.097 UTC
|
2019-08-21 13:54:11.033 UTC
| null | 3,578,997 | null | 618,584 | null | 1 | 93 |
javascript|fetch-api
| 117,289 |
<p>You need to use the <code>.text()</code> method, instead of <code>.json()</code>. This converts the byte stream into plain text, which can be parsed by the browser as HTML.</p>
|
4,757,890 |
When the use of a AntiForgeryToken is not required /needed?
|
<p><strong>UPD:</strong> Same question asked on <a href="https://security.stackexchange.com/questions/2120/when-the-use-of-a-antiforgerytoken-is-not-required-needed">security.stackexchange.com</a> and the answer I got is different. Please follow there, to get the correct answer!</p>
<p>I'm running a rather large site with thousands of visits every day, and a rather large userbase.</p>
<p>Since I started migrating to MVC 3, I've been putting the AntiForgeryToken in a number of forms, that modify protected data etc.</p>
<p>Some other forms, like the login / registration also use the AntiForgeryToken now, but I'm becoming dubious about their need there in the first place, for a couple reasons...</p>
<ol>
<li>The login form requires the poster to know the correct credentials. I can't really think of any way an csrf attack would benefit here. Especially if I check that the request came from the same host (checking the Referrer header) </li>
<li>The AntiForgeryToken token generates different values every time the page is loaded.. If I have two tabs open with the login page, and then try to post them, the first one will successfully load. The second will fail with a AntiForgeryTokenException (first load both pages, then try to post them). With more secure pages - this is obviously a necessary evil, with the login pages - seems like overkill, and just asking for trouble :S</li>
</ol>
<p>There are possibly other reasons why would one use/not use the token in their forms.. Am I correct in assuming that using the token in every post form is bad / overkill, and if so - what kind of forms would benefit from it, and which ones would definitely NOT benefit?</p>
| 4,762,560 | 1 | 2 | null |
2011-01-21 10:49:17.707 UTC
| 9 |
2011-02-23 11:03:42.083 UTC
|
2017-03-17 13:14:46.04 UTC
| null | -1 | null | 254,716 | null | 1 | 26 |
asp.net-mvc-3|csrf|antiforgerytoken
| 13,269 |
<p>Anti forgery tokens are useless in public parts of the site where users are not yet authenticated such as login and register forms. The way CSRF attack works is the following:</p>
<ol>
<li>A malicious user sets a HTML form on his site which resembles your site. This form could contain hidden fields as well.</li>
<li>He tricks one of your site users to visit his malicious url.</li>
<li>The user thinks that he is on your site, fills the form and submits it to your site.</li>
<li>If the user was already authenticated on your site the form submission succeeds and the unsuspecting user have deleted his account (or whatever you can imagine).</li>
</ol>
<p>So you could use anti forgery tokens on authenticated parts of your site containing actions that could modify somehow the user state.</p>
<p>Remark: checking the Referer header for identifying that a request came from your site is not secure. Anyone can forge a request and spoof this header.</p>
|
60,291,987 |
Idiomatic way of performance evaluation?
|
<p>I am evaluating a network+rendering workload for my project.</p>
<p>The program continuously runs a main loop:</p>
<pre><code>while (true) {
doSomething()
drawSomething()
doSomething2()
sendSomething()
}
</code></pre>
<p>The main loop runs more than 60 times per second.</p>
<p>I want to see the performance breakdown, how much time each procedure takes.</p>
<p>My concern is that if I print the time interval for every entrance and exit of each procedure,</p>
<p>It would incur huge performance overhead.</p>
<p>I am curious what is an idiomatic way of measuring the performance.</p>
<p>Printing of logging is good enough?</p>
| 60,293,070 | 1 | 2 | null |
2020-02-19 02:06:41.3 UTC
| 10 |
2022-08-09 06:43:57.157 UTC
| null | null | null | null | 11,211,510 | null | 1 | 10 |
benchmarking|microbenchmark
| 2,740 |
<p>Generally: For repeated short things, you can just time the whole repeat loop. (But microbenchmarking is hard; easy to distort results unless you understand the implications of doing that; for very short things, throughput and latency are different, so measure both separately by making one iteration use the result of the previous or not. Also beware that branch prediction and caching can make something look fast in a microbenchmark when it would actually be costly if done one at a time between other work in a larger program.
e.g. loop unrolling and lookup tables often look good because there's no pressure on I-cache or D-cache from anything else.)</p>
<p>Or if you insist on timing each separate iteration, record the results in an array and print later; you don't want to invoke heavy-weight printing code inside your loop.</p>
<p>This question is way too broad to say anything more specific.</p>
<p><strong>Many languages have benchmarking packages that will help you write microbenchmarks of a single function. Use them</strong>. e.g. for Java, JMH makes sure the function under test is warmed up and fully optimized by the JIT, and all that jazz, before doing timed runs. And runs it for a specified interval, counting how many iterations it completes.</p>
<p>Beware common microbenchmark pitfalls:</p>
<ul>
<li><p>Failure to warm up code / data caches and stuff: page faults within the timed region for touching new memory, or code / data cache misses, that wouldn't be part of normal operation. (Example of noticing this effect: *<a href="https://stackoverflow.com/questions/23723215/performance-memset*;">Performance: memset</a> example of a <a href="https://stackoverflow.com/questions/57125253/why-is-iterating-though-stdvector-faster-than-iterating-though-stdarray">wrong conclusion based on this mistake</a>)</p>
</li>
<li><p>Never-written memory (obtained fresh from the kernel) gets all its pages copy-on-write mapped to the same system-wide physical page (4K or 2M) of zeros if you read without writing, at least <a href="https://stackoverflow.com/questions/57125253/why-is-iterating-though-stdvector-faster-than-iterating-though-stdarray/57130924#57130924">on Linux</a>. So you can get cache hits but TLB misses. e.g. A large allocation from <code>new</code> / <code>calloc</code> / <code>malloc</code>, or a zero-initialized array in static storage in <code>.bss</code>. Use a non-zero initializer or memset.</p>
</li>
<li><p>Failure to give the CPU time to ramp up to max turbo: modern CPUs clock down to idle speeds to save power, only clocking up after a few milliseconds. (Or longer depending on the OS / HW).</p>
<p>related: on modern x86, <a href="https://stackoverflow.com/questions/13772567/how-to-get-the-cpu-cycle-count-in-x86-64-from-c/51907627#51907627">RDTSC counts reference cycles, not core clock cycles</a>, so it's subject to the same CPU-frequency variation effects as wall-clock time.</p>
</li>
<li><p>Most integer and FP arithmetic asm instructions (<a href="https://stackoverflow.com/questions/4125033/floating-point-division-vs-floating-point-multiplication/45899202#45899202">except divide and square root</a> which are already slower than others) have performance (latency and throughput) that doesn't depend on the actual data. Except for subnormal aka denormal floating point <a href="https://stackoverflow.com/questions/60969892/performance-penalty-denormalized-numbers-versus-branch-mis-predictions">being <em>very</em> slow</a>, and in some cases (e.g. <a href="https://stackoverflow.com/questions/31875464/huge-performance-difference-26x-faster-when-compiling-for-32-and-64-bits/31879376#31879376">legacy x87 but not SSE2</a>) also producing NaN or Inf can be slow.</p>
</li>
<li><p>On modern CPUs with out-of-order execution, <a href="https://stackoverflow.com/questions/54621381/rdtscp-in-nasm-always-returns-the-same-value">some things are too short to truly time meaningfully</a>, see also <a href="https://stackoverflow.com/questions/51607391/what-considerations-go-into-predicting-latency-for-operations-on-modern-supersca">this</a>. <strong>Performance of a tiny block of assembly language (e.g. generated by a compiler for one function) can't be characterized by a single number,</strong> even if it doesn't branch or access memory (so no chance of mispredict or cache miss). It has latency from inputs to outputs, but different throughput if run repeatedly with independent inputs is higher. e.g. an <code>add</code> instruction on a Skylake CPU has 4/clock throughput, but 1 cycle latency. So <code>dummy = foo(x)</code> can be 4x faster than <code>x = foo(x);</code> in a loop. Floating-point instructions have higher latency than integer, so it's often a bigger deal. Memory access is also pipelined on most CPUs, so looping over an array (address for next load easy to calculate) is often much faster than walking a linked list (address for next load isn't available until the previous load completes).</p>
<p>Obviously performance can differ between CPUs; in the big picture usually it's rare for version A to be faster on Intel, version B to be faster on AMD, but that can easily happen in the small scale. When reporting / recording benchmark numbers, always note what CPU you tested on.</p>
</li>
<li><p>Related to the above and below points: you can't "benchmark the <code>*</code> operator" in C in general, for example. Some use-cases for it will compile very differently from others, e.g. <code>tmp = foo * i;</code> in a loop can often turn into <code>tmp += foo</code> (strength reduction), or if the multiplier is a constant power of 2 the compiler will just use a shift. The same operator in the source can compile to very different instructions, depending on surrounding code.</p>
</li>
<li><p><strong>You <a href="https://stackoverflow.com/questions/32000917/c-loop-optimization-help-for-final-assignment-with-compiler-optimization-disabl/32001196#32001196">need to compile with optimization enabled</a>, but you also need to stop the compiler from optimizing away the work</strong>, or hoisting it out of a loop. Make sure you use the result (e.g. print it or store it to a <code>volatile</code>) so the compiler has to produce it. For an array, <code>volatile double sink = output[argc];</code> is a useful trick: the compiler doesn't know the value of <code>argc</code> so it has to generate the whole array, but you don't need to read the whole array or even call an RNG function. (Unless the compiler aggressively transforms to only calculate the one output selected by <code>argc</code>, but that tends not to be a problem in practice.)</p>
<p>For inputs, use a random number or <code>argc</code> or something instead of a compile-time constant so your compiler can't do constant-propagation for things that won't be constants in your real use-case. In C you can sometimes use inline asm or <code>volatile</code> for this, e.g. the stuff <a href="https://stackoverflow.com/questions/33975479/escape-and-clobber-equivalent-in-msvc">this question is asking about</a>. A good benchmarking package like <a href="https://github.com/google/benchmark" rel="nofollow noreferrer">Google Benchmark</a> will include functions for this.</p>
</li>
<li><p>If the real use-case for a function lets it inline into callers where some inputs are constant, or the operations can be optimized into other work, it's not very useful to benchmark it on its own.</p>
</li>
<li><p>Big complicated functions with special handling for lots of special cases can look fast in a microbenchmark when you run them repeatedly, especially with the <em>same</em> input every time. In real life use-cases, branch prediction often won't be primed for that function with that input. Also, a massively unrolled loop can look good in a microbenchmark, but in real life it slows everything else down with its big instruction-cache footprint leading to eviction of other code.</p>
</li>
</ul>
<p>Related to that last point: <strong>Don't tune only for huge inputs, if the real use-case for a function includes a lot of small inputs.</strong> e.g. a <code>memcpy</code> implementation that's great for huge inputs but takes too long to figure out which strategy to use for small inputs might not be good. It's a tradeoff; make sure it's good enough for large inputs (for an appropriate definition of "enough"), but also keep overhead low for small inputs.</p>
<p><strong>Litmus tests:</strong></p>
<ul>
<li><p>If you're benchmarking two functions in one program: <strong>if reversing the order of testing changes the results, your benchmark isn't fair</strong>. e.g. function A might only look slow because you're testing it first, with insufficient warm-up. example: <a href="https://stackoverflow.com/questions/60293633/why-is-stdvector-slower-than-an-array">Why is std::vector slower than an array?</a> (it's not, whichever loop runs first has to pay for all the page faults and cache misses; the 2nd just zooms through filling the same memory.)</p>
</li>
<li><p><strong>Increasing the iteration count of a repeat loop should linearly increase the total time</strong>, and not affect the calculated time-per-call. If not, then you have non-negligible measurement overhead or your code optimized away (e.g. hoisted out of the loop and runs only once instead of N times).</p>
</li>
<li><p>Vary other test parameters as a sanity check.</p>
</li>
</ul>
<hr />
<p><strong>For C / C++, see also</strong> <a href="https://stackoverflow.com/questions/50924929/simple-for-loop-benchmark-takes-the-same-time-with-any-loop-bound/50934895#50934895">Simple for() loop benchmark takes the same time with any loop bound</a> where I went into some more detail about microbenchmarking and using <code>volatile</code> or <code>asm</code> to stop important work from optimizing away with gcc/clang.</p>
|
31,380,784 |
Java 8 Stream String Null Or Empty Filter
|
<p>I've got Google Guava inside Stream:</p>
<pre><code>this.map.entrySet().stream()
.filter(entity -> !Strings.isNullOrEmpty(entity.getValue()))
.map(obj -> String.format("%s=%s", obj.getKey(), obj.getValue()))
.collect(Collectors.joining(","))
</code></pre>
<p>As you see there is a statement <code>!String.isNullOrEmpty(entity)</code> inside the filter function.</p>
<p>I don't want to use Guava anymore in the project, so I just want to replace it simply by:</p>
<pre><code>string == null || string.length() == 0;
</code></pre>
<p>How can I do it more elegant? </p>
| 31,381,251 | 6 | 9 | null |
2015-07-13 10:21:13.433 UTC
| 4 |
2019-10-16 05:46:03.723 UTC
|
2016-05-05 17:45:01.56 UTC
| null | 1,196,670 | null | 1,230,556 | null | 1 | 33 |
java|java-8|guava|java-stream
| 86,616 |
<p>You can write your own predicate:</p>
<pre><code>final Predicate<Map.Entry<?, String>> valueNotNullOrEmpty
= e -> e.getValue() != null && !e.getValue().isEmpty();
</code></pre>
<p>Then just use <code>valueNotNullOrEmpty</code> as your filter argument.</p>
|
20,011,862 |
How to change the text color. Simple?
|
<pre><code>If CDbl(totalAverage) >= 89 Then
lblGrade.Text = "A"
ElseIf CDbl(totalAverage) >= 79 Then
lblGrade.Text = "B"
ElseIf CDbl(totalAverage) >= 69 Then
lblGrade.Text = "C"
ElseIf CDbl(totalAverage) >= 59 Then
lblGrade.Text = "D"
ElseIf CDbl(totalAverage) >= 0 Then
lblGrade.Text = "F"
End If
</code></pre>
<p>Just trying to change the colors of the text to green for an A, B, or C. Orange for a D, and red for an F.</p>
<p>I was thinking it was lblGrade.Text.Color or something like that; however, that didn't seem to be a command and I've been looking around and was having trouble finding the answer to this and thought it would be easier to just ask here. Thanks for the help</p>
| 20,011,926 | 1 | 0 | null |
2013-11-15 22:39:41.54 UTC
| null |
2017-02-10 21:51:58.623 UTC
|
2017-02-10 21:51:58.623 UTC
| null | 6,771,952 | null | 2,990,050 | null | 1 | 2 |
vb.net
| 53,752 |
<p>lblGrade.Forecolor is what your looking for. </p>
<p>For orange, it would be "lblGrade.ForeColor = Color.Orange"</p>
|
55,326,416 |
fs.FileRead -> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined
|
<pre><code>function openFileDialog() {
dialog.showOpenDialog(win, {
properties: ['openFile']
} , filepath => {
if (filepath) {
fs.writeFile('path.txt', filepath, function (err, data) {
if (err) console.log(err);
});
scanFile(filepath)
}
})
}
function scanFile(filepath) {
if(!filepath || filepath[0] == 'undefined') return;
console.log(filepath)
fs.readFile(filepath,"utf8", (err,data) => { // ----> *ERROR*
if(err) console.log(err);
var arr = [];
if (data.substr(-4) === '.mp3' || data.substr(-4) === '.m4a'
|| data.substr(-5) === '.webm' || data.substr(-4) === '.wav'
|| data.substr(-4) === '.aac' || data.substr(-4) === '.ogg'
|| data.substr(-5) === '.opus') {
arr.push(files[i]);
}
var objToSend = {};
objToSend.files = arr;
objToSend.path = filepath;
win.webContents.send('selected-files', objToSend)
})
}
</code></pre>
<p>I tried to made electron music player app. As a first step is opening my file. When I open file, "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined" that error occured and error message showed that scanFile(filepath), fs.readFile(~~) caused error. How should I fix it?</p>
| 55,326,551 | 1 | 2 | null |
2019-03-24 17:17:51.9 UTC
| null |
2020-01-27 18:08:17.36 UTC
| null | null | null | null | 7,339,889 | null | 1 | 3 |
javascript|node.js|electron|fs
| 47,884 |
<p>The first line of <code>scanFile</code> reads: </p>
<p><code>if(!filepath || filepath[0] == 'undefined') return;</code></p>
<p>This indicates to me that <code>filepath</code> is an array, not a string (or Buffer or URL). Check the output of the <code>console.log</code> statement to see if this is the case. Since the <code>if</code> statement is checking for <code>filepath[0]</code>, I'd start there and update the code to read <code>fs.readFile(filepath[0],"utf8", (err,data) => {</code>, since the <code>if</code> statement implies that <code>filepath[0</code>] is the value you should be using</p>
|
24,138,398 |
How to implement PhantomJS with Selenium WebDriver using java
|
<p>I'm going mad, really. I have this code:</p>
<pre><code>public class Creazione extends TestCase {
private PhantomJSDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
File file = new File("C:/Program Files/phantomjs-1.9.7-windows/phantomjs.exe");
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
driver = new PhantomJSDriver();
baseUrl = "http://www.gts.fiorentina.test/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "/Account/Login.aspx?ReturnUrl=%2f");
findDynamicElement(By.id("tbUserName_I"), 2000);
driver.findElement(By.id("tbUserName_I")).clear();
driver.findElement(By.id("tbUserName_I")).sendKeys("rogai");
driver.findElement(By.id("tbPassword_I")).clear();
driver.findElement(By.id("tbPassword_I")).sendKeys("Fiorentina2014!");
driver.findElement(By.id("btnLogin_CD")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testCreazione() throws Exception {
driver.get(baseUrl + "/SegreteriaSportiva/Calciatori.aspx");
findDynamicElement(By.cssSelector("#ASPxButton1_CD > span"), 2000);
driver.findElement(By.cssSelector("#ASPxButton1_CD > span")).click();
findDynamicElement(By.id("FrmEdit_TS_TipoPersonaId_FK_B-1"), 2000);
driver.findElement(By.id("FrmEdit_TS_TipoPersonaId_FK_B-1")).click();
driver.findElement(By.id("FrmEdit_TS_TipoPersonaId_FK_DDD_L_LBI2T0")).click();
driver.findElement(By.id("FrmEdit_Nome_I")).clear();
driver.findElement(By.id("FrmEdit_Nome_I")).sendKeys("Prova");
driver.findElement(By.id("FrmEdit_Cognome_I")).clear();
driver.findElement(By.id("FrmEdit_Cognome_I")).sendKeys("Calciatore");
driver.findElement(By.id("FrmEdit_TS_RuoloId_FK_B-1")).click();
driver.findElement(By.id("FrmEdit_TS_RuoloId_FK_DDD_L_LBI3T0")).click();
driver.findElement(By.id("FrmEdit_DataNascita_I")).clear();
driver.findElement(By.id("FrmEdit_DataNascita_I")).sendKeys("01/01/2014");
driver.findElement(By.id("FrmEdit_Cittadinanza_I")).clear();
driver.findElement(By.id("FrmEdit_Cittadinanza_I")).sendKeys("italiana");
driver.findElement(By.id("FrmEdit_LuogoNascita_I")).clear();
driver.findElement(By.id("FrmEdit_LuogoNascita_I")).sendKeys("roma");
driver.findElement(By.cssSelector("#BTN_Edit_CD > span")).click();
driver.findElement(By.id("Grid_DXFREditorcol3_I")).click();
driver.findElement(By.id("Grid_DXFREditorcol3_I")).sendKeys("Prova");
assertEquals("Prova",driver.findElement(By.xpath("//tr[@id='Grid_DXDataRow0']/td[3]")).getText());
}
}
</code></pre>
<p>After execution I get these errors during runtime, following is that trace ---</p>
<pre><code>org.openqa.selenium.InvalidElementStateException: {"errorMessage":"Element is not currently interactable and may not be manipulated","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"27","Content-Type":"application/json; charset=utf-8","Host":"localhost:20497","User-Agent":"Apache-HttpClient/4.3.2 (java 1.5)"},"httpVersion":"1.1","method":"POST","post":"{\"id\":\":wdc:1402393987914\"}","url":"/clear","urlParsed":{"anchor":"","query":"","file":"clear","directory":"/","path":"/clear","relative":"/clear","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/clear","queryKey":{},"chunks":["clear"]},"urlOriginal":"/session/e4b71580-f084-11e3-959e-273aa801dd81/element/%3Awdc%3A1402393987914/clear"}}
Command duration or timeout: 215 milliseconds
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18'
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55'
Session ID: e4b71580-f084-11e3-959e-273aa801dd81
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver
Capabilities [{platform=XP, acceptSslCerts=false, javascriptEnabled=true, browserName=phantomjs, rotatable=false, driverVersion=1.1.0, locationContextEnabled=false, version=1.9.7, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=false, browserConnectionEnabled=false, webStorageEnabled=false, nativeEvents=true, proxy={proxyType=direct}, applicationCacheEnabled=false, driverName=ghostdriver, takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:113)
at com.example.tests.Creazione.testCreazione(Creazione.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.openqa.selenium.remote.ScreenshotException: Screen shot has been taken
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18'
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:136)
... 23 more
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: {"errorMessage":"Element is not currently interactable and may not be manipulated","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"27","Content-Type":"application/json; charset=utf-8","Host":"localhost:20497","User-Agent":"Apache-HttpClient/4.3.2 (java 1.5)"},"httpVersion":"1n.1","method":"POST","post":"{\"id\":\":wdc:1402393987914\"}","url":"/clear","urlParsed":{"anchor":"","query":"","file":"clear","directory":"/","path":"/clear","relative":"/clear","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/clear","queryKey":{},"chunks":["clear"]},"urlOriginal":"/session/e4b71580-f084-11e3-959e-273aa801dd81/element/%3Awdc%3A1402393987914/clear"}}
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18'
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55'
Driver info: driver.version: unknow
</code></pre>
<p>I have added the phantomjs.exe to the Windows Path, added as external library the ghostdriver.jar, but nothing...</p>
<p>It's like two days that I'm trying to make it work...</p>
| 25,444,253 | 4 | 1 | null |
2014-06-10 10:15:44.487 UTC
| 8 |
2017-02-14 01:28:47.49 UTC
|
2016-11-24 08:55:42.717 UTC
| null | 3,885,376 | null | 3,725,538 | null | 1 | 10 |
java|selenium|selenium-webdriver|phantomjs|screenshotexception
| 64,988 |
<p><strong>Try this, it worked for me</strong> </p>
<pre><code>DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", true);
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"your custom path\\phantomjs.exe"
);
WebDriver driver = new PhantomJSDriver(caps);
</code></pre>
<p>then rest of them are similar..and pls kindly comment your observation ,have a great day :)</p>
|
7,939,186 |
Inno Setup - #define directive - how to use previously defined variable?
|
<p>I am using Inno Setup version 5.4.2.</p>
<p>I want to define the path for the files to copy (the Source: parameter in the [Files] section as two parts, a base path and sub-directory names, that I use for special files (like .dlls).
I have tried the following:</p>
<pre><code>#define MyAppSetupDir "D:\MyApp\setup"
#define MyAppSetupQtDLLs {#MyAppSetupDir}"\DLLs"
[Files]
Source: {#MyAppSetupDir}\MyApp.exe; DestDir: {app}; Flags: ignoreversion
Source: {#MyAppSetupDLLs}\mstext35.dll; DestDir: {app}; Flags: ignoreversion
</code></pre>
<p>but I get the following compilation error</p>
<pre><code>[ISPP] Expression expected but opening brace ("{") found.
</code></pre>
<p>I also tried to enclose the braces in "", like</p>
<pre><code>#define MyAppSetupQtDLLs "{#MyAppSetupDir}\DLLs"
</code></pre>
<p>But this time I got</p>
<pre><code>Error: Source file "D:\MyApp\setup\{#MyAppSetupDir}\DLLs\mstext35.dll" does not exist.
</code></pre>
<p>So, ISSP is correctly replacing the MyAppSetupDir variable, but then puts again the simple text, as if it did not recognize the directive.</p>
<p>I have searched everywhere, and I already found a <a href="https://stackoverflow.com/questions/5043960/how-to-set-ispp-defines-based-on-default-inno-setup-variables">discussion</a> about using the <code>{commonappdata}</code>, but I could not find how to do this, neither in the documentation nor in the KB.
I would really appreciate some hints, as it looks I am close, but not finding the right solution..</p>
| 7,940,051 | 1 | 0 | null |
2011-10-29 13:28:02.213 UTC
| 5 |
2011-10-29 16:27:02.56 UTC
|
2017-05-23 10:31:23.45 UTC
| null | -1 | null | 1,019,789 | null | 1 | 47 |
inno-setup
| 15,711 |
<pre><code>#define MyAppSetupDir "D:\MyApp\setup"
#define MyAppSetupQtDLLs MyAppSetupDir + "\DLLs"
</code></pre>
|
1,554,751 |
How to handle push notifications if the application is already running?
|
<p>How do we handle push notifications if the application is <em>already</em> running ? I want to show an alert if the application is running (instead of a push notification alert). Only if the application is not running, then show a push notification alert.</p>
<p>Also, if I send a payload to APNs, how can I create an alert with a cancel button?</p>
| 1,554,831 | 4 | 0 | null |
2009-10-12 14:00:23.933 UTC
| 36 |
2017-06-27 14:54:35.13 UTC
|
2017-06-27 14:54:35.13 UTC
| null | 5,175,709 | null | 83,905 | null | 1 | 28 |
ios|objective-c|push-notification|apple-push-notifications
| 45,552 |
<p>You can implement <a href="https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveRemoteNotification:" rel="noreferrer"><code>application:didReceiveRemoteNotification:</code></a></p>
<p>Here is a possible sample code:</p>
<pre><code>- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSString *message = nil;
id alert = [userInfo objectForKey:@"alert"];
if ([alert isKindOfClass:[NSString class]]) {
message = alert;
} else if ([alert isKindOfClass:[NSDictionary class]]) {
message = [alert objectForKey:@"body"];
}
if (alert) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"AThe message." delegate:self
cancelButtonTitle:@"button 1"
otherButtonTitles:@"button", nil];
[alertView show];
[alertView release];
}
</code></pre>
|
1,647,359 |
Is there a way to get gcc to output raw binary?
|
<p>Is there a set of command-line options that will convince gcc to produce a flat binary file from a self-contained source file? For example, suppose the contents of foo.c are</p>
<pre><code>static int f(int x)
{
int y = x*x;
return y+2;
}
</code></pre>
<p>No external references, nothing to export to the linker. I'd like to get a small file with just the machine instructions for this function, without any other decoration. Sort of like a (DOS) .COM file except 32-bit protected mode.</p>
| 1,647,405 | 4 | 3 | null |
2009-10-30 00:26:14.077 UTC
| 18 |
2020-11-04 16:55:33.267 UTC
|
2016-10-18 20:49:59.013 UTC
| null | 1,483,676 | null | 8,677 | null | 1 | 35 |
linux|gcc|command-line|linker|x86
| 40,314 |
<p>Try this out:</p>
<pre><code>$ gcc -c test.c
$ objcopy -O binary -j .text test.o binfile
</code></pre>
<p>You can make sure it's correct with <code>objdump</code>:</p>
<pre><code>$ objdump -d test.o
test.o: file format pe-i386
Disassembly of section .text:
00000000 <_f>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 04 sub $0x4,%esp
6: 8b 45 08 mov 0x8(%ebp),%eax
9: 0f af 45 08 imul 0x8(%ebp),%eax
d: 89 45 fc mov %eax,-0x4(%ebp)
10: 8b 45 fc mov -0x4(%ebp),%eax
13: 83 c0 02 add $0x2,%eax
16: c9 leave
17: c3 ret
</code></pre>
<p>And compare it with the binary file:</p>
<pre><code>$ hexdump -C binfile
00000000 55 89 e5 83 ec 04 8b 45 08 0f af 45 08 89 45 fc |U......E...E..E.|
00000010 8b 45 fc 83 c0 02 c9 c3 |.E......|
00000018
</code></pre>
|
1,487,548 |
How to get the original value of an attribute in Rails
|
<p>is there a way to get the original value that an ActiveRecord attribute (=the value that was loaded from the database)?</p>
<p>I want something like this in an observer</p>
<pre><code>before_save object
do_something_with object.original_name
end
</code></pre>
<p>The task is to remove the object from a hash table (in fact, move it to another key in the table) upon updating.</p>
| 1,487,605 | 4 | 0 | null |
2009-09-28 15:03:20.157 UTC
| 13 |
2020-05-28 15:52:03.4 UTC
| null | null | null | null | 6,678 | null | 1 | 101 |
ruby-on-rails|activerecord
| 39,211 |
<h3>Before rails 5.1</h3>
<p>Appending <code>_was</code> to your attribute will give you the previous value.</p>
<h3>For rails 5.1+</h3>
<p><strong>Copied from Lucas Andrade's answer below</strong>: <a href="https://stackoverflow.com/a/50973808/9359123">https://stackoverflow.com/a/50973808/9359123</a> </p>
<hr>
<p>Appending <code>_was</code> is deprecated in rails 5.1, now you should append <code>_before_last_save</code></p>
<p>Something like:</p>
<pre><code>before_save object
do_something_with object.name_before_last_save
end
</code></pre>
<p>Will return the name value before your last save at database (works for save and create)<br><br>
<br>
The difference between <code>_was</code> and <code>_before_last_save</code> according to the documentation:</p>
<p><strong>_was</strong> source <a href="https://apidock.com/rails/ActiveRecord/Dirty/attribute_was" rel="noreferrer">from docs</a></p>
<pre><code>def attribute_was(attr)
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
</code></pre>
<p><strong>_before_last_save</strong> source <a href="http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html" rel="noreferrer">from docs</a></p>
<pre><code>def attribute_before_last_save(attr_name)
mutations_before_last_save.original_value(attr_name)
end
</code></pre>
|
28,635,496 |
Difference: LZ77 vs. LZ4 vs. LZ4HC (compression algorithms)?
|
<p>I understand the LZ77 and LZ78 algorithms.
I read about LZ4 <a href="http://www.brutaldeluxe.fr/products/crossdevtools/lz4/index.html" rel="noreferrer">here</a> and <a href="http://fastcompression.blogspot.co.uk/2011/05/lz4-explained.html" rel="noreferrer">here</a> and found <a href="http://code.google.com/p/lz4/source/browse/trunk/lz4hc.h?r=113" rel="noreferrer">code for it</a>.</p>
<p>Those links described the LZ4 block format. But it would be great if someone could explain (or direct me to some resource explaining):</p>
<ul>
<li>How LZ4 is different from LZ77?</li>
<li>How is LZ4HC different from LZ4? </li>
<li>What idea makes the LZ4HC algorithm so fast? </li>
</ul>
| 28,635,890 | 1 | 2 | null |
2015-02-20 18:09:37.997 UTC
| 38 |
2021-11-01 16:47:05.107 UTC
|
2015-02-27 18:22:54.457 UTC
| null | 2,714,852 | null | 4,485,500 | null | 1 | 49 |
lossless-compression|lz4|lz77
| 41,705 |
<p><a href="https://github.com/Cyan4973/lz4" rel="noreferrer">LZ4</a> is built to compress fast, at hundreds of MB/s per core. It's a fit for applications where you want compression that's very cheap: for example, you're trying to make a network or on-disk format more compact but can't afford to spend a bunch of CPU time on compression. It's in a family with, for example, <a href="https://github.com/google/snappy/" rel="noreferrer">snappy</a> and <a href="http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Oberhumer" rel="noreferrer">LZO</a>.</p>
<p>The natural comparison point is zlib's <a href="https://en.wikipedia.org/wiki/DEFLATE" rel="noreferrer">DEFLATE algorithm</a>, which uses <a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78" rel="noreferrer">LZ77</a> and <a href="https://en.wikipedia.org/wiki/Huffman_coding" rel="noreferrer">Huffman coding</a> and is used in gzip, the .ZIP and .PNG formats, and too many other places to count.</p>
<p>These fast compressors differ because:</p>
<ol>
<li>They use repetition-detection code that's faster (often a simple <a href="http://en.wikipedia.org/wiki/Hash_table" rel="noreferrer">hashtable</a> with no collision detection) but doesn't search through multiple possible matches for the best one (which would take time but result in higher compression), and can't find some short matches.</li>
<li>They only try to compress repetitions in input--they don't try to take advantage of some bytes being more likely than others <em>outside</em> of repetitions.</li>
<li>Closely related to 2, they generate bytes of output at a time, not bits; allowing fraction-of-a-byte codes would allow for more compression sometimes, but would require more CPU work (often bit-shifting and masking and branching) to encode and decode.</li>
<li>Lots of practical work has gone into making their implementations fast on modern CPUs.</li>
</ol>
<p>By comparison, DEFLATE gets better compression but compresses and decompresses slower, and high-compression algorithms like <a href="http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Markov_chain_algorithm" rel="noreferrer">LZMA</a>, <a href="http://en.wikipedia.org/wiki/Bzip2" rel="noreferrer">bzip2</a>, <a href="https://github.com/richgel999/lzham_codec" rel="noreferrer">LZHAM</a>, or <a href="https://github.com/google/brotli" rel="noreferrer">brotli</a> tend to take even more time (though <a href="https://quixdb.github.io/squash-benchmark/" rel="noreferrer">Brotli at its faster settings can compete with zlib</a>). There's a lot of variation among the high-compression algorithms, but broadly, they tend to capture redundancies over longer distances, take more advantage of context to determine what bytes are likely, and use more compact but slower ways to express their results in bits.</p>
<p>LZ4HC is a "high-compression" variant of LZ4 that, I believe, changes point 1 above--the compressor finds more than one match between current and past data and looks for the best match to ensure the output is small. This improves compression <em>ratio</em> but lowers compression <em>speed</em> compared to LZ4. Decompression speed isn't hurt, though, so if you compress once and decompress many times and mostly want extremely cheap decompression, LZ4HC would make sense.</p>
<p>Note that even a fast compressor might not allow one core to saturate a large amount of bandwidth, like that provided by SSDs or fast in-datacenter links. There are even quicker compressors with lower ratios, sometimes used to <a href="https://en.wikipedia.org/wiki/Virtual_memory_compression" rel="noreferrer">temporarily pack data in RAM</a>. <a href="https://github.com/berkus/wkdm" rel="noreferrer">WKdm</a> and <a href="https://github.com/centaurean/density" rel="noreferrer">Density</a> are two such compressors; one trait they share is acting on 4-byte <em>machine words</em> of input at a time rather than individual bytes. Sometimes specialized hardware can achieve very fast compression, like in <a href="https://github.com/XileForce/Vindicator-S6/blob/master/drivers/memory/exynos-mcomp.c" rel="noreferrer">Samsung's Exynos chips</a> or <a href="http://www.intel.com/content/www/us/en/ethernet-products/gigabit-server-adapters/quickassist-adapter-for-servers.html" rel="noreferrer">Intel's QuickAssist technology</a>.</p>
<p>If you're interested in compressing more than LZ4 but with less CPU time than deflate, the author of LZ4 (Yann Collet) wrote a library called <a href="https://github.com/facebook/zstd" rel="noreferrer">Zstd</a>--here's a <a href="https://code.facebook.com/posts/1658392934479273/smaller-and-faster-data-compression-with-zstandard/" rel="noreferrer">blog post from Facebook at its stable release</a>, background on the <a href="http://fastcompression.blogspot.com/2013/12/finite-state-entropy-new-breed-of.html" rel="noreferrer">finite state machines</a> used for compactly encoding info on repetitions, and a <a href="https://datatracker.ietf.org/doc/html/draft-kucherawy-dispatch-zstd" rel="noreferrer">detailed description in an RFC</a>. Its <a href="https://github.com/facebook/zstd/releases/tag/v1.3.4" rel="noreferrer">fast modes</a> could work in some LZ4-ish use cases. (Also, Apple developed <a href="https://github.com/lzfse/lzfse" rel="noreferrer">lzfse</a> on similar principles, and Google developed <a href="https://github.com/google/gipfeli" rel="noreferrer">gipfeli</a> as a 'medium' packer. Neither seemed to get much use in the outside world.) Also, a couple projects aim to provide faster/lighter DEFLATE: <a href="http://1wt.eu/projects/libslz/" rel="noreferrer">SLZ</a> and <a href="http://www.snellman.net/blog/archive/2015-06-05-updated-zlib-benchmarks/" rel="noreferrer">patches to zlib by CloudFlare and Intel</a>.</p>
<p>Compared to the fastest compressors, those "medium" packers add a form of <em>entropy encoding</em>, which is to say they take advantage of how some bytes are more common than others and (in effect) put fewer bits in the output for the more common byte values.</p>
<p>If you're compressing one long stream, and going faster using more cores is potentially helpful, parallel compression is available for gzip through <a href="http://zlib.net/pigz/" rel="noreferrer">pigz</a> and the zstd through the command-line tool's <code>-T</code> option (and in the library). (There are <a href="http://conorstokes.github.io/compression/2016/02/15/an-LZ-codec-designed-for-SSE-decompression" rel="noreferrer">various</a> experimental <a href="http://mattmahoney.net/dc/" rel="noreferrer">packers</a> out there too, but they exist more to push boundaries on speed or density, rather than for use today.)</p>
<p>So, in general, you have a pretty good spectrum of alternative compressors for different apps:</p>
<ul>
<li>For very fast compression: LZ4, zstd's lowest settings, or even weaker memory compressors</li>
<li>For balanced compression: DEFLATE is the old standard; Zstd and brotli on low-to-medium settings are good alternatives for new uses</li>
<li>For high compression: brotli, or Zstd on high settings</li>
<li>For very high compression (like static content that's compressed once and served many times): brotli</li>
</ul>
<p>As you move from LZ4 through DEFLATE to brotli you layer on more effort to predict and encode data and get more compression out at the cost of some speed.</p>
<p>As an aside, algorithms like brotli and zstd can generally outperform gzip--compress better at a given speed, or get the same compression faster--but this isn't actually because zlib did anything <em>wrong</em>. The main secret is probably that newer algos can use more memory: zlib dates to 1995 (and DEFLATE to <a href="https://en.wikipedia.org/wiki/PKZIP#PKZIP" rel="noreferrer">1993</a>). Back then RAM <a href="https://jcmit.net/memoryprice.htm" rel="noreferrer">cost</a> >3,000x as much as today, so just keeping 32KB of history made sense. Changes in CPUs over time may also be a factor: tons of of arithmetic (as used in finite state machines) is relatively cheaper than it used to be, and unpredictable <code>if</code>s (branches) are relatively more expensive.</p>
|
28,537,181 |
Spring Security OAuth2, which decides security?
|
<p>I've been trying to implement a OAuth2 authentication server using the guides by Dave Syer with some inspiration from JHipster. But I can't figure out how it all works together.</p>
<p>It looks like the security setup using the WebSecurityConfigurerAdapter is overwritten when I use ResourceServerConfigurerAdapter.</p>
<pre><code>@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {
private TokenExtractor tokenExtractor = new BearerTokenExtractor();
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(contextClearer(), AbstractPreAuthenticatedProcessingFilter.class)
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
private OncePerRequestFilter contextClearer() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (tokenExtractor.extract(request) == null) {
SecurityContextHolder.clearContext();
}
filterChain.doFilter(request, response);
}
};
}
@Component
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final AuthenticationManager authenticationManager;
@Autowired
public CustomWebSecurityConfigurerAdapter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.parentAuthenticationManager(authenticationManager);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login").permitAll()
.and()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and()
.requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
.and()
.authorizeRequests().anyRequest().authenticated();
}
}
</code></pre>
<p>This is code taken from a few different examples, so they might not mix that well. But I can't find a good documentation/example list for OAuth2 (unlike Spring Boot which has a awesome documentation), so I'm having problems understanding how thye all fit together.
If I don't add the loginForm to the ResourceServerConfigurerAdapter, it will just give me unauthorized. But I defined it in the WebSecurityConfigurererAdapter as permitAll().</p>
<p>This is the AuthorizationServerConfigurerAdapter:</p>
<pre><code>@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("authorization_code", "refresh_token",
"password").scopes("openid");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
}
</code></pre>
<p>Anything I'm doing wrong? Do I have to setup all the security within the ResourceServerConfigurerAdapter? Do I even need the WebSecurityConfigurerAdapter anymore?</p>
<p>If anyone know any guides, tutorials, blogs or anything alike that might help me wrap my head around how this works, that would be greatly appreciated.</p>
<p>Kind regards, Kenneth.</p>
| 28,604,260 | 1 | 4 | null |
2015-02-16 08:22:36.14 UTC
| 22 |
2018-10-24 14:52:58.807 UTC
| null | null | null | null | 1,385,837 | null | 1 | 42 |
spring|spring-security|spring-security-oauth2
| 23,969 |
<p>You need a <code>WebSecurityConfigurerAdapter</code> to secure the /authorize endpoint and to provide a way for users to authenticate. A Spring Boot application would do that for you (by adding its own <code>WebSecurityConfigurerAdapter</code> with HTTP basic auth). It creates a filter chain with order=0 by default, and protects all resources unless you provide a request matcher. The <code>@EnableResourceServer</code> does something similar, but the filter chain it adds is at order=3 by default. <code>WebSecurityConfigurerAdapter</code> has an @Order(100) annotation. So first the ResourceServer will be checked (authentication) and then your checks in your enxtension of WebSecurityConfigureAdapter will be checked.</p>
<p>Your configuration looks sane (the login chain takes precedence, but only matches a small set of requests).</p>
|
7,579,861 |
How do I disable and enable macros on the fly?
|
<p>I would like to test an Excel VBA app I made.<br>
However the VBA code messes around with the visibility of cells and that's a pest when editing the sheet. </p>
<p>Is there an option is enable and disable macro's on the fly without having to</p>
<pre><code>Close the sheet
Change the macro settings
Reopen the sheet
Close the sheet
Change the macro settings.
etc.
</code></pre>
| 7,579,986 | 6 | 0 | null |
2011-09-28 07:44:09.84 UTC
| 2 |
2020-08-16 09:36:29.41 UTC
|
2018-04-02 20:06:36.087 UTC
| null | 8,112,776 | null | 650,492 | null | 1 | 6 |
vba|excel|visibility
| 51,092 |
<p>As far as I know, you can't enable / disable macros from an opened workbook <em>on the fly</em>.<br>
Yet, you shouldn't have to because macros are only triggered thanks to a user click.</p>
<p>The only case I would see is for the Event Procedures (<code>Worksheet_Change</code> or else).<br>
You could then create procedures to activate / deactivate events and call them from buttons in your worksbook:</p>
<pre><code>Sub enableEvents()
Application.EnableEvents = True
End Sub
Sub disableEvents()
Application.EnableEvents = False
End Sub
</code></pre>
<p>You can also try these tips from <a href="http://www.cpearson.com/excel/Events.aspx" rel="noreferrer">Chris Pearson website</a> using global vars you would change depending on your needs:</p>
<pre><code>Public AbortChangeEvent As Boolean
</code></pre>
<p>And check if afterwards:</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
If AbortChangeEvent = True Then
Exit Sub
End If
'
' rest of code here
'
End Sub
</code></pre>
|
7,617,587 |
Is there an alternative to using time to seed a random number generation?
|
<p>I'm trying to run several instances of a piece of code (2000 instances or so) concurrently in a computing cluster. The way it works is that I submit the jobs and the cluster will run them as nodes open up every so often, with several jobs per node. This seems to produce the same values for a good number of the instances in their random number generation, which uses a time-seed. </p>
<p>Is there a simple alternative I can use instead? Reproducibility and security are not important, quick generation of unique seeds is. What would be the simplest approach to this, and if possible a cross platform approach would be good. </p>
| 7,617,612 | 10 | 10 | null |
2011-10-01 01:39:41.493 UTC
| 6 |
2016-03-29 17:00:35.24 UTC
|
2013-12-01 03:01:39.073 UTC
| null | 1,009,479 | null | 923,757 | null | 1 | 32 |
c|random|random-seed
| 13,916 |
<p>The <code>rdtsc</code> instruction is a pretty reliable (and random) seed.</p>
<p>In Windows it's accessible via the <code>__rdtsc()</code> intrinsic.</p>
<p>In GNU C, it's accessible via:</p>
<pre><code>unsigned long long rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((unsigned long long)hi << 32) | lo;
}
</code></pre>
<p>The instruction measures the total pseudo-cycles since the processor was powered on. Given the high frequency of today's machines, it's extremely unlikely that two processors will return the same value even if they booted at the same time and are clocked at the same speed.</p>
|
7,190,016 |
How to update an object in a List<> in C#
|
<p>I have a <code>List<></code> of custom objects.</p>
<p>I need to find an object in this list by some property which is unique and update another property of this object. </p>
<p>What is the quickest way to do it?</p>
| 7,190,035 | 11 | 0 | null |
2011-08-25 12:04:42.877 UTC
| 14 |
2022-06-23 14:36:11.68 UTC
|
2013-09-18 19:59:35.597 UTC
| null | 706,363 | null | 386,817 | null | 1 | 122 |
c#|asp.net|list|generics
| 323,296 |
<p>Using Linq to find the object you can do:</p>
<pre><code>var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;
</code></pre>
<p>But in this case you might want to save the List into a Dictionary and use this instead:</p>
<pre><code>// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;
</code></pre>
|
7,055,489 |
How to generate a random 10 digit number in C#?
|
<p>I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for <code>random.Next(1000000000,9999999999)</code> but I doubt this is what I want).</p>
<p>My code looks like this right now:</p>
<pre><code>[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
return random.Next(?);
}
</code></pre>
<p>**Update ended up doing like so,</p>
<pre><code>[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
string r = "";
int i;
for (i = 1; i < 11; i++)
{
r += random.Next(0, 9).ToString();
}
return r;
}
</code></pre>
| 7,055,537 | 13 | 5 | null |
2011-08-14 06:52:14.08 UTC
| 5 |
2020-06-22 23:49:14.113 UTC
|
2020-01-03 09:18:31.747 UTC
| null | 271,200 | null | 754,479 | null | 1 | 32 |
c#|.net|asp.net|random
| 87,368 |
<p>If you want ten digits but you allow <em>beginning with a 0</em> then it sounds like you want to generate a string, not a long integer.</p>
<p>Generate a 10-character string in which each character is randomly selected from '0'..'9'.</p>
|
13,951,005 |
Best Practice : Ways to handle errors and exception in web api controllers?
|
<p>I am working on a project and have relied heavily on web api for all my client side operations, be it account details update, new details added, modify everything has been done with ASP.NET Web Api and Backbone.js</p>
<p><strong>Current Scene :</strong></p>
<p>In the current scheme of things, I am returning a boolean value from my web api controllers, to indicate whether the operation was successfull or not.</p>
<p>Example : </p>
<pre><code>[ActionName("UpdateAccountDetails")]
public bool PostAccountDetails(SomeModel model)
{
bool updateStatus = _customService.UpdateAccountDetails(model);
return updateStatus;
}
</code></pre>
<p>so after making an ajax call to this action, I check the response for true/false and display error or success messages.</p>
<p><strong>Problem :</strong></p>
<p>Now what happened was I started getting exceptions in my action, and the action kept returning false, and the error message was shown. But I was not able to find why ?</p>
<p>So I was wondering if there is a standard api response structure which every one follows ?</p>
<p>I had initially come up with this idea to have each web api action to return this class </p>
<pre><code>public class OperationStatus
{
public bool Result { get; set; } // true/false
public string Status { get; set; } // success/failure/warning
public List<string> WarningMessages { get; set; }
public List<string> ErrorMessages { get; set; }
public string OtherDetails { get; set; }
}
</code></pre>
<p>This change would be a major change and would be time and resource consuming, so I thought its better to have a second/third/fourth opinion on this.</p>
<p>Please put some thoughts on this.</p>
<p><strong>Update :</strong></p>
<p>With some <a href="https://stackoverflow.com/a/13951599/1182982">little help</a> from <a href="https://stackoverflow.com/users/1440706/mark-jones">Mark Jones</a>, I have come up with this</p>
<pre><code>[ActionName("UpdateAccountDetails")]
public HttpResponseMessage PostAccountDetails(SomeModel model)
{
bool updateStatus;
string errorMessage;
try{
updateStatus = _customService.UpdateAccountDetails(model);
if(updateStatus)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
catch(Exception exception)
{
errorMessage = exception.Message;
return Request.CreateResponse(HttpStatusCode.InternalServerError, errorMessage);
}
return updateStatus;
}
</code></pre>
<p>Any thought on this ?</p>
| 13,955,683 | 2 | 2 | null |
2012-12-19 11:07:31.97 UTC
| 9 |
2012-12-19 15:29:50.083 UTC
|
2017-05-23 12:02:39.663 UTC
| null | -1 | null | 1,182,982 | null | 1 | 21 |
asp.net-mvc|asp.net-mvc-4|asp.net-web-api
| 16,307 |
<p>You should avoid using try/catch in the controller's action.</p>
<p>There are many ways to handle your problem.
The simplest and cleanest solution would probably be to use an <code>ActionFilter</code> to handle the exceptions, something along the lines of:</p>
<pre><code>public class ExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
Debug.WriteLine(context.Exception);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred!"),
ReasonPhrase = "Deadly Exception"
});
}
}
</code></pre>
<p>Then you can just decorate your action with <code>[ExceptionAttribute]</code>.
Of course you can extend that to behave differently for different types of exceptions - business exceptions, data exceptions, IO exceptions and so on, and return different status codes and feedback based on that as well.</p>
<p>I recommend you read an <strong>excellent article</strong> by Fredrik Normen - <em>"ASP.NET Web API Exception Handling"</em> <a href="http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx">http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx</a>. </p>
<p>He provides a great overview of exception handling techniques for Web API.</p>
|
14,181,180 |
Why do SQL databases use a write-ahead log over a command log?
|
<p>I read about Voltdb's <a href="http://voltdb.com/docs/UsingVoltDB/ChapCmdLog.php">command log</a>. The command log records the transaction invocations instead of each row change as in a write-ahead log. By recording only the invocation, the command logs are kept to a bare minimum, limiting the impact the disk I/O will have on performance.</p>
<p>Can anyone explain the database theory behind why Voltdb uses a command log and why the standard SQL databases such as Postgres, MySQL, SQLServer, Oracle use a write-ahead log?</p>
| 14,260,739 | 6 | 4 | null |
2013-01-06 10:19:18.6 UTC
| 29 |
2020-09-15 03:59:07.027 UTC
| null | null | null | null | 782,220 | null | 1 | 56 |
sql|database|logging|transactions|voltdb
| 14,579 |
<p>I think it is better to rephrase: </p>
<blockquote>
<p>Why does new distributed VoltDB use a command log over write-ahead log?</p>
</blockquote>
<p>Let's do an experiment and imagine you are going to write your own storage/database implementation. Undoubtedly you are advanced enough to abstract a file system and use block storage along with some additional optimizations.</p>
<p>Some basic terminology:</p>
<ul>
<li>State : stored information at a given point of time </li>
<li>Command : directive to the storage to change its state</li>
</ul>
<p>So your database may look like the following:</p>
<p><img src="https://i.stack.imgur.com/X7GCG.png" alt="enter image description here"> </p>
<p>Next step is to execute some command:</p>
<p><img src="https://i.stack.imgur.com/UN9pl.png" alt="enter image description here"></p>
<p>Please note several important aspects:</p>
<ol>
<li>A command may affect many stored entities, so many blocks will get dirty</li>
<li>Next state is a function of the current state and the command </li>
</ol>
<p>Some intermediate states can be skipped, because it is enough to have a chain of commands instead.</p>
<p><img src="https://i.stack.imgur.com/z9XMK.png" alt="enter image description here"></p>
<p>Finally, you need to guarantee data integrity.</p>
<ul>
<li><strong>Write-Ahead Logging</strong> - central concept is that <strong>State</strong> changes should be logged before any heavy update to permanent storage. Following our idea we can log incremental changes for each block.</li>
<li><strong>Command Logging</strong> - central concept is to log only <strong>Command</strong>, which is used to produce the state.</li>
</ul>
<p><img src="https://i.stack.imgur.com/OZ8GQ.png" alt="enter image description here"></p>
<p>There are Pros and Cons for both approaches. Write-Ahead log contains all changed data, Command log will require addition processing, but fast and lightweight. </p>
<p><a href="http://voltdb.com/docs/UsingVoltDB/ChapCmdLog.php" rel="noreferrer">VoltDB: Command Logging and Recovery</a></p>
<blockquote>
<p>The key to command logging is that it logs the invocations, not the
consequences, of the transactions. By recording only the invocation,
the command logs are kept to a bare minimum, limiting the impact the disk I/O will
have on performance.</p>
</blockquote>
<p><strong>Additional notes</strong></p>
<p><a href="http://www.sqlite.org/wal.html" rel="noreferrer">SQLite: Write-Ahead Logging</a></p>
<blockquote>
<p>The traditional rollback journal works by writing a copy of the
original unchanged database content into a separate rollback journal
file and then writing changes directly into the database file.</p>
<p>A COMMIT occurs when a special record indicating a commit is appended
to the WAL. Thus a COMMIT can happen without ever writing to the
original database, which allows readers to continue operating from the
original unaltered database while changes are simultaneously being
committed into the WAL.</p>
</blockquote>
<p><a href="http://www.postgresql.org/docs/9.1/static/wal-intro.html" rel="noreferrer">PostgreSQL: Write-Ahead Logging (WAL)</a></p>
<blockquote>
<p>Using WAL results in a significantly reduced number of disk writes,
because only the log file needs to be flushed to disk to guarantee
that a transaction is committed, rather than every data file changed
by the transaction. </p>
<p>The log file is written sequentially, and so the
cost of syncing the log is much less than the cost of flushing the
data pages. This is especially true for servers handling many small
transactions touching different parts of the data store. Furthermore,
when the server is processing many small concurrent transactions, one
fsync of the log file may suffice to commit many transactions. </p>
</blockquote>
<p><strong>Conclusion</strong></p>
<p>Command Logging:</p>
<ol>
<li>is faster</li>
<li>has lower footprint</li>
<li>has heavier "Replay" procedure</li>
<li>requires frequent snapshot</li>
</ol>
<p>Write Ahead Logging is a technique to provide atomicity. Better Command Logging performance should also improve transaction processing. <a href="http://db.cs.berkeley.edu/topics/lecs/dbprimer/" rel="noreferrer">Databases on 1 Foot</a></p>
<p><img src="https://i.stack.imgur.com/y6BVc.png" alt="enter image description here"></p>
<p><strong>Confirmation</strong></p>
<p><a href="http://blog.voltdb.com/intro-to-voltdb-command-logging/" rel="noreferrer">VoltDB Blog: Intro to VoltDB Command Logging</a></p>
<blockquote>
<p>One advantage of command logging over ARIES style logging is that a
transaction can be logged before execution begins instead of executing
the transaction and waiting for the log data to flush to disk. Another
advantage is that the IO throughput necessary for a command log is
bounded by the network used to relay commands and, in the case of
Gig-E, this throughput can be satisfied by cheap commodity disks.</p>
</blockquote>
<p>It is important to remember VoltDB is distributed by its nature. So transactions are a little bit tricky to handle and performance impact is noticeable.</p>
<p><a href="http://blog.voltdb.com/voltdbs-new-command-logging-feature/" rel="noreferrer">VoltDB Blog: VoltDB’s New Command Logging Feature</a></p>
<blockquote>
<p>The command log in VoltDB consists of stored procedure invocations and
their parameters. A log is created at each node, and each log is
replicated because all work is replicated to multiple nodes. This
results in a replicated command log that can be de-duped at replay
time. Because VoltDB transactions are strongly ordered, the command
log contains ordering information as well. Thus the replay can occur
in the exact order the original transactions ran in, with the full
transaction isolation VoltDB offers. Since the invocations themselves
are often smaller than the modified data, and can be logged before
they are committed, this approach has a very modest effect on
performance. This means VoltDB users can achieve the same kind of
stratospheric performance numbers, with additional durability
assurances.</p>
</blockquote>
|
47,269,402 |
How to center text in a row using Bootstrap 4
|
<p>The problem is that <code><p></code> and <code><h1></code> are appearing on same line and no matter what I do they can't be centered. </p>
<p><strong>HTML</strong></p>
<pre><code><div class="container">
<div class="row" id="appSummary">
<h1>Why This App Is Awesome</h1>
<p class="lead">Summary, once again, of your app's awesomeness</p>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#appSummary{
text-align:center;
}
</code></pre>
| 47,269,516 | 4 | 3 | null |
2017-11-13 16:45:04.857 UTC
| null |
2018-04-24 14:24:48.783 UTC
|
2018-04-24 14:24:48.783 UTC
| null | 8,918,893 | null | 7,131,162 | null | 1 | 4 |
twitter-bootstrap|bootstrap-4
| 42,550 |
<p>Since you're using Bootstrap 4 which uses the flex model, change your CSS rule to:</p>
<pre><code>#appSummary{
justify-content:center;
}
</code></pre>
<p><strong><a href="https://www.bootply.com/zcn84QPlzO" rel="noreferrer">Bootply example</a></strong></p>
|
43,525,052 |
RxJava2 observable take throws UndeliverableException
|
<p>As I understand RxJava2 <code>values.take(1)</code> creates another Observable that contains only one element from the original Observable. Which <strong>MUST NOT</strong> throw an exception as it is filtered out by the effect of <code>take(1)</code> as it's happened second.</p>
<p>as in the <strong>following</strong> code snippet</p>
<pre><code> Observable<Integer> values = Observable.create(o -> {
o.onNext(1);
o.onError(new Exception("Oops"));
});
values.take(1)
.subscribe(
System.out::println,
e -> System.out.println("Error: " + e.getMessage()),
() -> System.out.println("Completed")
);
</code></pre>
<h2>Output</h2>
<pre><code>1
Completed
io.reactivex.exceptions.UndeliverableException: java.lang.Exception: Oops
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:366)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
at ch02.lambda$main$0(ch02.java:28)
at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.internal.operators.observable.ObservableTake.subscribeActual(ObservableTake.java:30)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.Observable.subscribe(Observable.java:10827)
at io.reactivex.Observable.subscribe(Observable.java:10787)
at ch02.main(ch02.java:32)
Caused by: java.lang.Exception: Oops
... 8 more
Exception in thread "main" io.reactivex.exceptions.UndeliverableException: java.lang.Exception: Oops
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:366)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
at ch02.lambda$main$0(ch02.java:28)
at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.internal.operators.observable.ObservableTake.subscribeActual(ObservableTake.java:30)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.Observable.subscribe(Observable.java:10827)
at io.reactivex.Observable.subscribe(Observable.java:10787)
at ch02.main(ch02.java:32)
Caused by: java.lang.Exception: Oops
... 8 more
</code></pre>
<h2>My questions :</h2>
<ol>
<li>Am I understanding it correct ?</li>
<li>What's really happening to cause the exception.</li>
<li>How to solve this from the consumer ?</li>
</ol>
| 43,525,858 | 4 | 1 | null |
2017-04-20 16:29:53.6 UTC
| 15 |
2020-10-05 13:23:06.32 UTC
|
2017-04-20 17:46:50.453 UTC
| null | 4,586,030 | null | 4,586,030 | null | 1 | 41 |
java|observable|rx-java2|take
| 35,709 |
<ol>
<li>Yes, but because the observable 'ends' does not mean the code running inside <code>create(...)</code> is stopped. To be fully safe in this case you need to use <code>o.isDisposed()</code> to see if the observable has ended downstream.</li>
<li>The exception is there because RxJava 2 has the policy of NEVER allowing an <code>onError</code> call to be lost. It is either delivered downstream or thrown as a global <code>UndeliverableException</code> if the observable has already terminated. It is up to the creator of the Observable to 'properly' handle the case where the observable has ended and an Exception occurs.</li>
<li>The problem is the producer (<code>Observable</code>) and the consumer (<code>Subscriber</code>) disagreeing on when the stream ends. Since the producer is outliving the consumer in this case, the problem can only be fixed in the producer.</li>
</ol>
|
19,468,025 |
Add Items to ListView - Android
|
<p>This is my first experience with android. I'm trying to add items to my ListView.
I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.</p>
<p>I searched around, and I've always found</p>
<pre><code>adapter.notifyDataSetChanged();
</code></pre>
<p>but doesn't work for me.</p>
<p>I have created the project with, as I said, Fixed Tabs + Swipe.
I simply want to have listviews which rows have an EditText, a Spinner and a Button.
On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.</p>
<p>my custom Adapter:</p>
<pre><code>package com.andreapivetta.uconverter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;
public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
super(context, resource, bah);
this.context = context;
this.resourceID = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resourceID, parent, false);
return rowView;
}
}
</code></pre>
<p>fragment_main_dummy.xml</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<ListView
android:id="@+id/unitListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageButton
android:id="@+id/moreImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="@string/image_button_delete"
android:src="@android:drawable/ic_input_add" />
</RelativeLayout>
</code></pre>
<p>Row.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<EditText
android:id="@+id/unitEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="@+id/unitSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="@+id/unitEditText" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/unitEditText"
android:layout_alignParentRight="true"
android:onClick="removeItem"
android:contentDescription="@string/image_button_delete"
android:src="@android:drawable/ic_menu_delete" />
</RelativeLayout>
</code></pre>
<p>MainActivity...</p>
<pre><code>public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 4 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
ArrayList<String> myStringArray1 = new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
String[] myStringArray3 = new String[]{"ddd","eeee"};
String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
public static ArrayAdapter<String> adapter;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
//dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
// ListView
ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
myStringArray1.add("mmm");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
unitListView.setAdapter(adapter);
break;
case 2:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
unitListView.setAdapter(adapter);
break;
case 3:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
unitListView.setAdapter(adapter);
break;
case 4:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
unitListView.setAdapter(adapter);
break;
}
unitListView.setOnItemClickListener(listViewOnClickListener);
// ImageButton
ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
moreImageButton.setOnClickListener(moreListener);
return rootView;
}
public OnClickListener moreListener = new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myStringArray1.add("Andrea");
adapter.clear();
adapter.addAll(myStringArray1);
adapter.notifyDataSetChanged();
}
};
public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
};
}
}
</code></pre>
<p>Note that I'm working only with the first tab right now...</p>
<p>What am I doing wrong? :)</p>
| 19,468,504 | 3 | 2 | null |
2013-10-19 15:59:19.083 UTC
| 7 |
2016-11-01 08:50:43.223 UTC
|
2014-10-04 18:51:08.66 UTC
| null | 885,179 | null | 2,535,024 | null | 1 | 17 |
java|android|listview|android-listview|fragment
| 157,854 |
<pre><code>ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
</code></pre>
<p>Try it like this</p>
<pre><code>public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
</code></pre>
|
34,071,003 |
Bootstrap 3 datepicker - minDate and maxDate
|
<p><a href="http://eonasdan.github.io/bootstrap-datetimepicker/" rel="noreferrer">http://eonasdan.github.io/bootstrap-datetimepicker/</a></p>
<p>Hi</p>
<p>I am trying to use the min max date options but not sure how to use it as the documentation doesn't provide example code.</p>
<p>I found on stackoverflow that you can do this:</p>
<p>minDate: moment()</p>
<p>But that throws an error that moment is not defined.</p>
<p>I am guessing it can't find the moment.js which is included on the page otherwise the plugin wouldn't work.</p>
<p>What I am trying to achieve is to disable 10 days before the current day and show 30 days from the current day.</p>
<p>Thanks</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Here is the code (I have removed everything except whats important to simply show the code):
window[ns] = window[ns] || {};
(function ($, moment, app) {
'use strict';
// Private Methods
var nameSpace = 'global',
globalDataObject = null,
notifyRenderCallbacks = function (pageName) {
if ($('.js-calendar').length) {
$('.js-calendar').datetimepicker({
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
icons: {
next: 'icon icon-chevronright',
previous: 'icon icon-chevronleft'
},
enabledDates: moment().add(30, 'days')
});
}
},
// If this module requires global data
app.register(nameSpace, initialize);
}(jQuery, moment, window[ns] || {}));</code></pre>
</div>
</div>
</p>
| 34,333,138 | 4 | 4 | null |
2015-12-03 16:19:06.847 UTC
| 1 |
2019-11-21 12:27:43.08 UTC
|
2015-12-03 17:27:24.39 UTC
| null | 4,261,249 | null | 4,261,249 | null | 1 | 9 |
javascript
| 89,707 |
<p>To answer my question. The framework used required you to add moment to a config file otherwise it would not allow to use <a href="http://momentjs.com/" rel="noreferrer">http://momentjs.com/</a> or any other JS - spoke to the person who set up the framework and they did it for security reasons.</p>
<p>Kasun's answer is correct but a better way to do this is to use Moment.js since datetimepicker is using this JS.</p>
<p>So to answer the 2nd part which is to disable 10 days before the current day and show 30 days from the current day you need to set the options as below. I didn't need to do the 10 days before but wanted only a set number of days to be available to select. I've added comments to make things clear but they shouldn't be there.</p>
<pre><code>$mydatepicker.datetimepicker({
minDate: moment(), // Current day
maxDate: moment().add(30, 'days'), // 30 days from the current day
viewMode: 'days',
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
});
</code></pre>
<p>What the above will do is enable all the days between minDate and maxDate.</p>
<p>You could also directly enter the date range:</p>
<pre><code>$mydatepicker.datetimepicker({
minDate: moment("12/01/2015"),
maxDate: moment("12/30/2015"),
viewMode: 'days',
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
});
</code></pre>
<p>And this will disable all days before and after the dates you entered into moment().</p>
<p>This is not part of the question but I wanted to display the current day in the input value when the calendar loaded but it wouldn't, instead it would show the placeholder text. I think its because of the use if minDate so I simply used jQuery to replace the value of the input.</p>
<pre><code>$datepickerInput.val(moment());
</code></pre>
|
34,065,670 |
SQL Server Inner Join using WITH(NOLOCK)
|
<p>I have a database query:</p>
<pre><code>DECLARE @Pager_PageNumber AS INT, @Pager_PageSize AS INT;
SET @Pager_PageNumber = 1;
SET @Pager_PageSize = 12;
SELECT
[Name], [Description], [Table1ID], [VersionNo], [Status]
FROM
(SELECT
CAST(Table1.name AS VARCHAR(MAX)) As [Name],
CAST(Table1.description AS VARCHAR(MAX)) AS [Description],
CAST(CAST(Table1.Table1_ID AS DECIMAL(18,0)) AS VARCHAR(MAX)) AS [Table1ID],
CAST(CAST(Table1.VERSION_NO AS DECIMAL(18,0)) AS VARCHAR(MAX)) AS [VersionNo],
CAST(Table2.br_status AS VARCHAR(MAX)) AS [Status]
FROM
Table1 WITH (NOLOCK)
INNER JOIN
(SELECT
Table1_id, MAX(version_no) as version_no
FROM Table1
WHERE Table1.status = '00002'
GROUP BY Table1_id) AS BR WITH (NOLOCK) ON Table1.Table1_id = BR.Table1_id
AND BR.version_no = Table1.version_no
INNER JOIN
Table2 WITH (NOLOCK) ON Table1.status = Table2.br_status_code) A
ORDER BY
[Name], [Description], [Table1ID], [VersionNo], [Status]
OFFSET ((@Pager_PageNumber - 1) * @Pager_PageSize) ROWS
FETCH NEXT @Pager_PageSize ROWS ONLY;
SELECT COUNT(*)
FROM
(SELECT
CAST(Table1.name AS VARCHAR(MAX)) AS [Name],
CAST(Table1.description AS VARCHAR(MAX)) AS [Description],
CAST(CAST(Table1.Table1_ID AS DECIMAL(18,0)) AS VARCHAR(MAX)) AS [Table1ID],
CAST(CAST(Table1.VERSION_NO AS DECIMAL(18,0)) AS VARCHAR(MAX)) As [VersionNo],
CAST(Table2.br_status AS VARCHAR(MAX)) AS [Status]
FROM
Table1 WITH (NOLOCK)
INNER JOIN
(SELECT Table1_id, MAX(version_no) as version_no
FROM Table1
WHERE Table1.status = '00002'
GROUP BY Table1_id) AS BR WITH (NOLOCK) ON Table1.Table1_id = BR.Table1_id
AND BR.version_no = Table1.version_no
INNER JOIN
Table2 WITH (NOLOCK) ON Table1.status = Table2.br_status_code) A;
</code></pre>
<p>In SQL Server I get the error near : <code>BR WITH (NOLOCK)</code> that :</p>
<blockquote>
<blockquote>
<p>Incorrect syntax near the keyword 'WITH'.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.</p>
</blockquote>
</blockquote>
<p>But as per my understanding from sources <a href="http://sqlserverplanet.com/tsql/using-with-nolock" rel="nofollow">like</a> the syntax is as</p>
<pre><code>SELECT
first_name, last_name,
FROM
dbo.person p WITH (NOLOCK)
JOIN
dbo.employee e WITH (NOLOCK) ON e.person_id = p.person_id
WHERE
p.person_id = 1;
</code></pre>
<p>So, my query looks just about right.</p>
<p>Also, when I remove the WITH (NOLOCK) next to <code>BR WITH (NOLOCK)</code> i.e. my inner join query the query runs fine. Any ideas of what I might be missing??</p>
<p><strong>PS:</strong> My DB compatibility level is 110.</p>
| 34,065,793 | 5 | 4 | null |
2015-12-03 12:07:30.09 UTC
| null |
2015-12-03 13:59:15.903 UTC
|
2015-12-03 12:15:10.687 UTC
| null | 13,302 | null | 4,282,901 | null | 1 | 2 |
sql|sql-server|join|inner-join|self-join
| 40,660 |
<p>You apply <code>with (nolock)</code> to <em>tables</em>, not to subqueries. So, instead of:</p>
<pre><code>(SELECT Table1_id, MAX(version_no) as version_no
FROM Table1
where Table1.status='00002'
GROUP BY Table1_id
) as BR WITH (NOLOCK)
</code></pre>
<p>You would write:</p>
<pre><code>(SELECT Table1_id, MAX(version_no) as version_no
FROM Table1 WITH (NOLOCK)
where Table1.status='00002'
GROUP BY Table1_id
) BR
</code></pre>
|
52,428,973 |
How to minify a Flutter app with Proguard?
|
<p>I already made a Flutter app. The release apk is about 14MB. I searched methods to minify this and found this ons: <a href="https://flutter.io/android-release/#enabling-proguard" rel="noreferrer">https://flutter.io/android-release/#enabling-proguard</a></p>
<p>But my question is, <strong>how can I get to know all my used additional libraries</strong> for step 1? Are there any commands to know them or is it just all the dependencies that I added to the <code>pubspec.yaml</code> ?</p>
<p><strong>How</strong> do I need <strong>to implement</strong> them in this file <code>/android/app/proguard-rules.pro</code>? </p>
| 59,202,013 | 3 | 5 | null |
2018-09-20 15:55:58.91 UTC
| 10 |
2022-06-08 11:36:55.383 UTC
| null | null | null | null | 7,657,749 | null | 1 | 27 |
android|dart|flutter|proguard|minify
| 27,290 |
<p>First, we will enable shrinking and obfuscation in the build file. Find <code>build.gradle</code> file which sits inside <code>/android/app/</code> folder and add lines in bold</p>
<pre><code>android {
...
buildTypes {
release {
signingConfig signingConfigs.debug
minifyEnabled true
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
</code></pre>
<p>Next we will create a configuration which will preserve entire Flutter wrapper code. Create <code>/android/app/proguard-rules.pro</code> file and insert inside:</p>
<pre><code>#Flutter Wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.util.** { *; }
-keep class io.flutter.view.** { *; }
-keep class io.flutter.** { *; }
-keep class io.flutter.plugins.** { *; }
</code></pre>
<p>Note: Use <code>signingConfigs.release</code> instead <code>signingConfigs.debug</code> to build a apk or appbundle</p>
|
44,949,467 |
When do you embed mutex in struct in Go?
|
<p>NOTE: I found the word 'embed' in the title was bad choice, but I will keep it. </p>
<p>I see a lot of code does like this:</p>
<pre><code>type A struct {
mu sync.Mutex
...
}
</code></pre>
<p>And use it like this:</p>
<pre><code>a := &A{}
a.mu.Lock()
defer a.mu.Unlock()
a.Something()
</code></pre>
<p>Is it better than local mutex or global mutex?</p>
<pre><code>a := &A{}
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
a.Something()
</code></pre>
<p>When should I use former, or later?</p>
| 44,950,096 | 1 | 2 | null |
2017-07-06 12:53:27.897 UTC
| 10 |
2021-06-29 19:42:30.197 UTC
|
2017-07-08 16:02:38.207 UTC
| null | 1,932,530 | null | 1,932,530 | null | 1 | 28 |
go|struct|embed|mutex
| 20,035 |
<p>It's good practice to keep the mutex close to the data it is destined to protect. If a mutex ought to protect concurrent access to fields of a struct value, it's very convenient to add the mutex as a field of that struct, so its purpose is obvious.</p>
<p>If in your app there is only a single "instance" of <code>A</code>, it's fine to make the mutex a global variable too.</p>
<p>If your app is to create multiple values of <code>A</code>, all of which needs to be protected from concurrent access (but only individually, multiple values may be accessed concurrently), then obviously a global mutex is a bad choice, it would limit the concurrent access to a single value of <code>A</code> in any point in time.</p>
<p>Adding the mutex to the struct as a field, you will <em>naturally</em> have a separate mutex for each distinct struct values, responsible to guard that single, wrapper struct value (or its fields).</p>
<p>Although adding a mutex as in your example is not embedding, it's a regular, named field. An <a href="https://golang.org/ref/spec#Struct_types" rel="noreferrer">embedded field declaration</a> omits the field name.</p>
<p>It's known and used to a lesser extent, but it's also handy that you can "truly" embed a mutex in a struct, and you can call <code>Lock()</code> and <code>Unlock()</code> as if they would be part of the struct itself. It looks like this:</p>
<pre><code>var hits struct {
sync.Mutex
n int
}
hits.Lock()
hits.n++
hits.Unlock()
</code></pre>
<p>(This example is taken from <a href="https://talks.golang.org/2012/10things.slide#3" rel="noreferrer">10 things you (probably) don't know about Go, slide #3</a>.)</p>
|
35,206,015 |
Intellij Annotate Option Grayed Out
|
<p>I am trying to look at who changed a line in Intellij 15. I know I can use git blame but I want to learn how to do it correctly in intellij. I am right clicking on the line numbers on the file but when I get the context menu the <code>annotate</code> option is grayed out. What setting am I missing?</p>
<p>I looked at <a href="https://www.jetbrains.com/idea/help/working-with-annotations.html" rel="noreferrer">this</a> page and couldn't find an answer. What am I missing?</p>
| 35,466,762 | 12 | 5 | null |
2016-02-04 16:13:33.317 UTC
| 5 |
2021-05-21 10:19:34.99 UTC
| null | null | null | null | 2,654,083 | null | 1 | 53 |
intellij-idea|intellij-15
| 24,687 |
<p>Looks like its a fresh project. First configure the Version Control like Git and than <strong>commit at least once</strong>. After first commit Annotate option will not be grayed out.</p>
<p>Also update git for any new version.</p>
|
290,513 |
Regex pattern for numeric values
|
<p>I need an regular expression pattern to only accept positive whole numbers. It can also accept a single zero.</p>
<p>I do not want to accept decimals, negative number and numbers with leading zeros.</p>
<p>Any suggestions?</p>
| 290,539 | 5 | 1 | null |
2008-11-14 15:51:59.98 UTC
| 13 |
2015-04-08 18:07:24.507 UTC
|
2008-11-14 18:55:34.68 UTC
|
Michael Kniskern
| 26,327 |
Michael Kniskern
| 26,327 | null | 1 | 67 |
regex
| 323,072 |
<pre><code>^(0|[1-9][0-9]*)$
</code></pre>
|
1,009,485 |
Filter element based on .data() key/value
|
<p>Say I have 4 div elements with class <code>.navlink</code>, which, when clicked, use <code>.data()</code> to set a key called <code>'selected'</code>, to a value of <code>true</code>:</p>
<pre><code>$('.navlink')click(function() { $(this).data('selected', true); })
</code></pre>
<p>Every time a new <code>.navlink</code> is clicked, I would like to store the previously selected <code>navlink</code> for later manipulation. Is there a quick and easy way to select an element based on what was stored using <code>.data()</code>?</p>
<p>There don't seem to be any jQuery <strong>:filters</strong> that fit the bill, and I tried the following (within the same click event), but for some reason it doesn't work:</p>
<pre><code>var $previous = $('.navlink').filter(
function() { $(this).data("selected") == true }
);
</code></pre>
<p>I know that there are other ways to accomplish this, but right now I'm mostly just curious if it can be done via <code>.data()</code>.</p>
| 1,009,523 | 5 | 0 | null |
2009-06-17 20:57:57.397 UTC
| 26 |
2018-05-09 20:39:57.123 UTC
|
2015-11-04 10:17:52.83 UTC
| null | 4,370,109 | null | 113,716 | null | 1 | 130 |
jquery|filter
| 124,856 |
<p>your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.</p>
<pre><code>var $previous = $('.navlink').filter(function() {
return $(this).data("selected") == true
});
</code></pre>
|
126,260 |
Objections against Java Webstart?
|
<p>Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.</p>
<p>Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the right JVM installed? Do you have bad experiences using Web Start? If yes, which? What are you recommendations when using Web Start for distributing applications?</p>
| 126,314 | 6 | 0 | null |
2008-09-24 09:47:20.297 UTC
| 11 |
2012-07-13 06:47:17.947 UTC
| null | null | null |
Yaba
| 7,524 | null | 1 | 20 |
java|java-web-start
| 2,662 |
<p>In my company we used Java Web Start to deploy Eclipse RCP applications. It was a pain to setup, but it works very well once in place. So the only recommendation I could make is to start small, to get the hang of it. Deploying one simple application first. Trying to deploy a complete product that is already made without experience with JWS gets complicated rather quickly.</p>
<p>Also, learning how to pass arguments to the JWS application was invaluable for debugging. Setting the Environment variable JAVAWS_VM_ARGS allows setting any arbitrary property to the Java Virtual machine. In my case:</p>
<p>-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=4144</p>
<p>Helpful when you need to check problems during start-up (suspend=y)</p>
<p>I think the main problem for the acceptance of Java Web Start is that it is relatively difficult to setup. Also, somehow there is this dissonance: When you have a desktop application, people expects a installer they can double click. When you have a web application, people expects they can use it right from the browser. Java Web Start is neither here not there...</p>
<p>It is widely used in intranets, though.</p>
|
403,218 |
Does C# .NET support IDispatch late binding?
|
<hr>
<h2>The Question</h2>
<p>My question is: <strong>Does C# nativly support late-binding IDispatch?</strong></p>
<hr>
<p><em>Pretend</em> i'm trying to automate Office, while being compatible with whatever version the customer has installed. </p>
<p>In the .NET world if you developed with Office 2000 installed, every developer, and every customer, from now until the end of time, is required to have Office 2000.</p>
<p>In the world before .NET, we used <strong>COM</strong> to talk to Office applications. </p>
<p>For example:</p>
<p>1) Use the version independant ProgID</p>
<pre><code>"Excel.Application"
</code></pre>
<p>which resolves to:</p>
<pre><code>clsid = {00024500-0000-0000-C000-000000000046}
</code></pre>
<p>and then using COM, we ask for one of these classes to be instantiated into an object:</p>
<pre><code>IUnknown unk;
CoCreateInstance(
clsid,
null,
CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
IUnknown,
out unk);
</code></pre>
<p>And now we're off to the races - able to use Excel from inside my application. Of course, if <em>really</em> you want to use the object, you have to call have some way of calling methods. </p>
<p>We <em>could</em> get ahold of the various <strong>interface</strong> declarations, translated into our language. This technique is good because we get </p>
<ul>
<li>early binding</li>
<li>code-insight </li>
<li>compile type syntax checking</li>
</ul>
<p>and some example code might be:</p>
<pre><code>Application xl = (IExcelApplication)unk;
ExcelWorkbook workbook = xl.Workbooks.Add(template, lcid);
Worksheet worksheet = workbook.ActiveSheet;
</code></pre>
<hr>
<p>But there is a downside of using interfaces: we have to get ahold of the various interface declarations, transated into our language. And we're stuck using method-based invocations, having to specify all parameters, e.g.:</p>
<pre><code>ExcelWorkbook workbook = xl.Workbooks.Add(template, lcid);
xl.Worksheets.Add(before, after, count, type, lcid);
</code></pre>
<p>This has proved, in the real world, to have such downsides that we would willingly give up:</p>
<ul>
<li>early binding</li>
<li>code-insight</li>
<li>compile time syntax checking</li>
</ul>
<p>and instead use <strong>IDispatch</strong> late binding:</p>
<pre><code>Variant xl = (IDispatch)unk;
Variant newWorksheet = xl.Worksheets.Add();
</code></pre>
<p>Because Excel automation was designed for VB Script, a lot of parameters can be ommitted, even when there is no overload without them.</p>
<p><strong>Note:</strong> Don't confuse my example of Excel with a reason of why i want to use IDispatch. Not every COM object is Excel. Some COM objects have no support other than through IDispatch.</p>
| 489,272 | 6 | 1 | null |
2008-12-31 15:33:16.7 UTC
| 7 |
2011-11-09 18:33:44.96 UTC
|
2009-11-01 12:29:37.06 UTC
| null | 12,597 | null | 12,597 | null | 1 | 28 |
c#|late-binding|idispatch
| 16,784 |
<p>You can, relativly, use late-binding IDispatch binding in C#.</p>
<p><a href="http://support.microsoft.com/kb/302902" rel="noreferrer">http://support.microsoft.com/kb/302902</a></p>
<p>Here's some sample for using Excel. This way you don't need to add a needless dependancy on Microsoft's bloaty PIA:</p>
<pre><code>//Create XL
Object xl = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
//Get the workbooks collection.
// books = xl.Workbooks;
Object books = xl.GetType().InvokeMember( "Workbooks",
BindingFlags.GetProperty, null, xl, null);
//Add a new workbook.
// book = books.Add();
Objet book = books.GetType().InvokeMember( "Add",
BindingFlags.InvokeMethod, null, books, null );
//Get the worksheets collection.
// sheets = book.Worksheets;
Object sheets = book.GetType().InvokeMember( "Worksheets",
BindingFlags.GetProperty, null, book, null );
Object[] parameters;
//Get the first worksheet.
// sheet = sheets.Item[1]
parameters = new Object[1];
parameters[0] = 1;
Object sheet = sheets.GetType().InvokeMember( "Item",
BindingFlags.GetProperty, null, sheets, parameters );
//Get a range object that contains cell A1.
// range = sheet.Range["A1];
parameters = new Object[2];
parameters[0] = "A1";
parameters[1] = Missing.Value;
Object range = sheet.GetType().InvokeMember( "Range",
BindingFlags.GetProperty, null, sheet, parameters );
//Write "Hello, World!" in cell A1.
// range.Value = "Hello, World!";
parameters = new Object[1];
parameters[0] = "Hello, World!";
objRange_Late.GetType().InvokeMember( "Value", BindingFlags.SetProperty,
null, range, parameters );
//Return control of Excel to the user.
// xl.Visible = true;
// xl.UserControl = true;
parameters = new Object[1];
parameters[0] = true;
xl.GetType().InvokeMember( "Visible", BindingFlags.SetProperty,
null, xl, Parameters );
xl.GetType().InvokeMember( "UserControl", BindingFlags.SetProperty,
null, xl, Parameters );
</code></pre>
|
817,087 |
Call a function with argument list in python
|
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p>
<pre><code>def wrapper(func, args):
func(args)
def func1(x):
print(x)
def func2(x, y, z):
return x+y+z
wrapper(func1, [x])
wrapper(func2, [x, y, z])
</code></pre>
<p>In this case first call will work, and second won't.
What I want to modify is the wrapper function and not the called functions.</p>
| 817,296 | 6 | 0 | null |
2009-05-03 13:43:33.843 UTC
| 63 |
2018-02-24 15:18:15.863 UTC
|
2009-05-03 15:20:08.807 UTC
| null | 12,855 | null | 70,898 | null | 1 | 166 |
python|function
| 363,441 |
<p>To expand a little on the other answers:</p>
<p>In the line:</p>
<pre><code>def wrapper(func, *args):
</code></pre>
<p>The * next to <code>args</code> means "take the rest of the parameters given and put them in a list called <code>args</code>". </p>
<p>In the line:</p>
<pre><code> func(*args)
</code></pre>
<p>The * next to <code>args</code> here means "take this list called args and 'unwrap' it into the rest of the parameters.</p>
<p>So you can do the following:</p>
<pre><code>def wrapper1(func, *args): # with star
func(*args)
def wrapper2(func, args): # without star
func(*args)
def func2(x, y, z):
print x+y+z
wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])
</code></pre>
<p>In <code>wrapper2</code>, the list is passed explicitly, but in both wrappers <code>args</code> contains the list <code>[1,2,3]</code>.</p>
|
239,147 |
How do you import classes in JSP?
|
<p>I am a complete JSP beginner. I am trying to use a <code>java.util.List</code> in a JSP page. What do I need to do to use classes other than ones in <code>java.lang</code>?</p>
| 239,293 | 6 | 1 | null |
2008-10-27 05:26:18.683 UTC
| 43 |
2017-11-15 14:18:36.16 UTC
|
2013-04-30 17:05:52.6 UTC
| null | 2,598 |
jjnguy
| 2,598 | null | 1 | 249 |
java|jsp
| 622,952 |
<p>Use the following import statement to import <code>java.util.List</code>:</p>
<pre><code><%@ page import="java.util.List" %>
</code></pre>
<p>BTW, to import more than one class, use the following format:</p>
<pre><code><%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>
</code></pre>
|
58,873,022 |
How can I make a Selenium script undetectable using GeckoDriver and Firefox through Python?
|
<p>Is there a way to make your Selenium script undetectable in Python using <strong>geckodriver</strong>?</p>
<p>I'm using Selenium for scraping. Are there any protections we need to use so websites can't detect Selenium?</p>
| 58,879,076 | 4 | 9 | null |
2019-11-15 08:29:52.28 UTC
| 21 |
2022-03-29 09:41:15.663 UTC
|
2021-02-06 12:49:10.667 UTC
| null | 63,550 |
user12285770
| null | null | 1 | 23 |
python|selenium|firefox|geckodriver|selenium-firefoxdriver
| 24,912 |
<p>The fact that <em>selenium driven <strong>Firefox</strong> / <strong>GeckoDriver</strong> gets detected</em> doesn't depends on any specific <em>GeckoDriver</em> or <em>Firefox</em> version. The <em>Websites</em> themselves can detect the network traffic and can identify the <em>Browser Client</em> i.e. <em>Web Browser</em> as <strong>WebDriver controled</strong>.</p>
<p>As per the documentation of the <a href="https://w3c.github.io/webdriver/#dom-navigatorautomationinformation-webdriver" rel="noreferrer"><code>WebDriver Interface</code></a> in the latest editor's draft of <a href="https://w3c.github.io/webdriver/" rel="noreferrer"><strong>WebDriver - W3C Living Document</strong></a> the <strong><code>webdriver-active</code></strong> <em>flag</em> which is initially set as <strong>false</strong>, is set to true when the user agent is under remote control i.e. when controlled through <a href="https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491">Selenium</a>.</p>
<p><a href="https://i.stack.imgur.com/BM2Il.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BM2Il.png" alt="NavigatorAutomationInformation"></a></p>
<p>Now that the <strong><code>NavigatorAutomationInformation</code></strong> interface should not be exposed on <strong><code>WorkerNavigator</code></strong>.</p>
<p><a href="https://i.stack.imgur.com/1bOXf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1bOXf.png" alt="mixin NavigatorAutomationInformation"></a></p>
<p>So,</p>
<pre><code>webdriver
Returns true if webdriver-active flag is set, false otherwise.
</code></pre>
<p>where as,</p>
<pre><code>navigator.webdriver
Defines a standard way for co-operating user agents to inform the document that it is controlled by WebDriver, for example so that alternate code paths can be triggered during automation.
</code></pre>
<p>So, the bottom line is:</p>
<blockquote>
<p><strong>Selenium identifies itself</strong></p>
</blockquote>
<hr>
<p>However some generic approaches to avoid getting detected while web-scraping are as follows:</p>
<ul>
<li>The first and foremost attribute a website can determine your script/program is through your <strong>monitor size</strong>. So it is recommended <strong>not</strong> to use the conventional <a href="https://www.w3schools.com/css/css_rwd_viewport.asp" rel="noreferrer">Viewport</a>.</li>
<li>If you need to send multiple requests to a website, you need to keep on changing the <strong>User Agent</strong> on each request. Here you can find a detailed discussion on <a href="https://stackoverflow.com/questions/49565042/way-to-change-google-chrome-user-agent-in-selenium/49565254#49565254">Way to change Google Chrome user agent in Selenium?</a></li>
<li>To simulate <em>human like</em> behavior you may require to slow down the script execution even beyond <a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.wait.html#module-selenium.webdriver.support.wait" rel="noreferrer">WebDriverWait</a> and <a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#module-selenium.webdriver.support.expected_conditions" rel="noreferrer">expected_conditions</a> inducing <code>time.sleep(secs)</code>. Here you can find a detailed discussion on <a href="https://stackoverflow.com/questions/52603847/how-to-sleep-webdriver-in-python-for-milliseconds/52607451#52607451">How to sleep webdriver in python for milliseconds</a></li>
</ul>
|
37,788,342 |
Is it better to define state in constructor or using property initializers?
|
<p>According to <a href="https://babeljs.io/blog/2015/06/07/react-on-es6-plus" rel="noreferrer">this</a> babel documentation, the correct way to use ES6+ with React is to initial components like this:</p>
<pre><code>class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}
</code></pre>
<p>But some official examples, like Dan Abramov's own <a href="https://github.com/gaearon/react-dnd/blob/master/examples/04%20Sortable/Simple/Container.js" rel="noreferrer">React DnD</a> module, uses ES6+ but still defines state within the constructor:</p>
<pre><code>constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
// state stuff
}
}
</code></pre>
<p>Now Dan Abramov, being a significant contributor to React, probably knows that he can define state outside the constructor, yet still opts to do it within the constructor. </p>
<p>So I'm just wondering which way is better and why?</p>
| 37,788,410 | 3 | 3 | null |
2016-06-13 11:14:14.08 UTC
| 19 |
2019-08-20 11:42:06.17 UTC
|
2016-06-14 02:46:20.867 UTC
| null | 218,196 | null | 2,432,961 | null | 1 | 58 |
reactjs|ecmascript-next
| 16,822 |
<p>I believe it's a matter of personal preference. The transpiled output is the same in terms of semantics.</p>
<ul>
<li><strong><a href="https://babeljs.io/repl/#?evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-1%2Cstage-2%2Cstage-3&experimental=false&loose=false&spec=false&code=class%20Video%20%7B%0A%20%20state%20%3D%20%7B%0A%20%20%20%20loopsRemaining%3A%20this.props.maxLoops%2C%0A%20%20%7D%0A%7D" rel="noreferrer">Class Property</a></strong></li>
<li><strong><a href="https://babeljs.io/repl/#?evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-1%2Cstage-2%2Cstage-3&experimental=false&loose=false&spec=false&code=class%20Video%20%7B%0A%20%20constructor()%20%7B%0A%20%20%20%20this.state%20%3D%20%7B%0A%20%20%20%20%20%20loopsRemaining%3A%20this.props.maxLoops%2C%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D" rel="noreferrer">Constructor</a></strong></li>
</ul>
|
44,209,368 |
How to change a single value in a NumPy array?
|
<p>I want to change a single element of an array.
For example, I have:</p>
<pre><code>A = np.array([1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16])
</code></pre>
<p>I want to relace <code>A[2][1] = 10</code> with <code>A[2][1] = 150</code>.
How can I do it?</p>
| 44,209,429 | 1 | 2 | null |
2017-05-26 20:03:57.3 UTC
| 5 |
2022-05-24 15:55:51.24 UTC
|
2020-08-01 00:07:15.633 UTC
| null | 7,851,470 |
user8072140
| null | null | 1 | 47 |
python|numpy
| 198,480 |
<p>Is this what you are after? Just index the element and assign a new value.</p>
<pre><code>A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
</code></pre>
|
1,641,008 |
How to store arbitrary name/value key pairs in a Django model?
|
<p>I have a fixed data model that has a lot of data fields.</p>
<pre>
class Widget(Models.model):
widget_owner = models.ForeignKey(auth.User)
val1 = models.CharField()
val2 = models.CharField()
...
val568 = ...
</pre>
<p>I want to cram even more data into this Widget by letting my users specify custom data fields. What's a sane way to do this? Is storing name/value pairs where the user can specify additional "Widget fields" a good idea? My pseudo thoughts are below:</p>
<pre>
data_types = ('free_text', 'date', 'integer', 'price')
class CustomWidgetField(models.Model)
owner = ForeignKey(auth.User)
field_title = models.CharField(auth.User)
field_value_type = models.CharField(choices = data_types)
class CustomWidgetValue(models.Model)
field_type = ForeignKey(CustomWidgetField)
widget = ForeignKey(Widget)
value = models.TextField()
</pre>
<p>So I want to let each user build a new type of data field that will apply to all of their widgets and then specify values for each custom field in each widget. I will probably have to do filtering/searching on these custom fields just as I would on a native field (which I assume will be much slower than operating on native fields.) But the scale is to have a few dozen custom fields per Widget and each User will only have a few thousand Widgets in their inventory. I can also probably batch most of the searching/filtering on the custom fields into a backend script (maybe.)</p>
| 1,641,346 | 5 | 0 | null |
2009-10-29 00:37:19.437 UTC
| 9 |
2013-09-09 12:25:39.38 UTC
| null | null | null | null | 36,680 | null | 1 | 13 |
django|django-models
| 13,549 |
<p>Consider representing all custom properties with serialized dict. I used this in a recent project and it worked really well.</p>
<pre><code> class Widget(models.Model):
owner = models.ForeignKey(auth.User)
props = models.TextField(blank=True) # serialized custom data
@property
def props_dict(self):
return simplejson.loads(self.props)
class UserProfile(models.Model)
user = models.ForeignKey(auth.User)
widget_fields = models.TextField(blank=True) # serialized schema declaration
</code></pre>
|
1,884,979 |
JSON to Groovy parser
|
<p>I found many things about converting Groovy to JSON, but oddly enough, not the other way.</p>
<p>What is the (best) JSON to Groovy parser around there ?</p>
| 1,885,496 | 5 | 0 | null |
2009-12-10 23:59:45.957 UTC
| 8 |
2022-01-28 10:46:11.967 UTC
| null | null | null | null | 183,258 | null | 1 | 22 |
json|groovy
| 40,648 |
<p>Because compiled Groovy classes are compatible with Java classes, you should be able to use any Java library for converting JSON to POJOs (or POGOs). <a href="http://jackson.codehaus.org/" rel="nofollow noreferrer">Jackson</a> is a fairly popular choice which you can use to convert JSON like this:</p>
<pre><code>String json = '{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}'
</code></pre>
<p>to a Map using:</p>
<pre><code>Map<String,Object> userData = mapper.readValue(json, Map.class)
</code></pre>
<p>Or if you want to convert the JSON to a Groovy User class:</p>
<pre><code>User userData = mapper.readValue(json, User.class)
</code></pre>
<p>This will map properties in the Groovy class to keys in the JSON.</p>
<p>In the code above, <code>mapper</code> is an instance of <code>com.fasterxml.jackson.databind.ObjectMapper</code> from the Jackson library.</p>
|
2,160,635 |
Is there a way to print out the type of a variable/pointer in C?
|
<p>I want to print out (or otherwise ascertain) the type of some variable in my program. Is there a good way to do it? By good, I mean a way that works, even if it means intentionally throwing compiler errors.</p>
<p>For example:</p>
<pre><code>client.c:55: error: incompatible types in assignment
</code></pre>
<p>is the error I'm getting right now. What I WANT is it to tell me something like:</p>
<pre><code>client.c:55: error: attempting to assign type struct a to type struct b
</code></pre>
<p>or a function that I can use like so:</p>
<pre><code>printf(gettype(x));
</code></pre>
<p>which would output:</p>
<pre><code>struct b
</code></pre>
| 2,160,773 | 5 | 5 | null |
2010-01-29 08:06:47.753 UTC
| 6 |
2020-12-14 15:31:46.683 UTC
| null | null | null | null | 239,333 | null | 1 | 35 |
c|types
| 88,671 |
<p>try debugging using GDB, it will print all properties associated with the variable including it's type. But, your program should compile before using GDB.</p>
|
2,288,970 |
C++: How to build Strings / char*
|
<p>I'm new to C++. I want to make a <code>char*</code>, but I don't know how.<br>
In Java is it just this:</p>
<pre><code>int player = 0;
int cpu = 0;
String s = "You: " + player + " CPU: " + cpu;
</code></pre>
<p>How can I do this? I need a <code>char*</code>.</p>
<p>I'm focusing on pasting the integer after the string.</p>
| 2,289,025 | 6 | 3 | null |
2010-02-18 13:45:33.887 UTC
| 4 |
2014-02-06 18:06:44.01 UTC
|
2014-02-06 18:04:35.173 UTC
| null | 1,530,508 | null | 155,137 | null | 1 | 14 |
c++|string|char
| 75,934 |
<p>You almost certainly don't want to deal with char * if you can help it - you need the C++ std::string class:</p>
<pre><code>#include <string>
..
string name = "fred";
</code></pre>
<p>or the related stringstream class:</p>
<pre><code>#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
int player = 0;
int cpu = 0;
ostringstream os;
os << "You: " << player << " CPU: " << cpu;
string s = os.str();
cout << s << endl;
}
</code></pre>
<p>if you really need a character pointer (and you haven't said why you think you do), you can get one from a string by using its c_str() member function.</p>
<p>All this should be covered by any introductory C++ text book. If you haven't already bought one, get <a href="http://www.acceleratedcpp.com/" rel="noreferrer">Accelerated C++</a>. You cannot learn C++ from internet resources alone.</p>
|
2,261,858 |
boost::python Export Custom Exception
|
<p>I am currently writing a C++ extension for Python using Boost.Python. A function in this extension may generate an exception containing information about the error (beyond just a human-readable string describing what happened). I was hoping I could export this exception to Python so I could catch it and do something with the extra information.</p>
<p>For example:</p>
<pre><code>import my_cpp_module
try:
my_cpp_module.my_cpp_function()
except my_cpp_module.MyCPPException, e:
print e.my_extra_data
</code></pre>
<p>Unfortunately Boost.Python seems to translate all C++ exceptions (that are subclasses of <code>std::exception</code>) into <code>RuntimeError</code>. I realize that Boost.Python allows one to implement custom exception translation however, one needs to use <code>PyErr_SetObject</code> which takes a <code>PyObject*</code> (for the exception's type) and a <code>PyObject*</code> (for the exception's value)--neither of which I know how to get from my Boost.Python classes. Perhaps there is a way (which would be great) that I simply have not found yet. Otherwise does anyone know how to export a custom C++ exception so that I may catch it in Python?</p>
| 2,262,650 | 6 | 0 | null |
2010-02-14 16:47:17.923 UTC
| 14 |
2022-01-28 10:54:02.033 UTC
|
2016-06-13 21:38:10.16 UTC
| null | 2,069,064 | null | 61,663 | null | 1 | 25 |
c++|python|exception|boost-python
| 9,067 |
<p>The solution is to create your exception class like any normal C++ class</p>
<pre><code>class MyCPPException : public std::exception {...}
</code></pre>
<p>The trick is that all boost::python::class_ instances hold a reference to the object's type which is accessible through their ptr() function. You can get this as you register the class with boost::python like so:</p>
<pre><code>class_<MyCPPException> myCPPExceptionClass("MyCPPException"...);
PyObject *myCPPExceptionType=myCPPExceptionClass.ptr();
register_exception_translator<MyCPPException>(&translateFunc);
</code></pre>
<p>Finally, when you are translating the C++ exception to a Python exception, you do so as follows:</p>
<pre><code>void translate(MyCPPException const &e)
{
PyErr_SetObject(myCPPExceptionType, boost::python::object(e).ptr());
}
</code></pre>
<p>Here is a full working example:</p>
<pre><code>#include <boost/python.hpp>
#include <assert.h>
#include <iostream>
class MyCPPException : public std::exception
{
private:
std::string message;
std::string extraData;
public:
MyCPPException(std::string message, std::string extraData)
{
this->message = message;
this->extraData = extraData;
}
const char *what() const throw()
{
return this->message.c_str();
}
~MyCPPException() throw()
{
}
std::string getMessage()
{
return this->message;
}
std::string getExtraData()
{
return this->extraData;
}
};
void my_cpp_function(bool throwException)
{
std::cout << "Called a C++ function." << std::endl;
if (throwException)
{
throw MyCPPException("Throwing an exception as requested.",
"This is the extra data.");
}
}
PyObject *myCPPExceptionType = NULL;
void translateMyCPPException(MyCPPException const &e)
{
assert(myCPPExceptionType != NULL);
boost::python::object pythonExceptionInstance(e);
PyErr_SetObject(myCPPExceptionType, pythonExceptionInstance.ptr());
}
BOOST_PYTHON_MODULE(my_cpp_extension)
{
boost::python::class_<MyCPPException>
myCPPExceptionClass("MyCPPException",
boost::python::init<std::string, std::string>());
myCPPExceptionClass.add_property("message", &MyCPPException::getMessage)
.add_property("extra_data", &MyCPPException::getExtraData);
myCPPExceptionType = myCPPExceptionClass.ptr();
boost::python::register_exception_translator<MyCPPException>
(&translateMyCPPException);
boost::python::def("my_cpp_function", &my_cpp_function);
}
</code></pre>
<p>Here is the Python code that calls the extension:</p>
<pre><code>import my_cpp_extension
try:
my_cpp_extension.my_cpp_function(False)
print 'This line should be reached as no exception should be thrown.'
except my_cpp_extension.MyCPPException, e:
print 'Message:', e.message
print 'Extra data:',e.extra_data
try:
my_cpp_extension.my_cpp_function(True)
print ('This line should not be reached as an exception should have been' +
'thrown by now.')
except my_cpp_extension.MyCPPException, e:
print 'Message:', e.message
print 'Extra data:',e.extra_data
</code></pre>
|
1,473,155 |
how to get data between quotes in java?
|
<p>I have this lines of text the number of quotes could change like: </p>
<pre><code>Here just one "comillas"
But I also could have more "mas" values in "comillas" and that "is" the "trick"
I was thinking in a method that return "a" list of "words" that "are" between "comillas"
</code></pre>
<p>How I obtain the data between the quotes? </p>
<p>The result should be: </p>
<p>comillas<br>
mas, comillas, trick<br>
a, words, are, comillas </p>
| 1,473,198 | 6 | 0 | null |
2009-09-24 17:43:03.927 UTC
| 8 |
2019-07-23 23:02:23.933 UTC
|
2019-07-23 23:02:23.933 UTC
| null | 2,516,301 | null | 128,237 | null | 1 | 31 |
java|quotes|tokenize
| 68,054 |
<p>You can use a regular expression to fish out this sort of information. </p>
<pre><code>Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println(m.group(1));
}
</code></pre>
<p>This example assumes that the language of the line being parsed doesn't support escape sequences for double-quotes within string literals, contain strings that span multiple "lines", or support other delimiters for strings like a single-quote.</p>
|
1,766,492 |
Overloading operator== versus Equals()
|
<p>I'm working on a C# project on which, until now, I've used immutable objects and factories to ensure that objects of type <code>Foo</code> can always be compared for equality with <code>==</code>. </p>
<p><code>Foo</code> objects can't be changed once created, and the factory always returns the same object for a given set of arguments. This works great, and throughout the code base we assume that <code>==</code> always works for checking equality.</p>
<p>Now I need to add some functionality that introduces an edge case for which this won't always work. The easiest thing to do is to overload <code>operator ==</code> for that type, so that none of the other code in the project needs to change. But this strikes me as a code smell: overloading <code>operator ==</code> and not <code>Equals</code> just seems weird, and I'm used to the convention that <code>==</code> checks reference equality, and <code>Equals</code> checks object equality (or whatever the term is).</p>
<p>Is this a legitimate concern, or should I just go ahead and overload <code>operator ==</code>?</p>
| 1,766,558 | 6 | 1 | null |
2009-11-19 21:00:12.41 UTC
| 22 |
2016-09-16 19:47:06.567 UTC
|
2015-09-25 20:17:21.05 UTC
| null | 1,324 | null | 8,078 | null | 1 | 46 |
c#|operator-overloading|equals
| 34,218 |
<p>I believe the standard is that for most types, .Equals checks object similarity, and operator <code>==</code> checks reference equality.</p>
<p>I believe best practice is that for immutable types, operator <code>==</code> should be checking for similarity, as well as <code>.Equals</code>. And if you want to know if they really are the same object, use <code>.ReferenceEquals</code>. See the C# <code>String</code> class for an example of this.</p>
|
1,474,115 |
How to find the tag associated with a given git commit?
|
<p>For releases I usually tag with something like v1.1.0. During my build script I am creating a fwVersion.c file that contains the current git info. Currently, I have commit, and branch info in the file, but I would like to add the tag.</p>
<p>Is this possible?</p>
| 1,474,161 | 6 | 0 | null |
2009-09-24 20:58:22.16 UTC
| 24 |
2020-02-27 19:45:50.487 UTC
|
2018-05-31 16:32:23.597 UTC
| null | 895,245 | null | 178,727 | null | 1 | 111 |
git
| 60,142 |
<p>Check the documentation for <code>git describe</code>. It finds the nearest tag to a given commit (that is a tag which points to an ancestor of the commit) and describes that commit in terms of the tag.</p>
<p>If you only want to know if the commit is pointed to by a tag then you can check the output of:</p>
<pre><code>git describe --exact-match <commit-id>
</code></pre>
|
1,536,393 |
Good hash function for permutations?
|
<p>I have got numbers in a specific range (usually from 0 to about 1000). An algorithm selects some numbers from this range (about 3 to 10 numbers). This selection is done quite often, and I need to check if a permutation of the chosen numbers has already been selected.</p>
<p>e.g one step selects <code>[1, 10, 3, 18]</code> and another one <code>[10, 18, 3, 1]</code> then the second selection can be discarded because it is a permutation.</p>
<p>I need to do this check very fast. Right now I put all arrays in a hashmap, and use a custom hash function: just sums up all the elements, so 1+10+3+18=32, and also 10+18+3+1=32. For equals I use a bitset to quickly check if elements are in both sets (I do not need sorting when using the bitset, but it only works when the range of numbers is known and not too big).</p>
<p>This works ok, but can generate lots of collisions, so the equals() method is called quite often. I was wondering if there is a faster way to check for permutations?</p>
<p>Are there any good hash functions for permutations?</p>
<p><strong>UPDATE</strong></p>
<p>I have done a little benchmark: generate all combinations of numbers in the range 0 to 6, and array length 1 to 9. There are 3003 possible permutations, and a good hash should generated close to this many different hashes (I use 32 bit numbers for the hash):</p>
<ul>
<li>41 different hashes for just adding (so there are lots of collisions)</li>
<li>8 different hashes for XOR'ing values together</li>
<li>286 different hashes for multiplying</li>
<li>3003 different hashes for (R + 2e) and multiplying as abc has suggested (using 1779033703 for R)</li>
</ul>
<p>So abc's hash can be calculated very fast and is a lot better than all the rest. Thanks!</p>
<p>PS: I do not want to sort the values when I do not have to, because this would get too slow.</p>
| 1,537,189 | 7 | 7 | null |
2009-10-08 08:22:43.917 UTC
| 12 |
2011-03-31 05:48:05.977 UTC
|
2009-12-29 21:36:59.783 UTC
| null | 48,181 | null | 48,181 | null | 1 | 15 |
performance|hash|permutation
| 8,318 |
<p>One potential candidate might be this.
Fix a odd integer R.
For each element e you want to hash compute the factor (R + 2*e).
Then compute the product of all these factors.
Finally divide the product by 2 to get the hash.</p>
<p>The factor 2 in (R + 2e) guarantees that all factors are odd, hence avoiding
that the product will ever become 0. The division by 2 at the end is because
the product will always be odd, hence the division just removes a constant bit.</p>
<p>E.g. I choose R = 1779033703. This is an arbitrary choice, doing some experiments should show if a given R is good or bad. Assume your values are [1, 10, 3, 18].
The product (computed using 32-bit ints) is</p>
<pre><code>(R + 2) * (R + 20) * (R + 6) * (R + 36) = 3376724311
</code></pre>
<p>Hence the hash would be </p>
<blockquote>
<p>3376724311/2 = 1688362155.</p>
</blockquote>
|
1,677,990 |
What is the difference between :focus and :active?
|
<p>What is the difference between the <code>:focus</code> and <code>:active</code> pseudo-classes?</p>
| 1,678,020 | 7 | 0 | null |
2009-11-05 02:40:58.09 UTC
| 75 |
2020-05-31 03:05:45.323 UTC
|
2011-11-08 07:13:18.46 UTC
| null | 106,224 | null | 84,201 | null | 1 | 342 |
css|css-selectors|pseudo-class
| 277,737 |
<p><code>:focus</code> and <code>:active</code> are two different states.</p>
<ul>
<li><code>:focus</code> represents the state when the element is currently selected to receive input and </li>
<li><code>:active</code> represents the state when the element is currently being activated by the user.</li>
</ul>
<p>For example let's say we have a <code><button></code>. The <code><button></code> will not have any state to begin with. It just exists. If we use <kbd>Tab</kbd> to give "focus" to the <code><button></code>, it now enters its <code>:focus</code> state. If you then click (or press <kbd>space</kbd>), you then make the button enter its (<code>:active</code>) state.</p>
<p>On that note, when you click on an element, you give it focus, which also cultivates the illusion that <code>:focus</code> and <code>:active</code> are the same. <strong>They are not the same.</strong> When clicked the button is in <code>:focus:active</code> state.</p>
<p>An example:
<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><style type="text/css">
button { font-weight: normal; color: black; }
button:focus { color: red; }
button:active { font-weight: bold; }
</style>
<button>
When clicked, my text turns red AND bold!<br />
But not when focused only,<br />
where my text just turns red
</button></code></pre>
</div>
</div>
</p>
<p>edit: <a href="http://jsfiddle.net/NCwvj/" rel="noreferrer" title="jsfiddle">jsfiddle</a></p>
|
1,409,225 |
Changing a CSS rule-set from Javascript
|
<p>Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS which would change a CSS rule-set when the user clicks a widget)</p>
<p>This particular CSS rule-set is applied to lots of elements (via a class selector) on the page and I want to modify it when the user clicks the widget, so that all the elements having the <strong>class</strong> change.</p>
| 1,409,250 | 8 | 3 | null |
2009-09-11 06:06:33.277 UTC
| 12 |
2019-04-02 07:01:02.74 UTC
|
2019-04-02 07:01:02.74 UTC
| null | 860,099 | null | 140,970 | null | 1 | 70 |
javascript|css
| 46,405 |
<p>You can, but it's rather cumbersome. The best reference on how to do it is the following article: <a href="http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript" rel="noreferrer">Totally Pwn CSS with Javascript</a> (<a href="https://web.archive.org/web/20130709232042/http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript" rel="noreferrer">web archive link</a>).</p>
<p>I managed to get it to work with Firefox and IE - <del>I couldn't in Chrome, though it appears that it supports the DOM methods.</del><a href="https://stackoverflow.com/users/695639/ricosrealm">ricosrealm</a> reports that it works in Chrome, too.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.