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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,870,064 | How to play an mp3 file in java | <p>I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.</p>
<pre><code>public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
</code></pre>
<p>I have tried doing that but it gives me errors.</p>
<p>I have imported <code>JMF</code> and <code>JLayer</code>.</p>
<p>I have also read other questions that are like this one on this forum and none of them have helped me.</p>
<p>I just need a hand to help play an mp3 file.</p> | 16,870,115 | 3 | 2 | null | 2013-06-01 07:06:27.693 UTC | 1 | 2016-10-15 09:45:59.917 UTC | 2013-06-01 07:19:07.203 UTC | null | 241,605 | null | 2,413,200 | null | 1 | 4 | java|audio|mp3 | 47,188 | <p>For this you'll need to install <a href="http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-client-419417.html#7372-jmf-2.1.1e-oth-JPR" rel="nofollow">Java Media Framework (JMF)</a> in your PC. One you have it installed,then try this piece of code:</p>
<pre><code>import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
</code></pre>
<p>You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a βJMF MP3 pluginβ in order to play MP3 file.</p>
<p>Go Javaβs JMF website to download it
<a href="http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html" rel="nofollow">http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html</a></p>
<p>To be sure that you are using a supported format file, check here:</p>
<p><a href="http://www.oracle.com/technetwork/java/javase/formats-138492.html" rel="nofollow">http://www.oracle.com/technetwork/java/javase/formats-138492.html</a></p>
<p>If you are using windows7, you may have to read this as well:</p>
<p><a href="https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45" rel="nofollow">https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45</a></p> |
16,916,470 | Convert row value in to column in SQL server (PIVOT) | <p>I have table in SQL Server called <strong>test</strong> having 3 column</p>
<pre><code>| ITEM | ATTRIBUTE | VALUE |
-----------------------------
| item1 | Quality | A |
| item1 | color | Red |
| item2 | Quality | B |
| item2 | color | Black |
</code></pre>
<p>I want output like this:</p>
<pre><code>| ITEM | QUALITY | COLOR |
---------------------------
| item1 | A | Red |
| item2 | B | Black |
</code></pre>
<p>How can I get this in SQL Server.</p> | 16,916,639 | 3 | 0 | null | 2013-06-04 11:19:14.913 UTC | 4 | 2021-10-04 17:05:43.577 UTC | 2013-06-04 11:40:16.98 UTC | null | 1,369,235 | null | 901,188 | null | 1 | 11 | sql|sql-server-2008|pivot | 47,049 | <p>Try this one:</p>
<pre><code>SELECT *
FROM (SELECT Item, attribute, value FROM MyTable) AS t
PIVOT
(
MAX(value)
FOR attribute IN([Quality], [Color])
) AS p;
</code></pre>
<p>Output:</p>
<pre><code>βββββββββ¦ββββββββββ¦ββββββββ
β ITEM β QUALITY β COLOR β
β ββββββββ¬ββββββββββ¬ββββββββ£
β item1 β A β Red β
β item2 β B β Black β
βββββββββ©ββββββββββ©ββββββββ
</code></pre>
<h3>See <a href="http://sqlfiddle.com/#!18/2b315/1" rel="noreferrer">this SQLFiddle</a></h3>
<p>You can also use this dynamic query if you don't know the specific value of <code>attribute</code>:</p>
<pre><code>DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(attribute)
from MyTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Item,' + @cols + '
from
(
Select Item, attribute , value
from MyTable
) dta
pivot
(
MAX(Value)
for attribute in (' + @cols + ')
) pvt '
execute(@query);
</code></pre>
<h3>See <a href="http://sqlfiddle.com/#!18/2b315/3" rel="noreferrer">this SQLFiddle</a></h3> |
12,339,013 | Binding a map of lists in Spring MVC | <p>I am not sure if this is a complex problem but as a starting person this seems a bit complex to me.
I have an object based on which i need to show some values on the UI and let user select some of them, i need to send data back to another controller when user click on the submit button.Here is the structure of my data object</p>
<pre><code>public class PrsData{
private Map<String, List<PrsCDData>> prsCDData;
}
public class PrsCDData{
private Map<String, Collection<ConfiguredDesignData>> configuredDesignData;
}
public ConfiguredDesignData{
// simple fields
}
</code></pre>
<p>I have set the object in model before showing the view like</p>
<pre><code>model.addAttribute("prsData", productData.getPrData());
</code></pre>
<p>In the form i have following settings</p>
<pre><code><form:form method="post" commandName="prsData" action="${addProductToCartAction}" >
<form:hidden path="prsCDData['${prsCDDataMap.key}']
[${status.index}].configuredDesignData['${configuredDesignDataMap.key}']
[${configuredDesignDataStatus.index}].code"/>
<form:hidden path="prsCDData['${prsCDDataMap.key}']
[${status.index}].configuredDesignData['${configuredDesignDataMap.key}']
[${configuredDesignDataStatus.index}].description"/>
</form:form>
</code></pre>
<p>This is what i have at <code>AddProductToCartController</code></p>
<pre><code>public String addToCart(@RequestParam("productCodePost") final String code,
@ModelAttribute("prsData") final PrsData prsData, final Model model,
@RequestParam(value = "qty", required = false, defaultValue = "1") final long qty)
</code></pre>
<p>On submitting the form i am getting following exception</p>
<pre><code>org.springframework.beans.NullValueInNestedPathException: Invalid property 'prsCDData[Forced][0]'
of bean class [com.product.data.PrsData]:
Cannot access indexed value of property referenced in indexed property path 'prsCDData[Forced][0]': returned null
</code></pre>
<p>It seems like its trying to access the values on this controller while i am trying to send value to that controller and trying to create same object with selected values</p>
<p>Can any one tell me where i am doing wrong and what i need to take care of</p>
<p><strong>Edit</strong></p>
<p>I did some more research and came to know that Spring do not support auto-populating list/map for custom objects and based on the answer i tried to change implementation like</p>
<pre><code>public class PrsData{
private Map<String, List<PrsCDData>> prsCDData;
// lazy init
public PrsData()
{
this.prsCDData = MapUtils.lazyMap(new HashMap<String, List<PrsCDData>>(),
FactoryUtils.instantiateFactory(PrsCDData.class));
}
}
public class PrsCDData{
private Map<String, Collection<ConfiguredDesignData>> configuredDesignData;
public PrsCDData()
{
this.configuredDesignData = MapUtils.lazyMap(new HashMap<String,
List<ConfiguredDesignData>>(),
FactoryUtils.instantiateFactory(ConfiguredDesignData.class));
}
}
</code></pre>
<p>but i am getting following exception </p>
<pre><code>org.springframework.beans.InvalidPropertyException:
Invalid property 'prsCDData[Forced][0]' of bean class [com.data.PrsData]:
Property referenced in indexed property path 'prsCDData[Forced][0]'
is neither an array nor a List nor a Set nor a Map;
returned value was [com.data.PrsCDData@6043a24d]
</code></pre>
<p>i am not sure which thing i am doing wrong, it seems that either my JSTL expression is not right</p> | 12,340,425 | 1 | 1 | null | 2012-09-09 12:21:37.85 UTC | 8 | 2020-02-28 18:36:52.473 UTC | 2012-09-15 11:19:07.12 UTC | null | 400,545 | null | 471,607 | null | 1 | 7 | java|jsp|spring-mvc|jstl | 19,577 | <p><strong>Explanation :</strong> if in you controller you have <code>@ModelAttribute("user") User user</code>, and you load a corresponding page that contains <code><form:form commandName="user"></code>, an empty User is instantiated. </p>
<p>All its attributes are null, or empty in case of a List or a Map. Moreover, its empty lists/maps have been instantiated with an autogrowing implementation. What does it mean ? Let's say we have an empty autogrowing <code>List<Coconut> coconuts</code>. If I do <code>coconuts.get(someIndex).setDiameter(50)</code>, it will work instead of throwing an Exception, because the list auto grows and instantiate a coconut for the given index.<br>
Thanks to this autogrowing, submitting a form with the below input will work like a charm :</p>
<pre><code><form:input path="coconuts[${someIndex}].diameter" />
</code></pre>
<hr>
<p><strong>Now back to your problem :</strong> Spring MVC autogrowing works quite well with a chain of objects, each containing a map/list (<a href="https://stackoverflow.com/questions/9943386/bind-map-in-spring-mvc/9974851#9974851">see this post</a>). But given your exception, it looks like Spring doesn't autogrow the possible objects contained by the autogrowed list/map. In <code>Map<String, List<PrsCDData>> prsCDData</code>, the <code>List<PrsCDData></code> is a mere empty list with no autogrowing, thus leading to your Exception.</p>
<p>So the solution must use some kind of Apache Common's <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/list/LazyList.html" rel="nofollow noreferrer">LazyList</a> or Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/AutoPopulatingList.html" rel="nofollow noreferrer">AutoPopulatingList</a>.<br>
You must implement your own autogrowing map that instantiates a LazyList/AutoPopulatingList for a given index. Do it from scratch or using some kind of Apache Common's <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LazyMap.html" rel="nofollow noreferrer">LazyMap</a> / <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/MapUtils.html#lazyMap%28java.util.Map,%20org.apache.commons.collections.Transformer%29" rel="nofollow noreferrer">MapUtils.lazyMap</a> implementation (so far I have not found a Spring equivalent for LazyMap).</p>
<p>Example of solution, using Apache Commons Collections :</p>
<pre><code>public class PrsData {
private Map<String, List<PrsCDData>> prsCDData;
public PrsData() {
this.prsCDData = MapUtils.lazyMap(new HashMap<String,List<Object>>(), new Factory() {
public Object create() {
return LazyList.decorate(new ArrayList<PrsCDData>(),
FactoryUtils.instantiateFactory(PrsCDData.class));
}
});
}
}
</code></pre> |
12,541,370 | TypeError: 'encoding' is an invalid keyword argument for this function | <p>My python program has trouble opening a text file. When I use the basic open file for read, I get an ascii error. Someone helped me out by having me add an encoding parameter that works well in Idle, but when I run the program through terminal, I get this error message: "TypeError: 'encoding' is an invalid keyword argument for this function" How can I read this text file in to use it's data?</p>
<pre><code>try:
import tkinter as tk
from tkinter import *
except:
import Tkinter as tk
from Tkinter import *
import time
import sys
import os
import random
flashcards = {}
def Flashcards(key, trans, PoS):
if not key in flashcards:
flashcards[key] = [[trans], [PoS]]
else:
x = []
for item in flashcards[key][0]:
x.append(item)
x.append(trans)
flashcards[key][0] = x
x = []
for item in flashcards[key][1]:
x.append(item)
x.append(PoS)
flashcards[key][1] = x
def ImportGaeilge():
flashcards = {}
with open('gaeilge_flashcard_mode.txt','r', encoding='utf8') as file:
for line in file:
line1 = line.rstrip().split("=")
key = line1[0]
trans = line1[1]
PoS = line1[2]
Flashcards(key, trans, PoS)
def Gaeilge():
numberCorrect = 0
totalCards = 0
ImportGaeilge()
wrongCards = {}
x = input('Hit "ENTER" to begin. (Type "quit" to quit)')
while x != quit:
os.system('cls')
time.sleep(1.3)
card = flashcards.popitem()
if card == "":
## WRONG CARDS
print ("Deck one complete.")
Gaeilge()
print("\n\n")
print(str(card[0])+":")
x = input("\t:")
if x == 'quit':
break
else:
right = False
for item in card[1]:
if x == card[1]:
right = True
print("\nCorrect!")
numberCorrect += 1
if right == False:
print(card[0])
totalCards += 1
print("Correct answers:", str(numberCorrect) +"/"+str(totalCards))
Gaeilge()
</code></pre>
<p>gaeilge_flashcard_mode.txt:</p>
<pre><code>I=mΓ©=(pron) (emphatic)
I=mise=(n/a)
you=tΓΊ=(pron) (subject)
you=tusa=(emphatic)
y'all=sibh=(plural)
y'all=sibhse=(emphatic)
he=sΓ©=(pron)
he=Γ©=(n/a)
he=seisean=(emphatic)
he=eisean=(n/a)
she=sΓ=(pron)
she=Γ=(n/a)
she=sise=(emphatic)
she=ise=(emphatic)
him=Γ©=(pron)
him=eisean=(emphatic)
her=Γ=(pron)
her=ise=(emphatic)
her=a=(adj)
</code></pre> | 12,541,521 | 3 | 0 | null | 2012-09-22 06:31:12.1 UTC | 10 | 2020-10-30 19:26:24.663 UTC | 2020-10-30 19:26:24.663 UTC | null | 3,890,632 | null | 1,542,461 | null | 1 | 41 | python|python-3.x | 106,236 | <p>The terminal you are trying to run this on probably uses Python 2.x as standard.</p>
<p>Try using the command "Python3" specifically in the terminal: </p>
<p><code>$ Python3 yourfile.py</code></p>
<p>(Tested and confirmed that 2.7 will give that error and that Python3 handles it just fine.)</p> |
12,424,617 | Comparing Lift with Play2 | <p>I used play2 before with java. It felt a little bit like boilerplate especially if you used akka with java. But that is not the fault of the framework.</p>
<p>Yesterday I read "Scala for the impatient" and I really enjoy the language.</p>
<p>Now I looked at both frameworks Lift 2.5 and Play 2.0.3. I think lift has a higher learning curve and I could not just do something with lift. This is not a con for me. From what I saw, Lift has a very nice and clean design. </p>
<p>But for me it is hard to tell what the main differences are. I think both frameworks are great.</p>
<ul>
<li><p>The Views First approach doesn't allow you to code in your templates, instead you have to code in snippets. I like this a lot because it looks more organized to me. It also lets you use a normal html editor.
<em>(I have not much experience, this is just my first impression)</em></p></li>
<li><p>For the security I don't think that is the job of the framework. </p></li>
<li><p>Stateless/Stateful : It is hard to tell where the main differences are. I only know that play has also a state if you use web sockets.</p></li>
<li><p>Both frameworks are able to compile after you press F5. I like this feature a lot.</p></li>
<li><p>Both frameworks are using sbt</p></li>
<li><p>Lift comes with authorization but I think there is a play2 scala plugin that does the same thing</p></li>
<li><p>Lift has a ORM mapper for mongoDB. Because I want to use noSQL, this looks cleaner to me.<em>(Again not much experience)</em> <strong>Edit</strong> There is a ORM mapper for scala mongodb in play2 <a href="https://github.com/leon/play-salat">https://github.com/leon/play-salat</a></p></li>
<li><p>Async - Play 2 uses Akka. Don't know what lift uses but they also have something similar.</p></li>
<li><p>Lift ships with CSRF support. Play2 has a modul for CSRF but this adds a boilerplate to your code.</p></li>
<li><p>Stateless authentication seems to have some security vulnerabilities. Both frameworks have the stateful authentication. (play2 stateful/stateless , lift stateful)</p></li>
</ul>
<hr>
<hr>
<ul>
<li>What are the strengths of each framework? </li>
</ul> | 12,428,316 | 2 | 1 | null | 2012-09-14 12:30:33.92 UTC | 35 | 2013-07-20 10:14:25.65 UTC | 2012-09-14 13:53:04.177 UTC | null | 944,430 | null | 944,430 | null | 1 | 47 | scala|playframework-2.0|lift|web-frameworks | 27,159 | <p>Posting this after spending a week or two with Lift doesn't really
serve anybody's interests. However, I want to spend some time correcting
some mistakes and mis-perceptions.</p>
<blockquote>
<ul>
<li>For the security I don't think that is the job of the framework.</li>
</ul>
</blockquote>
<p>You're dead wrong. Security is the job of the framework. It's critical that security
is done by default rather than relying on each developer to understand every
security vulnerability and make sure every line of code takes that into account.</p>
<p>All we have to do is look at what happened to <a href="http://arstechnica.com/business/2012/03/hacker-commandeers-github-to-prove-vuln-in-ruby/" rel="noreferrer">GitHub</a>
to understand that even the best coders using well known technology
can make a critical mistake.</p>
<p>Lift gives a solid security layer on top, so by default, there's no XSS, CSRF, etc.
but the developer can dig down as deep as he wants to the HTTP request and deal
with the bytes on the wire.</p>
<blockquote>
<ul>
<li>Stateless/Stateful : It is hard to tell where the main differences are. I only know that play has also a state if you use web sockets.</li>
</ul>
</blockquote>
<p>Lift is very clear about where you need state and where you don't. Lift can support
stateless, partially stateful, and completely stateful apps. On a page-by-page and
request-by-request basis, a Lift app can be stateful or stateless (for example,
in <a href="http://foursquare.com" rel="noreferrer">Foursquare</a>, the venue pages are stateless for
search engine crawls, but stateful for browsers that are logged in.) For
more on the design decisions around state, please see <a href="http://lift.la/lift-state-and-scaling" rel="noreferrer">Lift, State, and Scaling</a>.</p>
<blockquote>
<ul>
<li>Both frameworks are using sbt</li>
</ul>
</blockquote>
<p>Lift uses Maven, sbt, Buildr, and even Ant. Lift is agnostic about the build environment
and about the deploy environment (Java EE container, Netty, whatever). This is important
because it make Lift easier to integrate with the rest of your environment.</p>
<blockquote>
<ul>
<li>Lift comes with authorization but I think there is a play2 scala plugin that does the same thing</li>
</ul>
</blockquote>
<p>Lift has been around for 5+ years and has a lot of modules and stuff for it. The Lift web framework (as distinguished from the modules) is agnostic about persistence, authentication, etc., so you can use anything with Lift.</p>
<blockquote>
<ul>
<li>Async - Play 2 uses Akka. Don't know what lift uses but they also have something similar.</li>
</ul>
</blockquote>
<p>Lift has had Async support for more than 5 years. It's baked into the framework. Lift's Comet support is <a href="http://seventhings.liftweb.net/comet" rel="noreferrer">the best of any web framework</a> because,
among other things, it multiplexes all the "push" requests on a page through a single request
to the server which avoids connection starvation. How Lift does async is a whole lot
less important because one of the core philosophies with Lift is that we remove the
plumbing from the developer so the developer can focus on business logic.</p>
<p>But for those who care, Lift has the best and lightest weight actors of any framework in
Scala-land. We were the first to break away from the Scala Actor's library and worked
to blaze the trail for different Actor libraries that allowed Akka and ScalaZ Actors
to flourish.</p>
<blockquote>
<ul>
<li>Lift ships with CSRF support. Play2 has a modul for CSRF but this adds a boilerplate to your code.</li>
</ul>
</blockquote>
<p>This is part of Lift's commitment to security. It's <a href="https://twitter.com/rasmus/status/5929904263" rel="noreferrer">important</a>.</p>
<blockquote>
<ul>
<li>Stateless authentication seems to have some security vulnerabilities. Both frameworks have the stateful authentication. (play2 stateful/stateless , lift stateful)</li>
</ul>
</blockquote>
<p>Lift apps can be as stateful or as stateless as you want. It's your choice and Lift
makes very clear how to make the decision.</p>
<p>Also, as I pointed out in the Lift, State, and Scaling post, making the developer figure out
how to serialize state in a secure, scalable, performant way
(because virtually every request on a web
app that recognizes specific users is stateful) should be done in a predictable,
secure way by the framework with reasonable overrides for the developers.</p>
<h2>Parting note</h2>
<p>Play is a lot like Rails: it's quick to get a site knocked together and it's
based on MVC, so a lot of developers understand it. But Play lacks the
depth and breadth of Rails (community, plugins, expertise, talent, etc.) If you
want quick, easy MVC, then go with Rails and JRuby and write your
back end in Scala (they work together extraordinarily well.)</p>
<p>Lift is a different beast. There's a significant unlearning curve (stop thinking
MVC and start thinking about user experience first that flows to business logic.)
But once you're up the unlearning curve, Lift sites are more secure, highly
scalable, super-interactive, and much easier to maintain over time.</p> |
12,253,965 | Complete Working Sample of the Gmail Three-Fragment Animation Scenario? | <p>TL;DR: I am looking for a <strong>complete working sample</strong> of what I'll refer to as "the Gmail three-fragment animation" scenario. Specifically, we want to start with two fragments, like this:</p>
<p><img src="https://i.stack.imgur.com/OsysI.png" alt="two fragments"></p>
<p>Upon some UI event (e.g., tapping on something in Fragment B), we want:</p>
<ul>
<li>Fragment A to slide off the screen to the left</li>
<li>Fragment B to slide to the left edge of the screen and shrink to take up the spot vacated by Fragment A</li>
<li>Fragment C to slide in from the right side of the screen and to take up the spot vacated by Fragment B</li>
</ul>
<p>And, on a BACK button press, we want that set of operations to be reversed.</p>
<p>Now, I have seen lots of partial implementations; I'll review four of them below. Beyond being incomplete, they all have their issues.</p>
<hr>
<p>@Reto Meier contributed <a href="https://stackoverflow.com/a/4819665/115145">this popular answer</a> to the same basic question, indicating that you would use <code>setCustomAnimations()</code> with a <code>FragmentTransaction</code>. For a two-fragment scenario (e.g., you only see Fragment A initially, and want to replace it with a new Fragment B using animated effects), I am in complete agreement. However:</p>
<ul>
<li>Since you can only specify one "in" and one "out" animation, I can't see how you would handle all the different animations required for the three-fragment scenario</li>
<li>The <code><objectAnimator></code> in his sample code uses hard-wired positions in pixels, and that would seem to be impractical given varying screen sizes, yet <code>setCustomAnimations()</code> requires animation resources, precluding the possibility of defining these things in Java</li>
<li>I am at a loss as to how the object animators for scale tie in with things like <code>android:layout_weight</code> in a <code>LinearLayout</code> for allocating space on a percentage basis</li>
<li>I am at a loss as to how Fragment C is handled at the outset (<code>GONE</code>? <code>android:layout_weight</code> of <code>0</code>? pre-animated to a scale of 0? something else?)</li>
</ul>
<hr>
<p>@Roman Nurik points out that <a href="https://stackoverflow.com/a/4936159/115145">you can animate any property</a>, including ones that you define yourself. That can help solve the issue of the hard-wired positions, at the cost of inventing your own custom layout manager subclass. That helps some, but I'm still baffled by the rest of Reto's solution.</p>
<hr>
<p>The author of <a href="http://pastebin.com/gh2eDkFS" rel="noreferrer">this pastebin entry</a> shows some tantalizing pseudocode, basically saying that all three fragments would reside in the container initially, with Fragment C hidden at the outset via a <code>hide()</code> transaction operation. We then <code>show()</code> C and <code>hide()</code> A when the UI event occurs. However, I don't see how that handles the fact that B changes size. It also relies on the fact that you apparently can add multiple fragments to the same container, and I am not sure whether or not that is reliable behavior over the long term (not to mention it should break <code>findFragmentById()</code>, though I can live with that).</p>
<hr>
<p>The author of <a href="http://android.amberfog.com/?p=758" rel="noreferrer">this blog post</a> indicates that Gmail is not using <code>setCustomAnimations()</code> at all, but instead directly uses object animators ("you just change left margin of the root view + change width of the right view"). However, this is still a two-fragment solution AFAICT, and the implementation shown once again hard-wires dimensions in pixels.</p>
<hr>
<p>I will continue plugging away at this, so I may wind up answering this myself someday, but I am really hoping that somebody has worked out the three-fragment solution for this animation scenario and can post the code (or a link thereto). Animations in Android make me want to pull my hair out, and those of you who have seen me know that this is a largely fruitless endeavor.</p> | 12,318,422 | 6 | 10 | null | 2012-09-03 21:00:51.52 UTC | 123 | 2018-05-01 18:22:35.727 UTC | 2017-05-23 12:26:13.973 UTC | null | -1 | null | 115,145 | null | 1 | 130 | android|android-fragments|android-animation | 30,000 | <p>OK, here is my own solution, derived from the Email AOSP app, per @Christopher's suggestion in the question's comments.</p>
<p><a href="https://github.com/commonsguy/cw-omnibus/tree/master/Animation/ThreePane" rel="noreferrer">https://github.com/commonsguy/cw-omnibus/tree/master/Animation/ThreePane</a></p>
<p>@weakwire's solution is reminiscent of mine, though he uses classic <code>Animation</code> rather than animators, and he uses <code>RelativeLayout</code> rules to enforce positioning. From the bounty standpoint, he will probably get the bounty, unless somebody else with a slicker solution yet posts an answer.</p>
<hr>
<p>In a nutshell, the <code>ThreePaneLayout</code> in that project is a <code>LinearLayout</code> subclass, designed to work in landscape with three children. Those childrens' widths can be set in the layout XML, via whatever desired means -- I show using weights, but you could have specific widths set by dimension resources or whatever. The third child -- Fragment C in the question -- should have a width of zero.</p>
<pre><code>package com.commonsware.android.anim.threepane;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
public class ThreePaneLayout extends LinearLayout {
private static final int ANIM_DURATION=500;
private View left=null;
private View middle=null;
private View right=null;
private int leftWidth=-1;
private int middleWidthNormal=-1;
public ThreePaneLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initSelf();
}
void initSelf() {
setOrientation(HORIZONTAL);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
left=getChildAt(0);
middle=getChildAt(1);
right=getChildAt(2);
}
public View getLeftView() {
return(left);
}
public View getMiddleView() {
return(middle);
}
public View getRightView() {
return(right);
}
public void hideLeft() {
if (leftWidth == -1) {
leftWidth=left.getWidth();
middleWidthNormal=middle.getWidth();
resetWidget(left, leftWidth);
resetWidget(middle, middleWidthNormal);
resetWidget(right, middleWidthNormal);
requestLayout();
}
translateWidgets(-1 * leftWidth, left, middle, right);
ObjectAnimator.ofInt(this, "middleWidth", middleWidthNormal,
leftWidth).setDuration(ANIM_DURATION).start();
}
public void showLeft() {
translateWidgets(leftWidth, left, middle, right);
ObjectAnimator.ofInt(this, "middleWidth", leftWidth,
middleWidthNormal).setDuration(ANIM_DURATION)
.start();
}
public void setMiddleWidth(int value) {
middle.getLayoutParams().width=value;
requestLayout();
}
private void translateWidgets(int deltaX, View... views) {
for (final View v : views) {
v.setLayerType(View.LAYER_TYPE_HARDWARE, null);
v.animate().translationXBy(deltaX).setDuration(ANIM_DURATION)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
v.setLayerType(View.LAYER_TYPE_NONE, null);
}
});
}
}
private void resetWidget(View v, int width) {
LinearLayout.LayoutParams p=
(LinearLayout.LayoutParams)v.getLayoutParams();
p.width=width;
p.weight=0;
}
}
</code></pre>
<p>However, at runtime, no matter how you originally set up the widths, width management is taken over by <code>ThreePaneLayout</code> the first time you use <code>hideLeft()</code> to switch from showing what the question referred to as Fragments A and B to Fragments B and C. In the terminology of <code>ThreePaneLayout</code> -- which has no specific ties to fragments -- the three pieces are <code>left</code>, <code>middle</code>, and <code>right</code>. At the time you call <code>hideLeft()</code>, we record the sizes of <code>left</code> and <code>middle</code> and zero out any weights that were used on any of the three, so we can completely control the sizes. At the point in time of <code>hideLeft()</code>, we set the size of <code>right</code> to be the original size of <code>middle</code>.</p>
<p>The animations are two-fold:</p>
<ul>
<li>Use a <code>ViewPropertyAnimator</code> to perform a translation of the three widgets to the left by the width of <code>left</code>, using a hardware layer</li>
<li>Use an <code>ObjectAnimator</code> on a custom pseudo-property of <code>middleWidth</code> to change the <code>middle</code> width from whatever it started with to the original width of <code>left</code></li>
</ul>
<p>(it is possible that it is a better idea to use an <code>AnimatorSet</code> and <code>ObjectAnimators</code> for all of these, though this works for now)</p>
<p>(it is also possible that the <code>middleWidth</code> <code>ObjectAnimator</code> negates the value of the hardware layer, since that requires fairly continuous invalidation)</p>
<p>(it is <em>definitely</em> possible that I still have gaps in my animation comprehension, and that I like parenthetical statements)</p>
<p>The net effect is that <code>left</code> slides off the screen, <code>middle</code> slides to the original position and size of <code>left</code>, and <code>right</code> translates in right behind <code>middle</code>.</p>
<p><code>showLeft()</code> simply reverses the process, with the same mix of animators, just with the directions reversed.</p>
<p>The activity uses a <code>ThreePaneLayout</code> to hold a pair of <code>ListFragment</code> widgets and a <code>Button</code>. Selecting something in the left fragment adds (or updates the contents of) the middle fragment. Selecting something in the middle fragment sets the caption of the <code>Button</code>, plus executes <code>hideLeft()</code> on the <code>ThreePaneLayout</code>. Pressing BACK, if we hid the left side, will execute <code>showLeft()</code>; otherwise, BACK exits the activity. Since this does not use <code>FragmentTransactions</code> for affecting the animations, we are stuck managing that "back stack" ourselves.</p>
<p>The project linked-to above uses native fragments and the native animator framework. I have another version of the same project that uses the Android Support fragments backport and <a href="http://nineoldandroids.com/" rel="noreferrer">NineOldAndroids</a> for the animation:</p>
<p><a href="https://github.com/commonsguy/cw-omnibus/tree/master/Animation/ThreePaneBC" rel="noreferrer">https://github.com/commonsguy/cw-omnibus/tree/master/Animation/ThreePaneBC</a></p>
<p>The backport works fine on a 1st generation Kindle Fire, though the animation is a bit jerky given the lower hardware specs and lack of hardware acceleration support. Both implementations seem smooth on a Nexus 7 and other current-generation tablets.</p>
<p>I am certainly open for ideas of how to improve this solution, or other solutions that offer clear advantages over what I did here (or what @weakwire used).</p>
<p>Thanks again to everyone who has contributed!</p> |
24,279,192 | Why does this Java code with "+ +" compile? | <p>I'm curious why this simple program could be compiled by java using IntelliJ (Java 7).</p>
<pre><code>public class Main {
public static void main(String[] args)
{
int e = + + 10;
System.out.println(e);
}
}
</code></pre>
<p>The output is still 10. What is the meaning of <code>+ + 10</code>?</p> | 24,279,306 | 8 | 7 | null | 2014-06-18 07:12:12.997 UTC | 2 | 2015-05-07 08:23:11.913 UTC | 2015-04-03 17:32:58.373 UTC | null | 2,891,664 | null | 2,058,133 | null | 1 | 31 | java | 4,095 | <p>It is <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.3">the unary plus</a>, twice. It is not a prefix increment because there is a space. Java does consider whitespace under many circumstances.</p>
<p>The unary plus basically does nothing, it just promotes the operand.</p>
<p>For example, this doesn't compile, because the unary plus causes the <code>byte</code> to be promoted to <code>int</code>:</p>
<pre><code>byte b = 0;
b = +b; // doesn't compile
</code></pre> |
3,899,525 | How to use GUI form created in IntelliJ IDEA | <p>I'm creating a simple GUI form with one button in IntelliJ IDEA 9. The class which was created with the form is not JFrame or any other swing class. How I can call my form in my source code?</p> | 3,899,609 | 3 | 0 | null | 2010-10-10 08:09:07.207 UTC | 9 | 2022-03-04 17:16:53.853 UTC | 2020-07-26 20:23:54.817 UTC | null | 214,143 | null | 471,411 | null | 1 | 34 | java|user-interface|swing|intellij-idea | 41,274 | <p>Simply go into the class associated with your form, press <kbd>alt</kbd> + <kbd>insert</kbd> and choose "Form main()".</p>
<hr>
<p><strong>Resources :</strong></p>
<ul>
<li><a href="https://www.jetbrains.com/help/idea/gui-designer-basics.html" rel="noreferrer">GUI Designer Basics</a></li>
</ul> |
3,229,883 | Static member initialization in a class template | <p>I'd like to do this:</p>
<pre><code>template <typename T>
struct S
{
...
static double something_relevant = 1.5;
};
</code></pre>
<p>but I can't since <code>something_relevant</code> is not of integral type. It doesn't depend on <code>T</code>, but existing code depends on it being a static member of <code>S</code>.</p>
<p>Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?</p> | 3,229,904 | 3 | 3 | null | 2010-07-12 15:45:41.777 UTC | 40 | 2018-12-05 17:02:35.47 UTC | 2013-05-22 13:50:34.853 UTC | null | 140,719 | null | 373,025 | null | 1 | 178 | c++|templates|static | 103,740 | <p>Just define it in the header: </p>
<pre><code>template <typename T>
struct S
{
static double something_relevant;
};
template <typename T>
double S<T>::something_relevant = 1.5;
</code></pre>
<p>Since it is part of a template, as with all templates the compiler will make sure it's only defined once. </p> |
3,725,501 | How to crop the parsed image in android? | <p>I am parsing a website to display the contents in a URL, in that some images are there. I want to crop the images which are parsed from the site. I'm really struggling on this, can any one help me regarding on this?</p> | 3,725,572 | 4 | 1 | null | 2010-09-16 09:53:13.727 UTC | 14 | 2013-04-30 08:35:22.063 UTC | 2012-07-24 09:27:41.6 UTC | null | 1,023,248 | null | 424,413 | null | 1 | 12 | android|crop | 17,789 | <p>I assume you've already "got" the images down from the website and want to resize rather than crop? I.e. create thumbnails.</p>
<p>If so, you can use the following:</p>
<pre><code> // load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
</code></pre> |
37,085,665 | In which conda environment is Jupyter executing? | <p>I have jupyter/anaconda/python3.5.</p>
<ol>
<li><p>How can I know which conda environment is my jupyter notebook running on? </p></li>
<li><p>How can I launch jupyter from a new conda environment?</p></li>
</ol> | 39,070,588 | 16 | 7 | null | 2016-05-07 07:14:50.93 UTC | 158 | 2022-01-14 19:29:12.403 UTC | 2016-08-24 04:52:10.643 UTC | null | 3,345,375 | null | 482,711 | null | 1 | 323 | ipython|anaconda|jupyter|jupyter-notebook | 417,561 | <h1>Question 1: Find the current notebook's conda environment</h1>
<p>Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen. </p>
<p>It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name. </p>
<p><a href="https://i.stack.imgur.com/c22av.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c22av.png" alt="jupyter notebook with name of environment"></a></p>
<hr>
<h1>Question 2: Start Jupyter Notebook from within a different conda environment</h1>
<p>Activate a conda environment in your terminal using <code>source activate <environment name></code> before you run <code>jupyter notebook</code>. This <a href="https://stackoverflow.com/q/38984238/3345375">sets the default environment</a> for Jupyter Notebooks. Otherwise, the [Root] environment is the default.</p>
<p><a href="https://i.stack.imgur.com/0Qgkx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0Qgkx.png" alt="jupyter notebooks home screen, conda tab, create new environment"></a></p>
<p>You can also create new environments from within Jupyter Notebook (home screen, Conda tab, and then click the plus sign).</p>
<p>And you can create a notebook in any environment you want. Select the "Files" tab on the home screen and click the "New" dropdown menu, and in that menu select a Python environment from the list.</p>
<p><a href="https://i.stack.imgur.com/otShT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/otShT.png" alt="jupyter notebooks home screen, files tab, create new notebook"></a></p> |
22,548,938 | Get row count of all tables in database: SQL Server | <p>I'm trying to familiarize myself with a large database and search for relevant information among the many tables. I often find myself calling up a table, to see if there is relevant data inside, only to find that the table has no records.</p>
<p>How to quickly call up a list of all tables and the number of records contained therein? I'm using sql server 2008.</p>
<p>Thanks!</p>
<p>Related Question: <a href="https://stackoverflow.com/questions/17066013/how-do-i-quickly-check-many-sql-database-tables-and-views-to-see-if-they-are-not">How do I QUICKLY check many sql database tables and views to see if they are not empty or contain records</a></p> | 22,548,953 | 2 | 4 | null | 2014-03-21 02:14:54.763 UTC | 3 | 2014-03-21 17:20:18.61 UTC | 2017-05-23 12:26:05.15 UTC | null | -1 | null | 2,912,917 | null | 1 | 6 | sql|sql-server | 63,458 | <p>Right click on database -> Reports -> Standard Reports -> Disk usage by Top Tables</p>
<p><img src="https://i.stack.imgur.com/ouSr4.png" alt="enter image description here"></p> |
20,393,373 | Performance wise, how fast are Bitwise Operators vs. Normal Modulus? | <p>Does using bitwise operations in normal flow or conditional statements like <code>for</code>, <code>if</code>, and so on increase overall performance and would it be better to use them where possible? For example:</p>
<pre><code>if(i++ & 1) {
}
</code></pre>
<p>vs.</p>
<pre><code>if(i % 2) {
}
</code></pre> | 20,393,501 | 8 | 4 | null | 2013-12-05 06:52:58.507 UTC | 15 | 2021-04-01 21:19:48.993 UTC | 2019-03-15 23:47:46.07 UTC | null | 10,883,424 | null | 971,741 | null | 1 | 44 | c++|bit-manipulation|bitwise-operators | 42,443 | <p>Unless you're using an ancient compiler, it can already handle this level of conversion on its own. That is to say, a modern compiler can and will implement <code>i % 2</code> using a bitwise <code>AND</code> instruction, provided it makes sense to do so on the target CPU (which, in fairness, it usually will).</p>
<p>In other words, don't expect to see <em>any</em> difference in performance between these, at least with a reasonably modern compiler with a reasonably competent optimizer. In this case, "reasonably" has a pretty broad definition too--even quite a few compilers that are decades old can handle this sort of micro-optimization with no difficulty at all.</p> |
11,413,616 | Is there a clock in iOS that can be used that cannot be changed by the user | <p>I am trying to design a system where real-time events happen and I want to synchronise them to a clock. <code>[NSDate date]</code> would normally be ok but the user could change this and cheat the system. All I need is a clock that I can take relative times from (a 64-bit counter for example) - I don't need absolute time (or time of day etc).</p>
<p>Is there such an API I can use?</p>
<p>EDIT: I would also like to add that this clock needs to be persistent over sessions of the application.</p> | 11,413,996 | 6 | 4 | null | 2012-07-10 12:45:32.037 UTC | 12 | 2014-05-14 11:24:22.03 UTC | 2014-05-14 11:24:22.03 UTC | null | 88,461 | null | 268,687 | null | 1 | 25 | objective-c|ios|time | 10,694 | <p>If all you need is a clock to measure events as monotonically increasing, you could just get the current system uptime ala <code>clock_gettime(CLOCK_MONOTONIC)</code>. If restarting the device is a problem, just save the last value used and at next launch use the last saved value as an offset. The Problem here may be that if they actually shut the device off, it won't count that time. But if you're worried about the user speeding up time, they can't do that, only slow it down.</p> |
11,029,256 | Difference between .nil?, .blank? and .empty? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails">A concise explanation of nil v. empty v. blank in Ruby on Rails</a> </p>
</blockquote>
<p>Can anyone tell me the difference between <code>nil?</code>, <code>blank?</code> and <code>empty?</code> in Ruby?</p> | 11,029,344 | 3 | 0 | null | 2012-06-14 08:22:29.23 UTC | 15 | 2020-03-14 09:55:38.317 UTC | 2020-03-06 05:39:31.473 UTC | null | 128,421 | null | 830,785 | null | 1 | 36 | ruby|ruby-on-rails-3|object | 38,214 | <p>In Ruby, <code>nil</code> in an object (a single instance of the class <code>NilClass</code>). This means that methods can be called on it. <code>nil?</code> is a standard method in Ruby that can be called on <em>all</em> objects and returns <code>true</code> for the <code>nil</code> object and <code>false</code> for anything else.</p>
<p><code>empty?</code> is a standard Ruby method on <em>some</em> objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns <code>true</code> if the object contains no elements.</p>
<p><code>blank?</code> is not a standard Ruby method but is added to <em>all</em> objects by Rails and returns <code>true</code> for <code>nil</code>, <code>false</code>, empty, or a whitespace string.</p>
<p>Because <code>empty?</code> is not defined for all objects you would get a <code>NoMethodError</code> if you called <code>empty?</code> on <code>nil</code> so to avoid having to write things like <code>if x.nil? || x.empty?</code> Rails adds the <code>blank?</code> method.</p>
<hr>
<p>After answering, I found an earlier question, "<a href="https://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails">How to understand nil vs. empty vs. blank in Rails (and Ruby)</a>", so you should check the answers to that too.</p> |
13,065,599 | Opposite of git add -p | <p>Is there an opposite to <code>git add -p</code>? Sometimes I add a chunk by mistake and want to remove it from the index (which I do by <code>git reset; git add -p</code> and adding all the good chunks again). An <code>git remove-from-index -p</code> command would be helpful in this case.</p> | 13,065,676 | 2 | 1 | null | 2012-10-25 09:31:53.52 UTC | 4 | 2016-12-09 09:13:45.977 UTC | 2016-12-09 09:13:45.977 UTC | null | 1,671,066 | null | 1,671,066 | null | 1 | 35 | git | 17,004 | <p>From the git-reset man page:</p>
<blockquote>
<p>This means that git reset -p is the opposite of git add -p</p>
<pre><code> ^
|
exact match of your post title
</code></pre>
</blockquote> |
12,914,917 | Using pointers to remove item from singly-linked list | <p>In a recent <a href="http://meta.slashdot.org/story/12/10/11/0030249/linus-torvalds-answers-your-questions" rel="noreferrer">Slashdot Interview</a> Linus Torvalds gave an example of how some people use pointers in a way that indicates they don't really understand how to use them correctly. </p>
<p>Unfortunately, since I'm one of the people he's talking about, I also failed to understand his example:</p>
<blockquote>
<p><em>I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing
something like</em></p>
<pre><code>if (prev)
prev->next = entry->next;
else
list_head = entry->next;
</code></pre>
<p><em>and whenever I see code like that, I just go "This person doesn't
understand pointers". And it's sadly quite common. People who
understand pointers just use a "pointer to the entry pointer", and
initialize that with the address of the list_head. And then as they
traverse the list, they can remove the entry without using any
conditionals, by just doing</em></p>
<pre><code>*pp = entry->next
</code></pre>
</blockquote>
<p>Can someone provide a bit more explanation about why this approach is better, and how it can work without a conditional statement?</p> | 12,915,035 | 8 | 1 | null | 2012-10-16 12:38:33.653 UTC | 46 | 2021-11-20 05:29:32.817 UTC | 2017-02-14 22:04:43.297 UTC | null | 703,382 | null | 138,256 | null | 1 | 64 | c|pointers|linked-list | 20,852 | <p>At the beginning, you do</p>
<pre><code>pp = &list_head;
</code></pre>
<p>and, as you traverse the list, you advance this "cursor" with</p>
<pre><code>pp = &(*pp)->next;
</code></pre>
<p>This way, you always keep track of the point where "you come from" and can modify the pointer living there.</p>
<p>So when you find the entry to be deleted, you can just do</p>
<p><code>*pp = entry->next</code></p>
<p>This way, you take care of all 3 cases <em>Afaq</em> mentions in another answer, effectively eliminating the <code>NULL</code> check on <code>prev</code>.</p> |
13,208,734 | Get the time and date of git tags | <p>I have a project that is using git and have tagged all the releases with a tag.</p>
<pre><code>$ git tag
v1.0.0
v1.0.1
v1.0.2
v1.0.3
v1.1.0
</code></pre>
<p>My goal is to list the releases and release dates in a web interface (tag/commit date = release date). Currently we list all the releases by using <code>git tag</code>.</p>
<p><strong>How can I get the time and date for when the tag was made (or the commit it points to)?</strong></p> | 13,208,830 | 7 | 4 | null | 2012-11-03 11:30:02.74 UTC | 21 | 2020-12-15 00:37:14.15 UTC | null | null | null | null | 298,195 | null | 1 | 123 | git|date|time|git-tag | 63,211 | <p>Use the <code>--format</code> argument to <code>git log</code>:</p>
<pre><code>git log -1 --format=%ai MY_TAG_NAME
</code></pre> |
11,083,254 | Casting to string in JavaScript | <p>I found three ways to cast a variable to <code>String</code> in JavaScript.<br>
I searched for those three options in the jQuery source code, and <strong>they are all in use</strong>.<br>
I would like to know if there are any differences between them:</p>
<pre><code>value.toString()
String(value)
value + ""
</code></pre>
<p><strong><a href="http://jsfiddle.net/67NaT/">DEMO</a></strong></p>
<p>They all produce the same output, but does one of them better than the others?<br>
I would say the <code>+ ""</code> has an advantage that it saves some characters, but that's not that big advantage, anything else? </p> | 11,083,415 | 8 | 8 | null | 2012-06-18 12:49:13.427 UTC | 29 | 2022-05-24 20:32:21.137 UTC | 2022-05-24 20:32:21.137 UTC | null | 5,459,839 | null | 601,179 | null | 1 | 210 | javascript|string | 376,376 | <p>They do behave differently when the <code>value</code> is <code>null</code>.</p>
<ul>
<li><code>null.toString()</code> throws an error - <em>Cannot call method 'toString' of null</em></li>
<li><code>String(null)</code> returns - <em>"null"</em></li>
<li><code>null + ""</code> also returns - <em>"null"</em></li>
</ul>
<p>Very similar behaviour happens if <code>value</code> is <code>undefined</code> (see <a href="https://stackoverflow.com/a/11083457/369247">jbabey's answer</a>).</p>
<p>Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.</p> |
16,721,945 | Delete a block of text in Vim | <p>So I can delete a text+line using <kbd>d</kbd><kbd>d</kbd> (normal mode) and all the below text moves up a line.</p>
<p>I can go into visual mode using <kbd>Ctrl</kbd>+<kbd>v</kbd></p>
<p>If I then say do <code>0</code> > <code>C+v</code> > <code>jjj</code> > <code>$</code> > <code>d</code> the text of 4 rows is deleted but the lines are not deleted.</p>
<p>How do I delete a block of text and delete the lines at the same time so any preceding lines of text move up to the cursor?</p> | 16,721,970 | 7 | 4 | null | 2013-05-23 19:06:05.147 UTC | 8 | 2018-10-02 15:58:50.173 UTC | 2013-05-24 15:20:37.94 UTC | null | 1,076,493 | null | 1,179,880 | null | 1 | 14 | vim | 18,672 | <p>For something like this I usually use <kbd>shift+v</kbd>, <kbd>j</kbd><kbd>j</kbd><kbd>j</kbd>...<kbd>d</kbd>, but you could delete using text objects as well.<br>
See <code>:h text-object</code>. A few examples:</p>
<p><code>di"</code> - delete inside <code>"</code><br>
<code>dap</code> - delete around paragraph </p>
<p>And you could of course use other commands than <code>d</code>, such as <code>c</code> or <code>v</code>.<br>
Something I use all the time is <code>ci(</code> and <code>ci"</code> for editing content inside <code>()</code> and <code>""</code>.</p>
<p>More cool examples using text-objects and visual mode can be found here:<br>
<a href="https://stackoverflow.com/questions/1218390/what-is-your-most-productive-shortcut-with-vim">What is your most productive shortcut with Vim?</a></p>
<hr>
<p>You could use as well, i.e. <code>4dd</code> as mentioned by FDinoff, or a range, mentioned by Jens. However in most scenarios I personally believe using visual line (<kbd>shift+v</kbd>) is more flexible, and you don't have to count lines or anything. It's easy to remember, you see the result instantly, you won't miss counting lines and it'll work even if you're at the top/bottom on the screen. </p> |
16,891,792 | How to read pdf file and write it to outputStream | <p>I need to read a pdf file with filepath "C:\file.pdf" and write it to outputStream. What is the easiest way to do that?</p>
<pre><code>@Controller
public class ExportTlocrt {
@Autowired
private PhoneBookService phoneBookSer;
private void setResponseHeaderTlocrtPDF(HttpServletResponse response) {
response.setContentType("application/pdf");
response.setHeader("content-disposition", "attachment; filename=Tlocrt.pdf" );
}
@RequestMapping(value = "/exportTlocrt.html", method = RequestMethod.POST)
public void exportTlocrt(Model model, HttpServletResponse response, HttpServletRequest request){
setResponseHeaderTlocrtPDF(response);
File f = new File("C:\\Tlocrt.pdf");
try {
OutputStream os = response.getOutputStream();
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
os.write(buf, 0, c);
os.flush();
}
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>...........................................................................................</p> | 16,891,978 | 2 | 4 | null | 2013-06-03 07:20:31.627 UTC | 6 | 2013-06-03 10:12:33.603 UTC | 2013-06-03 10:12:33.603 UTC | null | 2,006,847 | null | 2,006,847 | null | 1 | 16 | java|pdf|outputstream | 131,805 | <pre><code>import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
</code></pre>
<p>The easiest way so far. Hope this helps.</p> |
16,661,790 | Difference between plt.close() and plt.clf() | <p>In <code>matplotlib.pyplot</code>, what is the difference between <code>plt.clf()</code> and <code>plt.close()</code>? Will they function the same way?</p>
<p>I am running a loop where at the end of each iteration I am producing a figure and saving the plot. On first couple tries the plot was retaining the old figures in every subsequent plot. I'm looking for, individual plots for each iteration without the old figures, does it matter which one I use? The calculation I'm running takes a very long time and it would be very time consuming to test it out.</p> | 16,661,815 | 4 | 3 | null | 2013-05-21 03:47:04.423 UTC | 9 | 2022-05-21 14:54:50.927 UTC | 2021-09-25 19:10:32.153 UTC | null | 674,039 | null | 2,403,811 | null | 1 | 32 | python|matplotlib | 51,862 | <p><code>plt.close()</code> will close the figure window entirely, where <code>plt.clf()</code> will just clear the figure - you can still paint another plot onto it.</p>
<p>It sounds like, for your needs, you should be preferring <code>plt.clf()</code>, or better yet keep a handle on the line objects themselves (they are returned in lists by <code>plot</code> calls) and use <code>.set_data</code> on those in subsequent iterations. </p> |
16,752,887 | Play store Beta Testing returning 404 | <p>I'm a developer and i was thrilled when I was watching Google IO 2013 and learned about the new Beta testing feature. So I created a Google+ community and a google group and placed the testers in there (me included).</p>
<p><img src="https://i.stack.imgur.com/krjCN.jpg" alt="Beta test screenshot"></p>
<p>All we get (the developers and testers) when we visit the <a href="https://play.google.com/apps/testing/com.package.stuff" rel="noreferrer">https://play.google.com/apps/testing/com.package.stuff</a>
is this:</p>
<p><img src="https://i.stack.imgur.com/HNs4U.png" alt="404"></p>
<p>Is there any trick I am missing? I would really like to use this feature.</p>
<p>I know there are alternatives like <a href="https://testflightapp.com/" rel="noreferrer">https://testflightapp.com/</a> but I'd rather keep my app under this environment where I can "promote" the Beta apk to the Production phase and so on.</p> | 16,803,642 | 11 | 5 | null | 2013-05-25 18:54:23.33 UTC | 9 | 2019-02-02 11:57:40.693 UTC | 2018-12-03 14:33:39.02 UTC | null | 1,496,890 | null | 794,485 | null | 1 | 36 | android|google-play | 42,162 | <p>I had this same issue. The reason the link is not working is because the app must be published before the link will be active. I repeat the app must be published, this does not mean there must be an APK in production. On the top right of your applications developer console page there is a drop down menu that allows you to publish the app. That link will become active immediately and your app will be available in a few hours to your testers on the Play Store.</p>
<p><img src="https://i.stack.imgur.com/eyBQg.png" alt="enter image description here"></p> |
17,068,100 | Joining byte list with python | <p>I'm trying to develop a tool that read a binary file, makes some changes and save it. What I'm trying to do is make a list of each line in the file, work with several lines and then join the list again.</p>
<p>This is what I tried:</p>
<pre><code>file = open('myFile.exe', 'r+b')
aList = []
for line in f:
aList.append(line)
#Here im going to mutate some lines.
new_file = ''.join(aList)
</code></pre>
<p>and give me this error:</p>
<pre><code>TypeError: sequence item 0: expected str instance, bytes found
</code></pre>
<p>which makes sense because I'm working with bytes.</p>
<p>Is there a way I can use join function o something similar to join bytes?
Thank you.</p> | 17,068,310 | 2 | 3 | null | 2013-06-12 14:27:48.48 UTC | 6 | 2013-06-12 14:38:04.577 UTC | null | null | null | null | 2,309,536 | null | 1 | 60 | python|list|join|byte | 59,810 | <p>Perform the join on a byte string using <code>b''.join()</code>:</p>
<pre><code>>>> b''.join([b'line 1\n', b'line 2\n'])
b'line 1\nline 2\n'
</code></pre> |
16,768,302 | Does Python have a toString() equivalent, and can I convert a class to String? | <p>I'm writing a ToDo list app to help myself get started with Python. The app is running on GAE and I'm storing todo items in the Data Store. I want to display everyone's items to them, and them alone. The problem is that the app currently displays all items to all users, so I can see what you write, and you see what I write. I thought casting my todo.author object to a string and seeing if it matches the user's name would be a good start, but I can't figure out how to do that.</p>
<p>This is what I have in my main.py</p>
<pre><code>...
user = users.get_current_user()
if user:
nickname = user.nickname()
todos = Todo.all()
template_values = {'nickname':nickname, 'todos':todos}
...
def post(self):
todo = Todo()
todo.author = users.get_current_user()
todo.item = self.request.get("item")
todo.completed = False
todo.put()
self.redirect('/')
</code></pre>
<p>In my index.html I had this originally:</p>
<pre><code><input type="text" name="item" class="form-prop" placeholder="What needs to be done?" required/>
...
<ul>
{% for todo in todos %}
<input type="checkbox"> {{todo.item}} <hr />
{% endfor %}
</ul>
</code></pre>
<p>but I'd like to display items only to the user who created them. I thought of trying</p>
<pre><code>{% for todo in todos %}
{% ifequal todo.author nickname %}
<input type="checkbox"> {{todo.item}} <hr />
{% endifequal %}
{% endfor %}
</code></pre>
<p>to no avail. The list turns up blank. I assumed it is because todo.author is not a string. Can I read the value out as a string, or can I cast the object to String?</p>
<p>Thanks!</p>
<p>Edit: Here is my Todo class</p>
<pre><code>class Todo(db.Model):
author = db.UserProperty()
item = db.StringProperty()
completed = db.BooleanProperty()
date = db.DateTimeProperty(auto_now_add=True)
</code></pre>
<p>Will changing my author to a StringProperty effect anything negatively? Maybe I can forgo casting altogether.</p> | 16,768,514 | 6 | 0 | null | 2013-05-27 07:27:39.317 UTC | 10 | 2022-04-27 13:53:28.34 UTC | 2021-10-20 17:49:34.597 UTC | null | 2,308,683 | null | 2,415,209 | null | 1 | 123 | python|django-templates | 278,797 | <p>In python, the <a href="http://docs.python.org/2/library/functions.html#str" rel="noreferrer"><code>str()</code> method</a> is similar to the <code>toString()</code> method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the <code>__str__()</code> method of the parameter object to get its string representation.</p>
<p>In this case, however, you are comparing a <code>UserProperty</code> author from the database, which is of type <a href="https://cloud.google.com/appengine/docs/standard/python/users/userobjects" rel="noreferrer"><code>users.User</code></a> with the nickname string. You will want to compare the <code>nickname</code> property of the author instead with <code>todo.author.nickname</code> in your template.</p> |
4,407,336 | MongoDb - Utilizing multi CPU server for a write heavy application | <p>I am currently evaluating MongoDb for our write heavy application...</p>
<p>Currently MongoDb uses single thread for write operation and also uses global lock whenever it is doing the write... Is it possible to exploit multiple CPU on a multi-CPU server to get better write performance? What are your workaround for global write lock? </p> | 4,410,868 | 2 | 1 | null | 2010-12-10 09:28:32.773 UTC | 9 | 2020-07-30 13:40:22.007 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 30,917 | null | 1 | 22 | mongodb|performance|nosql | 14,772 | <p>So right now, the easy solution is to shard. </p>
<p>Yes, normally sharding is done across servers. However, it is completely possible to shard on a single box. You simply fire up the shards on different ports and provide them with different folders. <a href="http://www.mongodb.org/display/DOCS/A+Sample+Configuration+Session" rel="noreferrer">Here's a sample configuration</a> of 2 shards on one box.</p>
<p>The MongoDB team recognizes that this is kind of sub-par, and I know from talking to them that they're looking at better ways to do this.</p>
<p>Obviously once you get multiple shards on one box and increase your write threads, you will have to be wary of disk IO. In my experience, I've been able to saturate disks with a single write thread. If your inserts/updates are relatively simple, you may find that extra write threads don't do anything. (Map-Reduces are the exception here, sharding definitely helps there)</p> |
26,615,779 | React Checkbox not sending onChange | <p>TLDR: Use defaultChecked instead of checked, working <a href="http://jsbin.com/mecimayawe/1/edit?js,output" rel="noreferrer">jsbin</a>.</p>
<p>Trying to setup a simple checkbox that will cross out its label text when it is checked. For some reason handleChange is not getting fired when I use the component. Can anyone explain what I'm doing wrong?</p>
<pre class="lang-js prettyprint-override"><code>var CrossoutCheckbox = React.createClass({
getInitialState: function () {
return {
complete: (!!this.props.complete) || false
};
},
handleChange: function(){
console.log('handleChange', this.refs.complete.checked); // Never gets logged
this.setState({
complete: this.refs.complete.checked
});
},
render: function(){
var labelStyle={
'text-decoration': this.state.complete?'line-through':''
};
return (
<span>
<label style={labelStyle}>
<input
type="checkbox"
checked={this.state.complete}
ref="complete"
onChange={this.handleChange}
/>
{this.props.text}
</label>
</span>
);
}
});
</code></pre>
<p>Usage:</p>
<pre class="lang-js prettyprint-override"><code>React.renderComponent(CrossoutCheckbox({text: "Text Text", complete: false}), mountNode);
</code></pre>
<p>Solution:</p>
<p>Using checked doesn't let the underlying value change (apparently) and thus doesn't call the onChange handler. Switching to defaultChecked seems to fix this:</p>
<pre class="lang-js prettyprint-override"><code>var CrossoutCheckbox = React.createClass({
getInitialState: function () {
return {
complete: (!!this.props.complete) || false
};
},
handleChange: function(){
this.setState({
complete: !this.state.complete
});
},
render: function(){
var labelStyle={
'text-decoration': this.state.complete?'line-through':''
};
return (
<span>
<label style={labelStyle}>
<input
type="checkbox"
defaultChecked={this.state.complete}
ref="complete"
onChange={this.handleChange}
/>
{this.props.text}
</label>
</span>
);
}
});
</code></pre> | 26,615,956 | 7 | 5 | null | 2014-10-28 18:26:53.18 UTC | 21 | 2020-05-17 20:26:02.367 UTC | 2019-08-17 05:41:22.43 UTC | null | 12,216,735 | null | 866,067 | null | 1 | 200 | checkbox|onchange|reactjs | 334,476 | <p>To get the checked state of your checkbox the path would be:</p>
<pre><code>this.refs.complete.state.checked
</code></pre>
<p>The alternative is to get it from the event passed into the <code>handleChange</code> method:</p>
<pre><code>event.target.checked
</code></pre> |
9,915,941 | Opencart extremely slow loading speed | <p>I'm running Opencart 1.5.2 on my server and after importing a large number of products I got a massive speed down. I tried installing a <a href="http://www.opencart.com/index.php?route=extension/extension/info&extension_id=3444" rel="nofollow">vq mod</a> which had to speed up the site... it didn't.</p>
<p><a href="http://abvbooks.com/alba-books/" rel="nofollow">Store</a></p>
<p>I know I have some elements on the site which are relatively big but before the import it was running fine.</p> | 10,764,765 | 10 | 1 | null | 2012-03-28 21:29:50.55 UTC | 7 | 2015-09-03 02:20:11.503 UTC | 2015-07-22 20:38:42.327 UTC | null | 2,232,744 | null | 1,299,291 | null | 1 | 8 | performance|categories|opencart | 40,184 | <p>The product count in the categories is a significant source of slow page loads in opencart. There are a few places this could be calculated and you will have to get rid of all of them to notice an improvement in page load time due to this factor.</p>
<p>If you edit the <code>Catalog</code> module you can disable the product count for the navigation menu (displayed in the left column by default) by setting <code>Product Count:</code> to <code>Disabled</code>.</p>
<p>The default theme also has a product count displayed in the main menu of the site. You can find this code in <strong>catalog/controller/common/header.php</strong>:</p>
<pre><code>$product_total = $this->model_catalog_product->getTotalProducts($data);
$children_data[] = array(
'name' => $child['name'] . ' (' . $product_total . ')',
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
</code></pre>
<p>Remove or comment out any references to <code>$product_total</code>:</p>
<pre><code>//$product_total = $this->model_catalog_product->getTotalProducts($data);
$children_data[] = array(
'name' => $child['name'],
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
</code></pre>
<p>That should take care of all the references in a default opencart install, but if you are using a custom theme or modules there could be more. More generally, you can search the entire catalog/ directory for references to <code>model_catalog_product->getTotalProducts()</code>.</p>
<p>If you search for other references to <code>getTotalProducts()</code> Make sure you don't remove the references that use the product count for pagination, otherwise the pagination will not work properly. Here is an example from <strong>catalog/controller/product/search.php</strong>, a file that needs the product count to function properly.</p>
<pre><code>$pagination->total = $product_total;
</code></pre>
<p>Removing these references has led to almost a 10x speedup in page load time on my development servers in an opencart install with ~2,000 products.</p> |
9,898,698 | Convert XML to String and append to page | <p>I want to convert an xml element like this:</p>
<pre class="lang-js prettyprint-override"><code><asin>βB0013FRNKGβ</asin>β
</code></pre>
<p>to string in javascript</p>
<p>I used <code>XMLSerializer</code>:</p>
<pre class="lang-js prettyprint-override"><code>new XMLSerializer().serializeToString(xml);
</code></pre>
<p>the string only shows on alert() and in the console. On the page it just says </p>
<pre class="lang-js prettyprint-override"><code>[object Element][object Element]
</code></pre>
<p>I want to get the string.</p> | 9,898,931 | 6 | 1 | null | 2012-03-27 22:34:46.513 UTC | 11 | 2017-08-14 14:14:31.883 UTC | 2013-03-26 12:33:25.113 UTC | null | 1,047,741 | null | 1,296,726 | null | 1 | 32 | javascript|xml|xml-serialization | 107,445 | <p>You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:</p>
<pre class="lang-js prettyprint-override"><code>document.getElementById('SomeDiv').appendChild(xml);
</code></pre>
<p>and if you just want the full xml string to be displayed:</p>
<pre class="lang-js prettyprint-override"><code>var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);
</code></pre> |
10,196,344 | My app freezes but no error appears | <p>Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?</p>
<p>Can anybody help me? I just need an explanation about how use the tools.</p> | 10,196,439 | 6 | 2 | null | 2012-04-17 17:50:43.427 UTC | 10 | 2022-03-23 09:52:55.793 UTC | 2012-04-17 18:21:41.8 UTC | null | 603,977 | null | 1,013,554 | null | 1 | 36 | ios|debugging|xcode-instruments | 21,461 | <p>It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.</p>
<p><a href="https://i.stack.imgur.com/utV2J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/utV2J.png" alt="pause button"></a></p>
<p>Probably either a long loop on the main thread or a sync deadlock.</p> |
9,915,339 | How can I ignore ValueError when I try to remove an element from a list? | <p>How can I ignore the "not in list" error message if I call <code>a.remove(x)</code> when <code>x</code> is not present in list <code>a</code>?</p>
<p>This is my situation:</p>
<pre><code>>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> a.remove(9)
</code></pre> | 9,915,349 | 8 | 1 | null | 2012-03-28 20:42:54.4 UTC | 9 | 2021-11-05 13:03:05.417 UTC | 2015-08-20 00:45:50.387 UTC | null | 3,408,500 | null | 348,081 | null | 1 | 74 | python|list|error-handling|elements | 84,803 | <p>A good and thread-safe way to do this is to just try it and ignore the exception:</p>
<pre><code>try:
a.remove(10)
except ValueError:
pass # do nothing!
</code></pre> |
9,803,839 | Test with NO expected exception | <p>I want to create NUnit test to ensure that my function does not throw an exception. Is there some specific way to do it, or I should just write</p>
<pre><code>[Test]
public void noExceptionTest() {
testedFunction();
}
</code></pre>
<p>and it will succeed if no exception is thrown?</p> | 9,803,876 | 7 | 5 | null | 2012-03-21 11:35:27.6 UTC | 7 | 2021-02-16 09:13:25.943 UTC | 2018-08-30 13:38:59.58 UTC | null | 2,642,204 | null | 1,053,692 | null | 1 | 83 | c#|.net|unit-testing|testing|nunit | 61,355 | <pre><code>Assert.DoesNotThrow(() => { /* custom code block here*/});
</code></pre>
<p>OR just method</p>
<pre><code>Assert.DoesNotThrow(() => CallMymethod());
</code></pre>
<p>For more details see <a href="http://www.nunit.org/index.php?p=exceptionAsserts&r=2.5" rel="noreferrer">NUnit Exception Asserts</a></p> |
8,071,415 | How to efficiently record user typing using javascript? | <p>I'd like to be able to record then playback whatever happened in a textarea.</p>
<p>I've came across some solutions but they're not reliable, Like sending each keystroke via AJAX. In that case i'll end up having millions of rows in my DB.</p>
<p>The idea that i had in mind is to log the keystrokes to a variable in client side, updating that variable with the action, but keeping track of time between each keystoke. Also making sure that it supports deleting data as well.</p>
<p>At the end i'd send this whole variable to the db one time, then i can decode it later for playback.</p>
<p>Mind Map of what the variable would look like:</p>
<pre><code> hellooo[1.2][backspace][0.6][backspace]World![return]
Idle time __^ Removes one char __^
</code></pre>
<p>I believe that google docs is doing something like that to playback whatever users were typing.</p>
<p>Any Ideas?</p> | 8,071,701 | 3 | 0 | null | 2011-11-09 20:45:01.19 UTC | 9 | 2011-11-09 22:08:54.243 UTC | null | null | null | null | 241,654 | null | 1 | 6 | javascript | 4,223 | <p>Luckily JavaScript events already take care of all the encoding issues for you. You can just toss the whole event object that a keyup/keydown/keypress/whatever was directly into an array.</p>
<p>Each object contains:</p>
<ul>
<li>Type of event</li>
<li>Timestamp</li>
<li>What key was used (or combination of keys)</li>
<li>What was in focus</li>
<li>Some other stuff that might end up being useful.</li>
</ul>
<p>You can then just encode the array and send it off with your favourite ajax method to the server for storage.</p>
<p>So your code only needs a function that can store data. Don't use this exact function it's just for demonstration purposes.</p>
<pre><code>var handler = function (e) {
handler.data.push(e);
console.log(handler.data);
}
handler.data = [];
window.addEventListener("keyup", handler);
window.addEventListener("keydown", handler);
window.addEventListener("keypress", handler);
</code></pre>
<p>Since it's an array, they should all be in order, but in the odd event it goofs, you have timestamp data on each event (which also lets you find out the delay between events, which is <em>AWESOME</em> if you have mixed keypresses.).</p>
<p>You can then replay events however you wish to design them -- but now you don't have to invent your own spec because the lovely fokes at w3c did all the hard work for you when they designed the DOM event spec.</p> |
11,711,608 | Is there a shortcut for selecting word under cursor in Sublime Text, Atom | <p>Is there a shortcut or a command to select word under cursor in Sublime Text or Atom? I want a replacement for double-click. So I could press shortcut instead and get selection on a current word and start typing to replace it or get in quotes etc...</p> | 11,712,061 | 5 | 0 | null | 2012-07-29 17:59:02.577 UTC | 16 | 2019-04-29 07:03:19.63 UTC | 2015-06-26 00:01:49.327 UTC | null | 166,484 | null | 166,484 | null | 1 | 92 | keyboard-shortcuts|selection|sublimetext|atom-editor | 39,179 | <p><kbd>command</kbd>+<kbd>d</kbd> on OSX</p>
<p><kbd>control</kbd>+<kbd>d</kbd> on Windows/Linux</p>
<p>You can find all the default keybindings by going to <code>Preferences > Keybindings - Default</code> and perusing the list.</p> |
4,036,990 | Why are there extra pixels around my Android GridView? | <p>I have a GridView in my Android application that has a number of ImageViews in it. The space on my screen is limited and I want the images to take up as much of the available space as they can. Unfortunately, the GridView always leaves 5 pixels of empty screen space around the outside edge of the ImageViews (the space between ImageViews is set with horizontal/vertical spacing and behaves correctly). The empty space acts kind of like a margin around the ImageViews, but I can't get rid of it. Does anyone know what's causing this "border" and how I can get rid of it (or at least make it smaller)? Thanks.</p>
<p>Update: I'm creating the ImageViews by inflating an .xml file in the getView() method of my Adapter class. Here's the xml I'm inflating:</p>
<pre><code><ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FF00FF" />
</code></pre>
<p>I defined the GridView in my layout xml file like this:</p>
<pre><code><GridView
android:id="@+id/mygrid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/abutton"
android:layout_marginBottom="8dp"
android:numColumns="5" android:background="#FF0000"/>
</code></pre>
<p>Here's a screen shot of the problem. The red area in my GridView. The purple areas are my ImageViews. The image being displayed is a simple blue rectangle with a transparent center. The image is 45x45 pixels (but is only 30x30 pixels in my app - I'll worry about that later). The red border around the purple is what I am trying to eliminate.</p>
<p><img src="https://i.stack.imgur.com/6ZxDA.png" alt="alt text"></p> | 4,053,458 | 4 | 0 | null | 2010-10-27 19:35:32.823 UTC | 16 | 2013-10-25 13:55:47.293 UTC | 2010-10-28 20:39:52.393 UTC | null | 65,180 | null | 65,180 | null | 1 | 35 | android|gridview|imageview | 10,698 | <p>Thanks for the advice everyone, but it turns out the answer was somewhere that we didn't expect. The extra pixels were caused by the selector that was assigned to my GridView. I guess the default selector is a 9-patch image that has a 5 pixel border around it. When I created and assigned a 9-patch that had smaller borders (or no borders at all - just a normal .png file) the extra space in my GridView went away.</p> |
3,248,091 | F# Tail Recursive Function Example | <p>I am new to F# and was reading about tail recursive functions and was hoping someone could give me two different implementations of a function foo - one that is tail recursive and one that isn't so that I can better understand the principle.</p> | 3,248,477 | 5 | 4 | null | 2010-07-14 16:00:39.937 UTC | 16 | 2020-03-29 15:27:15.167 UTC | 2016-03-04 15:13:26.53 UTC | null | 1,243,762 | null | 215,546 | null | 1 | 41 | f#|tail-recursion | 22,616 | <p>Start with a simple task, like mapping items from 'a to 'b in a list. We want to write a function which has the signature</p>
<pre><code>val map: ('a -> 'b) -> 'a list -> 'b list
</code></pre>
<p>Where</p>
<pre><code>map (fun x -> x * 2) [1;2;3;4;5] == [2;4;6;8;10]
</code></pre>
<p>Start with <strong>non-tail recursive</strong> version:</p>
<pre><code>let rec map f = function
| [] -> []
| x::xs -> f x::map f xs
</code></pre>
<p>This isn't tail recursive because function still has work to do after making the recursive call. <code>::</code> is syntactic sugar for <code>List.Cons(f x, map f xs)</code>.</p>
<p>The function's non-recursive nature might be a little more obvious if I re-wrote the last line as <code>| x::xs -> let temp = map f xs; f x::temp</code> -- obviously its doing work after the recursive call.</p>
<p>Use an <strong>accumulator variable</strong> to make it tail recursive:</p>
<pre><code>let map f l =
let rec loop acc = function
| [] -> List.rev acc
| x::xs -> loop (f x::acc) xs
loop [] l
</code></pre>
<p>Here's we're building up a new list in a variable <code>acc</code>. Since the list gets built up in reverse, we need to reverse the output list before giving it back to the user.</p>
<p>If you're in for a little mind warp, you can use <strong>continuation passing</strong> to write the code more succinctly:</p>
<pre><code>let map f l =
let rec loop cont = function
| [] -> cont []
| x::xs -> loop ( fun acc -> cont (f x::acc) ) xs
loop id l
</code></pre>
<p>Since the call to <code>loop</code> and <code>cont</code> are the last functions called with no additional work, they're tail-recursive.</p>
<p>This works because the continuation <code>cont</code> is captured by a new continuation, which in turn is captured by another, resulting in a sort of tree-like data structure as follows:</p>
<pre><code>(fun acc -> (f 1)::acc)
((fun acc -> (f 2)::acc)
((fun acc -> (f 3)::acc)
((fun acc -> (f 4)::acc)
((fun acc -> (f 5)::acc)
(id [])))))
</code></pre>
<p>which builds up a list in-order without requiring you to reverse it.</p>
<hr>
<p>For what its worth, start writing functions in non-tail recursive way, they're easier to read and work with.</p>
<p>If you have a big list to go through, use an accumulator variable.</p>
<p>If you can't find a way to use an accumulator in a convenient way and you don't have any other options at your disposal, use continuations. I personally consider non-trivial, heavy use of continuations hard to read.</p> |
3,783,530 | python tuple to dict | <p>For the tuple, <code>t = ((1, 'a'),(2, 'b'))</code>
<code>dict(t)</code> returns <code>{1: 'a', 2: 'b'}</code></p>
<p>Is there a good way to get <code>{'a': 1, 'b': 2}</code> (keys and vals swapped)?</p>
<p>Ultimately, I want to be able to return <code>1</code> given <code>'a'</code> or <code>2</code> given <code>'b'</code>, perhaps converting to a dict is not the best way.</p> | 3,783,546 | 6 | 0 | null | 2010-09-24 01:04:04.04 UTC | 50 | 2019-03-15 09:42:45.837 UTC | 2018-06-08 19:37:18.04 UTC | null | 246,265 | null | 246,265 | null | 1 | 186 | python|dictionary|tuples | 263,629 | <p>Try:</p>
<pre><code>>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
</code></pre> |
3,487,895 | AS400 Emulator or Virtual Machine | <p>Do these exist? Can you recommend one?</p> | 3,491,892 | 8 | 5 | null | 2010-08-15 15:00:12.98 UTC | 6 | 2019-07-10 15:54:58.267 UTC | null | null | null | null | 48,545 | null | 1 | 16 | virtual-machine|ibm-midrange | 53,624 | <p>No. This is highly proprietary and I do not know of one.</p>
<p>You might find <a href="http://www.holgerscherer.de/cgi-bin/db2www/rz.nd/rz?menu=23&language=ENG" rel="noreferrer">http://www.holgerscherer.de/cgi-bin/db2www/rz.nd/rz?menu=23&language=ENG</a> interesting.</p> |
4,043,406 | How to filter by IP address in Wireshark? | <p>I tried <code>dst==192.168.1.101</code> but only get :</p>
<pre><code>Neither "dst" nor "192.168.1.101" are field or protocol names.
The following display filter isn't a valid display filter:
dst==192.168.1.101
</code></pre> | 4,043,596 | 8 | 0 | null | 2010-10-28 13:34:27.597 UTC | 49 | 2021-01-12 16:09:39.437 UTC | null | null | null | null | 417,798 | null | 1 | 294 | wireshark | 549,365 | <p>Match destination: <code>ip.dst == x.x.x.x</code></p>
<p>Match source: <code>ip.src == x.x.x.x</code></p>
<p>Match either: <code>ip.addr == x.x.x.x</code></p> |
3,779,088 | Database that can handle >500 millions rows | <p>I am looking for a database that could handle (create an index on a column in a reasonable time and provide results for <em>select queries</em> in less than 3 sec) more than 500 millions rows. Would Postgresql or Msql on low end machine (Core 2 CPU 6600, 4GB, 64 bit system, Windows VISTA) handle such a large number of rows?</p>
<p>Update: Asking this question, I am looking for information which database I should use on a low end machine in order to provide results to select questions with one or two fields specified in where clause. No joins. I need to create indices -- it can not take ages like on mysql -- to achieve sufficient performance for my select queries. This machine is a test PC to perform an experiment.</p>
<p>The table schema:</p>
<pre><code> create table mapper {
key VARCHAR(1000),
attr1 VARCHAR (100),
attr1 INT,
attr2 INT,
value VARCHAR (2000),
PRIMARY KEY (key),
INDEX (attr1),
INDEX (attr2)
}
</code></pre> | 3,779,131 | 9 | 9 | null | 2010-09-23 13:54:48.81 UTC | 16 | 2020-01-27 00:19:04.397 UTC | 2010-09-23 15:23:06.62 UTC | null | 410,823 | null | 410,823 | null | 1 | 49 | sql-server|database|postgresql | 93,676 | <p>MSSQL can handle that many rows just fine. The query time is completely dependent on a lot more factors than just simple row count.</p>
<p>For example, it's going to depend on:</p>
<ol>
<li>how many joins those queries do</li>
<li>how well your indexes are set up</li>
<li>how much ram is in the machine</li>
<li>speed and number of processors</li>
<li>type and spindle speed of hard drives </li>
<li>size of the row/amount of data returned in the query</li>
<li>Network interface speed / latency</li>
</ol>
<p>It's very easy to have a small (less than 10,000 rows) table which would take a couple minutes to execute a query against. For example, using lots of joins, functions in the where clause, and zero indexes on a Atom processor with 512MB of total ram. ;)</p>
<p>It takes a bit more work to make sure all of your indexes and foreign key relationships are good, that your queries are optimized to eliminate needless function calls and only return the data you actually need. Also, you'll need fast hardware.</p>
<p>It all boils down to how much money you want to spend, the quality of the dev team, and the size of the data rows you are dealing with.</p>
<p><strong>UPDATE</strong>
Updating due to changes in the question. </p>
<p>The amount of information here is still not enough to give a real world answer. You are going to just have to test it and adjust your database design and hardware as necessary.</p>
<p>For example, I could very easily have 1 billion rows in a table on a machine with those specs and run a "select top(1) id from tableA (nolock)" query and get an answer in milliseconds. By the same token, you can execute a "select * from tablea" query and it take a while because although the query executed quickly, transferring all of that data across the wire takes awhile.</p>
<p>Point is, you have to test. Which means, setting up the server, creating some of your tables, and populating them. Then you have to go through performance tuning to get your queries and indexes right. As part of the performance tuning you're going to uncover not only how the queries need to be restructured but also exactly what parts of the machine might need to be replaced (ie: disk, more ram, cpu, etc) based on the lock and wait types.</p>
<p>I'd highly recommend you hire (or contract) one or two DBAs to do this for you.</p> |
7,781,374 | Boost test linking | <p>I want to use <code>Boost test</code> in my project.</p>
<p>I use cmake in my project so I wrote a simple <code>CMakeList.txt</code> for wrapping it:</p>
<pre class="lang-none prettyprint-override"><code>find_package (Boost COMPONENTS unit_test_framework REQUIRED)
file(GLOB_RECURSE UnitTests_sources tests/*.cpp)
add_executable(UnitTests
${UnitTests_sources}
)
enable_testing()
ADD_TEST (UnitTests UnitTests)
</code></pre>
<p>So, cmake works fine here. The trouble becomes during compiling:</p>
<blockquote>
<p>Linking CXX executable ../../bin/UnitTests</p>
<p>/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.1/../../../../lib/crt1.o: In
function <code>_start': (.text+0x20): undefined reference to</code>main'
collect2: ld returned 1 exit status</p>
</blockquote>
<p>Here is the only file in <strong>tests</strong> folder (<code>LogManagerTest.cpp</code>):</p>
<pre><code>#include "Utils/LogManager.hpp"
#include <boost/test/unit_test.hpp>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE LogManager
BOOST_AUTO_TEST_CASE(LogManagerCase)
{
BOOST_REQUIRE(true);
/*LogManager manager;
manager.Initialize();
manager.Deinitialize();*/
}
</code></pre>
<p>What's wrong here?</p> | 7,781,393 | 4 | 1 | null | 2011-10-15 23:29:55.367 UTC | 12 | 2015-10-31 01:38:07.08 UTC | 2015-10-31 01:38:07.08 UTC | null | 56,083 | null | 87,152 | null | 1 | 21 | c++|unit-testing|boost|linker|boost-test | 18,765 | <p>Add </p>
<pre><code>ADD_DEFINITIONS(-DBOOST_TEST_DYN_LINK)
</code></pre>
<p>to your CMakeLists.txt so it will automatically generate a main() for you.
Also, </p>
<pre><code>#define BOOST_TEST_MODULE xxx
</code></pre>
<p>must be defined before you include unit_test.hpp.</p>
<p>You can find more information and options on:
<a href="http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/compilation.html">http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/compilation.html</a></p> |
8,011,401 | What is the easiest way to find the LINQ statement for a SQL statement | <p>I am a SQL Server DBA for a company that sells an ASP.NET MVC3 application that uses LINQ and Entity Framework 4 for all database access. When I find an inefficient query in my SQL Server's plan cache that was generated by LINQ, I would like to be able to find that LINQ statement in the source code so that I can optimize it. What is the best way to find the LINQ that generated a given SQL statement?</p>
<p>For example, is there any way to put an entry in a config file or decorate the code somehow so that the class and method name or the LINQ statement itself are included as comments in the generated SQL?</p> | 8,011,785 | 5 | 4 | null | 2011-11-04 15:09:16.097 UTC | 11 | 2011-11-04 16:08:23.773 UTC | null | null | null | null | 459,562 | null | 1 | 35 | sql|linq|entity-framework | 680 | <p>The commercial tools <a href="http://www.ormprofiler.com" rel="nofollow">ORM Profiler</a>, <a href="http://efprof.com" rel="nofollow">Entity Framework Profiler</a> or <a href="http://www.huagati.com/L2SProfiler/" rel="nofollow">Hugati Query Profiler</a> will both give you a stack trace for the methods which generated the SQL. That makes it fairly easy to find the LINQ in code, though it isn't displayed directly.</p>
<p>These tools also have the advantage that they make it easy to find inefficient queries amongst the many other SQL statements executed by the app.</p> |
8,278,981 | Datatables on-the-fly resizing | <p>I'm using the marvellous DataTables jQuery plug-in; <a href="http://datatables.net/" rel="noreferrer">http://datatables.net/</a> Added the FixedColumns and KeyTable extras.</p>
<p>Now the table does resize prettily when the window size is changed. However, the containing div of the table can also be resized in width by a jQuery animation, and I haven't found a way to resize the table with it-- it just stays stagnant in its original width. Only if I change the div width in the code before pageload, the table is resized correctly.</p>
<p>How can I make the DataTable resize on-the-fly according to both the window width and the containing div width? Thanks in advance! :-)</p> | 8,280,290 | 12 | 0 | null | 2011-11-26 14:12:43.577 UTC | 23 | 2019-06-20 20:05:06.367 UTC | null | null | null | null | 951,402 | null | 1 | 65 | javascript|jquery|datatables | 143,449 | <p>What is happening is that DataTables is setting the CSS width of the table when it is initialised to a calculated value - that value is in pixels, hence why it won't resize with your dragging. The reason it does this is to stop the table and the columns (the column widths are also set) jumping around in width when you change pagination.</p>
<p>What you can do to stop this behaviour in DataTables is set the <a href="http://datatables.net/reference/option/autoWidth" rel="noreferrer">autoWidth</a> parameter to false.</p>
<pre class="lang-js prettyprint-override"><code>$('#example').dataTable( {
"autoWidth": false
} );
</code></pre>
<p>That will stop DataTables adding its calculated widths to the table, leaving your (presumably) width:100% alone and allowing it to resize. Adding a relative width to the columns would also help stop the columns bouncing.</p>
<p>One other option that is built into DataTables is to set the sScrollX option to enable scrolling, as DataTables will set the table to be 100% width of the scrolling container. But you might not want scrolling.</p>
<p>The prefect solution would be if I could get the CSS width of the table (assuming one is applied - i.e. 100%), but without parsing the stylesheets, I don't see a way of doing that (i.e. basically I want $().css('width') to return the value from the stylesheet, not the pixel calculated value).</p> |
4,199,504 | What is the best way to compare dates in Perl? | <p>I need to read 2 dates and compare them.</p>
<p>One date is the current_date (year,month,date)
the other is determined by the business logic.
I then need to compare the 2 dates and see if one is before the other.</p>
<p>How can I do the same in Perl?</p>
<p>I am searching for good documentation, but I am finding so many Date modules in Perl. Don't know which one is appropriate for it.</p> | 4,199,534 | 3 | 1 | null | 2010-11-16 22:05:30.24 UTC | 2 | 2015-03-30 11:51:31.66 UTC | 2010-11-16 22:10:48.06 UTC | null | 40,725 | null | 211,528 | null | 1 | 14 | perl | 50,592 | <p>One of the most popular date modules is <a href="https://metacpan.org/pod/DateTime" rel="noreferrer">DateTime</a> which will handle all of the corner cases and other issues surrounding date math.</p>
<p>This link is a FAQ for DateTime which may help you get started: </p>
<ul>
<li><a href="http://datetime.perl.org/wiki/datetime/page/FAQ" rel="noreferrer">http://datetime.perl.org/wiki/datetime/page/FAQ</a></li>
</ul>
<p>The way the <code>DateTime</code> module works is that you convert your dates (which will presumably be strings) into <code>DateTime</code> objects, which you can then compare using one of several <code>DateTime</code> methods. </p>
<p>In the examples below, <code>$dt1</code> and <code>$dt2</code> are <code>DateTime</code> objects. </p>
<p><code>$days</code> is the delta between the two dates:</p>
<pre><code>my $days = $dt1->delta_days($dt2)->delta_days;
</code></pre>
<p><code>$cmp</code> is -1, 0 or 1, depending on whether <code>$dt1</code> is less than, equal to, or more than <code>$dt2</code>. </p>
<pre><code>my $cmp = DateTime->compare($dt1, $dt2);
</code></pre> |
4,603,787 | Setting MSMQ permissions for a private queue created by a different user | <p>The person who was previously using my PC at work set up a private MSMQ that I need to access. They have since left the bank but the permissions remain and I can't access the queue or give myself edit permission to remove the restriction. </p>
<p>I am an admin on this machine now so I'm assuming there's some way for me to change things..Been searching high and low but most of what I find is related to doing things through scripts.</p>
<p>Any help appreciated,</p>
<p>thanks</p> | 4,603,853 | 4 | 0 | null | 2011-01-05 12:02:06.44 UTC | 1 | 2021-05-14 09:16:03.077 UTC | null | null | null | null | 546,004 | null | 1 | 23 | permissions|msmq|admin | 39,766 | <p>Right click on Your Queue -> Properties -> Security -> Goto Advanced and modify permission for groups.</p> |
4,735,623 | UILabel layer cornerRadius negatively impacting performance | <p>I've created a document view which displays the page number in the corner. The page number is a uilabel with a semi-transparent background colour, and has a corner radius (using the <code>cornerRadius</code> property of the <code>view</code>'s <code>layer</code>). I've positioned this above a <code>UIScrollView</code>. However, this makes scrolling jerky. If I remove the <code>cornerRadius</code>, performance is good. Is there anything I can do about this? What would be a better solution? It seems to have been achieved in the <code>UIWebView</code> without any performance issues.</p> | 6,254,531 | 4 | 0 | null | 2011-01-19 13:11:34.593 UTC | 50 | 2016-03-11 22:29:15.307 UTC | 2012-05-23 14:56:51.7 UTC | null | 893,863 | null | 392,986 | null | 1 | 46 | ios|uiview|uilabel|calayer | 33,470 | <p>For labels, or views with rounded corners and or background colors and shadows on scrolling views the solution is pretty simple:</p>
<p>The biggest issue is from the masksToBounds layer option. This appears to tax performance significantly, however the label seems to need this ON to mask the background color to rounded corners. So to get around this you need to set the labels layer background color instead and switch off masksToBounds.</p>
<p>The second issue is that the default behavior is to redraw the view whenever possible which is totally unnecessary with static or slow changing items on scrolling views. Here we simply set layer.shouldRasterize = YES. This will allow CA to 'cache' a rasterized version of the view for quick drawing when scrolling (presumably with hardware acceleration).</p>
<p>You need to make sure your layer has an alpha channel otherwise rasterizing will affect the drawing of rounded corners. I've never had a problem as I have alpha set for my background colors, but you may need to check in your situation.</p>
<p>Here is a sample UILabel set up to work nicely on a scollview:</p>
<pre><code>UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(4, 4, 40.0, 24.0)];
lbl.font = [UIFont fontWithName:@"Helvetica" size:14.0];
lbl.textAlignment = UITextAlignmentRight;
lbl.text = @"Hello World";
// Must set the label background to clear so the layer background shows
lbl.backgroundColor = [UIColor clearColor];
// Set UILabel.layer.backgroundColor not UILabel.backgroundColor otherwise the background is not masked to the rounded border.
lbl.layer.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;
lbl.layer.cornerRadius = 8;
lbl.layer.borderColor = [UIColor blackColor].CGColor;
lbl.layer.borderWidth = 1;
// Huge change in performance by explicitly setting the below (even though default is supposedly NO)
lbl.layer.masksToBounds = NO;
// Performance improvement here depends on the size of your view
lbl.layer.shouldRasterize = YES;
lbl.layer.rasterizationScale = [UIScreen mainScreen].scale;
// self here is the child view in the scroll view
[self addSubview:lbl];
[lbl release];
</code></pre>
<p>I can fill the iPad 1 screen with views like this and still scroll smoothly :)</p> |
4,735,856 | Difference between a statement and a query in SQL | <p>I still live in this ambiguity: conceptually what's the difference between a <strong>statement</strong> and a <strong>query</strong> in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!</p>
<p><strong>ADDITIONALLY:</strong> How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (<code>;</code>)? Who already replied can edit his answer. Many thanks!</p> | 4,735,902 | 6 | 0 | null | 2011-01-19 13:37:02.723 UTC | 13 | 2016-01-08 11:55:31.033 UTC | 2016-01-08 11:55:31.033 UTC | null | 113,858 | null | 505,893 | null | 1 | 52 | sql|database|terminology | 50,028 | <p>A <em>statement</em> is any text that the database engine recognizes as a valid command. As of <code>SQL-92</code>:</p>
<blockquote>
<p>An SQL-statement is a string of characters that conforms to the format and syntax rules specified in this international standard.</p>
</blockquote>
<p>A <em>query</em> is a statement that returns a recordset (possibly empty).</p>
<blockquote>
<p>How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!</p>
</blockquote>
<p>A series of <code>SQL</code> statements sent to the server at once is called a <em>batch</em>.</p>
<p>Not all <code>SQL</code> engines required the statements in a batch to be semicolon delimited. <code>SQL Server</code>, for instance, generally does not and breaks the statements based on context. <code>CTE</code> statements starting with <code>WITH</code> are a notable exception.</p> |
4,563,704 | C# - how do you stop a timer? | <p>I know it sounds stupid, but I've tried everything to stop a timer, but the timer won't stop. I'm working on a game and i would appreciate if someone could tell me how to stop a timer.</p> | 4,563,738 | 7 | 4 | null | 2010-12-30 15:11:00.913 UTC | 11 | 2021-04-21 07:22:08.873 UTC | 2010-12-30 15:20:37.83 UTC | null | 8,976 | null | 558,410 | null | 1 | 82 | c#|.net|timer | 113,104 | <p>If you are using <code>System.Timers.Timer</code> stopping is performed by one of the options:</p>
<pre><code>//options 1
timer.Enabled = false
//option 2
timer.Stop()
</code></pre>
<p>if you are using <code>System.Threading.Timer</code>, use this method</p>
<pre><code>timer.Change(Timeout.Infinite , Timeout.Infinite)
</code></pre>
<p>if you are using <code>System.Windows.Forms.Timer</code>, use this method</p>
<pre><code>timer.Stop();
</code></pre> |
4,529,019 | How to use the .NET Timer class to trigger an event at a specific time? | <p>I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and when the time is equal to 4:00pm run the event. That works. But I'm wondering if there's a way to just get the callback once at 4:00pm and not having to keep checking.</p> | 4,529,050 | 9 | 0 | null | 2010-12-25 01:51:36.987 UTC | 23 | 2021-11-12 10:43:20.91 UTC | 2016-12-17 04:05:11.57 UTC | null | 5,541,055 | null | 270,589 | null | 1 | 55 | c#|.net|timer | 84,646 | <p>How about something like this, using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx" rel="noreferrer"><code>System.Threading.Timer</code></a> class?</p>
<pre><code>var t = new Timer(TimerCallback);
// Figure how much time until 4:00
DateTime now = DateTime.Now;
DateTime fourOClock = DateTime.Today.AddHours(16.0);
// If it's already past 4:00, wait until 4:00 tomorrow
if (now > fourOClock)
{
fourOClock = fourOClock.AddDays(1.0);
}
int msUntilFour = (int)((fourOClock - now).TotalMilliseconds);
// Set the timer to elapse only once, at 4:00.
t.Change(msUntilFour, Timeout.Infinite);
</code></pre>
<p>Note that if you use a <code>System.Threading.Timer</code>, the callback specified by <code>TimerCallback</code> will be executed on a thread pool (non-UI) threadβso if you're planning on doing something with your UI at 4:00, you'll have to marshal the code appropriately (e.g., using <code>Control.Invoke</code> in a Windows Forms app, or <code>Dispatcher.Invoke</code> in a WPF app).</p> |
4,802,038 | Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations | <p>I came across this question:
<strong>Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations.</strong></p>
<p>I initially thought of using a min-heap data structure which has O(1) complexity for a get_min(). But push_rear() and pop_front() would be O(log(n)).</p>
<p>Does anyone know what would be the best way to implement such a queue which has O(1) push(), pop() and min()?</p>
<p>I googled about this, and wanted to point out this <a href="http://groups.google.com/group/algogeeks/browse_thread/thread/157129d83d284e07?pli=1">Algorithm Geeks thread</a>. But it seems that none of the solutions follow constant time rule for all 3 methods: push(), pop() and min().</p>
<p>Thanks for all the suggestions.</p> | 4,802,260 | 11 | 8 | null | 2011-01-26 06:54:32.42 UTC | 66 | 2020-07-07 18:28:16.817 UTC | 2013-05-09 15:50:33.477 UTC | null | 501,557 | null | 360,844 | null | 1 | 82 | algorithm|data-structures|queue|big-o | 29,795 | <p>You can implement a stack with O(1) pop(), push() and get_min(): just store the current minimum together with each element. So, for example, the stack <code>[4,2,5,1]</code> (1 on top) becomes <code>[(4,4), (2,2), (5,2), (1,1)]</code>.</p>
<p>Then you can <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15750-s03/www/amortized-analysis.txt" rel="noreferrer">use two stacks to implement the queue</a>. Push to one stack, pop from another one; if the second stack is empty during the pop, move all elements from the first stack to the second one.</p>
<p>E.g for a <code>pop</code> request, moving all the elements from first stack <code>[(4,4), (2,2), (5,2), (1,1)]</code>, the second stack would be <code>[(1,1), (5,1), (2,1), (4,1)]</code>. and now return top element from second stack.</p>
<p>To find the minimum element of the queue, look at the smallest two elements of the individual min-stacks, then take the minimum of those two values. (Of course, there's some extra logic here is case one of the stacks is empty, but that's not too hard to work around).</p>
<p>It will have O(1) <code>get_min()</code> and <code>push()</code> and amortized O(1) <code>pop()</code>. </p> |
4,051,088 | Get DOS path instead of Windows path | <p>In a DOS window, how can I get the full DOS name/short name of the directory I am in?</p>
<p>For example, if I am in the directory <code>C:\Program Files\Java\jdk1.6.0_22</code>, I want to display it's short name <code>C:\PROGRA~1\Java\JDK16~1.0_2</code>.</p>
<p>I know running <code>dir /x</code> will give me the short names of files/directories in the current directory but I haven't been able to find a way to display the full path of the current directory in short name format. I'm having to work my way through the path from the root, directory by directory, running <code>dir /x</code> in each.</p>
<p>I'm sure there is an easier way to do this?</p> | 4,051,190 | 12 | 5 | null | 2010-10-29 10:46:04.443 UTC | 41 | 2021-04-14 19:38:03.32 UTC | 2017-10-10 09:42:41.793 UTC | null | 452,775 | null | 355,620 | null | 1 | 108 | windows|command-line | 187,886 | <pre><code>for %I in (.) do echo %~sI
</code></pre>
<p>Any simpler way?</p> |
14,490,182 | Repeating a user-defined function using replicate() or sapply() | <p>I have defined a custom function, like this:</p>
<pre><code>my.fun = function() {
for (i in 1:1000) {
...
for (j in 1:20) {
...
}
}
return(output)
}
</code></pre>
<p>which returns an output matrix, <code>output</code>, composed by 1000 rows and 20 columns.</p>
<p>What I need to do is to repeat the function say 5 times and to store the five <code>output</code> results into a brand new matrix, say <code>final</code>, but <em>without using another for-loop</em> (this for making the code clearer, and also because in a second moment I would like to try to parallelize these additional 5 repetitions). </p>
<p>Hence <code>final</code> should be a matrix with 5000 rows and 20 columns (the rationale behind these 5 repetitions is that within the two for-loops I use, among other functions, <code>sample</code>). </p>
<p>I tried to use <code>final <- replicate(5, my.fun())</code>, which correctly computes the five replications, but then I have to "manually" put the elements into a brand new 5000 x 20 matrix.. is there a more elgant way to do so? (maybe using <code>sapply()</code>?). Many thanks</p> | 14,490,315 | 4 | 0 | null | 2013-01-23 21:59:20.697 UTC | 9 | 2015-05-10 07:30:45.1 UTC | null | null | null | null | 1,662,648 | null | 1 | 10 | r|sapply|replicate | 23,254 | <p>As is stands you probably have an array with three dimensions. If you wanted to have a list you would have added simplify=FALSE. Try this:</p>
<pre><code>do.call( rbind, replicate(5, my.fun(), simplify=FALSE ) )
</code></pre>
<p>Or you can use <code>aperm</code> in the case where "final" is still an array:</p>
<pre><code>fun <- function() matrix(1:10, 2,5)
final <- replicate( 2, fun() )
> final
, , 1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
, , 2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> t( matrix(aperm(final, c(2,1,3)), 5,4) )
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
[3,] 1 3 5 7 9
[4,] 2 4 6 8 10
</code></pre>
<p>There may be more economical matrix operations. I just haven't discovered one yet.</p> |
14,507,542 | WebRTC Live Audio Streaming/Broadcast | <p>I'm trying to get my head round WebRTC. I need to be able to capture and stream live audio through a web browser.</p>
<p>I'm just having difficulty finding the code examples that I can understand or is up-to-date. If anyone could help me with just first capturing and playing audio in the same browser with HTML5/WebRTC I think that would help me get started and along my way.</p>
<p>Note: I'm only concerned about getting this to work in Chrome (or Chrome Canary for that matter!).</p>
<p>Thanks for any help!</p> | 14,513,672 | 2 | 0 | null | 2013-01-24 17:49:09.95 UTC | 15 | 2013-10-03 09:30:03.897 UTC | null | null | null | null | 1,565,497 | null | 1 | 11 | html|html5-audio|webrtc | 37,775 | <p>The <a href="http://www.html5rocks.com/en/tutorials/webrtc/basics/" rel="nofollow noreferrer">HTML5 Rocks article on WebRTC</a> is probably the best intro article that explains everything in layman's terms.</p>
<p>For simply capturing local video/audio, you'll want to focus on the MediaStream API (i.e., getUserMedia). Once you get that working, then you'll need to start looking into the RTCPeerConnection API.</p>
<p>The client-side code for the RTCPeerConnection API is pretty straightforward, but the server-side code required for signalling (i.e., establishing a peer-to-peer connection) can be tricky.</p>
<p>I ended up coding my own server-side solution in PHP, but to do so took me about three weeks of banging my head against the wall (i.e., trying to decipher the <a href="https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-17" rel="nofollow noreferrer">WebSocket specs</a>) to get it to work properly.
If you'd like to see actual code, I can post some of my working code.</p>
<p>If you're up for the challenge, I recommend trying to code the server-side script yourself, but otherwise, I would look into WebSocket libraries like Socket.IO, which do all the tricky server-side stuff for you.</p> |
14,542,238 | Treat a span as input element | <p>Is it possible to use a span to trigger input?</p>
<p>e.g. </p>
<pre><code><div class='btn'>
<span type="submit" aria-hidden="true" data-icon="&#xe000;"></span>
</div>
</code></pre>
<p>I may be missing something blindingly obvious but I basically just want to use an icon font as a send button.</p>
<p>Thanks!</p> | 14,542,265 | 3 | 4 | null | 2013-01-26 22:30:12.09 UTC | 1 | 2016-04-08 03:59:28.187 UTC | null | null | null | null | 664,806 | null | 1 | 14 | html|css|forms|icons | 46,465 | <p>You can't put <code>type="submit"</code> , but you can execute some Javascript codes when you click on it.</p>
<p><strong>JQuery</strong></p>
<pre><code><span id="mySpan"> </span>
$("#mySpan").click(function(){
//stuff here
});
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code><span id="mySpan" onclick="MyClick()"> </span>
function MyClick()
{
//stuff here
}
</code></pre>
<p><strong>SPAN working as a Submit Button</strong></p>
<pre><code><input type="text" id="usernameInputField />
<input type="email" id="emalInputField />
<span id="mySpan" onclick="Register()"></span>
</code></pre>
<p>Now in Javascript..</p>
<pre><code>function Register()
{
//First you need to do some validation
var username = document.getElementById("usernameInputField").value;
var email = document.getElementById("emailInputField").value;
//Password, Gender, etc...
//Then start doing your validation the way you like it...
/*if(password.length<6)
{
alert("Password is too short");
return false;
}
*/
//Then when everything is valid, Post to the Server
//This is a PHP Post Call
$.post("Register.php",{ username:username,email:email } ,function(data) {
//more codes
});
}
</code></pre> |
14,704,105 | Search text in stored procedure in SQL Server | <p>I want to search a text from all my database stored procedures. I use the below SQL:</p>
<pre><code>SELECT DISTINCT
o.name AS Object_Name,
o.type_desc
FROM sys.sql_modules m
INNER JOIN
sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like '%[ABD]%';
</code></pre>
<p>I want to search for <code>[ABD]</code> in all stored procedures including square brackets, but it's not giving the proper result. How can I change my query to achieve this?</p> | 14,704,157 | 25 | 2 | null | 2013-02-05 09:30:39.06 UTC | 259 | 2022-09-21 09:35:22.163 UTC | 2021-06-28 06:43:34.267 UTC | null | 4,390,133 | null | 815,244 | null | 1 | 1,021 | sql|sql-server|stored-procedures | 2,017,191 | <p>Escape the square brackets:</p>
<pre><code>...
WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'
</code></pre>
<p>Then the square brackets will be treated as a string literals not as wild cards.</p> |
7,337,882 | What is the difference between SQLite integer data types like int, integer, bigint, etc.? | <p><strong>What is the difference between integer data types in sqlite?</strong></p>
<p>INT<br>
INTEGER<br>
TINYINT<br>
SMALLINT<br>
MEDIUMINT<br>
BIGINT<br>
UNSIGNED BIG INT<br>
INT2<br>
INT8 </p>
<p>Which one can store 32-bit integers and which one can store 64-bit values? Is there support for 128-bit?</p>
<p>I find integer data size a little confusing for now, INTEGER for example can store up to 64-bit signed integers, but values may occupy only 32 bits on disk. </p>
<p>Calling <code>sqlite3_column_int</code> on an INTEGER column will work only if the value stored is less that int32 max value, how will it behave if higher?</p> | 7,337,945 | 1 | 1 | null | 2011-09-07 17:16:57.317 UTC | 11 | 2017-03-20 15:47:24.79 UTC | 2017-03-20 15:47:24.79 UTC | null | 1,781,026 | null | 572,586 | null | 1 | 65 | sqlite | 87,525 | <p>From the SQLite3 documentation:</p>
<p><a href="http://www.sqlite.org/datatype3.html" rel="noreferrer">http://www.sqlite.org/datatype3.html</a></p>
<blockquote>
<p>Most SQL database engines (every SQL database engine other than
SQLite, as far as we know) uses static, rigid typing. With static
typing, the datatype of a value is determined by its container - the
particular column in which the value is stored.</p>
<p>SQLite uses a more general dynamic type system. In SQLite, the
datatype of a value is associated with the value itself, not with its
container. The dynamic type system of SQLite is backwards compatible
with the more common static type systems of other database engines in
the sense that SQL statement that work on statically typed databases
should work the same way in SQLite. However, the dynamic typing in
SQLite allows it to do things which are not possible in traditional
rigidly typed databases.</p>
</blockquote>
<p>So in MS Sql Server (for example), an "int" == "integer" == 4 bytes/32 bits.</p>
<p>In contrast, a SqlLite "integer" can hold whatever you put into it: from a 1-byte char to an 8-byte long long.</p>
<p>The above link lists all types, and gives more details about Sqlite "affinity".</p>
<p>The C/C++ interface you're referring to must work with strongly typed languages.</p>
<p>So there are two APIs: sqlite3_column_int(), max 4-byte; and sqlite3_column_int64()</p>
<p><a href="http://www.sqlite.org/capi3ref.html#sqlite3_int64" rel="noreferrer">http://www.sqlite.org/capi3ref.html#sqlite3_int64</a></p> |
9,347,633 | How to implement "Press Any Key To Exit" | <p>Here is a simple code in C++:</p>
<pre><code>cout << "Press Any Key To Exit...";
</code></pre>
<p>What is the code for closing program when user presses any button on keyboard. What should I write after above code?
I know I can use cin.ignore(); and if user presses Enter the program will close, But my target is any key.</p>
<p>How to do that?</p> | 9,347,669 | 4 | 0 | null | 2012-02-19 07:54:28.163 UTC | 2 | 2019-07-04 03:39:57.28 UTC | 2019-07-04 03:39:57.28 UTC | null | 366,904 | null | 709,507 | null | 1 | 2 | c++ | 65,507 | <p>You can use the ncurses library to do this. The downside to this solution is that you won't be able to use cout for outputting anymore.</p>
<pre><code>#include <ncurses.h>
int main()
{
initscr();
printw("Press Any Key To Exit...");
getch();
endwin();
}
</code></pre>
<p>Be sure to <code>-lncurses</code> when compiling</p> |
53,947,928 | Enforce items at beginning and end of list | <p>How can I modify this list so that all <code>p's</code> appear at the beginning, the <code>q's</code> at the end, and the values in between are sorted alphabetically?</p>
<pre><code>l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
</code></pre>
<p>So I would like to have:</p>
<pre><code>['p','p','a','b','c','d','f','g','n','t','z','q','q']
</code></pre> | 53,947,953 | 8 | 0 | null | 2018-12-27 16:19:12.657 UTC | 7 | 2020-04-15 17:22:50.893 UTC | 2020-04-15 17:22:50.893 UTC | null | 9,698,684 | user10652346 | null | null | 1 | 29 | python|list|sorting | 1,738 | <p>You can use <a href="https://docs.python.org/3/howto/sorting.html" rel="noreferrer"><code>sorted</code></a> with the following <code>key</code>:</p>
<pre><code>sorted(l, key = lambda s: (s!='p', s=='q', s))
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
</code></pre>
<hr>
<p><b>Explanation </b></p>
<p>To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the <code>lambda</code> function defined in the <code>key</code> argument prior to making comparisons:</p>
<pre><code>t = [(s!='p', s=='q', s) for s in pl]
print(t)
[(True, False, 'f'),
(True, False, 'g'),
(False, False, 'p'),
(True, False, 'a'),
(False, False, 'p'),
(True, False, 'c'),
(True, False, 'b'),
(True, True, 'q'),
(True, False, 'z'),
(True, False, 'n'),
(True, False, 'd'),
(True, False, 't'),
(True, True, 'q')]
</code></pre>
<p>This will then be the <code>key</code> to be used to sort the items in the list, as mentioned in the <a href="https://docs.python.org/3/howto/sorting.html" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. </p>
</blockquote>
<p>So taking into account that <code>False = 0</code> and <code>True = 1</code>, when this list of tuples is sorted the result will be the following:</p>
<pre><code>sorted(t)
[(False, False, 'p'),
(False, False, 'p'),
(True, False, 'a'),
(True, False, 'b'),
(True, False, 'c'),
(True, False, 'd'),
(True, False, 'f'),
(True, False, 'g'),
(True, False, 'n'),
(True, False, 't'),
(True, False, 'z'),
(True, True, 'q'),
(True, True, 'q')]
</code></pre> |
45,777,770 | Catch all routes for Flask | <p>I'm using Flask with React. I'd like to create a catch all route similar to something like this (although this doesn't work):</p>
<pre><code>@app.route('*')
def get():
return render_template('index.html')
</code></pre>
<p>Since my app will use React and it's using the index.html to mount my React components, I'd like for every route request to point to my index.html page in templates. Is there a way to do this (or is using a redirect the best way)?</p> | 45,777,812 | 1 | 0 | null | 2017-08-20 01:49:32.153 UTC | 8 | 2020-05-27 00:20:15.7 UTC | null | null | null | null | 2,778,483 | null | 1 | 53 | python|flask | 35,866 | <p>You can follow this guideline: <a href="https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations" rel="noreferrer">https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations</a></p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
</code></pre> |
53,605,342 | How to make some columns align left and some column align center in React Table - React | <p>Hello Stack overflow members</p>
<p>This is array for the column headers. I want column 1 to column 5 left align (all the header, sub header and table data cells of column 1 to column 5 to be left aligned) while I I want column 6 to column 8 to be centre aligned (all the header, sub header and table data cells of column 1 to column 5 to be centre aligned). Please help me to solve this as I can only make either all columns center or all columns left aligned.</p>
<p><strong>I want to implement this particular style on column 6 to 8 header as shown in this image.</strong> <a href="https://i.stack.imgur.com/EfrqH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EfrqH.png" alt="Image"></a>.</p>
<p><strong>If you can help me, please provide a demo on CodeSandbox</strong></p>
<p>This is my Header Data</p>
<pre><code>const columns = [
{
Header: 'Column 1',
columns: [
{
Header: 'S Column 1',
accessor: 'firstName'
}
]
},
{
Header: 'Column 2',
columns: [
{
Header: 'S Column 2',
accessor: 'firstName'
}
]
},
{
Header: 'Column 3',
columns: [
{
Header: 'S Column 3',
accessor: 'firstName'
}
]
},
{
Header: 'Column 4',
columns: [
{
Header: 'S column 4',
accessor: 'firstName'
}
]
},
{
Header: 'Column 5',
columns: [
{
Header: 'S column 5',
accessor: 'firstName'
}
]
},
{
Header: 'Column 6',
columns: [
{
Header: 'S column 6a',
accessor: 'firstName'
},
{
Header: 'S column 6b',
accessor: 'firstName'
},
{
Header: 'S column 6c',
accessor: 'firstName'
},
{
Header: 'S column 6d',
accessor: 'firstName'
}
]
},
{
Header: 'Column 7',
columns: [
{
Header: 'S column 7',
accessor: 'firstName'
}
]
},
{
Header: 'Column 8',
columns: [
{
Header: 'S Column 8a',
accessor: 'firstName'
},
{
Header: 'S Column 8b',
accessor: 'firstName'
},
{
Header: 'S Column 8c',
accessor: 'firstName'
},
{
Header: 'S Column 8d',
accessor: 'firstName'
}
]
},
];
</code></pre> | 53,605,924 | 5 | 0 | null | 2018-12-04 03:38:21.01 UTC | 2 | 2022-08-30 06:54:14.957 UTC | 2018-12-04 04:52:49.793 UTC | null | 9,303,401 | user10374052 | null | null | 1 | 20 | javascript|html|css|reactjs|react-table | 57,362 | <p><strong>Method 1:</strong></p>
<p>Something like this should do the job</p>
<pre><code>columns: [
{
accessor: "firstName",
Header: () => (
<div
style={{
textAlign:"right"
}}
>S Column 1</div>)
},
</code></pre>
<blockquote>
<p>If you can help me, please provide a demo on CodeSandbox</p>
</blockquote>
<p>Play <a href="https://codesandbox.io/s/64ky3q4zqk" rel="noreferrer">here</a></p>
<p><a href="https://i.stack.imgur.com/h5e9G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h5e9G.png" alt="enter image description here" /></a></p>
<p><strong>Update after OP comment</strong></p>
<blockquote>
<p>but for columns which will be centre aligned , their sub cell data
will also be centre aligned</p>
</blockquote>
<p>Manipulate cell styles like this</p>
<pre><code>Cell: row => <div style={{ textAlign: "center" }}>{row.value}</div>
</code></pre>
<p>Play it <a href="https://codesandbox.io/s/64ky3q4zqk" rel="noreferrer">here</a></p>
<p><a href="https://i.stack.imgur.com/ZgVj3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZgVj3.png" alt="enter image description here" /></a></p>
<p><strong>Method 2:</strong></p>
<p>Use can use the <code>headerClassName</code> and specify a class name, in that class you can specify the rule <code>text-align:center</code></p>
<p>So the code will look like</p>
<pre><code>const columns = [{
Header: 'Column 5',
accessor: 'name',
headerClassName: 'your-class-name'
},
{
......
}
]
</code></pre>
<p><strong>Method 3:</strong></p>
<p>If you have lot of headers, adding headerClassName in all headers is a pain. In that case you can set the class name in <code>ReactTableDefaults</code></p>
<pre><code>import ReactTable, {ReactTableDefaults} from 'react-table';
const columnDefaults = {...ReactTableDefaults.column, headerClassName: 'text-left-classname'}
</code></pre>
<p>and in the ReactTable, use like this</p>
<pre><code><ReactTable
...
...
column = { columnDefaults }
/>
</code></pre>
<blockquote>
<p>Note: if you are using bootstrap you can assign the inbuilt class <code>text-center</code> to <code>headerClassName</code></p>
</blockquote> |
39,287,308 | WooCommerce - Remove downloads from menu in my account page | <p>I would like to remove downloads menu from <strong>my account page</strong>.</p>
<p>How can I do this? Is it any hook to remove a specific item from the menu? </p>
<p>Thanks.</p> | 39,287,381 | 3 | 0 | null | 2016-09-02 08:04:03.813 UTC | 21 | 2022-04-13 11:52:57.137 UTC | 2022-04-13 11:52:57.137 UTC | null | 1,117,368 | null | 6,329,707 | null | 1 | 59 | php|wordpress|woocommerce|settings|account | 69,904 | <p>Go to <code>WooCommerce > Settings > Advanced</code> and remove the entry for Downloads in the <strong>Account endpoints</strong> section, just leave it blank. And the menu will not be visible anymore.</p>
<p><a href="https://i.stack.imgur.com/4zVCd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4zVCd.png" alt="remove downloads link"></a></p> |
20,913,936 | How to use intercept-url pattern and access? | <p>I am using Spring security but i don't understand very well how intercept-url works. Here is my spring security config file :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
<!-- configuration des urls -->
<security:http auto-config="true">
<security:intercept-url pattern="/*" access="ROLE_USER" />
<security:form-login/>
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="authenticationProvider" />
</security:authentication-manager>
<bean id="authenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="userDetailsService"
class="com.nexthome.app.security.UserDetailsServiceImpl" />
</beans>
</code></pre>
<p>With this configuration, i cannot access without being authenticated. So when accessing the url <code>http://localhost:8080/nexthome</code> displays a spring login form (<code>http://localhost:8080/nexthome/spring_security_login</code>).
But when i change the to . I am able to access to <code>http://localhost:8080/nexthome/user/login</code> without login. </p>
<p>My aim is to protected some url :</p>
<pre><code>http://localhost:8080/nexthome all people must access
http://localhost:8080/nexthome/login all people must access ( how to display spring login form when trying to access the url?)
http://localhost:8080/nexthome/logout access to ROLE_USER and ROLE_ADMIN
</code></pre>
<p>Thanks for your help</p> | 20,930,408 | 3 | 0 | null | 2014-01-03 22:32:02.55 UTC | 2 | 2014-06-19 08:58:52.143 UTC | null | null | null | null | 1,613,902 | null | 1 | 3 | java|spring|spring-mvc|spring-security | 43,121 | <p>I've found the answer to my question : </p>
<pre><code><security:http auto-config="true">
<security:intercept-url pattern="/register"
access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/login*"
access="ROLE_USER" />
<security:intercept-url pattern="/logout*"
access="ROLE_USER,ROLE_ADMIN" />
<security:form-login/>
</security:http>
</code></pre>
<p>Now the url <br>
<code>http:localhost:8080/nexthome</code> is free access <br>
<code>http:localhost:8080/nexthome/regsiter</code> is free access <br>
<code>http:localhost:8080/nexthome/login</code> prompt the Spring Security login form before accessing the ressource <br>
<code>http:localhost:8080/nexthome/logout</code> prompt the Spring Security login form before accessing the ressource</p> |
37,452,041 | Difference between using the ASP.NET Core Web Application (.NET Core) with net461 set as the only framework and using the (.NET Framework) template | <p>With the release of .NET Core RC2 Microsoft made it so there are now 3 Web Application templates:</p>
<ul>
<li>ASP.NET Web Application (.NET Framework) β The old</li>
<li>ASP.NET Core Web Application (.NET Framework) β the new, to be hosting on Windows only</li>
<li>ASP.NET Core Web Application (.NET Core) β Linux, OSX, Windows</li>
</ul>
<p>I am trying to use the new Core Web Application template but without trying to target Linux, OSX, Windows so it seems like the ASP.NET Core Web Application (.NET Framework) is perfect for me. It took me a while but I learned that in order to add a class library that will work with this project type you need to add a Class Library (.NET Core) and change the frameworks section to only be net461 to match the Web Application.</p>
<pre><code>"frameworks": {
"net461": { }
}
</code></pre>
<p><strong>My Question:</strong></p>
<p>What is the difference between creating an ASP.NET Core Web Application (.NET Core) and in project.json making net461 the only target framework</p>
<p>and</p>
<p>just creating an ASP.NET Core Web Application (.NET Framework) project which only includes net461 by default.</p>
<p>Are there other differences that I am not aware of like the way the projects are published, etc.?</p> | 39,194,881 | 4 | 0 | null | 2016-05-26 05:08:18.39 UTC | 17 | 2021-04-24 10:59:29.433 UTC | 2021-04-24 10:59:29.433 UTC | null | 4,981,637 | null | 5,678,853 | null | 1 | 62 | c#|asp.net|.net|asp.net-core | 34,316 | <blockquote>
<p>What is the difference between creating a ASP.NET Core Web Application
(.NET Core) and in project.json making.NET461 the only target
Framework</p>
</blockquote>
<p>It's the same thing as making an <code>ASP.NET Core Web Application</code> (<code>.NET Framework</code>) project. The type of project between the two is determined by the <code>.csproj</code> file and you changed it in your <code>.csproj</code> from targeting <code>.NET Core</code> to targeting the <code>.NET Framework</code>. In previous release/beta versions of <code>ASP.NET Core</code> it was possible to have both Frameworks in a <code>project.json</code> file (which has been replaced by a simplified <code>.csproj</code> file in .NET Core 2.0 which more .NET developers are familiar with) but you could only publish to one.</p>
<blockquote>
<p>just creating a ASP.NET Core Web Application (.NET Framework) project which only includes.NET461 by default.</p>
<p>Are there other difference that I am not aware of like the way the the projects are published, etc
If you target the .NET Framework and not .NET Core your app cannot be cross platform and your app can only run on Windows and not Linux/Mac.</p>
</blockquote>
<p>The reason for there being separate <code>ASP.NET Core</code> Web Application (<code>.NET Core</code>) and <code>ASP.NET Core</code> Web Application (<code>.NET Framework</code>) is because the latter allows you to make use of functions, packages or 3rd party libraries that are dependent on Windows and the same <code>.NET Framework</code> or higher will be required to be installed on the machine.</p>
<p>The former doesn't have the <code>.NET Framework</code> requirement but allows your app to be cross platform and when you publish your app it publishes all the dependent <code>.NET Core</code> dll files to the publish directory in that way circumventing the <code>.NET Framework</code> installation requirement.</p>
<p>It will also affect compilation as if you target <code>.NET Core</code> and make use of a Windows specific function or package you will get a compilation error.</p>
<p>You can easily switch between the two by adjusting your <code>.csproj</code> to target the one or the other. </p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/articles/standard/choosing-core-framework-server" rel="noreferrer">Microsoft Docs</a> </p>
<blockquote>
<p>You should use .NET Core for your server application when:</p>
<ul>
<li><p>You have cross-platform needs.</p></li>
<li><p>You are targeting microservices.</p></li>
<li><p>You are using Docker containers.</p></li>
<li><p>You need high performance and scalable systems.</p></li>
<li><p>You need side by side of .NET versions by application.</p></li>
</ul>
<p>You should use .NET Framework for your server application when:</p>
<ul>
<li>Your application currently uses .NET Framework (recommendation is to extend instead of migrating)</li>
<li>You need to use third-party .NET libraries or NuGet packages not available for .NET Core.</li>
<li>You need to use .NET technologies that are not available for .NET Core.</li>
<li>You need to use a platform that doesnβt support .NET Core.</li>
</ul>
</blockquote>
<p><strong>Update (2018/10/30)</strong></p>
<p>It has been <a href="https://github.com/aspnet/Announcements/issues/324" rel="noreferrer">announced</a> that <code>ASP.Net Core 3</code> which has a release date in <a href="https://github.com/dotnet/core/blob/master/roadmap.md" rel="noreferrer">2019 Q1</a>, will only support <code>.NET Core</code> and <strong>NOT</strong> <code>.NET Framework</code></p>
<blockquote>
<p>As announced on the .NET Blog earlier this month, .NET Framework will get fewer of the newer platform and language features that come to .NET Core moving forward, due to the in-place update nature of .NET Framework and the desire to limit changes there that might break existing applications. To ensure ASP.NET Core can fully leverage the improvements coming to .NET Core moving forward, ASP.NET Core will only run on .NET Core starting from 3.0. Moving forward, you can simply think of ASP.NET Core as being part of .NET Core.</p>
<p>Customers utilizing ASP.NET Core on .NET Framework today can continue to do so in a fully supported fashion using the 2.1 LTS release. Support and servicing for 2.1 will continue until at least August 21, 2021 (3 years after its declaration as an LTS release) in accordance with the .NET Support Policy.</p>
</blockquote> |
5,815,013 | Eclipse dont have java doc to show information about class and methods. how to attach those? +android | <p><br>
I'm
working on android under eclipse holies environment. but my eclipse not helping me to find detail about class or method while writing code.<br>
Ex: <em>Toast android.widget.Toast.makeText(Context context, CharSequence text, int duration)</em></p>
<p>if i mouse hover on <strong>makeText()</strong> in above statement, getting following information</p>
<p>Note: This element has no attached source and the Javadoc could not be found in the attached Javadoc</p>
<p>where and what do i need to attach? </p> | 5,815,161 | 1 | 0 | null | 2011-04-28 07:14:54.72 UTC | 1 | 2011-04-28 08:27:16.16 UTC | null | null | null | null | 617,302 | null | 1 | 7 | android|eclipse|javadoc | 45,498 | <p>If you have installed the ADT plugin to Eclipse then you should make sure that you download the package called something along the lines of <strong>"Documentation for Android SDK 2.2,
API 8, revision 1"</strong> or whatever. Have you gone through the entire installation guide for the Android SDK as posted on the official website? <a href="http://developer.android.com/sdk/installing.html" rel="nofollow noreferrer">http://developer.android.com/sdk/installing.html</a> this is the one I'm talking about. It's been discussed on SO before as well: <a href="https://stackoverflow.com/questions/2268183/javadoc-in-an-eclipse-android-project">JavaDoc in an Eclipse Android Project</a></p>
<p>If you have done all this, then <a href="http://www.vogella.de/articles/Eclipse/article.html#classpath_jarjavadoc" rel="nofollow noreferrer">http://www.vogella.de/articles/Eclipse/article.html#classpath_jarjavadoc</a> does a good job of explaining how to add Sources & Javadocs to existing Libraries in case something went wrong.</p>
<p>For example, this is how my Libraries path looks: <img src="https://i.stack.imgur.com/qOwCY.png" alt="Weee!"></p>
<p>Go check and see how yours looks. Included is the location for the Javadocs normally (SDK Path/docs/reference/)</p>
<p>If you want to add the source code as well, see:
<a href="http://android.opensourceror.org/2010/01/18/android-source/" rel="nofollow noreferrer">http://android.opensourceror.org/2010/01/18/android-source/</a>
&
<a href="http://stuffthathappens.com/blog/2008/11/01/browsing-android-source-in-eclipse/" rel="nofollow noreferrer">http://stuffthathappens.com/blog/2008/11/01/browsing-android-source-in-eclipse/</a></p> |
55,256,671 | How to install latest cuDNN to conda? | <p>In conda the latest version of conda is:</p>
<pre><code>cudnn 7.3.1 cuda10.0_0 anaconda
</code></pre>
<p>But i need 7.4.2 for tensorflow-gpu.1.13
How install cuDNN==7.4.2 in conda?</p> | 55,285,589 | 6 | 0 | null | 2019-03-20 08:46:32.097 UTC | 6 | 2021-06-29 07:18:03.06 UTC | null | null | null | null | 10,715,858 | null | 1 | 20 | tensorflow|conda|cudnn | 64,835 | <p>This was not possible to do it with conda at the time the question was made. That is way it was suggested to try <a href="https://www.tensorflow.org/install/gpu#linux_setup" rel="nofollow noreferrer">this</a>. However, now it is possible. Follow the other answers</p> |
25,645,558 | ARRAY_CONTAINS muliple values in hive | <p>Is there a convenient way to use the ARRAY_CONTAINS function in hive to search for multiple entries in an array column rather than just one? So rather than:</p>
<pre><code>WHERE ARRAY_CONTAINS(array, val1) OR ARRAY_CONTAINS(array, val2)
</code></pre>
<p>I would like to write:</p>
<pre><code>WHERE ARRAY_CONTAINS(array, val1, val2)
</code></pre>
<p>The full problem is that I need to read <code>val1</code> and <code>val2</code> dynamically from the command line arguments when I run the script and I generally don't know how many values will be conditioned on. So you can think of <code>vals</code> being a comma separated list (or array) containing values <code>val1</code>, <code>val2</code>, <code>...</code>, and I want to write</p>
<pre><code>WHERE ARRAY_CONTAINS(array, vals)
</code></pre>
<p>Thanks in advance!</p> | 25,648,885 | 3 | 0 | null | 2014-09-03 13:23:28.943 UTC | 4 | 2019-09-17 12:50:38.847 UTC | null | null | null | null | 790,612 | null | 1 | 10 | sql|hive | 39,182 | <p>There is a UDF <a href="https://github.com/klout/brickhouse/blob/master/src/main/java/brickhouse/udf/collect/ArrayIntersectUDF.java" rel="noreferrer">here</a> that will let you take the intersection of two arrays. Assuming your values have the structure</p>
<pre><code>values_array = [val1, val2, ..., valn]
</code></pre>
<p>You could then do </p>
<pre><code>where array_intersection(array, values_array)[0] is not null
</code></pre>
<p>If they don't have any elements in common, <code>[]</code> will be returned and therefore <code>[][0]</code> will be <code>null</code></p> |
2,711,044 | Why doesn't Linux use the hardware context switch via the TSS? | <p>I read the following statement:</p>
<blockquote>
<p>The x86 architecture includes a
specific segment type called the Task
State Segment (TSS), to store hardware
contexts. Although Linux doesn't use
hardware context switches, it is
nonetheless forced to set up a TSS for
each distinct CPU in the system.</p>
</blockquote>
<p>I am wondering:</p>
<ul>
<li>Why doesn't Linux use the hardware support for context switch? </li>
<li>Isn't the hardware approach much faster than the software approach?</li>
<li>Is there any OS which does take advantage of the hardware context switch? Does windows use it?</li>
</ul>
<p>At last and as always, thanks for your patience and reply.</p>
<p>-----------Added--------------</p>
<p><a href="http://wiki.osdev.org/Context_Switching" rel="noreferrer">http://wiki.osdev.org/Context_Switching</a> got some explanation.</p>
<p>People as confused as me could take a look at it. 8^)</p> | 2,761,422 | 3 | 2 | null | 2010-04-26 03:46:33.18 UTC | 21 | 2014-04-17 07:43:26.167 UTC | 2014-04-17 07:43:26.167 UTC | null | 264,052 | null | 264,052 | null | 1 | 41 | linux|x86|linux-kernel|low-level | 12,057 | <p>The x86 TSS is very slow for hardware multitasking and offers almost no benefits when compared to software task switching. (In fact, I think doing it manually beats the TSS a lot of times) </p>
<p>The TSS is known also for being annoying and tedious to work with and it is not portable, even to x86-64. Linux aims at working on multiple architectures so they probably opted to use software task switching because it can be written in a machine independent way. Also, Software task switching provides a lot more power over what can be done and is generally easier to setup than the TSS is. </p>
<p>I believe Windows 3.1 used the TSS, but at least the NT >5 kernel does not. I do not know of any Unix-like OS that uses the TSS. </p>
<p>Do note that the TSS <strong>is mandatory.</strong> The thing that OSs do though is create a single TSS entry(per processor) and everytime they need to switch tasks, they just change out this single TSS. And also the only fields used in the TSS by software task switching is <code>ESP0</code> and <code>SS0</code>. This is used to get to ring 0 from ring 3 code for interrupts. Without a TSS, there would be no known Ring 0 stack which would of course lead to a GPF and eventually triple fault. </p> |
2,924,610 | How do you use the jQuery UI Datepicker with MVC's Html.TextBoxFor? | <p>I am using Model binding with the Entity Framework and have an Html.TextBoxFor(model =>model.date) input. I know how to tell jQuery how to implement a datepicker but not in this context. What would I need to add here to have a calendar popup when the user enters this field?</p> | 2,924,660 | 4 | 0 | null | 2010-05-27 20:23:21.14 UTC | 6 | 2012-01-20 15:09:56.823 UTC | null | null | null | null | 278,768 | null | 1 | 15 | asp.net-mvc|jquery-ui | 39,903 | <p>You'll want to use the HtmlHelper overload that allows you to specify Html attributes. Then target them with the jquery selector.</p>
<pre><code>// in view
<%= Html.TextBoxFor(x => x.Date, new { @class="datepicker" })%>
// in js
$(document).ready({
$('.datepicker').datepicker();
});
</code></pre>
<p>Though I recommend using <code>EditorFor</code> instead.</p>
<pre><code><%= Html.EditorFor(x => x.Date)%>
</code></pre>
<p>You can create an EditorTemplate to handle any field that is a <code>DateTime</code> and have it output the proper field.</p>
<p>Create <code>/Views/Shared/EditorTemplates/DateTime.ascx</code> and put this in it...</p>
<pre><code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%= Html.TextBox("", Model.ToShortDateString(), new { @class="datepicker" } )%>
</code></pre>
<p>Or if you need to allow DateTime's with nulls:</p>
<pre><code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("", (Model.HasValue? Model.Value.ToShortDateString():""), new { @class="datepicker"} )%>
</code></pre>
<p>Then you can always use EditorFor and have a central ascx to edit if you ever want to modify the way date times are handled in your views.</p> |
2,725,523 | How to Include CSS and JS files via HTTPS when needed? | <p>I am adding an external CSS file and an external JS file to my headers and footers.
When loading an HTTPS page, some browsers complain that I am loading unsecured content.</p>
<p>Is there an easy way to make the browser load the external content via HTTPS when the page itself is HTTPS?</p> | 2,725,594 | 4 | 0 | null | 2010-04-27 22:08:48.583 UTC | 19 | 2017-08-05 13:02:58.087 UTC | null | null | null | null | 25,645 | null | 1 | 80 | javascript|html|css|https | 73,192 | <p>Use protocol-relative paths.</p>
<p>Thus not</p>
<pre><code><link rel="stylesheet" href="http://example.com/style.css">
<script src="http://example.com/script.js"></script>
</code></pre>
<p>but so</p>
<pre><code><link rel="stylesheet" href="//example.com/style.css">
<script src="//example.com/script.js"></script>
</code></pre>
<p>then it will use the protocol of the parent page.</p> |
3,077,961 | How to delete an instance of a class? | <p>So, I have this project that creates multiple instances of a class, and list them.</p>
<p>At some point, the instanced class is not needed anymore. How can I flush it ?</p>
<p>So far, it doesn't happen, even when the class has nothing to do anymore (if it had been a single static class, the program would have shut down), it's still in my list, and its public variables are still available ...</p> | 3,077,988 | 5 | 4 | null | 2010-06-20 02:02:11.157 UTC | null | 2018-09-30 15:58:04.8 UTC | null | null | null | null | 370,809 | null | 1 | 3 | c#|class|flush | 43,090 | <p>You can have your instances raise an event (OnInactivated, say). The list class should add a handler for such events when the item is added to the list (subclass or encapsulate a list and override the Add method). When the event fires, the object will be removed from the list by the list. Assuming the object is not referenced in any other lists (which might also be listening), then the garbage collector is free to deal with the object.</p>
<p>In this way, the object does not need to keep track of all references to itself, and know how to inform the reference holder to release the reference.</p>
<p>Here's a runnable example: <a href="http://www.coderun.com/ide/?w=Hw83i0wAQkugUif5Oj2lmw" rel="nofollow noreferrer">http://www.coderun.com/ide/?w=Hw83i0wAQkugUif5Oj2lmw</a></p> |
37,933,204 | Building common dependencies with docker-compose | <p>Assuming I have a set of images which depend on a common base image:</p>
<ul>
<li><p>base (this is only a set of common dependencies)</p>
<pre class="lang-sh prettyprint-override"><code>FROM ubuntu:16.04
ENV FOO 1
</code></pre></li>
<li><p>child1</p>
<pre class="lang-sh prettyprint-override"><code>FROM mybaseimage # where mybaseimage corresponds to base
CMD ["bar1_command"]
</code></pre></li>
<li><p>child2</p>
<pre class="lang-sh prettyprint-override"><code>FROM mybaseimage # where mybaseimage corresponds to base
CMD ["bar2_command"]
</code></pre></li>
</ul>
<p>Is it possible to create <code>docker-compose</code> file which would build <code>base</code> without running it? Lets say I have following dependencies:</p>
<pre><code>version: '2'
services:
child1:
build: ./path-to-child1-dockerfile
services:
child2:
build: ./path-to-child2-dockerfile
depends_on:
- child1
</code></pre>
<p>I would like <code>base</code> to be build even if it is not explicitly started. Is something like this even possible? Or should I simply use external Makefile to build dependencies?</p>
<pre><code>build_base:
docker build -t mybaseimage mybaseimage
build_all: build_base
docker-compose build
</code></pre> | 37,945,466 | 3 | 0 | null | 2016-06-20 23:10:08.043 UTC | 4 | 2019-07-04 18:45:42.327 UTC | 2016-06-20 23:36:58.83 UTC | null | 6,491,440 | null | 6,491,440 | null | 1 | 37 | docker|docker-compose|dockerfile | 14,328 | <p>Use a Makefile. docker-compose is not designed to build chains of images, it's designed for running containers.</p>
<p>You might also be interested in <a href="http://dnephin.github.io/dobi/" rel="noreferrer">dobi</a> which is a build-automation tool (like make) designed to work with docker images and containers. </p>
<p>Disclaimer: I'm the author of <strong>dobi</strong></p> |
52,605,946 | Change the JSON serialization settings of a single ASP.NET Core controller | <p>I'm having two controller controllers: <code>ControllerA</code> and <code>ControllerB</code>. The base class of each controller is <code>Controller</code>.</p>
<p>The <code>ControllerA</code> needs to return JSON in the default format (camelCase). The <code>ControllerB</code> needs to return data in a different JSON format: snake_case. </p>
<p>How can I implement this in ASP.NET Core 3.x and 2.1?</p>
<p>I've tried the <code>startup</code> with: </p>
<pre><code>services
.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
})
.AddControllersAsServices();
</code></pre>
<p>But this will change the serialization for <strong>all</strong> controllers, not just for <code>ControllerB</code>. How can I configure or annotate this feature for 1 controller?</p> | 52,623,772 | 3 | 0 | null | 2018-10-02 09:51:14.22 UTC | 8 | 2021-09-12 22:30:27.757 UTC | 2020-04-18 00:29:03.323 UTC | null | 502,537 | null | 201,482 | null | 1 | 39 | c#|asp.net-core|.net-core|json.net|asp.net-core-mvc | 14,560 | <h3>ASP.NET Core 3.0+</h3>
<p>You can achieve this with a combination of an <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1#action-filters" rel="noreferrer">Action Filter</a> and an <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.outputformatter?view=aspnetcore-3.1" rel="noreferrer">Output Formatter</a>.</p>
<p>Things look a little different for 3.0+, where the default JSON-formatters for 3.0+ are based on <code>System.Text.Json</code>. At the time of writing, these <a href="https://github.com/dotnet/runtime/issues/782" rel="noreferrer">don't have built-in support for a snake-case naming strategy</a>.</p>
<p>However, if you're using Json.NET with 3.0+ (details in the <a href="https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#jsonnet-support" rel="noreferrer">docs</a>), the <code>SnakeCaseAttribute</code> from above is still viable, with a couple of changes:</p>
<ol>
<li><code>JsonOutputFormatter</code> is now <code>NewtonsoftJsonOutputFormatter</code>.</li>
<li>The <code>NewtonsoftJsonOutputFormatter</code> constructor requires an argument of <code>MvcOptions</code>.</li>
</ol>
<p>Here's the code:</p>
<pre><code>public class SnakeCaseAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext ctx)
{
if (ctx.Result is ObjectResult objectResult)
{
objectResult.Formatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
},
ctx.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>(),
ctx.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>().Value));
}
}
}
</code></pre>
<h2>ASP.NET Core 2.x</h2>
<p>You can achieve this with a combination of an <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#action-filters" rel="noreferrer">Action Filter</a> and an <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.outputformatter?view=aspnetcore-2.1" rel="noreferrer">Output Formatter</a>. Here's an example of what the Action Filter might look like:</p>
<pre><code>public class SnakeCaseAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext ctx)
{
if (ctx.Result is ObjectResult objectResult)
{
objectResult.Formatters.Add(new JsonOutputFormatter(
new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
},
ctx.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>()));
}
}
}
</code></pre>
<p>Using <code>OnActionExecuted</code>, the code runs after the corresponding action and first checks to see if the result is an <code>ObjectResult</code> (which also applies to <code>OkObjectResult</code> thanks to inheritance). If it is an <code>ObjectResult</code>, the filter simply adds a customised version of a <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.jsonoutputformatter?view=aspnetcore-2.1" rel="noreferrer"><code>JsonOutputFormatter</code></a> that will serialise the properties using <code>SnakeCaseNamingStrategy</code>. The second parameter in the <code>JsonOutputFormatter</code> constructor is retrieved from the DI container.</p>
<p>In order to use this filter, just apply it to the relevant controller:</p>
<pre><code>[SnakeCase]
public class ControllerB : Controller { }
</code></pre>
<hr>
<p>Note: You might want to create the <code>JsonOutputFormatter</code>/<code>NewtonsoftJsonOutputFormatter</code> ahead of time somewhere, for example - I've not gone that far in the example as that's secondary to the question at hand.</p> |
646,395 | How to use System.IdentityModel in own client-server application | <p>I've got a simple client-server application based on TcpClient/TcpListener and SslStream. Clients can authenticate themselves to the server using a X509Certificate or by sending a user name and password after the SslStream has been established.</p>
<p>WCF makes use of the <strong>System.IdentityModel</strong> namespace for authentication purposes, but <a href="http://www.leastprivilege.com/CommentView.aspx?guid=85585fae-f04f-4de9-8207-631a0b228b06" rel="noreferrer">apparently</a> that can be used in arbitrary applications--which sounds interesting. Information on how to do this is sparse though (or my Google foo is weak today).</p>
<p>So, my question is: <strong>What do I need to do to integrate System.IdentityModel with my application?</strong> I'm not sure if I need all that ClaimSet stuff, but it would be nice if users could log in just using their Windows account or any other provided authentication mechanism. (Unfortunately I can't just switch to WCF but have to use the custom protocol, although I can make some changes to it if necessary.)</p> | 646,830 | 2 | 0 | null | 2009-03-14 18:08:01.237 UTC | 11 | 2013-04-08 21:04:49.19 UTC | null | null | null | Unknown | 76,217 | null | 1 | 13 | c#|wcf-security|.net-3.0 | 8,051 | <p>My Google foo was indeed weak. The answer is right behind the link in my question. So here are a couple of links to <a href="http://leastprivilege.com/category/identitymodel/" rel="noreferrer">this blog</a> in case somebody has the same question eventually.</p>
<p>First, you should try to understand "that claim set stuff":</p>
<ul>
<li><a href="http://leastprivilege.com/2008/02/19/using-identitymodel-claims/" rel="noreferrer">Claims</a></li>
<li><a href="http://leastprivilege.com/2008/02/23/using-identitymodel-claim-sets/" rel="noreferrer">Claim Sets</a></li>
<li><a href="http://leastprivilege.com/2008/02/23/using-identitymodel-inspecting-claim-sets/" rel="noreferrer">Inspecting Claim Sets</a></li>
<li><a href="http://leastprivilege.com/2008/02/24/using-identitymodel-windows-and-x509certificate-claim-sets/" rel="noreferrer">Windows and X509Certificate Claim Sets</a></li>
<li><a href="http://leastprivilege.com/2008/02/24/using-identitymodel-typical-operations-on-claim-sets/" rel="noreferrer">Typical Operations on Claim Sets</a></li>
</ul>
<p>Then, you need to know where claim sets come from:</p>
<ul>
<li><a href="http://leastprivilege.com/2008/02/29/using-identitymodel-authorization-policies-context-and-claims-transformation/" rel="noreferrer">Authorization Policies, Context and Claims Transformation</a></li>
<li><a href="http://leastprivilege.com/2008/03/04/using-identitymodel-claims-transformation-in-wcf/" rel="noreferrer">Claims Transformation in WCF</a></li>
<li><a href="http://leastprivilege.com/2008/03/04/using-identitymodel-authorization-context-and-claims-transformation-outside-of-wcf/" rel="noreferrer">Authorization Context and Claims Transformation outside of WCF</a></li>
</ul>
<p>Armed with this knowledge, it actually becomes quite simple.</p>
<p>If I understand it correctly, the basic workflow would be something like this:</p>
<ol>
<li>Client creates a <code>SecurityToken</code> using a <code>SecurityTokenProvider</code></li>
<li>Client serializes the <code>SecurityToken</code> using a <code>SecurityTokenSerializer</code></li>
<li>Server deserializes the <code>SecurityToken</code> using a <code>SecurityTokenSerializer</code></li>
<li>Server creates <code>IAuthorizationPolicy</code>s using a <code>SecurityTokenAuthenticator</code></li>
<li>Server creates <code>AuthorizationContext</code> from <code>IAuthorizationPolicy</code>s</li>
<li>Done</li>
</ol>
<p>Example:</p>
<pre><code>// Create the SecurityTokenProvider
var p = new UserNameSecurityTokenProvider("username", "password");
// Get the SecurityToken from the SecurityTokenProvider
var t = p.GetToken(TimeSpan.FromSeconds(1.0)) as UserNameSecurityToken;
// ... transmit SecurityToken to server ...
// Create the SecurityTokenAuthenticator
var a = new CustomUserNameSecurityTokenAuthenticator(
UserNamePasswordValidator.None);
// Create IAuthorizationPolicies from SecurityToken
var i = a.ValidateToken(t);
// Create AuthorizationContext from IAuthorizationPolicies
var c = AuthorizationContext.CreateDefaultAuthorizationContext(i);
ShowClaims(c.ClaimSets);
</code></pre>
<p>For <code>X509SecurityToken</code>s use a <code>X509SecurityTokenProvider</code>/<code>Authenticator</code>. For <code>WindowsSecurityToken</code>s there's a <code>WindowsSecurityTokenAuthenticator</code> but not a provider; instead, use the <code>WindowsSecurityToken</code> constructor:</p>
<pre><code>var t = new WindowsSecurityToken(WindowsIdentity.GetCurrent());
</code></pre>
<p>This works quite well. The only thing I omitted so far above is the token serialization. There is a <code>SecurityTokenSerializer</code> class which has one implementation in the .NET framework: the <code>WSSecurityTokenSerializer</code> class which comes with WCF.</p>
<p>Serializing <code>UserNameSecurityToken</code>s and <code>X509SecurityToken</code>s works like a charm (haven't tried deserialization), but <code>WindowsSecurityToken</code>s are apparently not supported by the serializer. This leaves me with the two authentication methods that I already have (certificates and username/password) and, as I didn't want that <code>AuthorizationContext</code> anyway, I'll stick with what I have :)</p> |
1,309,050 | Emacs query-replace-regexp multiline | <p>How do you do a query-replace-regexp in Emacs that will match across multiple lines? </p>
<p>as a trivial example I'd want <code><p>\(.*?\)</p></code> to match</p>
<pre><code><p>foo
bar
</p>
</code></pre> | 1,309,157 | 2 | 4 | null | 2009-08-20 21:52:00.487 UTC | 2 | 2012-11-01 23:28:36.463 UTC | 2012-11-01 23:28:36.463 UTC | null | 1,749,675 | null | 118,910 | null | 1 | 29 | regex|emacs | 8,706 | <p>Try character classes. As long as you're using only ASCII character set, you can use <code>[[:ascii:]]</code> instead of the dot. Using the longer <code>[[:ascii:][:nonascii:]]</code> ought to work for everything.</p> |
1,281,188 | Text Field using Hibernate Annotation | <p>I am having trouble setting the type of a String, it goes like</p>
<pre><code>public void setTextDesc(String textDesc) {
this.textDesc = textDesc;
}
@Column(name="DESC")
@Lob
public String getTextDesc() {
return textDesc;
}
</code></pre>
<p>and it didn't work, I checked the mysql schema and it remains varchar(255), I also tried, </p>
<pre><code>@Column(name="DESC", length="9000")
</code></pre>
<p>or</p>
<pre><code>@Column(name="DESC")
@Type(type="text")
</code></pre>
<p>I am trying to make the type to be TEXT, any idea would be well appreciated!</p> | 1,281,216 | 2 | 2 | null | 2009-08-15 04:51:22.03 UTC | 15 | 2018-04-30 05:42:44.163 UTC | null | null | null | null | 125,935 | null | 1 | 54 | hibernate|annotations|blob | 83,780 | <p>You said "I checked the mysql schema and it remains varchar(255)" - did you expect Hibernate to automatically alter your database? It won't. Even if you have <code>hibernate.hbm2ddl.auto</code> set, I don't believe Hibernate would alter the existing column definition.</p>
<p>If you were to generate new database creation script, <code>@Lob</code> should generate "TEXT" type column if you don't specify length explicitly (or if you do and it's less that 65536). You can always force that by explicitly declaring type in <code>@Column</code> annotation, though keep in mind that's not portable between databases:</p>
<pre><code>@Column(name="DESC", columnDefinition="TEXT")
</code></pre> |
2,785,206 | The pImpl idiom and Testability | <p>The pImpl idiom in c++ aims to hide the implementation details (=private members) of a class from the users of that class.
However it also hides some of the dependencies of that class which is usually regarded bad from a testing point of view.</p>
<p>For example if class A hides its implementation details in Class AImpl which is only accessible from A.cpp and AImpl depends on a lot of other classes, it becomes very difficult to unit test class A since the testing framework has no access to the methods of AImpl and also no way to inject dependency into AImpl.</p>
<p>Has anyone come across this problem before? and have you found a solution?</p>
<p>-- edit --</p>
<p>On a related topic, it seems that people suggest one should only test public methods exposed by the interface and not the internals. While I can conceptually understand that statement, I often find that I need to test private methods in isolation. For example when a public method calls a private helper method that contains some non trivial logic. </p> | 2,785,468 | 5 | 1 | null | 2010-05-06 23:29:43.107 UTC | 10 | 2015-12-02 23:18:53.67 UTC | 2010-05-07 00:16:12.76 UTC | null | 334,929 | null | 334,929 | null | 1 | 20 | c++|testing|pimpl-idiom | 4,832 | <p>The idea behind pimpl is to not so much to hide implementation details from classes, (private members already do that) but to move implementation details out of the header. The problem is that in C++'s model of includes, changing the private methods/variables will force any file including this file to be recompiled. That is a pain, and that's why pimpl seeks to eliminate. It doesn't help with preventing dependencies on external libraries. Other techniques do that.</p>
<p>Your unit tests shouldn't depend on the implementation of the class. They should verify that you class actually acts as it should. The only thing that really matter is how the object interacts with the outside world. Any behavior which your tests cannot detect must be internal to the object and thus irrelevant. </p>
<p>Having said that, if you find too much complexity inside the internal implementation of a class, you may want to break out that logic into a separate object or function. Essentially, if your internal behavior is too complex to test indirectly, make it the external behavior of another object and test that.</p>
<p>For example, suppose that I have a class which takes a string as a parameter to its constructor. The string is actual a little mini-language that specifies some of the behavior the object. (The string probably comes from a configuration file or something). In theory, I should be able to test the parsing of that string by constructing different objects and checking behavior. But if the mini-language is complex enough this will be hard. So, I define another function that takes the string and returns a representation of the context (like an associative array or something). Then I can test that parsing function separately from the main object.</p> |
2,968,425 | get back to previous page | <p>just i want to make back button in my site. once i click the button it need to take the url in to previous page. how can i make this using jquery?</p> | 2,968,602 | 6 | 1 | null | 2010-06-03 17:41:35.633 UTC | 4 | 2020-09-02 16:05:40.827 UTC | 2016-02-19 07:28:21.507 UTC | null | 3,492,139 | null | 218,349 | null | 1 | 16 | javascript|jquery|browser-history | 76,565 | <p>the answer by wRAR is correct, you can use history.back or history.go(-1). However, if you are using ajax, you might need a bit more than that. </p>
<p>Stephen Walter has a nice article on how to use <a href="http://stephenwalther.com/archive/2010/04/08/jquery-asp-net-and-browser-history" rel="noreferrer">jQuery, ASP.NET, and Browser History</a> which basically describes how to save and restore the application state yourself. I recommend you give a read. </p>
<p>Elijah Manor(co-host of the Official jQuery Podcast) has also written a nice <a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff690558.aspx" rel="noreferrer">article</a> about this topic.</p>
<p>I hope this helps
-D</p> |
2,344,213 | Is Guid considered a value type or reference type? | <p>Guids are created using the <code>new</code> keyword which makes me think it's a reference type.</p>
<p>Is this correct?</p>
<p><code>Guid uid = new Guid();</code></p>
<p>Are Guids stored on the heap?</p> | 2,344,239 | 6 | 0 | null | 2010-02-26 19:21:14.487 UTC | 2 | 2021-06-11 22:48:09.513 UTC | 2010-02-27 03:46:42.06 UTC | null | 164,901 | null | 168,882 | null | 1 | 38 | c#|.net|guid|value-type|reference-type | 18,149 | <p>You can see the definition of a Guid yourself:</p>
<pre><code>public struct Guid ...
</code></pre>
<p>Or you can test it like this:</p>
<pre><code>bool guidIsValueType = typeof(Guid).IsValueType;
</code></pre>
<blockquote>
<p>Quote: "<em>GUID's are created using the new keyword which makes me think it's a reference type."</em></p>
</blockquote>
<p>Structs can have constructors too, for example <code>new DateTime(2012, 12, 23)</code>.</p> |
3,165,938 | How to increase the rotation speed in android? | <p>I have an image drawable. i rotating the image like a progress bar.</p>
<pre><code><rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
android:toDegrees="360" android:drawable="@drawable/spinner_white_48" />
</code></pre>
<p>i want to increase the rotation speed? for that, What attribute i have to use?</p> | 3,165,971 | 6 | 0 | null | 2010-07-02 13:11:44.857 UTC | 9 | 2020-08-26 06:50:01.617 UTC | null | null | null | null | 267,269 | null | 1 | 43 | android|animation|rotation | 38,040 | <p>Set the <a href="http://developer.android.com/reference/android/view/animation/Animation.html#attr_android:duration" rel="noreferrer">duration</a> and <a href="http://developer.android.com/reference/android/view/animation/Animation.html#attr_android:repeatCount" rel="noreferrer">repeatCount</a> that you want the animation to run.</p> |
2,400,076 | How to get the first child id inside the div using JQuery | <p>How to get the first child id inside the div using JQuery.</p>
<p>Sample code:</p>
<pre><code><div id='id1'>
<a id='a1' />
<a id='a2' />
<a id='a3' />
</div>
</code></pre>
<p>I want to get the id <code>a1</code>.</p>
<p>I have tried <code>$('#id1 a:first-child').html()</code> to get the text. How to get the id?</p> | 2,400,092 | 7 | 0 | null | 2010-03-08 08:35:53.073 UTC | 1 | 2020-11-24 18:52:12.07 UTC | 2011-05-02 00:44:06.523 UTC | null | 50,776 | null | 1,470,997 | null | 1 | 16 | jquery|dom | 87,103 | <pre><code>$("#id1:first-child").attr("id")
</code></pre> |
3,068,320 | Finalizing a Cursor that has not been deactivated or closed non-fatal error | <p>i'm getting a "Finalizing a Cursor that has not been deactivated or
closed" error on this piece of code.
The code is used to fill a listview. </p>
<p>Since it's a non-fatal error , there is no crash and all seems to works
fine..but i don't like the error. </p>
<p>If i close the cursor at the end of this code..the listview stay's
empty.
if i close the cursor in onStop , i get the same error. </p>
<p>How do i fix this?? </p>
<pre><code>private void updateList() {
DBAdapter db = new DBAdapter(this);
db.open();
//load all waiting alarm
mCursor=db.getTitles("state<2");
setListAdapter(new MyCursorAdapter(this, mCursor));
registerForContextMenu(getListView());
db.close();
}
error :
E/Cursor ( 2318): Finalizing a Cursor that has not been deactivated
or closed. database = /data/data/xxxxxxxxxxxxxxx.db, table = alerts,
query = SELECT _id, alert_id,
E/Cursor ( 2318):
android.database.sqlite.DatabaseObjectNotClosedException: Application
did not close the cursor or database
object that was opened here
E/Cursor ( 2318): at
android.database.sqlite.SQLiteCursor.<init>(SQLiteCursor.java:210)
E/Cursor ( 2318): at
android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDrΒiver.java:
53)
E/Cursor ( 2318): at
android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.jΒava:
1345)
E/Cursor ( 2318): at
android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.javaΒ:
1229)
....
....
</code></pre> | 3,069,263 | 9 | 0 | null | 2010-06-18 08:56:38.237 UTC | 16 | 2021-12-22 22:43:04.547 UTC | 2021-12-22 22:43:04.547 UTC | null | 4,294,399 | null | 368,598 | null | 1 | 33 | android|android-cursor | 48,836 | <p>You should not be getting that message if you close the <code>Cursor</code> in <code>onStop()</code> or <code>onDestroy()</code>. Please try that again. Or, call <code>startManagingCursor()</code> after you get the <code>Cursor</code> from your query, and Android will close the <code>Cursor</code> on its own.</p> |
2,714,517 | Getting "A valid signing identity matching this profile could not be found in your keychain" warning | <p>I hope to test my app on iPod Touch</p>
<p>I created development provisioning profile.</p>
<p>I dragged downloaded .mobileprovision file to Organizer</p>
<p>There is a yellow triangle warned that
"A valid signing identity matching this profile could not be found in your keychain"</p>
<p>The others distribution provisioning profiles have no any problem.</p>
<p>I checked my connected iPod Touch. Organizer also said that:</p>
<p>OS Installed on "interdev"'s iPod
3.1.3 (7E18)</p>
<p>Xcode Supported iPhone OS Versions</p>
<ul>
<li>3.1.1 (7C146)</li>
<li>3.1.1 (7C145)</li>
<li>3.1 (7C144)</li>
<li>3.0.1 (7A400)</li>
<li>3.0</li>
<li>2.2.1</li>
<li>2.2</li>
<li>2.1.1</li>
<li>2.1</li>
<li>2.0.2 (5C1)</li>
<li>2.0.1 (5B108)</li>
<li>2.0 (5A347)</li>
<li>2.0 (5A345)</li>
</ul>
<p>iOS 3.1.3</p>
<p>Xcode 3.1</p>
<p>Do I need to upgrade Xcode?</p> | 2,714,828 | 9 | 1 | null | 2010-04-26 15:07:06.817 UTC | 35 | 2019-07-24 13:09:17.48 UTC | 2015-07-04 16:49:09.89 UTC | null | 2,442,804 | null | 262,325 | null | 1 | 40 | iphone|xcode|keychain | 70,745 | <p>It sounds like you don't have a development certificate in your keychain that matches one of your provisioning profiles.</p>
<p><a href="https://i.stack.imgur.com/QsHvy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QsHvy.png" alt="dev portal screenshot"></a>
</p>
<p>Make sure that you have the dev cert and you have matching provisioning profiles. Also, if your app is using the keychain, make sure to include an Entitlements.plist (containing your app id, so your apps can share a "slice" of the keychain) in your project.</p> |
2,346,763 | Any simple way to explain why I cannot do List<Animal> animals = new ArrayList<Dog>()? | <p>I know why one shouldn't do that. But is there way to explain to a layman why this is not possible. You can explain this to a layman easily : <code>Animal animal = new Dog();</code>. A dog is a kind of animal but a list of dogs is not a list of animals.</p> | 2,346,855 | 13 | 1 | null | 2010-02-27 09:04:11.383 UTC | 10 | 2013-07-24 06:55:33.293 UTC | 2010-02-27 15:54:48.287 UTC | null | 82,118 | null | 184,730 | null | 1 | 22 | java|generics|oop|covariance | 6,141 | <p>Imagine you create a list of <strong>Dogs</strong>. You then declare this as <strong>List<Animal></strong> and hand it to a colleague. He, <em>not unreasonably</em>, believes he can put a <strong>Cat</strong> in it.</p>
<p>He then gives it back to you, and you now have a list of <strong>Dogs</strong>, with a <strong>Cat</strong> in the middle of it. Chaos ensues.</p>
<p>It's important to note that this restriction is there due to the mutability of the list. In Scala (for example), you can declare that a list of <strong>Dogs</strong> is a list of <strong>Animals</strong>. That's because Scala lists are (by default) immutable, and so adding a <strong>Cat</strong> to a list of <strong>Dogs</strong> would give you a <em>new</em> list of <strong>Animals</strong>.</p> |
2,700,256 | Why can't an object of abstract class be created? | <p>Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like </p>
<p>"Abstract class has not implemented method so, we cant create the object"
"The word 'Abstract' instruct the compiler to not create an object of the class"</p>
<p>But in a simple class where we have all virtual method, able to create an object???</p>
<p>Also, we can define different access modified to Abstract class constructor like private, protected or public.</p>
<p>My search terminated to this question:</p>
<p>Why we can't create object of an Abstract class?</p> | 2,700,272 | 16 | 0 | null | 2010-04-23 16:30:16.013 UTC | 10 | 2017-08-22 11:02:12.6 UTC | 2015-10-20 09:07:47.833 UTC | null | 4,442,023 | null | 122,574 | null | 1 | 21 | language-agnostic|oop | 102,885 | <p>An <em>abstract</em> type is <em>defined</em> largely as one that can't be created. You can create <em>subtypes</em> of it, but not of that type itself. The CLI will not let you do this.</p>
<p>An <code>abstract</code> class has a <code>protected</code> constructor (by default) allowing derived types to initialize it.</p>
<p>For example, the base-type <code>Stream</code> is abstract. Without a derived type <strong>where would the data go</strong>? What would <em>happen</em> when you call an <code>abstract</code> method? There would be no actual implementation of the method to invoke.</p> |
3,200,249 | HTML list-style-type dash | <p>Is there a way to create a list-style in HTML with a dash (i.e. - or – <code>&ndash;</code> or — <code>&mdash;</code>) i.e.</p>
<pre><code><ul>
<li>abc</li>
</ul>
</code></pre>
<p>Outputting:</p>
<pre><code>- abc
</code></pre>
<p>It's occurred to me to do this with something like <code>li:before { content: "-" };</code>, though I don't know the cons of that option (and would be much obliged for feedback).</p>
<p>More generically, I wouldn't mind knowing how to use generic characters for list items.</p> | 3,200,264 | 21 | 3 | null | 2010-07-08 02:06:39.88 UTC | 40 | 2022-02-06 18:41:36.917 UTC | 2011-10-09 12:14:19.873 UTC | null | 313,758 | null | 19,212 | null | 1 | 261 | html|css|xhtml|html-lists | 406,369 | <p>You could use <code>:before</code> and <code>content:</code> bearing in mind that this is not supported in IE 7 or below. If you're OK with that then this is your best solution. See the <a href="http://caniuse.com/#feat=css-gencontent" rel="noreferrer">Can I Use</a> or <a href="http://www.quirksmode.org/css/contents.html" rel="noreferrer">QuirksMode</a> CSS compatibility tables for full details.</p>
<p>A slightly nastier solution that should work in older browsers is to use an image for the bullet point and just make the image look like a dash. See the <a href="http://www.w3.org/wiki/CSS/Properties/list-style-type" rel="noreferrer">W3C <code>list-style-image</code> page</a> for examples.</p> |
40,224,607 | How do I build with watch enabled using angular-cli? | <p>I don't want to use serve, I know it watches for changes, builds and serves.
I want to build upon changes.
According to "ng help", build takes parameter --watch</p>
<blockquote>
<p>ng build Builds your app and places it into the output
path (dist/ by default).
--watch (Boolean) (Default: false)
aliases: -w --watcher (String)</p>
</blockquote>
<p>I tried both -w and --watcher but it just gives error.</p>
<pre><code>>ng build -w
Path must be a string. Received null
</code></pre> | 40,225,162 | 4 | 0 | null | 2016-10-24 17:58:19.483 UTC | 9 | 2021-01-13 16:22:17.14 UTC | 2016-10-24 18:21:42.21 UTC | null | 1,078,110 | null | 2,232,573 | null | 1 | 46 | angular|webpack|angular-cli | 61,141 | <p>I donΒ΄t know if itΒ΄s a bug or just not documented, but it seems that you need to add a output path for watching with <code>ng build -o dist -w</code> while dist is your output path.</p>
<p><strong>Update:</strong></p>
<p>The command is now: <code>ng build -op dist -w</code></p>
<p><strong>Update 2:</strong></p>
<p>The command is now: <code>ng build --output-path dist --watch</code></p> |
32,828,477 | How to implement service(concept in AngularJS) -like component in React | <p>All:</p>
<p>I am pretty new to React from AngularJS. In AngularJS, there is service dependency inject which can provide a service instance to do data fetching, processing, etc., other than UI operation. I wonder how to do this(or implement that injection) in React component?</p>
<p>Thanks</p> | 45,195,379 | 5 | 0 | null | 2015-09-28 17:18:29.56 UTC | 8 | 2019-07-29 10:29:20.507 UTC | 2015-09-28 19:11:20.703 UTC | null | 5,120,114 | null | 1,647,559 | null | 1 | 25 | angularjs|reactjs | 23,946 | <p>I prefer to create a service in another file that exposes the 'public' functions through module.exports.</p>
<p>e.g.</p>
<pre><code>module.exports = {
foo: function(){ return bar; }
}
</code></pre>
<p>which is then referenced by Components using</p>
<pre><code>import myService from './routetoservice/myService'
</code></pre> |
18,791,882 | How to make program go back to the top of the code instead of closing | <p>I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do</p>
<pre><code>start:
textwindow.writeline("Poo")
goto start
</code></pre>
<p>But I can't figure out how you do that in Python :/ Any ideas anyone?</p>
<p>The code I'm trying to loop is this</p>
<pre><code>#Alan's Toolkit for conversions
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
start()
</code></pre>
<p>So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.</p> | 18,791,952 | 7 | 0 | null | 2013-09-13 17:20:36.537 UTC | 12 | 2021-09-20 18:55:48.083 UTC | 2019-02-19 00:29:19.783 UTC | user1440897 | 6,862,601 | null | 2,756,717 | null | 1 | 12 | python|python-3.3 | 372,359 | <p>Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.</p>
<p><strong>1. Loops</strong></p>
<p>An example of how you could do exactly what your SmallBasic example does is as follows:</p>
<pre><code>while True :
print "Poo"
</code></pre>
<p>It's that simple.</p>
<p><strong>2. Recursion</strong></p>
<pre><code>def the_func() :
print "Poo"
the_func()
the_func()
</code></pre>
<p>Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!</p>
<h1>Edited to Answer Question More Specifically</h1>
<pre><code>#Alan's Toolkit for conversions
invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")
while invalid_input: # this will loop until invalid_input is set to be False
start()
</code></pre> |
30,239,823 | Laravel RESTful API versioning design | <p>I am new to Laravel (4 and 5) and I have recently been working on a RESTful API.
In order to allow multiple versions of the API, I am using a URL to determine the version.</p>
<p>It seems most people are following this approach:
<a href="https://stackoverflow.com/questions/16501010/how-to-organize-different-versioned-rest-api-controllers-in-laravel-4">How to organize different versioned REST API controllers in Laravel 4?</a></p>
<p>Folders structures:</p>
<pre><code>/app
/controllers
/Api
/v1
/UserController.php
/v2
/UserController.php
</code></pre>
<p>And in <code>UserController.php</code> files I set the namespace accordingly:</p>
<pre><code>namespace Api\v1;
</code></pre>
<p>or</p>
<pre><code>namespace Api\v2;
</code></pre>
<p>and in routes:</p>
<pre><code>Route::group(['prefix' => 'api/v1'], function () {
Route::get('user', 'Api\v1\UserController@index');
Route::get('user/{id}', 'Api\v1\UserController@show');
});
Route::group(['prefix' => 'api/v2'], function () {
Route::get('user', 'Api\v2\UserController@index');
Route::get('user/{id}', 'Api\v2\UserController@show');
});
</code></pre>
<p>The URL will simply be <code>http://..../api/v1</code> for version 1 and <code>http://..../api/v2</code> for version 2. This is straightforward.</p>
<p><strong>My questions is:</strong><br />
What if I am building a minor upgrade of the API, say v1.1, how do I organize my folder structure?<br />
My thought was as follows and should this be still fine as dot is a valid name of folders?</p>
<pre><code>/app
/controllers
/Api
/v1
/UserController.php
/v1.1
/UserController.php
/v1.2
/UserController.php
/v2
/UserController.php
</code></pre>
<p>Also, <strong>how should I write the namespace?</strong> There is no namespace like this</p>
<pre><code>namespace Api\v1.1;
</code></pre>
<p>Is there a naming convention I can refer to for using "dot" ?</p>
<p>Note: I do not want to call it version v2 because this is not a major upgrade.</p> | 30,240,198 | 3 | 1 | null | 2015-05-14 14:23:09.227 UTC | 19 | 2021-05-07 10:38:02.987 UTC | 2021-05-07 10:38:02.987 UTC | null | 9,213,345 | null | 4,900,126 | null | 1 | 49 | php|laravel|rest | 21,917 | <p>IMO, minor upgrades should not publish breaking changes to an API. So my suggestion is to stick to integer versioned APIs. Enhancements are no problems, but existing endpoints should behave as usual. </p>
<p>This way your API-Versions would be in sync with the route-prefixes and the namespaces as well as the tests.</p>
<p><strong>EXAMPLE</strong></p>
<ol>
<li>You begin with v1.0</li>
<li>You make a little change (eg. git-tag v1.1) which does not bring breaking changes to your api. Is there a need for developers to do anything else in their code? No, there is not. So you can safeley let the URI-Prefix stay at <code>V1</code>, so that developers calling your api do not need to change all their code which is calling your API (and therefore, automatically benefit from the new minor version). Maybe you just fixed a bug, which makes their code behave just as expected or you published a new feature, which by its self does not break existing feature-calls.</li>
<li>Your App grows and you publish new redesigned version of you API which contains breaking changes. In this case, you publish a new API-URI-prefix (<code>V2</code>).</li>
</ol>
<p>Be aware that you can of course keep track of the minor versions internally (e.g in SCM), but there should be no need for developers to change all of their API-Calls just to benefit from that little bugfix you published. Anyways, it is nice of course if you notify your clients of the newer minor versions and the bugfixes or enhancements they offer (blog, newsletter, ..)</p>
<p>Let me add, that i am not aware of any RESTful APIs with minor API-URL-prefixes, so i guess this is quite a common practice.</p> |
30,074,492 | What is the difference between utf8mb4 and utf8 charsets in MySQL? | <p>What is the difference between <code>utf8mb4</code> and <code>utf8</code> charsets in <em>MySQL</em>?</p>
<p>I already know about <em>ASCII</em>, <em>UTF-8</em>, <em>UTF-16</em> and <em>UTF-32</em> encodings;
but I'm curious to know whats the difference of <code>utf8mb4</code> group of encodings with other encoding types defined in <em>MySQL Server</em>.</p>
<p><strong>Are there any special benefits/proposes of using <code>utf8mb4</code> rather than <code>utf8</code>?</strong></p> | 30,074,553 | 5 | 2 | null | 2015-05-06 10:45:12.223 UTC | 110 | 2021-01-15 00:59:36.417 UTC | 2018-09-14 18:26:47.317 UTC | null | 4,217,744 | null | 2,721,611 | null | 1 | 465 | mysql|encoding|utf-8|character-encoding|utf8mb4 | 267,903 | <p><a href="https://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">UTF-8</a> is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL's encoding called "utf8" (alias of "utf8mb3") only stores a maximum of three bytes per code point.</p>
<p>So the character set "utf8"/"utf8mb3" cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the "<a href="http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane" rel="noreferrer">Basic Multilingual Plane</a>".
See also <a href="http://en.wikipedia.org/wiki/Comparison_of_Unicode_encodings#In_detail" rel="noreferrer">Comparison of Unicode encodings</a>.</p>
<p>This is what (a previous version of the same page at) <a href="https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html" rel="noreferrer">the MySQL documentation</a> has to say about it:</p>
<blockquote>
<p>The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:</p>
<ul>
<li><p>For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.</p>
</li>
<li><p>For a supplementary character, <strong>utf8[/utf8mb3] cannot store the character at all</strong>, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.</p>
</li>
</ul>
</blockquote>
<p>So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as <a href="https://en.wikipedia.org/wiki/Emoji" rel="noreferrer">emoji</a>, use "utf8mb4". See also <a href="https://stackoverflow.com/questions/5567249/what-are-the-most-common-non-bmp-unicode-characters-in-actual-use">What are the most common non-BMP Unicode characters in actual use?</a>.</p> |
9,002,236 | Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count | <p>I am getting this exception about commits and rollbacks but am not sure what exactly is wrong with my Stored Procedure. I have read the answers in other such questions and am unable to find where exactly the commit count is getting messed up.</p>
<p>So, this is the Stored Procedure I use:</p>
<pre><code>-- this is a procedure used for the purge utility. This procedure uses the parameters of a date and lets user select
-- if the leads that should be purge must be closed either before, on or since that date.
-- operator: 0-->less 1-->equal 2-->greater
-- @closed: closing date
-- leadscount: returns the count of leads deleted
IF OBJECT_ID ('LEAD_PURGE', 'P') IS NOT NULL
DROP PROCEDURE LEAD_PURGE
go
CREATE PROCEDURE LEAD_PURGE
@purgextns INT,
@leadscount INT OUTPUT
AS
BEGIN
BEGIN TRANSACTION
CREATE TABLE #ASSIGNMENTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #MAPRESULTS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #COMMAND_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #PROGRESS_STATUS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #DETAILS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
CREATE TABLE #NEEDS_DELETED
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
insert into #ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD);
SELECT @leadscount = (SELECT COUNT(*) FROM PURGE_LEAD);
INSERT INTO #MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
INSERT INTO #COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM #MAPRESULTS_DELETED)
INSERT INTO #PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
INSERT INTO #DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
INSERT INTO #NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM #PROGRESS_STATUS_DELETED)
DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM #COMMAND_DELETED)
DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED))
DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM #MAPRESULTS_DELETED)
DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
(SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED))
DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM #ASSIGNMENTS_DELETED)
DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #SALE_DELETED_EX
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD))
DELETE FROM SALEEXTENSIONS WHERE
SEQID IN (SELECT ID FROM #SALE_DELETED_EX)
DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM #NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM #DETAILS_DELETED)
DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM #NEEDS_DELETED UNION SELECT ID FROM #DETAILS_DELETED)
DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM PURGE_LEAD)
DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM PURGE_LEAD)
CREATE TABLE #PURGE_LEAD_E
(
ID NUMERIC(19, 0)
PRIMARY KEY (ID)
)
INSERT into #PURGE_LEAD_E Select SEQID FROM LEADEXTENSIONS WHERE
SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD)
if @purgextns = 1 begin
DELETE FROM LEADEXTENSIONS WHERE
SEQID IN (SELECT ID FROM PURGE_LEAD_E)
end
DELETE FROM PURGE_LEAD;
DROP TABLE #ASSIGNMENTS_DELETED
DROP TABLE #MAPRESULTS_DELETED
DROP TABLE #COMMAND_DELETED
DROP TABLE #PROGRESS_STATUS_DELETED
DROP TABLE #DETAILS_DELETED
DROP TABLE #NEEDS_DELETED
DROP TABLE #PURGE_LEAD_E
DROP TABLE #SALE_DELETED_EX
COMMIT
END
go
</code></pre>
<p>now I call this procedure in the following code:</p>
<pre><code> try {
c = new ConnectionHelper().getConnection();
String sql = "";
if (shouldPurgeExtns) {
progressModel.makeProgress("progress.deleting.dependents");
purgeMultiselect(c, LEAD, isMSSQL);
}
sql = "{CALL " + TOPLinkManager.getSchemaPrefix()
+ "LEAD_PURGE (?,?)}";
cs = c.prepareCall(sql);
cs.setInt(1, shouldPurgeExtns ? 0 : 1);
cs.registerOutParameter(2, java.sql.Types.INTEGER);
cs.executeUpdate();
int rowcount = cs.getInt(2);
cs.close();
progressModel.makeProgress("progress.recording.history");
recordHistory(c, isMSSQL, LEAD, DateTypeDecorator.CLOSED, date,
rowcount);
done(progressModel);
c.close();
return true;
} catch (Exception e) {
Logs.main.error("Error Purging Leads", e);
throw new Exception(e.getMessage());
}
</code></pre>
<p>And I get an exception on the line which say <code>int rowcount = cs.getInt(2);</code></p>
<p>The Exception is:</p>
<pre><code>com.microsoft.sqlserver.jdbc.SQLServerException: Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.processResults(SQLServerStatement.java:1083)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getOutParameter(SQLServerCallableStatement.java:112)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getterGetParam(SQLServerCallableStatement.java:387)
</code></pre>
<p>Please help me out.
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getValue(SQLServerCallableStatement.java:393)
at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.getInt(SQLServerCallableStatement.java:437)
at marketsoft.tools.purge.PurgeUtils.PurgeLeads(PurgeUtils.java:283)</p>
<p><strong>EDIT:</strong></p>
<p>as I have answered this question myself... I would like to change the question a bit now.</p>
<p><strong>Why was no exception thrown in the execute method???</strong></p> | 9,006,677 | 5 | 0 | null | 2012-01-25 11:51:20.5 UTC | 2 | 2013-08-08 14:48:20.77 UTC | 2012-01-27 05:14:57.213 UTC | null | 896,663 | null | 896,663 | null | 1 | 7 | java|sql-server|database|stored-procedures|jdbc | 73,650 | <p>Sorry Guys! Thanks for all your efforts, In the end, it was a very small mistake on my part in the Stored Procedure:</p>
<p>Look at line:</p>
<pre><code>if @purgextns = 1 begin
DELETE FROM LEADEXTENSIONS WHERE
SEQID IN (SELECT ID FROM PURGE_LEAD_E)
end
</code></pre>
<p>It should be <code>#PURGE_LEAD_E</code></p>
<p>All your answers helped me get a different perspective of store procedure development. Thanks a lot!</p> |
8,517,853 | Iterating over a QMap with for | <p>I've a <code>QMap</code> object and I am trying to write its content to a file.</p>
<pre><code>QMap<QString, QString> extensions;
//..
for(auto e : extensions)
{
fout << e.first << "," << e.second << '\n';
}
</code></pre>
<p>Why do I get: <code>error: 'class QString' has no member named 'first' nor 'second'</code></p>
<p>Is <code>e</code> not of type <code>QPair</code>?</p> | 8,529,084 | 9 | 0 | null | 2011-12-15 09:31:17.037 UTC | 13 | 2021-06-16 20:08:55.297 UTC | 2015-05-08 02:38:45.283 UTC | null | 596,951 | null | 336,635 | null | 1 | 62 | c++|qt|c++11|qmap | 91,027 | <p>If you want the STL style with <code>first</code> and <code>second</code>, do this:</p>
<pre><code>for(auto e : extensions.toStdMap())
{
fout << e.first << "," << e.second << '\n';
}
</code></pre>
<p>If you want to use what Qt offers, do this:</p>
<pre><code>for(auto e : extensions.keys())
{
fout << e << "," << extensions.value(e) << '\n';
}
</code></pre> |
253,051 | What's the difference between #import and @class, and when should I use one over the other? | <p>I've been teaching myself Objective-C over the past month or so (I'm a Java head) and I've got my brain wrapped around most of it now. One thing that's confusing me at the moment: What's the difference between importing a class via @class vs doing a #import? </p>
<p>Is one better than another one, or do I need to use one instead of the other in certain cases? I've been using just #import so far.</p> | 253,154 | 3 | 0 | null | 2008-10-31 10:21:04.093 UTC | 17 | 2012-06-21 18:36:01.653 UTC | 2012-06-21 18:36:01.653 UTC | Ned Batchelder | 1,422,200 | rustyshelf | 6,044 | null | 1 | 30 | objective-c|cocoa-touch | 9,675 | <p><code>#import</code> brings the entire header file in question into the current file; any files that THAT file <code>#import</code>s are also included. @class, on the other hand (when used on a line by itself with some class names), just tells the compiler "Hey, you're going to see a new token soon; it's a class, so treat it that way).</p>
<p>This is very useful when you've got the potential for 'circular includes'; ie, Object1.h makes reference to Object2, and Object2.h makes reference to Object1. If you <code>#import</code>both files into the other, the compiler can get confused as it tries to <code>#import</code> Object1.h, looks in it and sees Object2.h; it tries to <code>#import</code> Object2.h, and sees Object1.h, etc. </p>
<p>If, on the other hand, each of those files has <code>@class Object1;</code> or <code>@class Object2;</code>, then there's no circular reference. Just be sure to actually <code>#import</code> the required headers into your implementation (.m) files.</p> |
35,155,447 | The AspNetUserLogins table Identity | <p>What is the AspNetUserLogins for? Is It to store the logins from the user? How can I then update this table with that data?</p> | 35,156,159 | 1 | 1 | null | 2016-02-02 13:57:56.037 UTC | 7 | 2021-12-31 14:10:10.607 UTC | 2016-02-02 14:13:28.49 UTC | null | 1,549,450 | null | 4,444,267 | null | 1 | 52 | c#|asp.net-mvc|entity-framework|asp.net-identity | 23,429 | <p><strong>What is the AspNetUserLogins for?</strong>
In Asp.net Identity, the Identity system uses the <code>AspNetUserLogins</code> table to hold information about 3rd party/external logins, for example users who login into your site via Google, Facebook, Twitter etc. The <code>AspNetUsers</code> table is the primary table to store user information, this is linked to <code>AspNetUserLogins</code> via <code>UserId -> AspNetUsers.Id</code>.</p>
<p>For example if the user logs into your site via Facebook, then the <code>LoginProvider</code> is the name of the service which provided the login, so in this case "<strong>Facebook</strong>", the <code>ProviderKey</code> is a unique Facebook key associated with the user on Facebook.</p>
<p>This table is used by the Asp.net external authentication providers.</p>
<p><strong>Is it to store the logins from the user?</strong>
No not really, it is used as explained above</p>
<p><strong>How can I then update this table with that data?</strong>
You don't update the data in this table, usually when a user logs in via external provider, after user has been authenticated, the provider returns a <code>ClaimsIdentity</code>, which has users claims and one of those is a unique id of the user in the external provider, this gets automatically updated in this table.</p>
<p>read more about external providers <a href="http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity" rel="noreferrer">here</a></p> |
24,081,230 | How Does VideoToolbox.framework work? | <p>iOS8 just released beta version, I'm very interested in Video directly Encoding / Decoding.</p>
<blockquote>
<p><strong>Video Toolbox Framework</strong></p>
<p>The Video Toolbox framework (VideoToolbox.framework) includes direct
access to hardware video encoding and decoding.</p>
</blockquote>
<p>but I can not find any tutorial documents for this right now</p>
<p>as I know it's a private framework before, and some people already using it in some JB apps</p>
<p>so does anyone can share a very simple tutorial code for this ?</p> | 24,083,535 | 2 | 0 | null | 2014-06-06 11:53:14.24 UTC | 11 | 2016-10-10 08:14:35.823 UTC | null | null | null | null | 1,822,879 | null | 1 | 3 | ios|xcode | 10,487 | <p>Import the framework and look at the headers, they're all documented.</p>
<p>Apple also released a <a href="https://developer.apple.com/library/prerelease/ios/samplecode/VideoTimeline/Introduction/Intro.html#//apple_ref/doc/uid/TP40014525" rel="nofollow">sample using VTDecompressionSession</a></p> |
5,963,080 | disable request buffering in nginx | <p>It seems that nginx buffers requests before passing it to the updstream server,while it is OK for most cases for me it is very bad :)</p>
<p>My case is like this:</p>
<p>I have nginx as a frontend server to proxy 3 different servers:</p>
<ol>
<li>apache with a typical php app</li>
<li>shaveet(a open source comet server) built by me with python and gevent</li>
<li>a file upload server built again with gevent that proxies the uploads to rackspace cloudfiles
while accepting the upload from the client.</li>
</ol>
<p>#3 is the problem, right now what I have is that nginx buffers all the request and then sends that to the file upload server which in turn sends it to cloudfiles instead of sending each chunk as it gets it (those making the upload faster as i can push 6-7MB/s to cloudfiles).</p>
<p>The reason I use nginx is to have 3 different domains with one IP if I can't do that I will have to move the fileupload server to another machine.</p> | 12,288,463 | 4 | 3 | null | 2011-05-11 10:56:26.213 UTC | 9 | 2015-04-29 10:13:14.023 UTC | 2011-05-11 10:59:20.343 UTC | null | 211,359 | null | 334,886 | null | 1 | 11 | file-upload|nginx|asyncfileupload|gevent | 24,247 | <p>According to <a href="http://gunicorn.org/deploy.html" rel="noreferrer">Gunicorn</a>, they suggest you use nginx to actually buffer clients and prevent slowloris attacks. So this buffering is likely a good thing. However, I do see an option further down on that link I provided where it talks about removing the proxy buffer, it's not clear if this is within nginx or not, but it looks as though it is. Of course this is under the assumption you have Gunicorn running, which you do not. Perhaps it's still useful to you.</p>
<p>EDIT: I did some research and that buffer disable in nginx is for outbound, long-polling data. Nginx states on their <a href="http://wiki.nginx.org/HttpProxyModule" rel="noreferrer">wiki</a> site that inbound requests have to be buffered before being sent upstream.</p>
<blockquote>
<p>"Note that when using the HTTP Proxy Module (or even when using FastCGI), the entire client request will be buffered in nginx before being passed on to the backend proxied servers. As a result, upload progress meters will not function correctly if they work by measuring the data received by the backend servers."</p>
</blockquote> |
5,885,634 | create new instance of a class without "new" operator | <p>Just a simple question. As the title suggests, I've only used the "new" operator to create new instances of a class, so I was wondering what the other method was and how to correctly use it.</p> | 5,885,679 | 4 | 0 | null | 2011-05-04 15:10:09.677 UTC | 8 | 2013-06-30 20:35:24.043 UTC | 2013-06-30 20:35:24.043 UTC | null | 41,071 | null | 699,969 | null | 1 | 20 | c++|class | 43,305 | <p>You can also have <em>automatic</em> instances of your class, that doesn't use <code>new</code>, as:</p>
<pre><code>class A{};
//automatic
A a;
//using new
A *pA = new A();
//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();
//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
</code></pre>
<p>The last two are using <a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="nofollow noreferrer">placement-new</a> which is slightly different from just <em>new</em>. placement-new is used to construct the object by calling the constructor. In the third example, <code>malloc</code> only allocates the memory, it doesn't call the constructor, that is why <em>placement-new</em> is used to call the constructor to construct the object.</p>
<p>Also note how to delete the memory.</p>
<pre><code> //when pA is created using new
delete pA;
//when pA is allocated memory using malloc, and constructed using placement-new
pA->~A(); //call the destructor first
free(pA); //then free the memory
//when pA constructed using placement-new, and no malloc or new!
pA->~A(); //just call the destructor, that's it!
</code></pre>
<hr>
<p>To know what is placement-new, read these FAQs:</p>
<ul>
<li><a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="nofollow noreferrer">What is "placement new" and why would I use it?</a> (FAQ at parashift.com)</li>
<li><a href="https://stackoverflow.com/questions/222557/cs-placement-new">placement new</a> (FAQ at stackoverflow.com)</li>
</ul> |
46,092,104 | Subclass in type hinting | <p>I want to allow type hinting using Python 3 to accept sub classes of a certain class. E.g.:</p>
<pre><code>class A:
pass
class B(A):
pass
class C(A):
pass
def process_any_subclass_type_of_A(cls: A):
if cls == B:
# do something
elif cls == C:
# do something else
</code></pre>
<p>Now when typing the following code:</p>
<pre><code>process_any_subclass_type_of_A(B)
</code></pre>
<p>I get an PyCharm IDE hint 'Expected type A, got Type[B] instead.'</p>
<p>How can I change type hinting here to accept any subtypes of A?</p>
<p>According to <a href="https://www.python.org/dev/peps/pep-0484/#type-definition-syntax" rel="noreferrer">PEP 484</a> ("Expressions whose type is a subtype of a specific argument type are also accepted for that argument."), I understand that my solution <code>(cls: A)</code> should work?</p> | 46,092,347 | 3 | 3 | null | 2017-09-07 08:59:09.73 UTC | 20 | 2022-07-31 17:06:34.5 UTC | 2021-10-06 13:40:31.66 UTC | null | 13,990,016 | null | 1,211,030 | null | 1 | 176 | python|subclass|type-hinting|python-typing | 67,355 | <p>When you specify <code>cls: A</code>, you're saying that <code>cls</code> expects an <em>instance</em> of type <code>A</code>. The type hint to specify <code>cls</code> as a class object for the type <code>A</code> (or its subtypes) uses <a href="https://docs.python.org/3/library/typing.html#typing.Type" rel="noreferrer"><code>typing.Type</code></a>.</p>
<pre><code>from typing import Type
def process_any_subclass_type_of_A(cls: Type[A]):
pass
</code></pre>
<p>From <a href="http://mypy.readthedocs.io/en/latest/kinds_of_types.html#the-type-of-class-objects" rel="noreferrer">The type of class objects
</a>:</p>
<blockquote>
<p>Sometimes you want to talk about class objects that inherit from a
given class. This can be spelled as <code>Type[C]</code> where <code>C</code> is a class. In
other words, when <code>C</code> is the name of a class, using <code>C</code> to annotate an
argument declares that the argument is an instance of <code>C</code> (or of a
subclass of <code>C</code>), but using <code>Type[C]</code> as an argument annotation declares
that the argument is a class object deriving from <code>C</code> (or <code>C</code> itself).</p>
</blockquote> |
66,246,587 | How to fix error 'not found husky-run' when committing new code? | <p>When committing on a project that uses Husky, I get an error that says <code>not found husky-run</code></p>
<p>I checked the <code>package.json</code> and it has husky as a dependency, and I can see the pre-commit hook configuration for Husky in the <code>package.json</code>. So I don't know what to do to fix this. Additionally, other members on my team can commit and husky works for them.</p>
<p>I also tried <code>rm -rf node_modules && npm install</code> and then committing again, but still, I get the same error.</p>
<p>Anyone else have ideas on how to fix this?</p> | 66,246,588 | 9 | 1 | null | 2021-02-17 17:00:51.08 UTC | 5 | 2022-06-15 15:55:01.84 UTC | null | null | null | null | 586,809 | null | 1 | 46 | git|husky | 65,400 | <p>To fix this there are two methods, depending on which version of Husky you are already on.</p>
<p>If you're using Husky v4 or lower, do the following:</p>
<pre class="lang-sh prettyprint-override"><code>rm -rf .git/hooks
npm install
</code></pre>
<p>For Husky v7 or greater, do the following:</p>
<pre class="lang-sh prettyprint-override"><code># For NPM
npm install husky@7 --save-dev \
&& npx husky-init \
&& npm exec -- github:typicode/husky-4-to-7 --remove-v4-config
# For Yarn
yarn add husky@7 --dev \
&& npx husky-init \
&& npm exec -- github:typicode/husky-4-to-7 --remove-v4-config
# or
yarn add husky@7 --dev \
&& yarn dlx husky-init --yarn2 \
&& npm exec -- github:typicode/husky-4-to-7 --remove-v4-config
</code></pre>
<p>At this point you should be able to commit and have your hooks working again.</p>
<p>If anything goes wrong, please read the <a href="https://github.com/typicode/husky-4-to-7" rel="noreferrer">documentation for migration from 4 to 7</a>.</p> |
53,752,102 | Persistent authorisation for mounting Google Drive in Google Colab | <p>I'm using Google Colab and need to restart my notebook at least once a day due to their usage limits.</p>
<p>To mount my Google Drive I have the following code:</p>
<pre><code>from google.colab import drive
drive.mount('drive')
</code></pre>
<p>I then get a prompt:</p>
<blockquote>
<p>Go to this URL in a browser: <a href="https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxxx" rel="noreferrer">https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxxx</a>....</p>
<p>Enter your authorization code: ___________________________________________________</p>
</blockquote>
<hr>
<p>How can I authorise only once and have that authorisation remembered?</p>
<p>Ideally, that authorisation will have already happened as I'm signed in to Gmail and I can just specify the account email address of the Drive to mount.</p>
<p>However any solution of persistent authorisation where I don't store the auth code in the notebook would be great.</p> | 59,273,991 | 1 | 2 | null | 2018-12-12 22:06:25.717 UTC | 10 | 2020-02-06 23:27:51.17 UTC | 2018-12-17 07:55:17.49 UTC | null | 5,353,461 | null | 5,353,461 | null | 1 | 18 | google-drive-api|google-oauth|google-colaboratory | 10,126 | <p>You can't set it to only authenticate once and stay that way for a new runtime, because Colab runs on a VM that is recycled periodically. You can make sure <code>force_remount</code> is set to <code>False</code> so it doesn't unnecessarily ask you to reauthorize:</p>
<pre><code>drive.mount('/content/gdrive', force_remount=False)
</code></pre>
<p>But any time you reset the runtime, you will need to reauthenticate with a different authorization code. </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.