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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,901,149 | com.google.android.gms.maps.MapFragment: Cannot resolve symbol "maps" | <p>I've followed all of the directions here with no issues:</p>
<p><a href="https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2">https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2</a></p>
<p>Finally, I follow the last instruction to test if the map is working, updating my activity_map.xml file with:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</code></pre>
<p>However, in the last line, everything after <code>com.google</code> is red, and on mouse over I get the message that "Cannot resolve symbol 'MapFragment'.</p>
<p>Any ideas would be a big help right now.</p> | 28,392,913 | 8 | 6 | null | 2014-11-13 04:05:40.933 UTC | 4 | 2021-12-01 00:19:47.04 UTC | null | null | null | null | 2,363,734 | null | 1 | 31 | android|google-maps | 59,068 | <p>Do the following to solve the issue:</p>
<p><img src="https://i.stack.imgur.com/w5Ust.png" alt="Install Google Play services" /></p>
<p><img src="https://i.stack.imgur.com/tGSEZ.png" alt="Go File->Project Structure..." /></p>
<p><img src="https://i.stack.imgur.com/Y0ciS.png" alt="Dependencies Tab, Add com.google.android.gms" /></p>
<p>Finally: click on <strong>"+"</strong> button</p>
<p><a href="https://i.stack.imgur.com/l4fgf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l4fgf.png" alt="enter image description here" /></a></p>
<p>After that, clean and rebuild the project!</p> |
9,857,420 | ViewPager Fragments getting destroyed over time? | <p>I am using Android's <code>support.v4</code> package to develop a ViewPager containing multiple <code>Fragment</code>s.</p>
<p>I am trying to hide the Views when the user changes page. So, I implemented an <code>OnPageChangeListener</code> to listen to my adapter, and call an <code>update()</code> method in my <code>Fragment</code>s when when a page change occurs. But I'm getting a <code>NullPointerException</code>, and I cannot figure out why.</p>
<p>Here is the code:</p>
<pre><code>public class MyActivity extends FragmentActivity implements
OnPageChangeListener {
private static final int NUM_ITEMS = 2;
private ViewPager mPager;
private static SpaceAdapter mAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new SpaceAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setOnPageChangeListener(this);
}
public static class SpaceAdapter extends FragmentPagerAdapter {
public SpaceAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyFragment();
case 1:
return new MyFragment();
default:
return new MyFragment();
}
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
Log.i("pagination", "scroll state changed: " + arg0);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// Log.i("pagination", "page scroll: " + arg0 + " with: " + arg1 + ", " + arg2);
if (mAdapter.getItem(arg0) instanceof IUpdateOnPage) {
((IUpdateOnPage) mAdapter.getItem(arg0)).updateOnPage();
}
}
@Override
public void onPageSelected(int arg0) {
Log.i("pagination", "page selected: " + arg0);
}
}
</code></pre>
<p>and</p>
<pre><code>public class MyFragment extends Fragment implements
SurfaceHolder.Callback, IUpdateOnPage {
private SurfaceView charts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.crew, null);
bindViews(v);
return v;
}
private void bindViews(View v) {
charts = (SurfaceView) v.findViewById(R.id.civ_charts);
charts.getHolder().addCallback(this);
Log.i("wtf", "huh " + String.valueOf(charts == null)); // logs false
}
@Override
public void updateOnPage() {
if (charts != null) {
Log.i("crew surface", "hidden");
charts.setVisibility(View.GONE);
} else {
Log.i("crew surface", "charts is null"); //THIS HERE gets logged
}
}
}
</code></pre>
<p>wWhen I copy/pasted I removed the <code>SurfaceHolder.Callback</code> methods, but they are there. The <code>bindViews(v)</code> method logs if <code>charts == null</code>, and that always returns false. When I page, <code>updateOnPage</code> gets called, and <code>charts == null</code> returns true. Why does this happen and how do I get around it?</p>
<p>and this is line 108:</p>
<pre><code>charts.setVisibility(View.GONE);
</code></pre> | 9,857,921 | 2 | 3 | null | 2012-03-25 02:20:43.08 UTC | 13 | 2012-06-27 08:17:51.437 UTC | 2012-05-23 14:18:24.307 UTC | null | 844,882 | null | 1,215,251 | null | 1 | 17 | java|android|nullpointerexception|android-fragments|android-viewpager | 8,856 | <p>Add the following when you initialize your <code>ViewPager</code>,</p>
<pre><code>mPager.setOffscreenPageLimit(NUM_ITEMS-1);
</code></pre>
<p>In your case, this will set the number of off-screen pages to 1 (i.e. it will keep the additional off-screen page in memory when the other page is currently in focus). This will force your <code>ViewPager</code> to keep all of the <code>Fragment</code>s even when they are not in focus.</p> |
10,102,869 | How do I get a live stream of deltas from Meteor collection, for use outside of a webapp? | <p>How do I get a live stream of deltas from Meteor collection, for use outside of a webapp?</p>
<p>I'm looking for an initial result set, plus a series of operations on that result set, delivered as the happen.</p>
<p>Thanks,</p>
<p>Chris.</p> | 10,120,571 | 3 | 0 | null | 2012-04-11 09:00:24.287 UTC | 10 | 2013-06-07 00:18:32.68 UTC | null | null | null | null | 129,805 | null | 1 | 19 | node.js|meteor | 3,331 | <p>The Meteor protocol is called DDP. It does exactly what you're asking for: you send a "subscribe" message that says what data you want to get, and then you get back the initial result set and then a stream of create/update/delete messages.</p>
<p>So what you need is a DDP client for whatever language the other program is written in. Since Meteor is so new, these don't exist yet. But a lot of people already written in to say that they want to write them. If you're interested in getting involved with that you should send a message to [email protected].</p> |
9,728,269 | Content-length and other HTTP headers? | <p>Does it give me any advantage if I set this header when generating normal HTML pages?</p>
<p>I see that some frameworks out there will set this header property and I was wondering why...
(Along with other headers, like <code>Content-Type: text/html</code>)</p>
<p>Does browser load the site faster or smoother?</p>
<p>ps: they do it like:</p>
<pre><code>ob_start();
... stuff here...
$content = ob_get_contents();
$length = strlen($content);
header('Content-Length: '.$length);
echo $content;
</code></pre> | 9,728,576 | 7 | 1 | null | 2012-03-15 21:14:46.043 UTC | 7 | 2021-01-31 01:16:22.803 UTC | 2018-04-09 14:36:42.133 UTC | null | 7,733,026 | null | 1,234,607 | null | 1 | 20 | php|http-headers | 80,574 | <p>I think its only because of the HTTP Spec says to do this in every case possible.</p>
<blockquote>
<p>Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.</p>
</blockquote>
<p>You can also look <a href="https://stackoverflow.com/questions/3854842/content-length-header-with-head-requests/3854983#3854983">at Pauls Answer</a> on the <a href="https://stackoverflow.com/questions/3854842/content-length-header-with-head-requests">Question of Deaomon</a>.</p>
<p>I think this will answer yours too.</p>
<p>Also you should use Content-Length if you want someone download a file with another header:
e.g.</p>
<pre><code><?php
$file = "original.pdf"
$size = filesize($file);
header('Content-type: application/pdf');
header("Content-length: $size");
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($file);
?>
</code></pre> |
9,813,983 | Troubles uninstalling oh-my-zsh? | <p>I'm on OSX and want to switch back to my original zsh config from <a href="http://github.com/robbyrussell/oh-my-zsh" rel="noreferrer">oh-my-zsh</a>, however when I run the <code>uninstall</code> script it gives me an error:</p>
<pre><code>$ sudo uninstall oh-my-zsh
>> Preparing Uninstall...
Uninstall Began...
Uninstall Failed...
Reason: ErrorMissingBundle
</code></pre>
<p>Can anyone please tell me what this means? Thanks!</p> | 10,051,578 | 5 | 0 | null | 2012-03-21 22:46:12.69 UTC | 7 | 2020-03-05 11:50:11.6 UTC | null | null | null | null | 1,146,840 | null | 1 | 27 | config|uninstallation|zsh | 95,914 | <p>Have you tried just running the commands from uninstall script by hand? It's really straight forward: <a href="https://github.com/robbyrussell/oh-my-zsh/blob/master/tools/uninstall.sh">https://github.com/robbyrussell/oh-my-zsh/blob/master/tools/uninstall.sh</a>. For the most part it just removes OMZ and attempts to restore a back up file:</p>
<pre><code>rm -rf ~/.oh-my-zsh
rm ~/.zshrc
cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc
source ~/.zshrc
</code></pre> |
9,949,077 | Difference between ForeignKey(User, unique=True) and OneToOneField | <p>What is different between <code>models.ForeignKey(Modelname, unique=True)</code> and <code>models.OneToOneField</code> in Django? </p>
<p>Where should I use <code>models.OneToOneField</code> and <code>models.ForeignKey(Modelname, unique=True)</code>?</p> | 9,949,278 | 2 | 1 | null | 2012-03-30 19:09:10.513 UTC | 8 | 2016-03-02 23:07:21.837 UTC | 2012-03-30 19:27:24.393 UTC | null | 113,962 | null | 513,302 | null | 1 | 32 | django|django-models | 22,898 | <p>A <code>OneToOneField</code> is very similar to a <code>ForeignKey</code> with <code>unique=True</code>. Unless you are doing multiple table inheritance, in which case you have to use <code>OneToOneField</code>, the only real difference is the api for accessing related objects.</p>
<p>In the <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#onetoonefield" rel="noreferrer">Django docs</a> it says:</p>
<blockquote>
<p>Conceptually, this is similar to a <code>ForeignKey</code> with <code>unique=True</code>, but the "reverse" side of the relation will directly return a single object.</p>
</blockquote>
<p>Let's show what that means with an example. Consider two models, <code>Person</code> and <code>Address</code>. We'll assume each person has a unique address.</p>
<pre><code>class Person(models.Model):
name = models.CharField(max_length=50)
address = models.ForeignKey('Address', unique=True)
class Address(models.Model):
street = models.CharField(max_length=50)
</code></pre>
<p>If you start with a person, you can access the address easily:</p>
<pre><code>address = person.address
</code></pre>
<p>However if you start with an address, you have to go via the <code>person_set</code> manager to get the person.</p>
<pre><code>person = address.person_set.get() # may raise Person.DoesNotExist
</code></pre>
<p>Now let's replace the <code>ForeignKey</code> with a <code>OneToOneField</code>.</p>
<pre><code>class Person(models.Model):
name = models.CharField(max_length=50)
address = models.OneToOneField('Address')
class Address(models.Model):
street = models.CharField(max_length=50)
</code></pre>
<p>If you start with a person, you can access the address in the same way:</p>
<pre><code>address = person.address
</code></pre>
<p>And now, we can access the person from the address more easily.</p>
<pre><code>person = address.person # may raise Person.DoesNotExist
</code></pre> |
27,988,174 | Returning String Methods in Java? | <p>I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements. </p>
<p>For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?</p>
<p>Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.</p>
<p>Statements Required: output, loop control, decision making, class (optional), methods.</p>
<p>Sample Output:</p>
<p>Sales for October</p>
<p>Day Daily Sales Graph</p>
<p>2 37081 *************************************</p>
<p>3 28355 **************************** </p>
<p>4 39158 ***************************************</p>
<p>5 24904 ************************</p>
<p>6 28879 ****************************</p>
<p>7 13348 *************
"</p>
<p>Here's what I have: </p>
<pre><code>import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
</code></pre>
<p>Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:</p>
<pre><code>import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
</code></pre> | 27,988,323 | 3 | 6 | null | 2015-01-16 16:14:30.707 UTC | 1 | 2015-01-16 18:15:26.373 UTC | 2015-01-16 17:01:32.54 UTC | null | 636,009 | null | 4,462,339 | null | 1 | 5 | java|string|methods | 89,710 | <p>You're correct that your issues are rooted in not understanding <code>static</code>. There are many resources on this, but suffice to say here that something <code>static</code> belongs to a <strong>Class</strong> whereas something that isn't static belogns to a specific <strong>instance</strong>. That means that</p>
<pre><code>public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
</code></pre>
<p>So related to that your method <code>histogram</code> isn't <code>static</code>, so you need an instance to call it. You shouldn't need an instance though; just make the method static:</p>
<p>Change <code>public String histogram(int randomNum)</code> to <code>public static String histogram(int randomNum)</code>.</p>
<p>With that done, the line <code>histogram(randomNum);</code> becomes valid. However, you'll still get an error on <code>System.out.print(histogram + "\n");</code>, because <code>histogram</code> as defined here is a function, not a variable. This is related to the <code>return</code> statement. When something says <code>return x</code> (for any value of <code>x</code>), it is saying to terminate the current method call and yield the value <code>x</code> to whoever called the method.</p>
<p>For example, consider the expression <code>2 + 3</code>. If you were to say <code>int x = 2 + 3</code>, you would expect <code>x</code> to have value <code>5</code> afterwards. Now consider a method:</p>
<pre><code>public static int plus(int a, int b){
return a + b;
}
</code></pre>
<p>And the statement: <code>int x = plus(2, 3);</code>. Same here, we would expect <code>x</code> to have value <code>5</code> afterwards. The computation is done, and whoever is waiting on that value (of type <code>int</code>) receives and uses the value however a single value of that type would be used in place of it. For example:</p>
<p><code>int x = plus(plus(1,2),plus(3,plus(4,1));</code> -> <code>x</code> has value 11.</p>
<p>Back to your example: you need to assign a variable to the String value returned from <code>histogram(randomNum);</code>, as such:</p>
<p>Change <code>histogram(randomNum)</code> to <code>String s = histogram(randomNum)</code>.</p>
<p>This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable <code>main</code> method needs to be static. So change your main method to have the signature:</p>
<pre><code>public static void main(String[] args){...}
</code></pre>
<p>Then hit the green button!</p> |
9,875,076 | Adding three months to a date in PHP | <p>I have a variable called <code>$effectiveDate</code> containing the date <strong>2012-03-26</strong>.</p>
<p>I am trying to add three months to this date and have been unsuccessful at it.</p>
<p>Here is what I have tried:</p>
<pre><code>$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
</code></pre>
<p>and </p>
<pre><code>$effectiveDate = strtotime(date("Y-m-d", strtotime($effectiveDate)) . "+3 months");
</code></pre>
<p>What am I doing wrong? Neither piece of code worked.</p> | 9,875,196 | 10 | 6 | null | 2012-03-26 15:33:48.123 UTC | 18 | 2022-09-02 06:02:58.12 UTC | 2012-03-26 17:28:41.057 UTC | null | 122,607 | null | 979,331 | null | 1 | 104 | php|date|strtotime | 223,758 | <p>Change it to this will give you the expected format:</p>
<pre><code>$effectiveDate = date('Y-m-d', strtotime("+3 months", strtotime($effectiveDate)));
</code></pre> |
9,943,065 | "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server | <p>I have a 64 bit windows 7 and SQLServer 2008 R2 (64 bit)</p>
<p>I follow the instructions that are <a href="http://interdata.cl/?p=602" rel="noreferrer">here</a> to import excel file to sql server but in figure3 section of that post when I try to access excel file and when I click next this error make me stop:</p>
<pre><code>The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
</code></pre>
<p>I search the web i knew that I must install <code>AccessDatabaseEngine_x64</code>.
but when I install it I have a same problem</p>
<p>Can you please help me what to do?</p> | 10,655,821 | 8 | 0 | null | 2012-03-30 12:36:15.393 UTC | 31 | 2022-07-06 05:13:08.25 UTC | 2017-02-01 17:52:17.287 UTC | null | 2,040,375 | null | 645,181 | null | 1 | 130 | sql-server-2008|excel|oledb | 344,975 | <p>Install the following to resolve your error.</p>
<p><a href="https://download.cnet.com/2007-Office-System-Driver-Data-Connectivity-Components/3000-10254_4-75452798.html" rel="noreferrer">2007 Office System Driver: Data Connectivity Components</a></p>
<p>AccessDatabaseEngine.exe (25.3 MB)</p>
<blockquote>
<p>This download will install a set of components that facilitate the
transfer of data between existing Microsoft Office files such as
Microsoft Office Access 2007 (*.mdb and <em>.accdb) files and Microsoft
Office Excel 2007 (</em>.xls, *.<strong>xlsx</strong>, and *.xlsb) files <strong>to other data
sources such as Microsoft SQL Server</strong>.</p>
</blockquote> |
8,311,457 | Are destructors called after a throw in C++? | <p>I ran a sample program and indeed destructors for stack-allocated objects are called, but is this guaranteed by the standard?</p> | 8,311,472 | 3 | 3 | null | 2011-11-29 13:23:21.077 UTC | 20 | 2019-06-19 03:02:51.347 UTC | 2011-12-22 09:41:12.787 UTC | null | 673,730 | null | 673,730 | null | 1 | 60 | c++|exception-handling|try-catch|raii | 24,290 | <p>Yes, it is guaranteed (provided the exception is caught), down to <em>the order</em> in which the destructors are invoked:</p>
<blockquote>
<p>C++11 <strong>15.2 Constructors and destructors [except.ctor]</strong></p>
<p>1 As control passes from a throw-expression to a handler, destructors are invoked for all
automatic objects constructed since the try block was entered. The
automatic objects are destroyed in the reverse order of the completion
of their construction.</p>
</blockquote>
<p>Furthermore, if the exception is thrown during object construction, the subobjects of the partially-constructed object are guaranteed to be correctly destroyed:</p>
<blockquote>
<p>2 An object of any storage duration whose initialization or
destruction is terminated by an exception will have destructors
executed for all of its fully constructed subobjects (excluding the
variant members of a union-like class), that is, for subobjects for
which the principal constructor (12.6.2) has completed execution and
the destructor has not yet begun execution. Similarly, if the
non-delegating constructor for an object has completed execution and a
delegating constructor for that object exits with an exception, the
object’s destructor will be invoked. If the object was allocated in a
new-expression, the matching deallocation function (3.7.4.2, 5.3.4,
12.5), if any, is called to free the storage occupied by the object.</p>
</blockquote>
<p>This whole process is known as "stack unwinding":</p>
<blockquote>
<p>3 The process of calling destructors for automatic objects constructed
on the path from a try block to a throw-expression is called “stack
unwinding.” If a destructor called during stack unwinding exits with
an exception, std::terminate is called (15.5.1).</p>
</blockquote>
<p>Stack unwinding forms the basis of the widely-used technique called <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">Resource Acquisition Is Initialization (RAII)</a>.</p>
<p>Note that stack unwinding is not necessarily done if the exception is not caught. In this case it's up to the implementation whether stack unwinding is done. But whether stack unwinding is done or not, in this case you're guaranteed a final call to <code>std::terminate</code>.</p>
<blockquote>
<p>C++11 <strong>15.5.1 The std::terminate() function [except.terminate]</strong></p>
<p>2 … In the situation where no matching handler is found,
it is implementation-defined whether or not the stack is unwound before <code>std::terminate()</code> is called.</p>
</blockquote> |
11,773,225 | push data into an array with pair values | <p>how can I push data into an array in js if it's type is likw this... d= [[label, value]]. At first I want to push the label data then the values....
I get the data from an xml file.
If I had only a simple array I used the simple variable.push sintax.
Will varialble[][0].push or variable[][1].push work</p> | 11,773,326 | 3 | 1 | null | 2012-08-02 07:53:32.733 UTC | 5 | 2020-09-22 13:34:43.873 UTC | null | null | null | null | 214,949 | null | 1 | 14 | javascript|arrays | 64,212 | <p>Maybe you would be better of using an object,</p>
<p>So you could do</p>
<pre><code>var d = {
"Label" : "Value"
};
</code></pre>
<p>And to add the value you could</p>
<pre><code>d.label = "value";
</code></pre>
<p>This might be a more structured approach and easier to understand if your arrays become big. And if you build the JSON valid it's easy to make a string and parse it back in.</p>
<p>Like <code>var stringD = JSON.stringify(d); var parseD = JSON.parse(stringD);</code></p>
<p>UPDATE - ARRAY 2D</p>
<p>This is how you could declare it</p>
<pre><code>var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]);
</code></pre>
<p>And the alert is reading from it,</p>
<p>To add things to it you would say <code>items[0][0] = "Label" ; items[0][1] = "Value";</code></p>
<p>If you want to do all the labels then all the values do...</p>
<pre><code>for(var i = 0 ; i < labelssize; i ++)
{
items[i][0] = labelhere;
}
for(var i = 0 ; i < labelssize; i ++)
{
items[i][1] = valuehere;
}
</code></pre> |
11,592,033 | Regex match text between tags | <p>I have this string:</p>
<pre><code>My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.
</code></pre>
<p>I'd like to get the text between <code>b</code> tags to an array, that is:</p>
<pre><code>['Bob', '20', 'programming']
</code></pre>
<p>I tried this <code>/<b>(.*?)<\/b>/.exec(str)</code> but it will only get the first text.</p> | 11,592,042 | 4 | 3 | null | 2012-07-21 12:08:21.757 UTC | 18 | 2020-02-17 14:49:31.157 UTC | null | null | null | null | 325,241 | null | 1 | 72 | javascript|regex | 136,868 | <pre><code>/<b>(.*?)<\/b>/g
</code></pre>
<p><img src="https://www.debuggex.com/i/YYZQqw2c-dvi5OwW.png" alt="Regular expression visualization"></p>
<p>Add <code>g</code> (<em>global</em>) flag after:</p>
<pre><code>/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
</code></pre>
<p>However if you want to get all matched elements, then you need something like this:</p>
<pre><code>var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"]
</code></pre>
<p>If an element has attributes, regexp will be:</p>
<pre><code>/<b [^>]+>(.*?)<\/b>/g.exec(str)
</code></pre> |
3,838,452 | Servlet.service() for servlet jsp threw exception java.lang.NullPointerException | <p>i am getting below exception and tomcat hangs and my services are down.</p>
<pre><code>SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
at org.apache.jsp.search_005fresult_jsp._jspService(search_005fresult_jsp.java:86)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:384)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:276)
at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:81)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:517)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Thread.java:619)
Sep 29, 2010 2:57:17 PM org.apache.catalina.core.ApplicationC
</code></pre> | 3,838,778 | 5 | 1 | null | 2010-10-01 10:47:57.58 UTC | null | 2017-06-14 12:16:49.453 UTC | 2010-10-01 10:54:26.613 UTC | null | 289,396 | null | 463,770 | null | 1 | 1 | jsp|tomcat | 63,868 | <p>You are trying to call a method on an object that is <code>null</code></p>
<p>See, on line 86 of:</p>
<blockquote>
<p>/path/to/tomcat/work/Catalina/localhost/yourAppName/org/apache/jsp/search_005fresult_jsp.java</p>
</blockquote> |
3,495,872 | How is font size calculated? | <p>I have a complex js function with an equation in which I actually need to understand how much space in pixels font sizes take up.</p>
<p>I have noticed that some font's sizes are different depending on the font.</p>
<p>How is a font's size calculated? If its set to <code>12px</code>, in css, what does the <code>12px</code> mean? Is that <code>12px</code> wide? High? Or is it a diagonal pixel measurement?</p> | 3,495,925 | 5 | 2 | null | 2010-08-16 17:57:43.247 UTC | 10 | 2021-07-12 15:13:21.88 UTC | 2013-09-05 16:22:20.12 UTC | null | 358,834 | null | 358,834 | null | 1 | 15 | css|fonts|font-size|pixels|typography | 26,529 | <p>See the <a href="http://www.w3.org/TR/CSS2/fonts.html#font-size-props" rel="nofollow noreferrer">spec</a>:</p>
<blockquote>
<p>The font size corresponds to the em
square, a concept used in typography.<br>
Note that certain glyphs may bleed
outside their em squares. </p>
</blockquote> |
3,627,840 | Meaning of () => Operator in C#, if it exists | <p>I read this interesting line <a href="https://stackoverflow.com/questions/3626931/method-call-overhead">here</a>, in an answer by Jon Skeet.</p>
<p>The interesting line is this, where he advocated using a delegate:</p>
<pre><code>Log.Info("I did something: {0}", () => action.GenerateDescription());
</code></pre>
<p>Question is, what is this ()=> operator, I wonder? I tried Googling it but since it's made of symbols Google couldn't be of much help, really. Did I embarrassingly miss something here?</p> | 3,627,858 | 5 | 1 | null | 2010-09-02 14:02:00.53 UTC | 14 | 2019-04-24 18:01:25.43 UTC | 2017-05-23 12:18:33.263 UTC | null | -1 | null | 223,876 | null | 1 | 46 | c#|.net|delegates|operators | 36,702 | <p>This introduces a lambda function (anonymous delegate) with no parameters, it's equivalent to and basically short-hand for:</p>
<pre><code>delegate void () { return action.GenerateDescription(); }
</code></pre>
<p>You can also add parameters, so:</p>
<pre><code>(a, b) => a + b
</code></pre>
<p>This is roughly equivalent to:</p>
<pre><code>delegate int (int a, int b) { return a + b; }
</code></pre> |
3,230,863 | Is #inject on hashes considered good style? | <p>Inside the Rails code, people tend to use the <code>Enumerable#inject</code> method to create hashes, like this:</p>
<pre><code>somme_enum.inject({}) do |hash, element|
hash[element.foo] = element.bar
hash
end
</code></pre>
<p>While this appears to have become a common idiom, does anyone see an advantage over the "naive" version, which would go like:</p>
<pre><code>hash = {}
some_enum.each { |element| hash[element.foo] = element.bar }
</code></pre>
<p>The only advantage I see for the first version is that you do it in a closed block and you don't (explicitly) initialize the hash. Otherwise it abuses a method unexpectedly, is harder to understand and harder to read. So why is it so popular?</p> | 3,230,982 | 6 | 4 | null | 2010-07-12 17:56:04.607 UTC | 21 | 2020-04-13 06:28:51.297 UTC | 2020-04-13 06:25:46.403 UTC | null | 128,421 | null | 136,246 | null | 1 | 28 | ruby-on-rails|ruby | 36,532 | <p>Beauty is in the eye of the beholder. Those with some functional programming background will probably prefer the <code>inject</code>-based method (as I do), because it has the same semantics as the <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)" rel="noreferrer"><code>fold</code> higher-order function</a>, which is a common way of calculating a single result from multiple inputs. If you understand <code>inject</code>, then you should understand that the function is being used as intended.</p>
<p>As one reason why this approach seems better (to my eyes), consider the lexical scope of the <code>hash</code> variable. In the <code>inject</code>-based method, <code>hash</code> only exists within the body of the block. In the <code>each</code>-based method, the <code>hash</code> variable inside the block needs to agree with some execution context defined outside the block. Want to define another hash in the same function? Using the <code>inject</code> method, it's possible to cut-and-paste the <code>inject</code>-based code and use it directly, and it almost certainly won't introduce bugs (ignoring whether one should use C&P during editing - people do). Using the <code>each</code> method, you need to C&P the code, and rename the <code>hash</code> variable to whatever name you wanted to use - the extra step means this is more prone to error.</p> |
3,533,451 | Database structure for storing historical data | <p>Preface:
I was thinking the other day about a new database structure for a new application and realized that we needed a way to store historical data in an efficient way. I was wanting someone else to take a look and see if there are any problems with this structure. I realize that this method of storing data may very well have been invented before (I am almost certain it has) but I have no idea if it has a name and some google searches that I tried didn't yield anything.</p>
<p>Problem:
Lets say you have a table for orders, and orders are related to a customer table for the customer that placed the order. In a normal database structure you might expect something like this:</p>
<pre><code>orders
------
orderID
customerID
customers
---------
customerID
address
address2
city
state
zip
</code></pre>
<p>Pretty straightforward, orderID has a foreign key of customerID which is the primary key of the customer table. But if we were to go and run a report over the order table, we are going to join the customers table to the orders table, which will bring back the current record for that customer ID. What if when the order was placed, the customers address was different and it has been subsequently changed. Now our order no longer reflects the history of that customers address, at the time the order was placed. Basically, by changing the customer record, we just changed all history for that customer.</p>
<p>Now there are several ways around this, one of which would be to copy the record when an order was created. What I have come up with though is what I think would be an easier way to do this that is perhaps a little more elegant, and has the added bonus of logging anytime a change is made.</p>
<p>What if I did a structure like this instead:</p>
<pre><code>orders
------
orderID
customerID
customerHistoryID
customers
---------
customerID
customerHistoryID
customerHistory
--------
customerHistoryID
customerID
address
address2
city
state
zip
updatedBy
updatedOn
</code></pre>
<p>please forgive the formatting, but I think you can see the idea. Basically, the idea is that anytime a customer is changed, insert or update, the customerHistoryID is incremented and the customers table is updated with the latest customerHistoryID. The order table now not only points to the customerID (which allows you to see all revisions of the customer record), but also to the customerHistoryID, which points to a specific revision of the record. Now the order reflects the state of data at the time the order was created.</p>
<p>By adding an updatedby and updatedon column to the customerHistory table, you can also see an "audit log" of the data, so you could see who made the changes and when. </p>
<p>One potential downside could be deletes, but I am not really worried about that for this need as nothing should ever be deleted. But even still, the same effect could be achieved by using an activeFlag or something like it depending on the domain of the data.</p>
<p>My thought is that all tables would use this structure. Anytime historical data is being retrieved, it would be joined against the history table using the customerHistoryID to show the state of data for that particular order. </p>
<p>Retrieving a list of customers is easy, it just takes a join to the customer table on the customerHistoryID.</p>
<p>Can anyone see any problems with this approach, either from a design standpoint, or performance reasons why this is bad. Remember, no matter what I do I need to make sure that the historical data is preserved so that subsequent updates to records do not change history. Is there a better way? Is this a known idea that has a name, or any documentation on it?</p>
<p>Thanks for any help.</p>
<p><strong>Update:</strong>
This is a very simple example of what I am really going to have. My real application will have "orders" with several foreign keys to other tables. Origin/destination location information, customer information, facility information, user information, etc. It has been suggested a couple of times that I could copy the information into the order record at that point, and I have seen it done this way many times, but this would result in a record with hundreds of columns, which really isn't feasible in this case.</p> | 3,533,522 | 7 | 4 | null | 2010-08-20 17:44:05.28 UTC | 14 | 2021-10-01 21:29:34.247 UTC | 2015-02-27 12:31:16.34 UTC | null | 181,336 | null | 7,186 | null | 1 | 17 | sql|database|database-design | 22,657 | <p>When I've encountered such problems one alternative is to make the order the history table. Its functions the same but its a little easier to follow</p>
<pre><code>orders
------
orderID
customerID
address
City
state
zip
customers
---------
customerID
address
City
state
zip
</code></pre>
<p>EDIT: if the number of columns gets to high for your liking you can separate it out however you like.</p>
<p>If you do go with the other option and using history tables you should consider using <a href="http://www.simple-talk.com/sql/t-sql-programming/a-primer-on-managing-data-bitemporally/" rel="noreferrer">bitemporal</a> data since you may have to deal with the possibility that historical data needs to be corrected. For example Customer Changed his current address From A to B but you also have to correct address on an existing order that is currently be fulfilled. </p>
<p>Also if you are using MS SQL Server you might want to consider using indexed views. That will allow you to trade a small incremental insert/update perf decrease for a large select perf increase. If you're not using MS SQL server you can replicate this using triggers and tables.</p> |
3,398,258 | Edit shell script while it's running | <p>Can you edit a shell script while it's running and have the changes affect the running script?</p>
<p>I'm curious about the specific case of a csh script I have that batch runs a bunch of different build flavors and runs all night. If something occurs to me mid operation, I'd like to go in and add additional commands, or comment out un-executed ones.</p>
<p>If not possible, is there any shell or batch-mechanism that would allow me to do this?</p>
<p>Of course I've tried it, but it will be hours before I see if it worked or not, and I'm curious about what's happening or not happening behind the scenes.</p> | 3,398,307 | 11 | 4 | null | 2010-08-03 15:49:52.373 UTC | 22 | 2021-03-18 13:20:22.283 UTC | null | null | null | null | 32,840 | null | 1 | 111 | linux|shell|csh | 55,018 | <p>Scripts don't work that way; the executing copy is independent from the source file that you are editing. Next time the script is run, it will be based on the most recently saved version of the source file.</p>
<p>It might be wise to break out this script into multiple files, and run them individually. This will reduce the execution time to failure. (ie, split the batch into one build flavor scripts, running each one individually to see which one is causing the trouble).</p> |
3,586,566 | 'datetime2' error when using entity framework in VS 2010 .net 4.0 | <p>Getting this error:</p>
<blockquote>
<p>System.Data.SqlClient.SqlException : The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.</p>
</blockquote>
<p>My entity objects all line up to the DB objects.</p>
<p>I found only a single reference to this error via Google:</p>
<p><a href="http://ramonaeid.spaces.live.com/blog/cns!A77704F1DB999BB0!182.entry" rel="noreferrer">Google result</a></p>
<p>After reading this, I remember that we <em>did</em> add 2 fields and then updated the entity model from VS 2010. I'm not sure what he means by "hand coding" the differences. I don't see any.</p>
<p>All I'm doing in code is populating the entity object and then saving. (I also populate the new fields in code) I populated the date field with <code>DateTime.Now</code>..</p>
<p>The important part of the code is this: <code>ctx.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);</code></p>
<p>The database is SQL Server 2008.</p>
<p><strong><em>Thoughts?</em></strong></p>
<p>The rest of the error:</p>
<blockquote>
<p>at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at SafariAdmin.Site.WebServices.SpeciesPost.SaveOrUpdateSpecies(String sid, String fieldName, String authToken) in SpeciesPost.svc.cs: line 58
at SafariAdmin.TestHarness.Tests.Site.WebServices.SpeciesPostSVC_Tester.SaveNewSpecies() in SpeciesPostSVC_Tester.cs: line 33
--SqlException
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary<code>2 identifierValues, List</code>1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) </p>
</blockquote> | 3,586,607 | 16 | 1 | null | 2010-08-27 17:08:30.85 UTC | 19 | 2017-08-02 09:29:23.76 UTC | 2017-08-02 09:29:23.76 UTC | null | 777,716 | null | 129,565 | null | 1 | 61 | c#|sql-server|entity-framework|sql-server-2008 | 64,210 | <p>Entity framework handles all the dates as a Datetime2, so, if your fields in the database are Datetime, this could be a problem.
We had the same problem here, and from what we found, populating all the date fields and changing the datatype, are the most commom solutions</p> |
3,793,892 | How to show code outline in Visual Studio? | <p>This kind of stuff exists in Eclipse:</p>
<p><img src="https://i.stack.imgur.com/faDrr.jpg" alt="alt text"></p>
<p>But I've not found it in Visual Studio yet. Is there such a window to show code outline at all?</p>
<p>I tried both Document Outline and Class View windows. The Class View is close, but it only shows class information, can it come up with function info also?</p> | 3,794,313 | 20 | 1 | null | 2010-09-25 12:56:18.29 UTC | 15 | 2021-04-07 17:19:57.453 UTC | 2012-10-20 06:12:04.4 UTC | null | 681,785 | null | 417,798 | null | 1 | 80 | visual-studio|outline-view | 88,240 | <ul>
<li><p>not free, but if you install Visual AssistX, each document gets a dropdown box listing all methods in a file (alphabetically or in the order they occur)</p></li>
<li><p>check Class View again, it does show functions (but not per document). Also check out the Code Definition Window, extremely nice when combined with Class View.</p></li>
</ul> |
7,874,751 | How to use regex OR in grep in Cygwin? | <p>I need to return results for two different matches from a single file.</p>
<pre><code>grep "string1" my.file
</code></pre>
<p>correctly returns the single instance of string1 in my.file</p>
<pre><code>grep "string2" my.file
</code></pre>
<p>correctly returns the single instance of string2 in my.file</p>
<p>but</p>
<pre><code>grep "string1|string2" my.file
</code></pre>
<p>returns nothing</p>
<p>in regex test apps that syntax is correct, so why does it not work for grep in cygwin ?</p> | 7,874,789 | 4 | 0 | null | 2011-10-24 11:14:17.967 UTC | 8 | 2014-01-11 17:22:50.683 UTC | 2011-10-24 20:46:38.41 UTC | null | 82,474 | null | 799,759 | null | 1 | 52 | regex|cygwin|grep | 50,715 | <p>Using the <code>|</code> character without escaping it in a basic regular expression will only match the <code>|</code> literal. For instance, if you have a file with contents</p>
<pre><code>string1
string2
string1|string2
</code></pre>
<p>Using <code>grep "string1|string2" my.file</code> will only match the last line</p>
<pre><code>$ grep "string1|string2" my.file
string1|string2
</code></pre>
<p>In order to use the alternation operator <code>|</code>, you could: </p>
<ol>
<li><p>Use a basic regular expression (just <code>grep</code>) and escape the <code>|</code> character in the regular expression</p>
<p><code>grep "string1\|string2" my.file</code></p></li>
<li><p>Use an extended regular expression with <code>egrep</code> or <code>grep -E</code>, as Julian already pointed out in <a href="https://stackoverflow.com/a/7874786/851811">his answer</a></p>
<p><code>grep -E "string1|string2" my.file</code> </p></li>
<li><p>If it is two different patterns that you want to match, you could also specify them separately in <code>-e</code> options: </p>
<p><code>grep -e "string1" -e "string2" my.file</code></p></li>
</ol>
<p>You might find the following sections of the <code>grep</code> reference useful: </p>
<ul>
<li><a href="http://www.gnu.org/software/grep/manual/grep.html#Basic-vs-Extended" rel="nofollow noreferrer">Basic vs Extended Regular Expressions</a></li>
<li><a href="http://www.gnu.org/software/grep/manual/grep.html#Matching-Control" rel="nofollow noreferrer">Matching Control</a>, where it explains <code>-e</code></li>
</ul> |
7,900,994 | Programmatically log-in a user using spring security | <p>The opposite of: <a href="https://stackoverflow.com/q/5727380/106261">How to manually log out a user with spring security?</a></p>
<p>In my app I have <em>register new user screen</em>, which posts to a controller which creates a new user within db (and does a few obvious checks).I then want this new user to be automatically logged in ... I kind of want somethign like this :</p>
<pre><code>SecurityContextHolder.getContext().setPrincipal(MyNewUser);
</code></pre>
<p><strong>Edit</strong>
Well I have almost implemented based on the answer to <a href="https://stackoverflow.com/q/7614541/106261">How to programmatically log user in with Spring Security 3.1</a></p>
<pre><code> Authentication auth = new UsernamePasswordAuthenticationToken(MyNewUser, null);
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
</code></pre>
<p>However, when deployed the jsp can not access my <code>MyNewUser.getWhateverMethods()</code> whereas it does when normal login procedure followed. the code that works nomrally, but throws an error when logged in like above is below :</p>
<pre><code><sec:authentication property="principal.firstname" />
</code></pre> | 7,903,912 | 4 | 0 | null | 2011-10-26 09:40:51.863 UTC | 23 | 2022-05-26 14:22:37.387 UTC | 2018-04-20 17:04:19.703 UTC | null | 1,390,251 | null | 106,261 | null | 1 | 69 | spring-mvc|spring-security | 52,392 | <p>In my controller i have this, which logs user in <em>as normal</em> :</p>
<pre><code>Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
</code></pre>
<p>Where user is my custom user object(implementing UserDetails) that is newly created. The <a href="http://docs.spring.io/autorepo/docs/spring-security/3.2.7.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetails.html#getAuthorities()"><code>getAuthorities()</code></a> method does this (just because all my users have the same role): </p>
<pre><code>public Collection<GrantedAuthority> getAuthorities() {
//make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
//anonymous inner type
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
</code></pre> |
8,191,536 | Dynamic Return Type in Java method | <p>I've seen a question similar to this multiple times here, but there is one big difference.</p>
<p>In the other questions, the return type is to be determined by the parameter. What I want/need to do is determine the return type by the parsed value of a <code>byte[]</code>. From what I've gathered, the following could work:</p>
<pre><code>public Comparable getParam(String param, byte[] data) {
if(param.equals("some boolean variable")
return data[0] != 0;
else(param.equals("some float variable") {
//create a new float, f, from some 4 bytes in data
return f;
}
return null;
}
</code></pre>
<p>I just want to make sure that this has a chance of working before I screw anything up. Thanks in advance.</p> | 8,191,649 | 5 | 3 | null | 2011-11-19 02:57:24.823 UTC | 7 | 2018-11-20 11:33:53.25 UTC | null | null | null | null | 599,436 | null | 1 | 21 | java|dynamic|return-type | 57,001 | <p>You can't do it. Java return types have to be either a fixed fundamental type
or an object class. I'm pretty sure the best you can do is return a wrapper type
which has methods to fetch various possible types of values, and an internal enum
which says which one is valid.</p>
<p>--- edit --- after Danieth's correction!</p>
<pre><code>public <Any> Any getParam(boolean b){
return((Any)((Boolean)(!b)));
}
public <Any> Any getParam(float a) {
return((Any)((Float)(a+1)));
}
public <Any> Any getParam(Object b) {
return((Any)b);
}
public void test(){
boolean foo = getParam(true);
float bar = getParam(1.0f);
float mumble = getParam(this); // will get a class cast exception
}
</code></pre>
<p>You still incur some penalties for boxing items and type checking
the returned values, and of course if your call isn't consistent with
what the implementations of getParam actually do, you'll get a class
cast exception.</p> |
8,033,619 | 'An exception occurred during a WebClient request" while using C# ASP.NET | <p>So, I have built an auto update program to my program. </p>
<p>The code that is running in here is:</p>
<pre><code>new WebClient().DownloadFile("XXXX", checkingfolder.SelectedPath);
</code></pre>
<p>the XXX is my webserver that is running as a VPS server in verio, with the newest IIS and everything. </p>
<p>When the user clicks on the download button, it says:</p>
<pre><code>'An exception occurred during a WebClient request.
</code></pre>
<p>The thing is, that I dont even know why - i am just doing try catch. </p>
<p>Anyone here have any idea why this happened?</p>
<p>Thanks for any help you will give me, you have no idea how much you are helping me here - thanks again !</p> | 8,033,687 | 6 | 4 | null | 2011-11-07 07:06:18.537 UTC | 6 | 2018-07-13 04:55:49.913 UTC | 2011-11-07 09:29:59.02 UTC | null | 1,741,868 | null | 1,032,254 | null | 1 | 26 | c# | 96,757 | <p>I can reproduce this if I specify, as <em>seems</em> to be the case in your example, a <strong>folder</strong> name rather than a <strong>file</strong> name the destination. Supply a <strong>file</strong> name instead.</p>
<p>As an aside; if I look at the <code>InnerException</code>, it tells me that the problem relates to the file path:</p>
<pre><code>using(var client = new WebClient())
{
try
{
client.DownloadFile(
"http://stackoverflow.com/questions/8033619/an-exception-occurred-durning-a-webclient-request-c-sharp-asp-net/8033687#8033687",
@"j:\MyPath");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
}
}
}
</code></pre>
<p>Which gives:</p>
<pre><code>An exception occurred during a WebClient request.
Access to the path 'j:\MyPath' is denied.
</code></pre>
<p>If I change it to a <strong>file</strong>, it works fine:</p>
<pre><code>client.DownloadFile(
"http://stackoverflow.com/questions/8033619/an-exception-occurred-durning-a-webclient-request-c-sharp-asp-net/8033687#8033687",
@"j:\MyPath\a.html");
</code></pre> |
4,752,715 | Why are both little- and big-endian in use? | <p>Why are both little- and big-endian still in use <strong>today</strong>, after ~40 years of binary computer-science? Are there algorithms or storage formats that work better with one and much worse with the other? Wouldn't it be better if we all switched to one and stick with it?</p> | 4,753,537 | 3 | 2 | null | 2011-01-20 21:20:06.887 UTC | 11 | 2011-01-20 22:46:28.343 UTC | null | null | null | null | 565,635 | null | 1 | 53 | computer-science|endianness | 14,984 | <p>When adding two numbers (on paper or in a machine), you start with the least significant digits and work towards the most significant digits. (Same goes for many other operations).</p>
<p>On the Intel 8088, which had 16-bit registers but an 8-bit data bus, being little-endian allowed such instructions to start operation after the first memory cycle. (Of course it should be possible for the memory fetches of a word to be done in decreasing order rather than increasing but I suspect this would have complicated the design a little.)</p>
<p>On most processors the bus width matches the register width so this no longer confers an advantage.</p>
<p>Big-endian numbers, on the other hand, can be compared starting with the MSB (although many compare instructions actually do a subtract which needs to start with the LSB anyway). The sign bit is also very easy to get.</p>
<blockquote>
<p>Are there algorithms or storage
formats that work better with one and
much worse with the other?</p>
</blockquote>
<p>No. There are small advantages here and there but nothing major.</p>
<p>I actually think litte-endian is more natural and consistent: the significance of a bit is
2 ^ (bit_pos + 8 * byte_pos). Whereas with with big endian the significance of a bit is
2 ^ (bit_pos + 8 * (word_size - byte_pos - 1)).</p>
<blockquote>
<p>Wouldn't it be better if we all switched to one and stick with it?</p>
</blockquote>
<p>Due to the dominance of x86, we've definitely gravitated towards little-endian. The ARM chips in many mobile devices have configurable endianness but are often set to LE to be more compatible with the x86 world. Which is fine by me.</p> |
4,836,897 | Validate the number of has_many items in Ruby on Rails | <p>Users can add tags to a snippet:</p>
<pre><code>class Snippet < ActiveRecord::Base
# Relationships
has_many :taggings
has_many :tags, :through => :taggings
belongs_to :closing_reason
end
</code></pre>
<p>I want to validate the number of tags: at least 1, at most 6. How am I about to do this? Thanks.</p> | 4,836,927 | 3 | 0 | null | 2011-01-29 12:34:23.037 UTC | 15 | 2021-10-14 20:11:05.533 UTC | null | null | null | user142019 | null | null | 1 | 69 | ruby-on-rails|validation|tagging|has-many | 32,686 | <p>You can always create a <a href="http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations" rel="noreferrer">custom validation</a>. </p>
<p>Something like</p>
<pre><code> validate :validate_tags
def validate_tags
errors.add(:tags, "too much") if tags.size > 5
end
</code></pre> |
4,725,668 | How to deploy SNAPSHOT with sources and JavaDoc? | <p>I want to deploy sources and javadocs with my snapshots. This means that I want to automize the following command:</p>
<pre><code>mvn clean source:jar javadoc:jar deploy
</code></pre>
<p>Just to execute:</p>
<pre><code>mvn clean deploy
</code></pre>
<p>I don't want to have javadoc/sources generation executed during the <code>install</code> phase (i.e. local builds).</p>
<p>I know that source/javadoc plugins can be synchronized with the execution of the <code>release</code> plugin but I can't figure out how to wire it to the snapshots releases.</p> | 4,725,728 | 3 | 0 | null | 2011-01-18 15:08:33.937 UTC | 27 | 2020-05-13 05:50:31.41 UTC | null | null | null | null | 80,711 | null | 1 | 102 | java|maven-2|maven-release-plugin | 52,079 | <pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<phase>deploy</phase>
<goals><goal>jar-no-fork</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>deploy</phase>
<goals><goal>jar</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- explicitly define maven-deploy-plugin after other to force exec order -->
<artifactId>maven-deploy-plugin</artifactId>
<executions>
<execution>
<id>deploy</id>
<phase>deploy</phase>
<goals><goal>deploy</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
<p>See <a href="https://repo1.maven.org/maven2/org/sonatype/oss/oss-parent/5/oss-parent-5.pom" rel="noreferrer">Sonatype's OSS parent POM</a> for a complete example.</p> |
4,548,089 | IntelliJ Split Window Navigation | <p>If I split the editor window (horizontal or vertical) into N tab groups, how do I switch/toggle from one tab group to another via the keyboard? If all of the tabs are in the same group you can switch from each tab easily (CTRL + right/left arrow), but when they're in separate tab groups I can't. I've searched through the key mappings and have not found one that seems to accomplish this. I know I can use the mouse, but I'm trying to find ways to avoid the mouse and stay with the keyboard. </p>
<p>TIA for any help on this.</p> | 4,548,181 | 3 | 1 | null | 2010-12-28 17:49:24.783 UTC | 15 | 2019-09-12 02:50:10.743 UTC | null | null | null | null | 551,899 | null | 1 | 113 | intellij-idea | 28,248 | <p><strong>Ctrl+Tab</strong> and <strong>Ctrl+Shift+Tab</strong> for Window | <strong>Goto Next Splitter</strong> and <strong>Goto Previous Splitter</strong>. However, these hotkeys may be taken by the <strong>Switcher</strong>, so you need to remap them in <strong>Settings | Keymap</strong>.</p> |
4,717,060 | Convert to absolute value in Objective-C | <p>How do I convert a negative number to an absolute value in Objective-C?</p>
<p>i.e.</p>
<p>-10 </p>
<p>becomes</p>
<p>10?</p> | 4,717,090 | 3 | 1 | null | 2011-01-17 19:35:45.76 UTC | 37 | 2022-03-23 19:32:17.613 UTC | null | null | null | null | 147,915 | null | 1 | 190 | objective-c | 103,261 | <p>Depending on the type of your variable, one of <code>abs(int)</code>, <code>labs(long)</code>, <code>llabs(long long)</code>, <code>imaxabs(intmax_t)</code>, <code>fabsf(float)</code>, <code>fabs(double)</code>, or <code>fabsl(long double)</code>.</p>
<p>Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)</p>
<p>(Alas, there is no <code>habs(short)</code> function. Or <code>scabs(signed char)</code> for that matter...)</p>
<hr>
<p>Apple's and GNU's Objective-C headers also include an <code>ABS()</code> macro which is type-agnostic. I don't recommend using <code>ABS()</code> however as it is not guaranteed to be side-effect-safe. For instance, <code>ABS(a++)</code> will have an undefined result.</p>
<hr>
<p>If you're using C++ or Objective-C++, you can bring in the <code><cmath></code> header and use <code>std::abs()</code>, which is templated for all the standard integer and floating-point types.</p> |
4,298,439 | Opensource/free HTML5/CSS3/JavaScript IDE? | <p>What is the best open source/free HTML5/CSS3/JavaScript IDE?</p>
<p>Thank you!!!</p> | 4,298,448 | 6 | 2 | null | 2010-11-28 19:01:36.667 UTC | 7 | 2012-02-24 16:32:16.33 UTC | null | null | null | null | 352,555 | null | 1 | 25 | javascript|open-source|html|ide|css | 50,756 | <p>Most of the time when I write code I am programming C# applications using Visual Studio, which is my favorite IDE. However, when it comes to Javascript VS is quite poor. It does not support collapse to definitions (AKA code folding in other IDEs / editors), does not support code outlining and also has a very primitive and most of the times useless autocomplete.</p>
<p>Because of that, at some point I have started to search alternative tools for JS programming and the best I came across was <strong>Aptana Studio</strong>. It also has support for HTML and CSS (as well as for some server side languages like Ruby, PHP, Phyton), but I have only used it for JS and that is an area where it shines. It has very good code outlining and one of the best autocomplete implementations I have ever seen for Javascript (even thought it is still improvable).</p>
<p>Aptana Studio is based Eclipse and is available as a plugin or as a full package version. On their site they are saying that the next version is going to totally independent from Eclipse, which would make it a lot more light weight and more performant. However, the current Beta version of Aptana Studio 3 is still based on Eclipse.</p>
<p>You can find more on Aptana Studio 3 on the official page: <a href="http://aptana.com/products/studio3">http://aptana.com/products/studio3</a></p> |
4,386,446 | Issue using ImageIO.write jpg file: pink background | <p>I'm using the following code to write a jpg file:</p>
<pre><code>String url="http://img01.taobaocdn.com/imgextra/i1/449400070/T2hbVwXj0XXXXXXXXX_!!449400070.jpg";
String to="D:/temp/result.jpg";
ImageIO.write(ImageIO.read(new URL(url)),"jpg", new File(to));
</code></pre>
<p>But I get the <code>result.jpg</code> is a pink background image:</p>
<p><img src="https://i.stack.imgur.com/jNVm0.jpg" alt="alt text"></p> | 4,388,542 | 6 | 8 | null | 2010-12-08 10:28:41.263 UTC | 14 | 2018-11-06 16:34:44.63 UTC | 2018-11-06 16:34:44.63 UTC | null | 1,033,581 | null | 165,589 | null | 1 | 51 | java|image-processing | 51,760 | <p>You can work around this by using <code>Toolkit.createImage(url)</code> instead of <code>ImageIO.read(url)</code> which uses a different implementation of the decoding algorithm.</p>
<p>If you are using the JPEG encoder included with the Sun JDK then you must also ensure that you pass it an image with no alpha channel.</p>
<p>Example:</p>
<pre><code>private static final int[] RGB_MASKS = {0xFF0000, 0xFF00, 0xFF};
private static final ColorModel RGB_OPAQUE =
new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
// ...
String sUrl="http://img01.taobaocdn.com/imgextra/i1/449400070/T2hbVwXj0XXXXXXXXX_!!449400070.jpg";
URL url = new URL(sUrl);
Image img = Toolkit.getDefaultToolkit().createImage(url);
PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, true);
pg.grabPixels();
int width = pg.getWidth(), height = pg.getHeight();
DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
BufferedImage bi = new BufferedImage(RGB_OPAQUE, raster, false, null);
String to = "D:/temp/result.jpg";
ImageIO.write(bi, "jpg", new File(to));
</code></pre>
<hr>
<p>Note: My guess is that the color profile is corrupted, and <code>Toolkit.createImage()</code> ignores all color profiles. If so then this will reduce the quality of JPEGs that have a correct color profile.</p> |
4,758,414 | 6 digits regular expression | <p>I need a regular expression that requires at least ONE digits and SIX maximum. </p>
<p>I've worked out this, but neither of them seems to work.</p>
<pre><code>^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$
^[0-999999]$
</code></pre>
<p>Any other suggestion?</p> | 4,758,441 | 7 | 0 | null | 2011-01-21 11:47:15.193 UTC | 10 | 2022-07-23 03:51:41.123 UTC | 2014-11-11 17:26:04.243 UTC | null | 639,505 | null | 253,329 | null | 1 | 74 | regex|vb.net | 209,556 | <p>You can use range quantifier <code>{min,max}</code> to specify minimum of 1 digit and maximum of 6 digits as:</p>
<pre><code>^[0-9]{1,6}$
</code></pre>
<p>Explanation:</p>
<pre><code>^ : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$ : End anchor
</code></pre>
<p><strong>Why did your regex not work ?</strong></p>
<p>You were almost close on the regex:</p>
<pre><code>^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$
</code></pre>
<p>Since you had escaped the <code>?</code> by preceding it with the <code>\</code>, the <code>?</code> was no more acting as a regex meta-character ( for <code>0</code> or <code>1</code> repetitions) but was being treated literally.</p>
<p>To fix it just remove the <code>\</code> and you are there.</p>
<p><a href="http://www.rubular.com/r/nukHrSSmr7"><strong>See it on rubular</strong></a>.</p>
<p>The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.</p>
<p>Your second regex:</p>
<pre><code>^[0-999999]$
</code></pre>
<p>is equivalent to:</p>
<pre><code>^[0-9]$
</code></pre>
<p>which matches strings with exactly one digit. They are equivalent because a character class <code>[aaaab]</code> is same as <code>[ab]</code>.</p> |
4,717,632 | Code compare tool for Linux | <p>What is the best code compare tool available for Linux? I have been using Beyond Compare in Windows and am looking for something similar for Ubuntu with nautilus integration.</p> | 4,717,670 | 10 | 0 | null | 2011-01-17 20:36:38.737 UTC | 10 | 2020-12-30 01:31:08.327 UTC | 2013-12-10 07:34:30.087 UTC | null | 881,229 | null | 87,968 | null | 1 | 21 | linux|ubuntu|beyondcompare | 33,426 | <p>Try <a href="http://meldmerge.org/">meld</a> , there is a <a href="https://github.com/mablo/nautilus-meld-compare">nautilus extension</a> for it too.</p> |
4,412,749 | Are flexible array members valid in C++? | <p>In C99, you can declare a flexible array member of a struct as such:</p>
<pre><code>struct blah
{
int foo[];
};
</code></pre>
<p>However, when someone here at work tried to compile some code using clang in C++, that syntax did not work. (It had been working with MSVC.) We had to convert it to:</p>
<pre><code>struct blah
{
int foo[0];
};
</code></pre>
<p>Looking through the C++ standard, I found no reference to flexible member arrays at all; I always thought <code>[0]</code> was an invalid declaration, but apparently for a flexible member array it is valid. Are flexible member arrays actually valid in C++? If so, is the correct declaration <code>[]</code> or <code>[0]</code>?</p> | 4,412,832 | 10 | 8 | null | 2010-12-10 19:55:32.26 UTC | 8 | 2021-06-08 20:25:33.83 UTC | null | null | null | null | 6,210 | null | 1 | 56 | c++|flexible-array-member | 35,622 | <p>C++ was first standardized in 1998, so it predates the addition of flexible array members to C (which was new in C99). There was a corrigendum to C++ in 2003, but that didn't add any relevant new features. The next revision of C++ (C++2b) is still under development, and it seems flexible array members still aren't added to it.</p> |
4,817,414 | Spring Scheduler does not work | <p>I have a problem with Spring's annotation based task scheduler - I can't get it working, I don't see any problem here...</p>
<p>application-context.xml</p>
<pre><code><task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />
</code></pre>
<p>bean</p>
<pre><code>@Service
public final class SchedulingTest {
private static final Logger logger = Logger.getLogger(SchedulingTest.class);
@Scheduled(fixedRate = 1000)
public void test() {
logger.debug(">>> Scheduled test service <<<");
}
}
</code></pre> | 11,157,845 | 14 | 2 | null | 2011-01-27 14:14:43.023 UTC | 2 | 2021-04-15 16:56:29.947 UTC | 2016-11-04 15:22:30.76 UTC | null | 157,882 | null | 419,516 | null | 1 | 31 | spring|spring-mvc|scheduling | 62,032 | <p>If you want to use <code>task:annotation-driven</code> approach and your @Scheduled annotation is not working, then you most probably missed <code>context:component-scan</code> in your context xml.
Without this line, spring cannot guess where to search for your annotations.</p>
<pre><code><context:component-scan base-package="..." />
</code></pre> |
4,362,104 | Strange Jackson exception being thrown when serializing Hibernate object | <p>Jackson is throwing a weird exception that I don't know how to fix. I'm using Spring, Hibernate and Jackson.</p>
<p>I have already considered that lazy-loading is causing the problem, but I have taken measures to tell Jackson to NOT process various properties as follows:</p>
<pre><code>@JsonIgnoreProperties({ "sentMessages", "receivedMessages", "educationFacility" })
public class Director extends UserAccount implements EducationFacilityUser {
....
}
</code></pre>
<p>I have done the same thing for all the other UserAccount subclasses as well.</p>
<p>Here's the exception being thrown:</p>
<pre><code>org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[46]->jobprep.domain.educationfacility.Director_$$_javassist_2["handler"])
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:268)
at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:146)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:118)
at org.codehaus.jackson.map.ser.ContainerSerializers$IndexedListSerializer.serializeContents(ContainerSerializers.java:236)
at org.codehaus.jackson.map.ser.ContainerSerializers$IndexedListSerializer.serializeContents(ContainerSerializers.java:189)
at org.codehaus.jackson.map.ser.ContainerSerializers$AsArraySerializer.serialize(ContainerSerializers.java:111)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:296)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:224)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:925)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:153)
</code></pre>
<p>Suggestions on how I can get more info to see what's causing this? Anyone know how to fix it?</p>
<p><strong>EDIT:</strong> I discovered that getHander() and other get*() methods exist on the proxy object. GRR!! Is there any way I can tell Jackson to not process anything on the proxy, or am I sol? This is really weird because the method that spits out the JSON only crashes under certain circumstances, not all the time. Nonetheless, it's due to the get*() methods on the proxy object.</p>
<p>Aside: Proxies are evil. They disrupt Jackson, equals() and many other parts of regular Java programming. I am tempted to ditch Hibernate altogether :/</p> | 4,362,163 | 15 | 7 | null | 2010-12-05 23:57:09.723 UTC | 27 | 2017-05-24 07:15:59.907 UTC | 2010-12-06 00:04:46.523 UTC | null | 331,439 | null | 331,439 | null | 1 | 61 | java|json|hibernate|spring-mvc|jackson | 114,288 | <p>It's not ideal, but you could disable Jackson's auto-discovery of JSON properties, using <code>@JsonAutoDetect</code> at the class level. This would prevent it from trying to handle the Javassist stuff (and failing).</p>
<p>This means that you then have to annotate each getter manually (with <code>@JsonProperty</code>), but that's not necessarily a bad thing, since it keeps things explicit.</p> |
4,739,483 | Number of days between two NSDates | <p>How could I determine the number of days between two <code>NSDate</code> values (taking into consideration time as well)?</p>
<p>The <code>NSDate</code> values are in whatever form <code>[NSDate date]</code> takes.</p>
<p>Specifically, when a user enters the inactive state in my iPhone app, I store the following value:</p>
<pre><code>exitDate = [NSDate date];
</code></pre>
<p>And when they open the app back up, I get the current time:</p>
<pre><code>NSDate *now = [NSDate date];
</code></pre>
<p>Now I'd like to implement the following:</p>
<pre><code>-(int)numberOfDaysBetweenStartDate:exitDate andEndDate:now
</code></pre> | 4,739,650 | 16 | 0 | null | 2011-01-19 19:02:29.083 UTC | 77 | 2021-03-09 18:51:01.903 UTC | 2016-12-22 11:50:59.11 UTC | null | 4,078,527 | null | 412,082 | null | 1 | 154 | ios|objective-c|cocoa-touch|nsdate | 100,221 | <p>Here's an implementation I used to determine the number of calendar days between two dates:</p>
<pre><code>+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime
{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Fantastic solution above, here's Swift version below as an extension on <code>NSDate</code>:</p>
<pre><code>extension NSDate {
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
var fromDate: NSDate?, toDate: NSDate?
calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)
let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])
return difference.day
}
}
</code></pre>
<p>A bit of force unwrapping going on which you may want to remove depending on your use case.</p>
<p>The above solution also works for time zones other than the current time zone, perfect for an app that shows information about places all around the world.</p> |
14,462,390 | How to declare the type for local variables using PHPDoc notation? | <p>I use Zend Studio to develop in PHP with CakePHP, and one of the problems with CakePHP is that the views all reference undeclared local variables.</p>
<p>So for example, in the controller you would</p>
<p><code>$this->set('job',new MyJobObject());</code></p>
<p>Then in the view you could</p>
<p><code>echo $job->getName();</code></p>
<p>My problem is that Zend Studio can't perform autocomplete on <code>$job</code>, because it's type is unknown. Now there are PHPDoc tags that allow you to declare the type so that IDE's can perform autocomplete. The <code>@var</code> tag for example can be used in a class to define a property's type.</p>
<pre><code>class MyJobObject
{
/**
* @var MyStatusObject
*/
public $status;
}
</code></pre>
<p><strong>Is there a way to do something like this for local variables?</strong></p> | 14,462,512 | 3 | 0 | null | 2013-01-22 15:44:02.663 UTC | 4 | 2020-06-04 08:15:42.993 UTC | 2020-06-04 08:15:42.993 UTC | null | 5,153,116 | null | 1,031,569 | null | 1 | 36 | php|cakephp|zend-studio|eclipse-pdt|cakephp-2.2 | 22,159 | <p>You have to use the one-line form: <code>/** @var $job MyJobObject */</code></p>
<p>Note that some editors prefer the syntax the other way around: <code>/** @var MyJobObject $job */</code></p> |
14,689,531 | How to match a newline character in a raw string? | <p>I got a little confused about Python raw string. I know that if we use raw string, then it will treat <code>'\'</code> as a normal backslash (ex. <code>r'\n'</code> would be <code>\</code> and <code>n</code>). However, I was wondering what if I want to match a new line character in raw string. I tried <code>r'\\n'</code>, but it didn't work.</p>
<p>Anybody has some good idea about this?</p> | 14,689,821 | 4 | 2 | null | 2013-02-04 15:05:45.097 UTC | 14 | 2022-02-15 03:39:29.88 UTC | 2022-02-15 03:39:29.88 UTC | null | 355,230 | null | 1,783,403 | null | 1 | 51 | python|regex|python-re|rawstring | 131,007 | <p>In a regular expression, you need to specify that you're in multiline mode:</p>
<pre><code>>>> import re
>>> s = """cat
... dog"""
>>>
>>> re.match(r'cat\ndog',s,re.M)
<_sre.SRE_Match object at 0xcb7c8>
</code></pre>
<p>Notice that <code>re</code> translates the <code>\n</code> (raw string) into newline. As you indicated in your comments, you don't actually <strong>need</strong> <a href="http://docs.python.org/2/library/re.html#re.M"><code>re.M</code></a> for it to match, but it does help with matching <code>$</code> and <code>^</code> more intuitively:</p>
<pre><code>>> re.match(r'^cat\ndog',s).group(0)
'cat\ndog'
>>> re.match(r'^cat$\ndog',s).group(0) #doesn't match
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> re.match(r'^cat$\ndog',s,re.M).group(0) #matches.
'cat\ndog'
</code></pre> |
14,879,168 | $(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){}) | <p>I was trying to find out what is the difference between</p>
<pre><code>$(document).on('click', '#id', function(){});
</code></pre>
<p>and</p>
<pre><code>$('#id').on('click', function(){});
</code></pre>
<p>I've not been able to find any information on if there is any difference between the two, and if so what that difference may be.</p>
<p>Can someone please explain if there is any difference at all?</p> | 14,879,213 | 2 | 7 | null | 2013-02-14 16:14:59.9 UTC | 42 | 2013-02-14 16:24:20.683 UTC | null | null | null | null | 1,315,498 | null | 1 | 85 | jquery|syntax | 133,808 | <p>The first example demonstrates <em>event delegation</em>. The event handler is bound to an element higher up the DOM tree (in this case, the <code>document</code>) and will be executed when an event reaches that element having originated on an element matching the selector.</p>
<p>This is possible because most DOM events <em>bubble</em> up the tree from the point of origin. If you click on the <code>#id</code> element, a click event is generated that will bubble up through all of the ancestor elements (<em>side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target</em>). You can capture the event on any of those ancestors.</p>
<p>The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.</p>
<p>By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your <code>#id</code> element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.</p> |
22,771,826 | BeanDefinitionStoreException Failed to read candidate component class | <p>Can someone tell me how to solve this issue?</p>
<p>I have narrowed down the problem to the pom.xml file. My project works but when I add the following dependency I get an error</p>
<pre><code> <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
</code></pre>
<p>The error stack is as follow </p>
<pre><code>ERROR DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [C:\workspace-sts\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Webtest1\WEB-INF\classes\com\springweb\controller\SetHomePageController.class]; nested exception is java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:290) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1438) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:185) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) ~[spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) ~[spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) ~[spring-context-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) [spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at javax.servlet.GenericServlet.init(GenericServlet.java:160) [servlet-api.jar:3.0.FR]
at org.apache.catalina.core.Standar
</code></pre>
<p>I can't understand what is wrong with the dependency, I need spring-data jpa dependency later when I'm going to add a dao that uses extends JpaRepository.</p>
<p>Thanks in advance.</p> | 22,773,635 | 9 | 0 | null | 2014-03-31 20:45:44.41 UTC | 5 | 2022-03-25 19:34:51.343 UTC | null | null | null | null | 2,744,399 | null | 1 | 24 | spring|web | 117,702 | <p>You most likely have conflicting Spring dependencies on your classpath. It's probably an old <code>spring-asm</code> JAR.</p>
<p>Run <code>mvn dependency:tree -Dincludes=:spring*::</code> and check for conflicts. The best way to avoid these is to put a dependency on the <code>spring-framework-bom</code> in your project's <code>dependencyManagement</code> section, as follows</p>
<pre><code> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.0.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</code></pre>
<p><a href="http://search.maven.org/#search%7Cgav%7C1%7Cg%3a%22org.springframework%22%20AND%20a%3a%22spring-framework-bom%22">These versions</a> are supported.</p> |
49,942,640 | Official Spring security oauth2 example doesn't work because of cookies clashing(authorization code mechanism) | <p>According the tutorial <a href="https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_authserver" rel="noreferrer">Spring Boot and OAuth2</a></p>
<p>I have following project structure:</p>
<p><a href="https://i.stack.imgur.com/O0A5t.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/O0A5t.jpg" alt="enter image description here"></a></p>
<p>And following source code:</p>
<p><strong>SocialApplication.class:</strong> </p>
<pre><code>@SpringBootApplication
@RestController
@EnableOAuth2Client
@EnableAuthorizationServer
@Order(200)
public class SocialApplication extends WebSecurityConfigurerAdapter {
@Autowired
OAuth2ClientContext oauth2ClientContext;
@RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
Map<String, String> map = new LinkedHashMap<>();
map.put("name", principal.getName());
return map;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
.logoutSuccessUrl("/").permitAll().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// @formatter:on
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
// @formatter:on
}
}
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
@Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
@Bean
@ConfigurationProperties("github")
public ClientResources github() {
return new ClientResources();
}
@Bean
@ConfigurationProperties("facebook")
public ClientResources facebook() {
return new ClientResources();
}
private Filter ssoFilter() {
CompositeFilter filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(ssoFilter(facebook(), "/login/facebook"));
filters.add(ssoFilter(github(), "/login/github"));
filter.setFilters(filters);
return filter;
}
private Filter ssoFilter(ClientResources client, String path) {
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
path);
OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(
client.getResource().getUserInfoUri(),
client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(new UserInfoTokenServices(
client.getResource().getUserInfoUri(),
client.getClient().getClientId()));
return filter;
}
}
class ClientResources {
@NestedConfigurationProperty
private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
@NestedConfigurationProperty
private ResourceServerProperties resource = new ResourceServerProperties();
public AuthorizationCodeResourceDetails getClient() {
return client;
}
public ResourceServerProperties getResource() {
return resource;
}
}
</code></pre>
<p><strong>index.html:</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Demo</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width"/>
<base href="/"/>
<link rel="stylesheet" type="text/css"
href="/webjars/bootstrap/css/bootstrap.min.css"/>
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
<script type="text/javascript"
src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Login</h1>
<div class="container unauthenticated">
With Facebook: <a href="/login/facebook">click here</a>
</div>
<div class="container authenticated" style="display: none">
Logged in as: <span id="user"></span>
<div>
<button onClick="logout()" class="btn btn-primary">Logout</button>
</div>
</div>
<script type="text/javascript"
src="/webjars/js-cookie/js.cookie.js"></script>
<script type="text/javascript">
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.type == 'POST' || settings.type == 'PUT'
|| settings.type == 'DELETE') {
if (!(/^http:.*/.test(settings.url) || /^https:.*/
.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-XSRF-TOKEN",
Cookies.get('XSRF-TOKEN'));
}
}
}
});
$.get("/user", function (data) {
$("#user").html(data.userAuthentication.details.name);
$(".unauthenticated").hide();
$(".authenticated").show();
});
var logout = function () {
$.post("/logout", function () {
$("#user").html('');
$(".unauthenticated").show();
$(".authenticated").hide();
});
return true;
}
</script>
</body>
</html>
</code></pre>
<p><strong>application.yml:</strong></p>
<pre><code>server:
port: 8080
security:
oauth2:
client:
client-id: acme
client-secret: acmesecret
scope: read,write
auto-approve-scopes: '.*'
facebook:
client:
clientId: 233668646673605
clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
accessTokenUri: https://graph.facebook.com/oauth/access_token
userAuthorizationUri: https://www.facebook.com/dialog/oauth
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://graph.facebook.com/me
github:
client:
clientId: bd1c0a783ccdd1c9b9e4
clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
accessTokenUri: https://github.com/login/oauth/access_token
userAuthorizationUri: https://github.com/login/oauth/authorize
clientAuthenticationScheme: form
resource:
userInfoUri: https://api.github.com/user
logging:
level:
org.springframework.security: DEBUG
</code></pre>
<p>But when I open browser and try to hit <code>http://localhost:8080</code></p>
<p>In browser console I see:</p>
<pre><code>(index):44 Uncaught TypeError: Cannot read property 'details' of undefined
at Object.success ((index):44)
at j (jquery.js:3073)
at Object.fireWith [as resolveWith] (jquery.js:3185)
at x (jquery.js:8251)
at XMLHttpRequest.<anonymous> (jquery.js:8598)
</code></pre>
<p>in code:</p>
<pre><code>$.get("/user", function (data) {
$("#user").html(data.userAuthentication.details.name);
$(".unauthenticated").hide();
$(".authenticated").show();
});
</code></pre>
<p>It happens because <code>/user</code> response with 302 status code and js callback try to parse result of <code>localhost:8080</code>:</p>
<p><a href="https://i.stack.imgur.com/LFbfu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/LFbfu.jpg" alt="enter image description here"></a></p>
<p>I don't understand why this redirect happens. Can you explain this behavior and help to fix it?</p>
<h2>UPDATE</h2>
<p>I took this code from <a href="https://github.com/spring-guides/tut-spring-boot-oauth2" rel="noreferrer">https://github.com/spring-guides/tut-spring-boot-oauth2</a></p>
<h2>important:</h2>
<p>It reproduces <strong>only after I start client application.</strong></p>
<h2>P.S.</h2>
<p><strong>How to reproduce:</strong></p>
<blockquote>
<p>To test the new features you can just run both apps and visit
localhost:9999/client in your browser. The client app will redirect to
the local Authorization Server, which then gives the user the usual
choice of authentication with Facebook or Github. Once that is
complete control returns to the test client, the local access token is
granted and authentication is complete (you should see a "Hello"
message in your browser). If you are already authenticated with Github
or Facebook you may not even notice the remote authentication</p>
</blockquote>
<h2>ANSWER:</h2>
<p><a href="https://stackoverflow.com/a/50349078/2674303">https://stackoverflow.com/a/50349078/2674303</a></p> | 50,349,078 | 3 | 5 | null | 2018-04-20 13:20:46.62 UTC | 2 | 2018-12-10 12:06:44.49 UTC | 2018-12-10 12:06:44.49 UTC | null | 2,674,303 | null | 2,674,303 | null | 1 | 30 | java|spring-security|oauth-2.0|spring-oauth2 | 5,843 | <p>Finally I've found the problem. I see this behaviour due the fact of cookies clashing for client and server if you start both applications on localhost.</p>
<p>It happens due the fact of usage wrong property for context.</p>
<p>So to fix application you need to replace:</p>
<pre><code>server:
context-path: /client
</code></pre>
<p>with</p>
<pre><code>server:
servlet:
context-path: /client
</code></pre>
<h2>P.S.</h2>
<p>I've created issue on github: </p>
<p><a href="https://github.com/spring-guides/tut-spring-boot-oauth2/issues/80" rel="nofollow noreferrer">https://github.com/spring-guides/tut-spring-boot-oauth2/issues/80</a></p>
<p>and made the pull request:</p>
<p><a href="https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81" rel="nofollow noreferrer">https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81</a></p>
<h2>P.S.2</h2>
<p>Finally my pull request was merged:
<a href="https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81" rel="nofollow noreferrer">https://github.com/spring-guides/tut-spring-boot-oauth2/pull/81</a></p> |
3,209,208 | What is the cleverest use of source repository that you have ever seen? | <p>This actually stems from on my earlier question where one of the answers made me wonder how people are using the scm/repository in different ways for development.</p> | 3,209,767 | 3 | 0 | null | 2010-07-09 01:19:42.747 UTC | 19 | 2010-07-27 07:50:33.207 UTC | 2010-07-09 01:36:31.397 UTC | null | 14,122 | null | 1,748,769 | null | 1 | 22 | version-control | 3,844 | <p><strong><a href="http://unethicalblogger.com/posts/2009/12/pretested_commits_hudson_and_git" rel="nofollow noreferrer">Pre-tested commits</a></strong></p>
<p>Before (TeamCity, build manager):</p>
<blockquote>
<p>The concept is simple, the build system stands as a roadblock between your commit entering trunk and only after the build system determines that your commit doesn't break things does it allow the commit to be introduced into version control, where other developers will sync and integrate that change into their local working copies</p>
</blockquote>
<p>After (using a DVCS like Git, that is a source repository):</p>
<blockquote>
<p>My workflow with Hudson for pre-tested commits involves three separate Git repositories: </p>
<ul>
<li>my local repo (local), </li>
<li>the canonical/central repo (origin) </li>
<li>and my "world-readable" (inside the firewall) repo (public). </li>
</ul>
<p>For pre-tested commits, I utilize a constantly changing branch called "pu" (potential updates) on the world-readable repo.<br>
Inside of Hudson I created a job that polls the world-readable repo (public) for changes in the "pu" branch and will kick off builds when updates are pushed.</p>
<p>my workflow for taking a change from inception to origin is:</p>
</blockquote>
<pre><code>* hack, hack, hack
* commit to local/topic
* git pup public
* Hudson polls public/pu
* Hudson runs potential-updates job
* Tests fail?
o Yes: Rework commit, try again
o No: Continue
* Rebase onto local/master
* Push to origin/master
</code></pre>
<blockquote>
<p>Using this pre-tested commit workflow <strong>I can offload the majority of my testing requirements to the build system's cluster of machines instead of running them locally, meaning I can spend the majority of my time writing code instead of waiting for tests to complete on my own machine in between coding iterations</strong>.</p>
</blockquote>
<hr>
<p>(Variation) <strong><a href="http://blog.javabien.net/2009/12/01/serverless-ci-with-git/" rel="nofollow noreferrer">Private Build</a></strong> (David Gageot, Algodeal)</p>
<p>Same principle than above, but the build is done on the same workstation than the one used to develop, but on a cloned repo:</p>
<blockquote>
<p>How not to use a CI server in the long term and not suffer the increasing time lost staring at the builds locally?</p>
<p>With git, it’s a piece of cake.<br>
First, we ‘git clone’ the working directory to another folder. Git does the copy <em>very</em> quickly.<br>
Next times, we don’t need to clone. Just tell git get the deltas. Net result: instant cloning. Impressive.</p>
<p>What about the consistency?<br>
Doing a simple ‘<code>git pull</code>’ from the working directory will realize, using delta’s digests, that the changes where already pushed on the shared repository.<br>
Nothing to do. Impressive again.</p>
<p><strong>Of course, while the build is running in the second directory, we can keep on working on the code. No need to wait.</strong></p>
<p>We now have a private build with no maintenance, no additional installation, not dependant on the IDE, ran with a single command line. No more broken build in the shared repository. We can recycle our CI server.</p>
<p>Yes. You’ve heard well. We’ve just built a serverless CI. Every additional feature of a real CI server is noise to me.</p>
</blockquote>
<pre><code>#!/bin/bash
if [ 0 -eq `git remote -v | grep -c push` ]; then
REMOTE_REPO=`git remote -v | sed 's/origin//'`
else
REMOTE_REPO=`git remote -v | grep "(push)" | sed 's/origin//' | sed 's/(push)//'`
fi
if [ ! -z "$1" ]; then
git add .
git commit -a -m "$1"
fi
git pull
if [ ! -d ".privatebuild" ]; then
git clone . .privatebuild
fi
cd .privatebuild
git clean -df
git pull
if [ -e "pom.xml" ]; then
mvn clean install
if [ $? -eq 0 ]; then
echo "Publishing to: $REMOTE_REPO"
git push $REMOTE_REPO master
else
echo "Unable to build"
exit $?
fi
fi
</code></pre>
<hr>
<p><a href="https://stackoverflow.com/users/101516/dmitry-tashkinov">Dmitry Tashkinov</a>, who has an <a href="https://stackoverflow.com/questions/3326483/continuous-integration-with-distributed-source-code-control/3326544#3326544">interesting question on DVCS and CI</a>, asks:</p>
<blockquote>
<p>I don't understand how "We’ve just built a serverless CI" cohere with Martin Fowler's state:<br>
"Once I have made my own build of a properly synchronized working copy I can then finally commit my changes into the mainline, which then updates the repository. However my commit doesn't finish my work. At this point we build again, but this time on an integration machine based on the mainline code. Only when this build succeeds can we say that my changes are done. There is always a chance that I missed something on my machine and the repository wasn't properly updated."<br>
Do you ignore or bend it?</p>
<blockquote>
<p>@Dmitry: I do not ignore nor bend the process described by <a href="http://martinfowler.com/articles/continuousIntegration.html" rel="nofollow noreferrer">Martin Fowler in his ContinuousIntegration entry</a>.<br>
But you have to realize that <a href="https://stackoverflow.com/questions/2563836/sell-me-distributed-revision-control/2563917#2563917">DVCS adds publication as an orthogonal dimension to branching</a>.<br>
The serverless CI described by David is just an implementation of the general CI process detailed by Martin: instead of having a CI server, you push to a local copy where a local CI runs, then you push "valid" code to a central repo.</p>
<blockquote>
<p>@VonC, but the idea was to run CI NOT locally particularly not to miss something in transition between machines.<br>
When you use the so called local CI, then it may pass all the tests just because it is local, but break down later on another machine.<br>
So is it integeration? I'm not criticizing here at all, the question is difficult to me and I'm trying to understand.</p>
<blockquote>
<p>@Dmitry: "So is it integeration"?<br>
It is one level of integration, which can help get rid of all the basic checks (like format issue, code style, basic static analysis detection, ...)<br>
Since you have that publication mechanism, you can chain that kind of CI to another CI server if you want. That server, in turn, can automatically push (if this is still fast-forward) to the "central" repo. </p>
<p>David Gageot didn't need that extra level, being already at target in term of deployment architecture (PC->PC) and needed only that basic kind of CI level.<br>
That doesn't prevent him to setup more complete system integration server for more complete testing.</p>
</blockquote>
</blockquote>
</blockquote>
</blockquote> |
2,622,144 | Is there a decimal math library for JavaScript? | <p>Is there a mature library for doing decimal-based math, possibly arbitrary-precision, in JavaScript?</p>
<p><strong>Edit:</strong> I want this information for a reference page on floating-point-related problems and alternatives to use when binary floating-point is inappropriate: <a href="http://floating-point-gui.de/" rel="noreferrer">http://floating-point-gui.de/</a></p> | 2,622,196 | 3 | 6 | null | 2010-04-12 12:50:44.153 UTC | 6 | 2016-11-24 20:45:43.573 UTC | 2010-04-12 13:06:51.593 UTC | null | 16,883 | null | 16,883 | null | 1 | 28 | javascript|decimal|bigdecimal | 13,573 | <p>There's been a "port" of the Java <code>BigDecimal</code> class (I think it's here: <a href="http://freshmeat.net/projects/js_bigdecimal/" rel="nofollow noreferrer">http://freshmeat.net/projects/js_bigdecimal/</a> ) for a long time. I looked at it a long time ago and it seemed kind-of cumbersome and huge, but (if that's the one I'm thinking of) it's been used as part of some cryptography tools so there's a decent chance that it works OK.</p>
<p>Because cryptography is a likely area to generate a need for such things, that's a good way to snoop around for such packages.</p>
<p><strong>edit:</strong> Thanks @Daniel (comment to question) for this older SO question: <a href="https://stackoverflow.com/questions/744099/javascript-bigdecimal-library">https://stackoverflow.com/questions/744099/javascript-bigdecimal-library</a></p> |
2,754,423 | use a variable for table name in mysql sproc | <p>I'm trying to pass a table name into my mysql stored procedure to use this sproc to select off of different tables but it's not working...</p>
<p>this is what I"m trying:</p>
<pre><code>CREATE PROCEDURE `usp_SelectFromTables`(
IN TableName varchar(100)
)
BEGIN
SELECT * FROM @TableName;
END
</code></pre>
<p>I've also tried it w/o the @ sign and that just tells me that TableName doesn't exist...which I know :)</p> | 2,754,443 | 3 | 0 | null | 2010-05-02 18:09:37.78 UTC | 15 | 2012-12-14 06:25:59.997 UTC | 2010-05-02 18:12:46.607 UTC | null | 21,234 | null | 233,971 | null | 1 | 43 | mysql|stored-procedures|query-parameters | 86,214 | <p>It depends on the DBMS, but the notation usually requires Dynamic SQL, and runs into the problem that the return values from the function depend on the inputs when it is executed. This gives the system conniptions. As a general rule (and therefore probably subject to exceptions), DBMS do not allow you to use placeholders (parameters) for structural elements of a query such as table names or column names; they only allow you to specify values such as column values.</p>
<p>Some DBMS do have stored procedure support that will allow you to build up an SQL string and then work with that, using 'prepare' or 'execute immediate' or similar operations. Note, however, that you are suddenly vulnerable to SQL injection attacks - someone who can execute your procedure is then able to control, in part, what SQL gets executed.</p> |
2,873,086 | How to handle the back button on Windows Phone 7 | <p>On the windows phone 7 emulator, when the hardware back button is pressed, the default behaviour is for it to close your current application. I want to override this default behaviour so that it navigates to the previous page in my application.</p>
<p>After some research, it seems it should be possible to do this by overriding the OnBackKeyPress method, like so:</p>
<pre><code>protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
// do some stuff ...
// cancel the navigation
e.Cancel = true;
}
</code></pre>
<p>However, clicking the back button still closes my application. Putting a breakpoint on the above method reveals that it is never called. I have another breakpoint on my application exit code, and this breakpoint <em>is</em> hit.</p>
<p>Is there something else I need to do to intercept the back button?</p> | 2,875,471 | 3 | 2 | null | 2010-05-20 11:07:31.093 UTC | 16 | 2011-05-28 00:13:57.51 UTC | 2010-05-20 11:08:16.16 UTC | null | 21,234 | null | 209,578 | null | 1 | 43 | windows-phone-7 | 39,301 | <p>It would appear that it's not possible to override the OnBackKeyPress method to intercept the back key unless you use the <code>Navigate</code> method to move between pages in your application.</p>
<p>My previous method of navigation was to change the root visual, like:</p>
<pre><code>App.Current.RootVisual = new MyPage();
</code></pre>
<p>This meant I could keep all my pages in memory so I didn't need to cache the data stored on them (some of the data is collected over the net).</p>
<p>Now it seems I need to actually use the Navigate method on the page frame, which creates a new instance of the page I'm navigating to.</p>
<pre><code>(App.Current.RootVisual as PhoneApplicationFrame).Navigate(
new Uri("/MyPage.xaml", UriKind.Relative));
</code></pre>
<p>Once I started navigating using this method, I could then override the back button handling in the way described in my question...</p> |
2,695,426 | Are LinkedBlockingQueue's insert and remove methods thread safe? | <p>I'm using <code>LinkedBlockingQueue</code> between two different threads. One thread adds data via <code>add</code>, while the other thread receives data via <code>take</code>.</p>
<p>My question is, do I need to synchronize access to <code>add</code> and <code>take</code>. Is <code>LinkedBlockingQueue</code>'s insert and remove methods thread safe?</p> | 2,695,437 | 3 | 1 | null | 2010-04-23 00:23:53.543 UTC | 8 | 2016-09-13 13:19:47.13 UTC | null | null | null | null | 24,396 | null | 1 | 60 | java|multithreading|concurrency|synchronization | 39,176 | <p>Yes. From <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" rel="noreferrer">the docs</a>: </p>
<blockquote>
<p>"BlockingQueue implementations are
thread-safe. All queuing methods
achieve their effects atomically using
internal locks or other forms of
concurrency control. However, the bulk
Collection operations addAll,
containsAll, retainAll and removeAll
are not necessarily performed
atomically unless specified otherwise
in an implementation. So it is
possible, for example, for addAll(c)
to fail (throwing an exception) after
adding only some of the elements in
c."</p>
</blockquote> |
2,407,095 | Use ssh from Windows command prompt | <p><strong>Question:</strong>
How to use ssh & scp from the Windows command prompt?</p>
<p>I remember I installed a program in the past that let me do this but can't remember now what it was. </p>
<p><strong>Note:</strong>
I do not want to use putty. </p> | 2,452,446 | 4 | 6 | null | 2010-03-09 06:40:38.46 UTC | 12 | 2015-11-19 13:45:55.707 UTC | 2015-11-19 13:45:55.707 UTC | null | 1,789,095 | null | 105,066 | null | 1 | 54 | windows|ssh|cmd|scp | 237,478 | <p>New, resurrected project site (Win7 compability and more!): <a href="http://sshwindows.sourceforge.net" rel="noreferrer">http://sshwindows.sourceforge.net</a></p>
<blockquote>
<p><strong>1st January 2012</strong> </p>
<ul>
<li>OpenSSH for Windows 5.6p1-2 based release created!!</li>
<li>Happy New Year all! Since COpSSH has started charging I've resurrected this project </li>
<li>Updated all binaries to current releases</li>
<li>Added several new supporting DLLs as required by all executables in package</li>
<li>Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build</li>
<li>Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated</li>
</ul>
</blockquote> |
33,804,500 | Screen width in React Native | <p>How do I get screen width in React native?
I need it because I use some absolute components that overlap and their position on screen changes with different devices.</p> | 33,807,375 | 15 | 0 | null | 2015-11-19 12:50:39.47 UTC | 16 | 2022-05-19 08:31:11.28 UTC | 2021-05-04 14:56:05.367 UTC | null | 6,904,888 | null | 4,507,367 | null | 1 | 137 | react-native | 165,490 | <p>In React-Native we have an Option called Dimensions</p>
<p>Include Dimensions at the top var where you have include the Image,and Text and other components.</p>
<p>Then in your Stylesheets you can use as below,</p>
<pre><code>ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
</code></pre>
<p>In this way you can get the device window and height.</p> |
54,144,551 | Google Chrome shows the status of XHR call as (blocked:other) | <p>I am getting the following status in one of my http call. I haven't seen this status before. All my call are being blocked and no hits are received at server.</p>
<p>I tried looking up for it and found that it might be due to something called Mixed content. Unfortunately, I do not have much idea about that either.</p>
<p>Can someone explain what might be causing this issue and how to get around it. ?</p> | 56,232,409 | 3 | 1 | null | 2019-01-11 10:22:17.543 UTC | 4 | 2021-06-01 13:41:51.877 UTC | null | null | null | null | 5,316,255 | null | 1 | 45 | javascript|google-chrome|http|browser|webserver | 26,923 | <p>one possible resolution if you use adblock or any plugins like that, unenable that</p> |
49,453,571 | How can I set default build target for Cargo? | <p>I tried to make 'Hello World' in Rust using <a href="https://rustwasm.github.io/book/game-of-life/hello-world.html" rel="noreferrer">this tutorial</a>, but the build command is a bit verbose:</p>
<pre><code>cargo +nightly build --target wasm32-unknown-unknown --release
</code></pre>
<p>Is it possible to set the default target for <code>cargo build</code>?</p> | 49,453,658 | 2 | 0 | null | 2018-03-23 15:46:05.137 UTC | 4 | 2020-05-04 15:49:47.597 UTC | 2019-05-06 09:22:53.987 UTC | null | 133,864 | null | 133,864 | null | 1 | 34 | rust|rust-cargo | 27,434 | <p>You could use a <a href="https://doc.rust-lang.org/cargo/reference/config.html" rel="noreferrer">Cargo configuration file</a> to specify a default target-triple for your project. In your project's root, create a <code>.cargo</code> directory and a <code>config</code> file in it with the following contents:</p>
<pre><code>[build]
target = "wasm32-unknown-unknown"
</code></pre> |
49,616,379 | Where is the Messages Window in Android Studio 3.1 | <p>After upgrading Android Studio from 3.0 to 3.1, the Messages window seems to have disappeared, even though some build outputs (e.g. proguard) continue to refer to it. Where is it?</p> | 49,616,380 | 4 | 0 | null | 2018-04-02 18:07:36.913 UTC | 3 | 2020-08-06 11:49:36.663 UTC | null | null | null | null | 3,394,973 | null | 1 | 44 | android|android-studio|android-studio-3.1 | 21,117 | <p>After some poking around, I found this button on the left side of the Build window:</p>
<p><a href="https://i.stack.imgur.com/6wH2R.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6wH2R.png" alt="Toggle View"></a></p>
<p>Clicking this button toggles the view between the new "Build" view and a text output version which resembles the old Messages view - although it isn't exactly the same.</p>
<p>I hope this helps!</p>
<p>UPDATE: In Android Studio 3.3 the button now looks like this:</p>
<p><a href="https://i.stack.imgur.com/h6X7P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h6X7P.png" alt="Toggle View 3.3"></a></p>
<p>UPDATE 2: In Android Studio 3.6 the button is gone. Instead, the build window is permanently split between text output and visual output. If you can't find the text output, it might be fully collapsed, so look on the top right of the build window for something like this:</p>
<p><a href="https://i.stack.imgur.com/3lKKZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3lKKZ.png" alt="enter image description here"></a></p>
<p>And try to drag it left to reveal the build window, like this:</p>
<p><a href="https://i.stack.imgur.com/OTkBE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OTkBE.png" alt="enter image description here"></a></p>
<p>Hope this helps!</p> |
34,990,652 | why do we need np.squeeze()? | <p>Very often, arrays are squeezed with <code>np.squeeze()</code>. In the documentation, it says </p>
<blockquote>
<p>Remove single-dimensional entries from the shape of a.</p>
</blockquote>
<p>However I'm still wondering: Why <em>are</em> zero and nondimensional entries in the shape of a? Or to put it differently: Why do both <code>a.shape = (2,1)</code> <em>and</em> <code>(2,)</code> exist?</p> | 34,991,288 | 4 | 0 | null | 2016-01-25 10:45:02.39 UTC | 17 | 2019-09-28 23:37:29.83 UTC | null | null | null | user2553692 | null | null | 1 | 50 | python|numpy | 55,652 | <p>Besides the mathematical differences between the two things, there is the issue of predictability. If your suggestion was followed, you could at no point rely on the dimension of your array. So any expression of the form <code>my_array[x,y]</code> would need to be replaced by something that first checks if <code>my_array</code> is actually two-dimensional and did not have an implicit <code>squeeze</code> at some point. This would probably obfuscate code far more than the occasional <code>squeeze</code>, which does a clearly specified thing.</p>
<p>Actually, it might even be very hard to tell, which axis has been removed, leading to a whole host of new problems.</p>
<p>In the spirit of <a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">The Zen of Python</a>, also <code>Explicit is better than implicit</code>, we can also say that we should prefer explicit <code>squeeze</code> to implicit array conversion.</p> |
29,328,420 | Read specific column from .dat-file in Python | <p>I have a results.dat file with some data like this:</p>
<pre><code>7522126 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
7825452 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
8073799 0 0 0 0 0 0 -345.551 -140.711 1819.04 -0.0220266 -0.85992 -2.29598
</code></pre>
<p>The values are each separated by a tab.</p>
<p>I want to extract the value in e.g the 8th column for every single line, and save it to an array. So the output should be this:</p>
<pre><code>-419.795
-419.795
-345.551
</code></pre>
<p>What's the easiest way to accomplish this?</p> | 29,328,543 | 4 | 0 | null | 2015-03-29 11:16:37.847 UTC | 5 | 2015-11-21 16:47:53.207 UTC | 2015-11-21 16:47:53.207 UTC | null | 1,505,120 | null | 2,358,221 | null | 1 | 7 | python|file-io | 43,626 | <pre><code>with open('results.dat') as f:
[line.split()[7] for line in f]
</code></pre>
<p>or define a function, </p>
<pre><code>get_col = lambda col: (line.split('\t')[col-1] for line in open('results.dat'))
</code></pre>
<p>Now call the function with desired column number. <code>get_col(8)</code> gives 8th column data. To store it in array, </p>
<pre><code>array.array('d',map(float,get_col(8)))
</code></pre> |
32,035,427 | How to scroll horizontal RecyclerView programmatically? | <p>I have a <code>horizontal RecyclerView</code> and two button (Next,Previous) as shown in the image below.</p>
<p><a href="https://i.stack.imgur.com/xLlgQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xLlgQ.png" alt="enter image description here"></a></p>
<p>so i need to move to the next item or position by use these buttons , i know about method called <code>scrollTo</code> but i don't know how does it work</p> | 32,145,850 | 5 | 0 | null | 2015-08-16 13:10:41.387 UTC | 8 | 2021-07-20 02:09:50.507 UTC | 2015-08-21 17:06:33.643 UTC | null | 3,005,903 | null | 3,005,903 | null | 1 | 17 | android|android-layout|android-activity|android-recyclerview | 22,050 | <p>I found the answer:</p>
<pre class="lang-cs prettyprint-override"><code>case R.id.next:
mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findLastVisibleItemPosition() + 1);
break;
case R.id.pre:
mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findFirstVisibleItemPosition() - 1);
break;
</code></pre> |
31,693,521 | How to add leading zero in a number in Oracle SQL query? | <p>I am retrieving a column named removal_count in my query using COUNT() function. In result set the datatype of removal_count is BIGDECIMAL. I want to convert number into five digits. SO if value is less than five digits then it should be represented with leading zero's.</p>
<p>e.g 1) If removal count is 540 then display 00540<br>
2) If removal count is 60 then display 00060</p>
<p>If the removal count is integer/string value then I can add leading zero's using java expression :</p>
<pre><code>--if removal_count is integer--
String.format("%05d",removal_count)
--if removal_count is string--
("00000"+removal_count).subString(removal_count.length())
</code></pre>
<p>Can we convert removal_count into string or integer ( from big decimal) so that I can use given java expression? Or else is there any way to add leading zero's in query itself?</p> | 31,693,668 | 3 | 0 | null | 2015-07-29 07:08:12.157 UTC | 7 | 2018-03-21 14:51:34.22 UTC | null | null | null | null | 4,822,479 | null | 1 | 28 | sql|oracle | 129,576 | <p>You could do it in two ways.</p>
<p><strong>Method 1</strong></p>
<p>Using <strong>LPAD</strong>.</p>
<p>For example,</p>
<pre><code>SQL> WITH DATA(num) AS(
2 SELECT 540 FROM dual UNION ALL
3 SELECT 60 FROM dual UNION ALL
4 SELECT 2 FROM dual
5 )
6 SELECT num, lpad(num, 5, '0') num_pad FROM DATA;
NUM NUM_P
---------- -----
540 00540
60 00060
2 00002
SQL>
</code></pre>
<p>The WITH clause is only to build sample data for demo, in your actual query just do:</p>
<pre><code>lpad(removal_count, 5, '0')
</code></pre>
<p>Remember, a <strong>number</strong> cannot have <strong>leading zeroes</strong>. The output of above query is a <strong>string</strong> and not a <strong>number</strong>.</p>
<p><strong>Method 2</strong></p>
<p>Using <strong>TO_CHAR</strong> and format model:</p>
<pre><code>SQL> WITH DATA(num) AS(
2 SELECT 540 FROM dual UNION ALL
3 SELECT 60 FROM dual UNION ALL
4 SELECT 2 FROM dual
5 )
6 SELECT num, to_char(num, '00000') num_pad FROM DATA;
NUM NUM_PA
---------- ------
540 00540
60 00060
2 00002
SQL>
</code></pre>
<p><strong>Update</strong> : To avoid the extra leading space which is used for minus sign, use <strong>FM</strong> in the <code>TO_CHAR</code> format:</p>
<p><strong>Without FM:</strong></p>
<pre><code>SELECT TO_CHAR(1, '00000') num_pad,
LENGTH(TO_CHAR(1, '00000')) tot_len
FROM dual;
NUM_PAD TOT_LEN
------- ----------
00001 6
</code></pre>
<p><strong>With FM:</strong></p>
<pre><code>SELECT TO_CHAR(1, 'FM00000') num_pad,
LENGTH(TO_CHAR(1, 'FM00000')) tot_len
FROM dual;
NUM_PAD TOT_LEN
------- ----------
00001 5
</code></pre> |
26,033,426 | Bootstrap: Remove form field border | <p>I am new to CSS and I am using Bootstrap and I want to use forms in 2 ways: With or without borders around the form fields. How can I achieve that best? Here is an example of a Bootstrap form I want to remove the borders for: plnkr.co/edit/xxx1Wy4kyCESNsChK4Ra?p=preview.</p>
<p>For curiosity, the reason I want this, is that I want to first show the user the data he has, and then toggle showing the borders according to if the form is in "edit" mode or not. The user can enter "edit" mode by clicking an "edit"-link or just start editing a field.</p> | 26,033,936 | 4 | 0 | null | 2014-09-25 07:59:25.93 UTC | 9 | 2022-09-09 08:41:29.517 UTC | null | null | null | null | 2,420,037 | null | 1 | 25 | twitter-bootstrap | 107,306 | <p>In that example, to remove the border simply write:</p>
<pre><code>.form-control {
border: 0;
}
</code></pre>
<p>In your CSS file.</p>
<p>This will remove borders from all your form fields though, a more flexible approach would be to attach a class to the form fields you want to have no border, so your HTML would be something like:</p>
<pre><code><input type="email" class="form-control no-border" id="inputEmail3" placeholder="Email">
</code></pre>
<p>and your CSS:</p>
<pre><code>.no-border {
border: 0;
box-shadow: none; /* You may want to include this as bootstrap applies these styles too */
}
</code></pre> |
27,238,963 | How to reduce the size of captions in all figures | <p>I want the captions of my figures and table to have the same size as \footnotesize. Is there something to put in the preambule of my document to do this?</p> | 27,243,065 | 1 | 0 | null | 2014-12-01 23:01:26.807 UTC | 3 | 2014-12-02 06:18:54.367 UTC | null | null | null | null | 4,313,555 | null | 1 | 14 | latex | 59,196 | <p>Use the <a href="http://ctan.org/pkg/caption" rel="noreferrer"><code>caption</code> package</a> to set the <code>font</code> key-value to <code>footnotesize</code>:</p>
<p><img src="https://i.stack.imgur.com/3m2OO.png" alt="enter image description here"></p>
<pre><code>\documentclass{article}
\usepackage{caption}
\captionsetup{font=footnotesize}
\begin{document}
Some regular text set in \verb|\normalsize|.
\begin{table}[t]
\caption{A table using \texttt{\string\footnotesize}.}
\end{table}
\begin{figure}[t]
\caption{A figure using \texttt{\string\footnotesize}.}
\end{figure}
\end{document}
</code></pre>
<p>It is also possible to adjust the label and text formats individually for <code>figure</code>s and <code>table</code>s separately. However, consistency is a better option here.</p> |
6,251,797 | Effect of enable-call-by-reference | <p>I get the messages</p>
<pre><code><Warning> <EJB> <BEA-010202> <Call-by-reference is not enabled for the EJB 'myEjb'.
The server will have better performance if it is enabled. To enable call-by-reference, set the enable-call-by-reference element to True in the weblogic-ejb-jar.xml deployment descriptor or corresponding annotation for this EJB.>
</code></pre>
<p>and</p>
<pre><code><Warning> <EJB> <BEA-012035> <The Remote interface method: 'public abstract java.util.Collection my.sessionfassade.ejb.myFassade.myMethod(java.lang.String,java.lang.String,java.util.Collection) throws my.Exception' in EJB 'myEjb' contains a parameter of type: 'java.util.Collection' which is not Serializable. Though the EJB 'myEjb' has call-by-reference set to false, this parameter is not Serializable and hence will be passed by reference. A parameter can be passed using call-by-value only if the parameter type is Serializable.>
</code></pre>
<p>Why would this not be enabled by default, as remote calls are still possible and done by value if the flag is set to True? Is there any negative effect when setting it to True?</p> | 6,259,720 | 1 | 0 | null | 2011-06-06 12:11:13.767 UTC | 9 | 2014-08-30 14:20:50.77 UTC | 2011-06-06 12:27:06.677 UTC | null | 766,149 | null | 766,149 | null | 1 | 13 | performance|weblogic|ejb | 11,808 | <p>call-by-reference = true is not compliant with the EJB specification.</p>
<p>The goal of remote EJBs was to provide a location transparency. In other words, if the target EJB is in another JVM, then clearly the data must somehow be copied to that JVM, so for consistency, calls to an EJB in the same JVM are also copied. If calls to an EJB in the same JVM weren't copied, then the caller/callee wouldn't know whether they need to defensively copy an ArrayList, for example. By always copying, this ambiguity is removed but at the cost of performance.</p>
<p>If you can fully trust all clients and EJBs in the same JVM and you establish a convention for copying data when necessary, then you can enable call-by-reference = true.</p> |
37,931,260 | How to Export/Import a Data Source from DataGrip? | <p>I can't seem to figure out how to export a data source configuration in DataGrip (currently on 2016.2 EAP).</p>
<p>I would like to export a handful of data sources and share them with my teammates to make it easier for them to get up and running on DG.</p>
<p>I've tried <code>File->Export Settings</code> (exporting all settings) and did not notice the data source configurations within the resulting jar file.</p>
<p>I seem to recall that in earlier versions of the tool (when it was still called 0xDBE), you could find data source configuration files on the drive and share them that way, but I am unable to locate any at this time.</p>
<p>Perhaps it's not possible?</p> | 37,944,760 | 6 | 0 | null | 2016-06-20 20:27:12.783 UTC | 9 | 2021-04-20 09:41:48.727 UTC | 2021-02-10 17:30:45.263 UTC | null | 1,828,296 | null | 1,822,537 | null | 1 | 47 | datasource|datagrip | 56,679 | <p><strong>UPDATE FROM 2021!</strong></p>
<p>Starting from version 2021.1, you can just press Ctrl/Cmd+C on the data source, and then Ctrl/Cmd+V it in another IDE. The clipboard contains XML for the data source, so you can send it to the colleague via e-mail, messenger etc.</p>
<hr />
<p>It is possible!
You need to share a project with your friend — all you do in DataGrip is in the context of a project. If you did not create a new one, everything is under the default project. Look at the gif:</p>
<p><a href="https://i.stack.imgur.com/pLeix.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/pLeix.gif" alt="enter image description here" /></a></p>
<p>The more detailed information can be found in the tutorial: <a href="https://blog.jetbrains.com/datagrip/2018/05/21/copy-and-share-data-sources-in-datagrip/" rel="noreferrer">https://blog.jetbrains.com/datagrip/2018/05/21/copy-and-share-data-sources-in-datagrip/</a></p> |
24,975,746 | Can a paid app be tested in alpha/beta for free | <p>I've looked on SO at a lot of questions regarding this, and they all seem to say that if the app is a paid app, then Alpha and Beta testers will also have to pay to test it.</p>
<p>However, I'm naively hoping that as 99% of the answers I read are from mid 2013 when the Alpha/Beta testing feature first came out, that maybe Google have listened to people and changed this since then.</p>
<p>If not, what are my alternatives? I see them as the following</p>
<ol>
<li>I presume I can refund people out of my own pocket but that means Google will keep their 30% so it'll cost me 30% of my app cost for each tester.</li>
<li>I could email them all the apk, but that way I'll have to do it for every update, rather than letting the play store do it for me. Also, if I have a lot of testers it could be annoying sending out multiple emails (unless I do one huge BCC of course)</li>
<li>Could I somehow set up two versions of the app in the store, one called free and one called paid. Only give the free version out to the testers, and then delete that app, and push the final apk to the paid app.</li>
</ol>
<p>I think 3. is the best option, but more hassle than I'd expect from this presumably very common occurrence.</p>
<p>On a side note, who could I contact over this question, directly at Google? Someone at the play store team? How do you even find an address for that!?</p>
<p>UPDATE: When I do this now, I create promo codes and give them to my individual beta testers. It doesn't take more than 20secs per person, so for my number of people I'm good with that</p> | 25,542,224 | 8 | 0 | null | 2014-07-26 21:35:33.21 UTC | 7 | 2019-09-18 09:08:51.723 UTC | 2017-11-09 15:23:27.203 UTC | null | 1,018,843 | null | 1,018,843 | null | 1 | 30 | android|google-play | 14,619 | <p>I've had the same problem and contacted the google support, the result was: If you want to let your testers test the app for free, you have to create a free clone of the paid app. </p>
<p>You can find the full question and answer below.</p>
<p>Question:</p>
<blockquote>
<p>Is it possible to offer a paid app for free to alpha/beta test users
without creating a free clone of the app?</p>
</blockquote>
<p>Answer:</p>
<blockquote>
<p>Thanks for contacting Google Play Developer support about Beta
Testing. Please note that once you've set the price of an application,
you can change it at any time. However, once you’ve published an
application for free, you cannot change it to be priced at a later
time. Currently, this means Alpha and Beta versions will have to be at
least $0.99 if you want to charge for the app when it goes to
Production. Alpha/Beta testers will be charged for this amount. We do
this to prevent users who download a free app from being charged
during future updates or failing a licensing check when running the
app.</p>
<p>If you'd like to sell an application that was previously published as
free, you'll need to upload a new APK and add a price. While you will
be unable to upload the same package name again, you will be able to
upload a slight variation on the original package name. As an
alternative, you may also implement in-app billing for your free app.</p>
<p>We hope this helps answer your question. If we can assist you further,
please let us know.</p>
<p>Regards, ... Google Play Developer Support</p>
</blockquote>
<p><strong>Update:</strong>
You can use promo codes to allow testers to access your paid app for free:
<a href="https://support.google.com/googleplay/android-developer/answer/6321495">https://support.google.com/googleplay/android-developer/answer/6321495</a>
<a href="https://developer.android.com/google/play/billing/billing_promotions.html">https://developer.android.com/google/play/billing/billing_promotions.html</a></p> |
18,485,098 | Python Threading with Event object | <p>I've seen a lot of Python scripts that use Threads in a class and a lot of them use the <code>threading.Event()</code>. For example:</p>
<pre><code>class TimerClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
def run(self):
while not self.event.is_set():
print "something"
self.event.wait(120)
</code></pre>
<p>In the <code>while</code> loop, why do they check the condition if they don't set <code>self.event</code>?</p> | 18,485,226 | 1 | 2 | null | 2013-08-28 10:14:52.48 UTC | 12 | 2014-07-01 15:01:21.17 UTC | 2014-07-01 14:58:05.463 UTC | null | 321,731 | null | 2,724,899 | null | 1 | 47 | python|python-multithreading | 67,594 | <p>Because someone else will set it.</p>
<p>You generally start a thread in one part of your application and continue to do whatever you do:</p>
<pre><code>thread = TimerClass()
thread.start()
# Do your stuff
</code></pre>
<p>The thread does it's stuff, while you do your stuff. If you want to terminate the thread you just call:</p>
<pre><code>thread.event.set()
</code></pre>
<p>And the thread will stop.</p>
<p>So the answer is: event, in this case, is not used for controlling the thread from inside the thread object itself. It is used for controlling the thread from outside (from the object which holds the reference to the thread).</p> |
23,617,900 | How to select .NET 4.5.2 as a target framework in Visual Studio | <p>I have installed <a href="http://www.microsoft.com/en-us/download/details.aspx?id=42642" rel="noreferrer">.NET Framework 4.5.2</a> on Windows 8.1. But in Visual Studio 2013 I do not see the .NET Framework 4.5.2 option (see screenshot). How do I target my project for .NET 4.5.2?</p>
<p><img src="https://i.stack.imgur.com/Xsm0x.png" alt="Enter image description here"></p> | 23,618,042 | 2 | 0 | null | 2014-05-12 20:07:03.697 UTC | 18 | 2017-10-23 04:41:51.19 UTC | 2016-11-21 17:31:20.29 UTC | null | 63,550 | null | 695,797 | null | 1 | 124 | .net|visual-studio|.net-4.5.2 | 84,016 | <p>You need to install the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=42637" rel="noreferrer">Microsoft .NET Framework 4.5.2 Developer Pack</a></p>
<p>This contains the following components (emphasis added by me):</p>
<blockquote>
<ul>
<li><p>.NET Framework 4.5.2</p>
</li>
<li><p><strong>.NET Framework 4.5.2 Multi-Targeting Pack: Contains the reference assemblies needed to build apps that target the .NET Framework 4.5.2</strong></p>
</li>
<li><p>.NET Framework 4.5.2 Language Packs</p>
</li>
<li><p>.NET Framework 4.5.2 Multi-Targeting Pack Language Packs: Contains the IntelliSense files to display help while building apps that target
the .NET Framework 4.5.2 through Visual Studio and third party IDEs.</p>
</li>
</ul>
</blockquote> |
52,763,291 | Get current resource usage of a pod in Kubernetes with Go client | <p>The kubernetes go client has tons of methods and I can't find how I can get the current CPU & RAM usage of a specific (or all pods).</p>
<p>Can someone tell me what methods I need to call to get the current usage for pods & nodes?</p>
<p><strong>My NodeList:</strong></p>
<pre><code>nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
</code></pre>
<p>Kubernetes Go Client: <a href="https://github.com/kubernetes/client-go" rel="noreferrer">https://github.com/kubernetes/client-go</a></p>
<p>Metrics package: <a href="https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/metrics" rel="noreferrer">https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/metrics</a></p>
<p>As far as I got the metrics server implements the Kubernetes metrics package in order to fetch the resource usage from pods and nodes, but I couldn't figure out where & how they do it: <a href="https://github.com/kubernetes-incubator/metrics-server" rel="noreferrer">https://github.com/kubernetes-incubator/metrics-server</a></p> | 53,032,629 | 3 | 0 | null | 2018-10-11 15:00:43.873 UTC | 8 | 2018-10-31 09:51:20.707 UTC | 2018-10-23 14:58:09.493 UTC | null | 3,924,219 | null | 3,924,219 | null | 1 | 14 | go|kubernetes | 9,433 | <p>It is correct that go-client does not have support for metrics type, but in the metrics package there is a pregenerated <a href="https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/metrics/pkg/client/clientset/versioned" rel="noreferrer">client</a> that can be used for fetching metrics objects and assign them right away to the appropriate structure. The only thing you need to do first is to generate a config and pass it to metrics client. So a simple client for metrics would look like this:</p>
<pre><code>package main
import (
"k8s.io/client-go/tools/clientcmd"
metrics "k8s.io/metrics/pkg/client/clientset/versioned"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func main() {
var kubeconfig, master string //empty, assuming inClusterConfig
config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
if err != nil{
panic(err)
}
mc, err := metrics.NewForConfig(config)
if err != nil {
panic(err)
}
mc.MetricsV1beta1().NodeMetricses().Get("your node name", metav1.GetOptions{})
mc.MetricsV1beta1().NodeMetricses().List(metav1.ListOptions{})
mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).List(metav1.ListOptions{})
mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).Get("your pod name", metav1.GetOptions{})
}
</code></pre>
<p>Each of the above methods from metric client returns an appropriate structure (you can check those <a href="https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/metrics/pkg/apis/metrics/v1beta1/types.go" rel="noreferrer">here</a>) and an error (if any) which you should process according to your requirements. </p> |
51,238,420 | how to use local flutter package in another flutter application? | <p>How to use local flutter package in another flutter application?</p>
<p>I created a package using following command:</p>
<pre><code>flutter create --template=package my_new_package
</code></pre>
<p>and then in my application source code => main.dart</p>
<pre><code>import "package:my_new_package/my_new_package.dart" // can not find the package
</code></pre> | 51,238,421 | 4 | 1 | null | 2018-07-09 04:55:50.953 UTC | 20 | 2021-07-26 19:23:57.807 UTC | null | null | null | null | 5,004,206 | null | 1 | 140 | dart|flutter|flutter-dependencies | 65,617 | <p>Find this file in your flutter application => pubspec.yaml</p>
<p>Use local dependency</p>
<pre class="lang-yaml prettyprint-override"><code> dependencies:
flutter:
sdk: flutter
my_new_package:
path: ./my_new_package
</code></pre>
<p>Note: The <code>./my_new_package</code> above means that the <code>my_new_package</code> directory containing the <code>pubspec.yaml</code> for the package is a sub-directory of the app.</p>
<p>If you have the package as a directory at the same level as the app, in other words one level higher up in the directory tree, you can use <code>../my_new_package</code> (note the double dot) or a full path to the package directory.</p> |
594,239 | How to Add/Remove reference programmatically? | <p>My Application is built to a scan MS Access database in VB.NET.</p>
<p>When the Access application is distributed to end users, they may have different versions of COM components. Is it possible to Add/Remove references programmatically to resolve broken references due to differing versions? </p>
<p>Please share me code or link for reference.</p> | 594,475 | 2 | 0 | null | 2009-02-27 10:33:29.57 UTC | 9 | 2012-09-13 05:50:21.51 UTC | 2009-03-09 23:45:13.64 UTC | Gortok | 16,587 | Sugam | 45,255 | null | 1 | 8 | vb.net|ms-access | 31,457 | <p>Here is some sample code:</p>
<p><strong>Create Reference from File</strong></p>
<pre><code> Sub AddWS()
'Create a reference to Windows Script Host, '
'where you will find FileSystemObject '
'Reference name: "IWshRuntimeLibrary" '
'Reference Name in references list: "Windows Script Host Object Model" '
ReferenceFromFile "C:\WINDOWS\System32\wshom.ocx"
End Sub
Function ReferenceFromFile(strFileName As String) As Boolean
Dim ref As Reference
On Error GoTo Error_ReferenceFromFile
References.AddFromFile (strFileName)
ReferenceFromFile = True
Exit_ReferenceFromFile:
Exit Function
Error_ReferenceFromFile:
ReferenceFromFile = False
Resume Exit_ReferenceFromFile
End Function
</code></pre>
<p><strong>Delete Reference</strong></p>
<pre><code> Sub DeleteRef(RefName)
Dim ref As Reference
'You need a reference to remove '
Set ref = References(RefName)
References.Remove ref
End Sub
You can use the references collection to find if a reference exists.
</code></pre>
<p><strong>Reference Exists</strong></p>
<pre><code> Function RefExists(RefName)
Dim ref As Object
RefExists = False
For Each ref In References
If ref.Name = RefName Then
RefExists = True
End If
Next
End Function
</code></pre>
<p>From: <a href="http://wiki.lessthandot.com/index.php/Add,_Remove,_Check_References" rel="noreferrer">http://wiki.lessthandot.com/index.php/Add,_Remove,_Check_References</a></p>
<p><strong>You may also wish to read</strong> <a href="http://www.mvps.org/access/modules/mdl0022.htm" rel="noreferrer">http://www.mvps.org/access/modules/mdl0022.htm</a></p> |
3,037,027 | Android: OutofMemoryError: bitmap size exceeds VM budget with no reason I can see | <p>I am having an OutOfMemory exception with a gallery over 600x800 pixels JPEG's.</p>
<hr>
<p><strong>The environment</strong></p>
<p>I've been using Gallery with JPG images around 600x800 pixels.</p>
<p>Since my content may be a bit more complex than just images, I have set each view to be a RelativeLayout that wraps ImageView with the JPG.</p>
<p>In order to "speed up" the user experience I have a simple cache of 4 slots that prefetches (in a looper) about 1 image left and 1 image right to the displayed image and keeps them in a 4 slot HashMap. </p>
<p><strong>The platform</strong></p>
<p>I am using AVD of 256 RAM and 128 Heap Size, with a 600x800 screen.
It also happens on an Entourage Edge target, except that with the device it's harder to debug.</p>
<hr>
<p><strong>The problem</strong></p>
<p>I have been getting an exception:</p>
<pre><code>OutofMemoryError: bitmap size exceeds VM budget
</code></pre>
<p>And it happens when fetching the fifth image. I have tried to change the size of my image cache, and it is still the same.</p>
<hr>
<p><strong>The strange thing: There should not be a memory problem</strong></p>
<p>In order to make sure the heap limit is very far away from what I need, I have defined a dummy 8MB array in the beginning, and left it unreferenced so it's immediately dispatched. It is a member of the activity thread and is defined as following</p>
<pre><code>static { @SuppressWarnings("unused")
byte dummy[] = new byte[ 8*1024*1024 ]; }
</code></pre>
<p>The result is that the heap size is nearly 11MB and it's all free.
<em>Note</em> I have added that trick after it began to crash. It makes OutOfMemory less frequent.</p>
<p>Now, I am using DDMS. Just before the crash (does not change much after the crash), DDMS shows:</p>
<pre><code>ID Heap Size Allocated Free %Used #Objects
1 11.195 MB 2.428 MB 8.767 MB 21.69% 47,156
</code></pre>
<p>And in the detail table it shows:</p>
<pre><code>Type Count Total Size Smallest Largest Median Average
free 1,536 8.739MB 16B 7.750MB 24B 5.825KB
</code></pre>
<p>The largest block is 7.7MB. And yet the LogCat says:</p>
<pre><code>ERROR/dalvikvm-heap(1923): 925200-byte external allocation too large for this process.
</code></pre>
<p>If you mind the relation of the median and the average, it is plausible to assume that most of the available blocks are very small. However, <strong>there is a block large enough for the bitmap, it's 7.7M. How come it is still not enough?</strong></p>
<p>Note: I recorded a heap trace. When looking at the amount of data allocated, it does not feel like more than 2M is allocated. It does match the free memory report by DDMS.</p>
<hr>
<ul>
<li>Could it be that I experience some problem like heap-fragmentation?</li>
<li>How do I solve/workaround the problem?</li>
<li>Is the heap shared to all threads?</li>
<li>Could it be that I interpret the DDMS readout in a wrong way, and there is really no 900K block to allocate? If so, can anybody please tell me where I can see that?</li>
</ul>
<p>Thanks a lot</p>
<p>Meymann</p> | 3,184,850 | 5 | 3 | null | 2010-06-14 12:02:50.553 UTC | 6 | 2015-05-15 21:11:53.927 UTC | 2010-06-14 12:20:36.053 UTC | null | 361,169 | null | 361,169 | null | 1 | 34 | android|gallery|imageview|out-of-memory|ddms | 26,688 | <p>I think there's nothing special in your case. There's just not enough memory. You can't have several 600x800 bitmaps in memory, they consume too much memory. You should save them to SD and load to memory on demand. I think that's exactly what you do.</p>
<p>One thing you should be aware of: DDMS displays java heap memory consumption. But there's also native memory that is not displayed in DDMS. And bitmaps as far as I understand are created in native memory. So DDMS is just a bad tool to track these memory issues. You just need to be sure that you free your memory, that images are collected by Garbage Collector after you don't need them any more.</p>
<p>Garbage Collector works on it's own schedule. That's why you should call Bitmap.recycle() method on bitmaps that you don't need any more. This method frees exactly the native memory that you run out of. This way you don't depend on GC and you can free largest piece of memory as soon as possible.</p>
<p>First of all you should ensure that you don't leak bitmaps.</p>
<p>Here's a nice <a href="https://stackoverflow.com/questions/2298208/how-to-discovery-memory-usage-on-my-application-in-android/2299813#2299813">post</a> on memory allocations, it can help you to dig deeper </p> |
2,852,381 | 'Calling a method' OR 'sending a message' in Objective C | <p>In C or any ECMAscript based language you 'call a public method or function' on an object. But in documentation for Objective C, there are no public method calls, only the sending of messages.</p>
<p>Is there anything wrong in thinking that when you 'send a message' in ObjC you are actually 'calling a public method on an Object'.?</p> | 2,852,409 | 5 | 2 | null | 2010-05-17 20:11:06.123 UTC | 25 | 2014-01-11 18:34:37.18 UTC | null | null | null | null | 129,899 | null | 1 | 54 | objective-c|javascript | 15,354 | <p>Theoretically, they're different.</p>
<p>Practically, not so much.</p>
<p>They're different in that in Objective-C, objects can choose to not respond to messages, or forward messages on to different objects, or whatever. In languages like C, function calls are really just jumping to a certain spot in memory and executing code. There's no dynamic behavior involved.</p>
<p>However, in standard use cases, when you send a message to an object, the method that the message represented will usually end up being called. So about 99% of the time, sending a message will result in calling a method. As such, we often say "call a method" when we really mean "send a message". So practically, they're almost always the same, <em>but they don't have to be</em>.</p>
<p>A while ago, I waxed philosophical on this topic and blogged about it: <a href="http://davedelong.tumblr.com/post/58428190187/an-observation-on-objective-c" rel="noreferrer">http://davedelong.tumblr.com/post/58428190187/an-observation-on-objective-c</a></p>
<p><strong>edit</strong></p>
<p>To directly answer your question, there's usually nothing wrong with saying "calling a method" instead of "sending a message". However, it's important to understand that there is a very significant implementation difference.</p>
<p>(And as an aside, my personal preference is to say "invoke a method on an object")</p> |
2,410,710 | Why is the new Tuple type in .Net 4.0 a reference type (class) and not a value type (struct) | <p>Does anyone know the answer and/or have an opinion about this?</p>
<p>Since tuples would normally not be very large, I would assume it would make more sense to use structs than classes for these. What say you?</p> | 5,856,728 | 5 | 1 | null | 2010-03-09 16:40:05.143 UTC | 15 | 2019-10-30 06:32:00.273 UTC | 2019-10-30 06:32:00.273 UTC | null | 3,646,777 | null | 444,976 | null | 1 | 90 | performance|class|struct|.net-4.0 | 17,461 | <p>Microsoft made all tuple types reference types in the interests of simplicity.</p>
<p>I personally think this was a mistake. Tuples with more than 4 fields are very unusual and should be replaced with a more typeful alternative anyway (such as a record type in F#) so only small tuples are of practical interest. My own benchmarks showed that unboxed tuples up to 512 bytes could still be faster than boxed tuples.</p>
<p>Although memory efficiency is one concern, I believe the dominant issue is the overhead of the .NET garbage collector. Allocation and collection are <em>very expensive</em> on .NET because its garbage collector has not been very heavily optimized (e.g. compared to the JVM). Moreover, the default .NET GC (workstation) has not yet been parallelized. Consequently, parallel programs that use tuples grind to a halt as all cores contend for the shared garbage collector, destroying scalability. This is not only the dominant concern but, AFAIK, was completely neglected by Microsoft when they examined this problem.</p>
<p>Another concern is virtual dispatch. Reference types support subtypes and, therefore, their members are typically invoked via virtual dispatch. In contrast, value types cannot support subtypes so member invocation is entirely unambiguous and can always be performed as a direct function call. Virtual dispatch is hugely expensive on modern hardware because the CPU cannot predict where the program counter will end up. The JVM goes to great lengths to optimize virtual dispatch but .NET does not. However, .NET does provide an escape from virtual dispatch in the form of value types. So representing tuples as value types could, again, have dramatically improved performance here. For example, calling <code>GetHashCode</code> on a 2-tuple a million times takes 0.17s but calling it on an equivalent struct takes only 0.008s, i.e. the value type is 20× faster than the reference type.</p>
<p>A real situation where these performance problems with tuples commonly arises is in the use of tuples as keys in dictionaries. I actually stumbled upon this thread by following a link from the Stack Overflow question <a href="https://stackoverflow.com/questions/5850243/fsharp-runs-my-algorithm-slower-than-python">F# runs my algorithm slower than Python!</a> where the author's F# program turned out to be slower than his Python precisely because he was using boxed tuples. Manually unboxing using a hand-written <code>struct</code> type makes his F# program several times faster, and faster than Python. These issues would never had arisen if tuples were represented by value types and not reference types to begin with...</p> |
2,389,602 | Maven2 cannot find parent from relative path | <p>I'm trying to use Maven2 but my child projects cannot find the parent project.</p>
<p>Directory structure is as follows:</p>
<pre><code>--parent
--pom.xml
--child
--pom.xml
</code></pre>
<p>Child pom.xml file looks like:</p>
<pre><code><parent>
<groupId>com.mycompany.app</groupId>
<artifactId>myapp</artifactId>
<version>${app.version}</version>
<relativePath>.../parent/pom.xml</relativePath>
</parent>
</code></pre>
<p>However when I use maven it doesn't even seem to look in the relative path, it seems to try and download it from the maven repository. It's obviously not in the repo. I want it to look at the relative path. What am I doing wrong? Here's the error message:</p>
<pre><code>[INFO] Scanning for projects...
Downloading: http://repo1.maven.org/maven2/com/mycompany/app/myapp/${app.version}/myapp-
${app.version}.pom
[INFO] Unable to find resource 'com.mycompany.app:myapp:pom:${app.version}' in reposit
ory central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).
Project ID: null:web:jar:null
Reason: Cannot find parent: com.mycompany.app:myapp for project: null:web:jar:null for
project null:web:jar:null
</code></pre> | 2,390,264 | 6 | 0 | null | 2010-03-05 20:00:33.363 UTC | 1 | 2017-12-04 12:07:27.253 UTC | 2010-03-06 14:35:37.637 UTC | null | 265,143 | null | 204,349 | null | 1 | 13 | maven-2|maven | 52,547 | <p>You can't use a property for the parent version - it must match. At the moment this is required for the build to be reproducible at a later date. A number of people are tracking this on issue <a href="https://issues.apache.org/jira/browse/MNG-624" rel="nofollow noreferrer">https://issues.apache.org/jira/browse/MNG-624</a></p> |
2,464,870 | fancybox iframe dimension | <p>In the fancybox homepage (<a href="http://fancybox.net/home" rel="noreferrer">http://fancybox.net/home</a>) there is an example that opens an iFrame dimensioned as the 75% of the screen.</p>
<p>I can't get it by modifying the width and height properties on the .js file as described on the site.</p> | 2,892,779 | 7 | 0 | null | 2010-03-17 18:30:43.143 UTC | null | 2013-09-07 06:56:28.14 UTC | 2012-10-19 20:02:24.06 UTC | null | 396,458 | null | 225,877 | null | 1 | 9 | jquery|fancybox|dynamic-resizing | 47,486 | <p>You should try this:</p>
<pre><code>$('iframeLink').fancybox({
'width':300,
'height':200,
'type':'iframe',
'autoScale':'false'
});
</code></pre> |
2,513,031 | How to use multiple @RequestMapping annotations in spring? | <p>Is it possible to use multiple <code>@RequestMapping</code> annotations over a method? </p>
<p>Like :</p>
<pre><code>@RequestMapping("/")
@RequestMapping("")
@RequestMapping("/welcome")
public String welcomeHandler(){
return "welcome";
}
</code></pre> | 2,814,463 | 7 | 0 | null | 2010-03-25 04:19:56.463 UTC | 52 | 2022-04-30 17:48:13.687 UTC | 2020-03-22 17:52:54.72 UTC | null | 8,340,997 | null | 291,059 | null | 1 | 286 | java|spring|spring-mvc | 197,977 | <p><code>@RequestMapping</code> has a <code>String[]</code> value parameter, so you should be able to specify multiple values like this:</p>
<pre class="lang-java prettyprint-override"><code>@RequestMapping(value={"", "/", "welcome"})
</code></pre> |
3,187,414 | Clang vs GCC - which produces faster binaries? | <p>I'm currently using GCC, but I discovered Clang recently and I'm pondering switching. There is one deciding factor though - quality (speed, memory footprint, reliability) of binaries it produces - if <code>gcc -O3</code>can produce a binary that runs 1% faster, or Clang binaries take up more memory or just fail due to compiler bugs, it's a deal-breaker.</p>
<p>Clang boasts better compile speeds and lower compile-time memory footprint than GCC, but I'm really interested in benchmarks/comparisons of resulting compiled software - could you point me to some pre-existing resources or your own benchmarks?</p> | 15,043,814 | 7 | 1 | null | 2010-07-06 15:01:50.923 UTC | 108 | 2022-01-02 22:05:55.027 UTC | 2021-12-27 10:34:41.637 UTC | null | 13,857,035 | null | 249,618 | null | 1 | 287 | optimization|gcc|compiler-construction|clang|benchmarking | 147,352 | <p>Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2
and Clang 3.2 for C++.</p>
<p><strong>UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.</strong></p>
<p><strong>UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.</strong></p>
<p>I maintain an OSS tool that is built for Linux with both GCC and Clang,
and with Microsoft's compiler for Windows. The tool, <em>coan</em>, is a preprocessor
and analyser of C/C++ source files and codelines of such: its
computational profile majors on recursive-descent parsing and file-handling.
The development branch (to which these results pertain)
comprises at present around 11K LOC in about 90 files. It is coded,
now, in C++ that is rich in polymorphism and templates and but is still
mired in many patches by its not-so-distant past in hacked-together C.
Move semantics are not expressly exploited. It is single-threaded. I
have devoted no serious effort to optimizing it, while the "architecture"
remains so largely ToDo.</p>
<p>I employed Clang prior to 3.2 only as an experimental compiler
because, despite its superior compilation speed and diagnostics, its
C++11 standard support lagged the contemporary GCC version in the
respects exercised by coan. With 3.2, this gap has been closed.</p>
<p>My Linux test harness for current coan development processes roughly
70K sources files in a mixture of one-file parser test-cases, stress
tests consuming 1000s of files and scenario tests consuming < 1K files.</p>
<p>As well as reporting the test results, the harness accumulates and
displays the totals of files consumed and the run time consumed in coan (it just passes each coan command line to the Linux <code>time</code> command and captures and adds up the reported numbers). The timings are flattered by the fact that any number of tests which take 0 measurable time will all add up to 0, but the contribution of such tests is negligible. The timing stats are displayed at the end of <code>make check</code> like this:</p>
<pre class="lang-none prettyprint-override"><code>coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.
</code></pre>
<p>I compared the test harness performance as between GCC 4.7.2 and
Clang 3.2, all things being equal except the compilers. As of Clang 3.2,
I no longer require any preprocessor differentiation between code
tracts that GCC will compile and Clang alternatives. I built to the
same C++ library (GCC's) in each case and ran all the comparisons
consecutively in the same terminal session.</p>
<p>The default optimization level for my release build is -O2. I also
successfully tested builds at -O3. I tested each configuration 3
times back-to-back and averaged the 3 outcomes, with the following
results. The number in a data-cell is the average number of
microseconds consumed by the coan executable to process each of
the ~70K input files (read, parse and write output and diagnostics).</p>
<pre class="lang-none prettyprint-override"><code> | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|
</code></pre>
<p>Any particular application is very likely to have traits that play
unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking
employs diverse applications. With that well in mind, the noteworthy
features of these data are:</p>
<ol>
<li>-O3 optimization was marginally detrimental to GCC</li>
<li>-O3 optimization was importantly beneficial to Clang</li>
<li>At -O2 optimization, GCC was faster than Clang by just a whisker</li>
<li>At -O3 optimization, Clang was importantly faster than GCC.</li>
</ol>
<p>A further interesting comparison of the two compilers emerged by accident
shortly after those findings. Coan liberally employs smart pointers and
one such is heavily exercised in the file handling. This particular
smart-pointer type had been typedef'd in prior releases for the sake of
compiler-differentiation, to be an <code>std::unique_ptr<X></code> if the
configured compiler had sufficiently mature support for its usage as
that, and otherwise an <code>std::shared_ptr<X></code>. The bias to <code>std::unique_ptr</code> was
foolish, since these pointers were in fact transferred around,
but <code>std::unique_ptr</code> looked like the fitter option for replacing
<code>std::auto_ptr</code> at a point when the C++11 variants were novel to me.</p>
<p>In the course of experimental builds to gauge Clang 3.2's continued need
for this and similar differentiation, I inadvertently built
<code>std::shared_ptr<X></code> when I had intended to build <code>std::unique_ptr<X></code>,
and was surprised to observe that the resulting executable, with default -O2
optimization, was the fastest I had seen, sometimes achieving 184
msecs. per input file. With this one change to the source code,
the corresponding results were these;</p>
<pre class="lang-none prettyprint-override"><code> | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |
</code></pre>
<p>The points of note here are:</p>
<ol>
<li>Neither compiler now benefits at all from -O3 optimization.</li>
<li>Clang beats GCC just as importantly at each level of optimization.</li>
<li>GCC's performance is only marginally affected by the smart-pointer type
change.</li>
<li>Clang's -O2 performance is importantly affected by the smart-pointer type
change.</li>
</ol>
<p>Before and after the smart-pointer type change, Clang is able to build a
substantially faster coan executable at -O3 optimisation, and it can
build an equally faster executable at -O2 and -O3 when that
pointer-type is the best one - <code>std::shared_ptr<X></code> - for the job.</p>
<p>An obvious question that I am not competent to comment upon is <em>why</em>
Clang should be able to find a 25% -O2 speed-up in my application when
a heavily used smart-pointer-type is changed from unique to shared,
while GCC is indifferent to the same change. Nor do I know whether I should
cheer or boo the discovery that Clang's -O2 optimization harbours
such huge sensitivity to the wisdom of my smart-pointer choices.</p>
<p><strong>UPDATE: GCC 4.8.1 v clang 3.3</strong></p>
<p>The corresponding results now are:</p>
<pre class="lang-none prettyprint-override"><code> | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |
</code></pre>
<p>The fact that all four executables now take a much greater average time than previously to process
1 file does <em>not</em> reflect on the latest compilers' performance. It is due to the
fact that the later development branch of the test application has taken on lot of
parsing sophistication in the meantime and pays for it in speed. Only the ratios are
significant.</p>
<p>The points of note now are not arrestingly novel:</p>
<ul>
<li>GCC is indifferent to -O3 optimization</li>
<li>clang benefits very marginally from -O3 optimization</li>
<li>clang beats GCC by a similarly important margin at each level of optimization.</li>
</ul>
<p>Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that
GCC has clawed back about a quarter of clang's lead at each optimization level. But
since the test application has been heavily developed in the meantime one cannot
confidently attribute this to a catch-up in GCC's code-generation.
(This time, I have noted the application snapshot from which the timings were obtained
and can use it again.)</p>
<p><strong>UPDATE: GCC 4.8.2 v clang 3.4</strong></p>
<p>I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would
stick to the same coan snaphot for further updates. But I decided
instead to test on that snapshot (rev. 301) <em>and</em> on the latest development
snapshot I have that passes its test suite (rev. 619). This gives the results a
bit of longitude, and I had another motive:</p>
<p>My original posting noted that I had devoted no effort to optimizing coan for
speed. This was still the case as of rev. 301. However, after I had built
the timing apparatus into the coan test harness, every time I ran the test suite
the performance impact of the latest changes stared me in the face. I saw that
it was often surprisingly big and that the trend was more steeply negative than
I felt to be merited by gains in functionality.</p>
<p>By rev. 308 the average processing time per input file in the test suite had
well more than doubled since the first posting here. At that point I made a
U-turn on my 10 year policy of not bothering about performance. In the intensive
spate of revisions up to 619 performance was always a consideration and a
large number of them went purely to rewriting key load-bearers on fundamentally
faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this
U-turn,</p>
<p>Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:</p>
<p><em><strong>coan - rev.301 results</strong></em></p>
<pre class="lang-none prettyprint-override"><code> | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|
</code></pre>
<p>The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing
is a trifle better. Clang's is a trifle worse. Noise could well account for this.
Clang still comes out ahead by <code>-O2</code> and <code>-O3</code> margins that wouldn't matter in most
applications but would matter to quite a few.</p>
<p>And here is the matrix for rev. 619.</p>
<p><em><strong>coan - rev.619 results</strong></em></p>
<pre class="lang-none prettyprint-override"><code> | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|
</code></pre>
<p>Taking the 301 and the 619 figures side by side, several points speak out.</p>
<ul>
<li><p>I was aiming to write faster code, and both compilers emphatically vindicate
my efforts. But:</p>
</li>
<li><p>GCC repays those efforts far more generously than Clang. At <code>-O2</code>
optimization Clang's 619 build is 46% faster than its 301 build: at <code>-O3</code> Clang's
improvement is 31%. Good, but at each optimization level GCC's 619 build is
more than twice as fast as its 301.</p>
</li>
<li><p>GCC more than reverses Clang's former superiority. And at each optimization
level GCC now beats Clang by 17%.</p>
</li>
<li><p>Clang's ability in the 301 build to get more leverage than GCC from <code>-O3</code> optimization
is gone in the 619 build. Neither compiler gains meaningfully from <code>-O3</code>.</p>
</li>
</ul>
<p>I was sufficiently surprised by this reversal of fortunes that I suspected I
might have accidentally made a sluggish build of clang 3.4 itself (since I built
it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The
results were practically the same as for 3.4.</p>
<p>So as regards reaction to the U-turn: On the numbers here, Clang has done much
better than GCC at at wringing speed out of my C++ code when I was giving it no
help. When I put my mind to helping, GCC did a much better job than Clang.</p>
<p>I don't elevate that observation into a principle, but I take
the lesson that "Which compiler produces the better binaries?" is a question
that, even if you specify the test suite to which the answer shall be relative,
still is not a clear-cut matter of just timing the binaries.</p>
<p>Is your better binary the fastest binary, or is it the one that best
compensates for cheaply crafted code? Or best compensates for <em>expensively</em>
crafted code that prioritizes maintainability and reuse over speed? It depends on the
nature and relative weights of your motives for producing the binary, and of
the constraints under which you do so.</p>
<p>And in any case, if you deeply care about building "the best" binaries then you
had better keep checking how successive iterations of compilers deliver on your
idea of "the best" over successive iterations of your code.</p> |
2,430,303 | Disadvantages of scanf | <p>I want to know the disadvantages of <code>scanf()</code>.</p>
<p>In many sites, I have read that using <code>scanf</code> might cause buffer overflows. What is the reason for this? Are there any other drawbacks with <code>scanf</code>?</p> | 2,430,310 | 9 | 1 | null | 2010-03-12 03:20:49.52 UTC | 73 | 2022-04-13 22:38:38.16 UTC | 2015-02-20 15:17:30.01 UTC | null | 3,049,655 | null | 284,118 | null | 1 | 80 | c|input|user-input|scanf | 72,486 | <p>The problems with scanf are (at a minimum):</p>
<ul>
<li>using <code>%s</code> to get a string from the user, which leads to the possibility that the string may be longer than your buffer, causing overflow.</li>
<li>the possibility of a failed scan leaving your file pointer in an indeterminate location.</li>
</ul>
<p>I very much prefer using <code>fgets</code> to read whole lines in so that you can limit the amount of data read. If you've got a 1K buffer, and you read a line into it with <code>fgets</code> you can tell if the line was too long by the fact there's no terminating newline character (last line of a file without a newline notwithstanding).</p>
<p>Then you can complain to the user, or allocate more space for the rest of the line (continuously if necessary until you have enough space). In either case, there's no risk of buffer overflow.</p>
<p>Once you've read the line in, you <em>know</em> that you're positioned at the next line so there's no problem there. You can then <code>sscanf</code> your string to your heart's content without having to save and restore the file pointer for re-reading.</p>
<p>Here's a snippet of code which I frequently use to ensure no buffer overflow when asking the user for information.</p>
<p>It could be easily adjusted to use a file other than standard input if necessary and you could also have it allocate its own buffer (and keep increasing it until it's big enough) before giving that back to the caller (although the caller would then be responsible for freeing it, of course).</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
#define SMALL_BUFF 3
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Size zero or one cannot store enough, so don't even
// try - we need space for at least newline and terminator.
if (sz < 2)
return SMALL_BUFF;
// Output prompt.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
// Get line with buffer overrun protection.
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// Catch possibility of `\0` in the input stream.
size_t len = strlen(buff);
if (len < 1)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[len - 1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[len - 1] = '\0';
return OK;
}
</code></pre>
<p>And, a test driver for it:</p>
<pre><code>// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
</code></pre>
<p>Finally, a test run to show it in action:</p>
<pre><code>$ printf "\0" | ./tstprg # Singular NUL in input stream.
Enter string>
No input
$ ./tstprg < /dev/null # EOF in input stream.
Enter string>
No input
$ ./tstprg # A one-character string.
Enter string> a
OK [a]
$ ./tstprg # Longer string but still able to fit.
Enter string> hello
OK [hello]
$ ./tstprg # Too long for buffer.
Enter string> hello there
Input too long [hello the]
$ ./tstprg # Test limit of buffer.
Enter string> 123456789
OK [123456789]
$ ./tstprg # Test just over limit.
Enter string> 1234567890
Input too long [123456789]
</code></pre> |
2,622,591 | Is an "infinite" iterator bad design? | <p>Is it generally considered bad practice to provide <code>Iterator</code> implementations that are "infinite"; i.e. where calls to <code>hasNext()</code> always(*) return true?</p>
<p>Typically I'd say "yes" because the calling code could behave erratically, but in the below implementation <code>hasNext()</code> will return true unless the caller removes all elements from the List that the iterator was initialised with; i.e. <strong>there is a termination condition</strong>. Do you think this is a legitimate use of <code>Iterator</code>? It doesn't seem to violate the contract although I suppose one could argue it's unintuitive.</p>
<pre><code>public class CyclicIterator<T> implements Iterator<T> {
private final List<T> l;
private Iterator<T> it;
public CyclicIterator<T>(List<T> l) {
this.l = l;
this.it = l.iterator();
}
public boolean hasNext() {
return !l.isEmpty();
}
public T next() {
T ret;
if (!hasNext()) {
throw new NoSuchElementException();
} else if (it.hasNext()) {
ret = it.next();
} else {
it = l.iterator();
ret = it.next();
}
return ret;
}
public void remove() {
it.remove();
}
}
</code></pre>
<p><strong>(Pedantic) EDIT</strong></p>
<p>Some people have commented how an <code>Iterator</code> could be used to generate values from an unbounded sequence such as the Fibonacci sequence. However, the Java <code>Iterator</code> documentation states that an Iterator is:</p>
<blockquote>
<p>An iterator over a collection.</p>
</blockquote>
<p>Now you could argue that the Fibonacci sequence is an infinite collection but in Java I would equate collection with the <code>java.util.Collection</code> interface, which offers methods such as <code>size()</code> implying that a collection must be bounded. Therefore, is it legitimate to use <code>Iterator</code> as a generator of values from an unbounded sequence?</p> | 2,622,605 | 11 | 7 | null | 2010-04-12 14:00:35.43 UTC | 10 | 2018-05-13 14:57:24.593 UTC | 2010-08-05 16:42:32.633 UTC | null | 127,479 | null | 127,479 | null | 1 | 66 | java|collections|iterator | 6,428 | <p>I think it is <strong>entirely legitimate</strong> - an <code>Iterator</code> is just a stream of "stuff". Why should the stream necessarily be bounded?</p>
<p>Plenty of other languages (e.g. Scala) have the concept of unbounded streams built in to them and these can be iterated over. For example, using scalaz</p>
<pre><code>scala> val fibs = (0, 1).iterate[Stream](t2 => t2._2 -> (t2._1 + t2._2)).map(_._1).iterator
fibs: Iterator[Int] = non-empty iterator
scala> fibs.take(10).mkString(", ") //first 10 fibonnacci numbers
res0: String = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
</code></pre>
<p><strong>EDIT:</strong> <em>In terms of the principle of least surprise, I think it depends entirely on the context. For example, what would I expect this method to return?</em></p>
<pre><code>public Iterator<Integer> fibonacciSequence();
</code></pre> |
2,891,937 | Strtotime() doesn't work with dd/mm/YYYY format | <p>I really like the <code>strtotime()</code> function, but the user manual doesn't give a complete description of the supported date formats. <code>strtotime('dd/mm/YYYY')</code> doesn't work, it works only with <code>mm/dd/YYYY</code> format.</p>
<p>If I have date in <code>dd/mm/YYYY</code> format, how can I convert it to <code>YYYY-mm-dd</code>?
I can do it by using <code>explode()</code> function, but I think there are better solutions.</p> | 2,891,949 | 17 | 1 | null | 2010-05-23 13:41:54.24 UTC | 50 | 2021-02-05 12:41:52.19 UTC | 2016-12-13 13:21:30.137 UTC | null | 2,149,414 | null | 291,772 | null | 1 | 186 | php | 381,865 | <p>Here is the simplified solution:</p>
<pre><code>$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>2010-05-25
</code></pre>
<p><a href="http://php.net/manual/en/function.strtotime.php" rel="noreferrer">The <code>strtotime</code> documentation</a> reads:</p>
<blockquote>
<p>Dates in the <strong><em>m/d/y</em></strong> or <strong><em>d-m-y</em></strong> formats are disambiguated by looking at the separator between the various components: if the separator is a slash (<strong>/</strong>), then the American <strong><em>m/d/y</em></strong> is assumed; whereas if the separator is a dash (<strong>-</strong>) or a dot (<strong>.</strong>), then the European <strong><em>d-m-y</em></strong> format is assumed.</p>
</blockquote> |
40,443,331 | How to get everything from the list except the first element using list slicing | <p>So I have something that I am parsing, however here is an example of what I would like to do:</p>
<pre><code>list = ['A', 'B', 'C']
</code></pre>
<p>And using list slicing have it return to me everything but the first index. So in this case: </p>
<pre><code>['B', 'C']
</code></pre>
<p>I have been messing with stuff like list[:-1], list[::-1], list[0:-1], etc. But I can't seem to be able to find this out.</p>
<p>What I am actual doing is:
* I have a error message that has a error code in the beginning such as:</p>
<pre><code>['226', 'Transfer', 'Complete']
</code></pre>
<p>and I want to just display Transfer Complete on a popup widget. Of course I am casting to a string.</p>
<p>Thank you for all help, and if answer differs via Python 2.7.x and Python 3.x.x Please answer for both versions. </p>
<p>Thanks, looked a lot around stackoverflow and python tutorials couldn't really quite get what I was looking for. Thanks for your help!</p> | 40,443,345 | 2 | 9 | null | 2016-11-05 21:20:28.127 UTC | 3 | 2016-11-06 04:40:33.91 UTC | 2016-11-05 21:22:36.553 UTC | null | 5,366,130 | null | 5,366,130 | null | 1 | 88 | python|python-2.7|list|python-3.x | 125,876 | <p>You can just do [1:].
This will work on both versions.</p> |
40,109,698 | How can I call parent method in a child React component? | <p>I have a parent and child compoents and I want to call a parent method in the child component like this:</p>
<pre><code>import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click() {
Parent.someMethod();
}
render() {
<div>Hello Child onClick={this.click}</>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<div>Hello Parent</>
}
}
</code></pre>
<p>This returns an error message:</p>
<p><code>Uncaught TypeError: _Parent2.default.someMethod is not a function</code></p>
<p>How can this parent method be called in the child component?</p> | 40,109,797 | 2 | 1 | null | 2016-10-18 13:30:36.377 UTC | 3 | 2021-12-10 21:55:31.953 UTC | 2021-12-10 21:55:31.953 UTC | null | 1,264,804 | null | 1,742,006 | null | 1 | 36 | javascript|reactjs | 92,932 | <p>Try this. Passing the function down as props to the child component.</p>
<pre><code>import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click = () => {
this.props.parentMethod();
}
render() {
<div onClick={this.click}>Hello Child</div>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}
</code></pre> |
10,454,919 | What’s the easiest way to preview data from an image column? | <p>I have some columns with <code>image</code> data type and I want to preview (or browse) the data in those tables. When I use <code>Select top 1000 rows</code> in SQL Server Management Studio, the value of image columns is displayed in hexadecimal. What’s the easiest way to preview those images since the hex-value is not useful to me?</p>
<p>PS.: database is not under my control, so changing data type is not an option.</p> | 10,486,026 | 6 | 0 | null | 2012-05-04 19:22:49.907 UTC | 7 | 2018-09-02 15:06:42.7 UTC | null | null | null | null | 259,237 | null | 1 | 20 | sql|sql-server|sql-server-2008 | 56,431 | <p>I would write a proc (or query; see below) to export the binary out to the file system and then use any old off the shelf photo management utility <strong>(i.e. Windows Photo Viewer)</strong> to take a look at what's inside. </p>
<p>If your clever in your file naming you could give yourself enough information about each image in the name to quickly find it in the database again once you've visually located what your looking for. </p>
<p>Here is a proc that will export binary to the file system. I modified from <a href="http://jahaines.blogspot.com/2009/10/exporting-binary-files-to-file-system.html" rel="noreferrer">this sample code</a>. It's untested but should be extremely close for concept. It's using BCP to export your binary. Check here for the <a href="http://msdn.microsoft.com/en-us/library/ms162802%28v=sql.105%29.aspx" rel="noreferrer">full docs on the BCP utility</a>. </p>
<p>The proc also gives you the ability to export everything in the table, or only a single row based on a the passed primarykey. It uses a cursor (yuck), as well as some dynamic sql (yuck, yuck) but sometimes you gotta do what you gotta do.</p>
<pre><code> CREATE PROCEDURE ExportMyImageFiles
(
@PriKey INT,
@OutputFilePath VARCHAR(500)
)
AS
BEGIN
DECLARE @sql VARCHAR(8000)
IF @PriKey IS NULL /* export all images */
BEGIN
DECLARE curExportBinaryImgs CURSOR FAST_FORWARD FOR
SELECT 'BCP "SELECT MyImage FROM [dbo].[MyTable]
WHERE PrimaryKey =' + CAST(PrimaryKey AS VARCHAR(25)) +
'" queryout ' + @OutputFilePath + MyImageName + '.' +
MyImageType + ' -S MyServer\MyInstance -T -fC:\Documents.fmt'
FROM [dbo].[MyTable]
OPEN curExportBinaryImgs
FETCH NEXT FROM curExportBinaryImgs INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC xp_cmdshell @sql, NO_OUTPUT
FETCH NEXT FROM curExportBinaryImgs INTO @sql
END
CLOSE curExportBinaryImgs
DEALLOCATE curExportBinaryImgs
END
ELSE /* Export only the primary key provided */
BEGIN
SELECT @sql = 'BCP "SELECT MyImage FROM [dbo].[MyTable]
WHERE PrimaryKey =' + CAST(PrimaryKey AS VARCHAR(25)) +
'" queryout ' + @OutputFilePath
+ MyImageName + '.' + MyImageType +
' -S MyServer\MyInstance -T -fC:\Documents.fmt'
FROM [dbo].[MyTable]
WHERE PrimaryKey = @PriKey
EXEC xp_cmdshell @sql,NO_OUTPUT
END
END
</code></pre>
<p>This is all assuming of course that what is stored in your Image column is actually an image and not some other file type. Hopefully if it is an image you also know the type, bmp, jpg, png, gif, etc.</p>
<p><strong>If you don't want the hassle or reusability of a full blown proc try single query like this:</strong></p>
<hr>
<pre><code> DECLARE @OutputFilePath VarChar(500) = /* put output dir here */
DECLARE @sql VARCHAR(8000)
DECLARE curExportBinaryImgs CURSOR FAST_FORWARD FOR
SELECT 'BCP "SELECT MyImage FROM [dbo].[MyTable]
WHERE PrimaryKey =' + CAST(PrimaryKey AS VARCHAR(25)) +
'" queryout ' + @OutputFilePath + MyImageName + '.' +
MyImageType + ' -S MyServer\MyInstance -T -fC:\Documents.fmt'
FROM [dbo].[MyTable]
OPEN curExportBinaryImgs
FETCH NEXT FROM curExportBinaryImgs INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC xp_cmdshell @sql, NO_OUTPUT
FETCH NEXT FROM curExportBinaryImgs INTO @sql
END
CLOSE curExportBinaryImgs
DEALLOCATE curExportBinaryImgs
</code></pre> |
10,597,869 | How to add an hour onto the time of this datetime string? | <p>Here's an example of the datetime strings I am working with:</p>
<pre><code>Tue May 15 10:14:30 +0000 2012
</code></pre>
<p>Here is my attempt to add an hour onto it:</p>
<pre><code>$time = 'Tue May 15 10:14:30 +0000 2012';
$dt = new DateTime($time);
$dt->add(new DateInterval('P1h'));
</code></pre>
<p>But the second line gives the error that it couldn't be converted.</p>
<p>Thanks.</p> | 10,597,923 | 3 | 0 | null | 2012-05-15 09:29:38.177 UTC | 7 | 2021-12-17 09:49:45.607 UTC | null | null | null | null | 964,634 | null | 1 | 42 | php | 90,904 | <p>You should add a <code>T</code> before the time specification part:</p>
<pre><code>$time = 'Tue May 15 10:14:30 +0000 2012';
$dt = new DateTime($time);
$dt->add(new DateInterval('PT1H'));
</code></pre>
<p>See the <code>DateInterval</code> <a href="http://php.net/manual/en/dateinterval.construct.php" rel="noreferrer">constructor</a> documentation:</p>
<blockquote>
<p>The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. <em>If the duration contains time elements, that portion of the specification is <strong>preceded by the letter T</em></strong>. </p>
</blockquote>
<p><sub>(Emphasis added)</sub></p> |
23,166,283 | How to set Input Mask and QValidator to a QLineEdit at a time in Qt? | <p>I want a line edit which accepts an ip address. If I give input mask as:</p>
<pre><code>ui->lineEdit->setInputMask("000.000.000.000");
</code></pre>
<p>It is accepting values greater than 255. If I give a validator then we have to give a dot(.) after every three digits. What would the best way to handle it?</p> | 23,166,561 | 5 | 0 | null | 2014-04-19 05:33:36.71 UTC | 4 | 2020-04-14 09:16:56.933 UTC | 2014-05-30 02:05:56.92 UTC | null | 2,682,142 | null | 3,413,974 | null | 1 | 8 | c++|qt|qtgui|qtcore|qlineedit | 47,586 | <blockquote>
<p>It is accepting value greater than 255.</p>
</blockquote>
<p>Absolutely, because '0' means <a href="http://qt-project.org/doc/qt-5/qlineedit.html#inputMask-prop" rel="noreferrer">this</a>:</p>
<pre><code>ASCII digit permitted but not required.
</code></pre>
<p>As you can see, this is not your cup of tea. There are at least the following ways to circumvent it:</p>
<ul>
<li><p>Write a custom validator</p></li>
<li><p>Use regex</p></li>
<li><p>Split the input into four entries and validate each entry on its own while still having visual delimiters between the entries.</p></li>
</ul>
<p>The regex solution would be probably the quick, but also ugliest IMHO:</p>
<pre><code>QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
// You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
QRegExp ipRegex ("^" + ipRange
+ "\\." + ipRange
+ "\\." + ipRange
+ "\\." + ipRange + "$");
QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
lineEdit->setValidator(ipValidator);
</code></pre>
<p>Disclaimer: this will only validate IP4 addresses properly, so it will not work for IP6 should you need that in the future.</p> |
18,963,286 | Routes, path helpers and STI in Rails 4.0 | <p>This is driving me crazy! I have the two models <code>Lion</code> and <code>Cheetah</code>. Both inherit from <code>Wildcat</code>.</p>
<pre><code>class Wildcat < ActiveRecord::Base; end
class Lion < Wildcat; end
class Cheetah < Wildcat; end
</code></pre>
<p>STI is used here.</p>
<p>They all get handled through the controller <code>WildcatsController</code>. There, I have a <code>before_filer</code> to get the <code>type</code> of wildcat from the <code>params[:type]</code> and all the other stuff to use the correct class.</p>
<p>In my <code>routes.rb</code>, I created the following routes:</p>
<pre><code>resources :lions, controller: 'wildcats', type: 'Lion'
resources :cheetahs, controller: 'wildcats', type: 'Cheetah'
</code></pre>
<p>If I now want to use the path helpers, that I get from the routes (<code>lions_path</code>,<code>lion_path</code>,<code>new_lion_path</code>, etc.), everything is working as expected, except the <code>show</code> and the <code>new</code> paths. For example <code>lions_path</code> returns the path <code>/lions</code>. The <code>new</code> path returns <code>/lions/new?type=Lion</code>. Same with the <code>show</code> path. When I try to enter <code>/lions/new</code> to my root domain it correctly adds the type param in the background.</p>
<p>So, my question is, why does Rails add the <code>type</code> parameter to the url if I use the path helper? And why only for <code>new</code> and <code>show</code>?</p>
<p>I am running Rails 4.0.0 with Ruby 2.0 using a fresh Rails app.</p> | 18,963,418 | 2 | 0 | null | 2013-09-23 15:35:24.74 UTC | 8 | 2015-01-04 16:15:16.067 UTC | null | null | null | null | 961,553 | null | 1 | 7 | ruby-on-rails|ruby|routes|ruby-on-rails-4|sti | 2,531 | <p>Why using <code>type</code>? Why not use inherited controllers?</p>
<pre><code>resources :lions
resources :cheetahs
</code></pre>
<p>Then</p>
<pre><code>class LionsController < WildCatsController
end
class CheetahController < WildCatsController
end
class WildCatsController < ApplicationController
before_filter :get_type
def index
@objs = @klass.scoped
end
def show
@obj = @klass.find(params[:id])
end
def new
@obj = @klass.new
end
# blah blah
def get_type
resource = request.path.split('/')[0]
@klass = resource.singularize.capitalize.constantize
end
</code></pre> |
30,058,798 | Can I turn a string into a block of code in swift? | <p>Is there any way to turn a string into a block of code? I'm making an Ajax request to a website of mine that has an endpoint that returns some swift code as a string. I can get that code back as a string, but I can't run that code because it doesn't know that it is code.</p> | 30,058,875 | 2 | 1 | null | 2015-05-05 16:47:38.613 UTC | 8 | 2018-11-12 21:56:30.217 UTC | null | null | null | null | 4,241,640 | null | 1 | 7 | ios|swift | 3,271 | <p>No, you can't do that. Swift is a compiled language, not interpreted like Ajax.</p>
<p>The Swift compiler runs on your Mac, not on the iOS device. (The same is true for Objective-C).</p>
<p>Plus, Apple's app store guidelines forbid delivering executable code to your apps, so even if you figured out a way to do it, your app would be rejected.</p>
<h2>Edit:</h2>
<p>Note that with the advent of Swift playgrounds, it is possible to run the Swift compiler on an iPad. Recent high-end iPhones are probably also up to the job, but you'd have to figure out how to get it installed.</p>
<p>As stated above though, Apple's app store guidelines forbid you from delivering code to your apps at runtime.</p> |
28,242,496 | SSRS expression - If null value then return 0 instead of blank | <p>I've seen a few examples but I just can't figure it out for my case.
My expressions sums all values from field <code>Total</code> from the dataset <code>AutoDeliveryCount</code>. I need to reference the dataset since I'm using a few <code>Total</code> fields in my report. If the stored procedure returns null, how can I have my expression return 0 instead of a blank?</p>
<pre><code>=Sum(Fields!Total.Value, "AutoDeliveryCount")
</code></pre> | 28,244,353 | 6 | 0 | null | 2015-01-30 18:36:00.52 UTC | 3 | 2020-01-17 08:09:22.413 UTC | 2019-08-30 19:07:29.91 UTC | null | 1,839,439 | null | 3,749,447 | null | 1 | 10 | reporting-services|ssrs-2008 | 55,243 | <pre><code>=IIf(IsNothing(Sum(Fields!Total.Value, "AutoDeliveryCount"))=True, 0, Sum(Fields!Total.Value, "AutoDeliveryCount"))
</code></pre> |
43,060,655 | Update values of a list of dictionaries in python | <p>I have a CSV file that looks like this:</p>
<pre><code>Martin;Sailor;-0.24
Joseph_4;Sailor;-0.12
Alex;Teacher;-0.23
Maria;Teacher;-0.57
</code></pre>
<p>My objective is to create a list with dictionaries for each job.</p>
<p>For example: </p>
<pre><code>list_of_jobs = [{'Job' : Sailor, 'People' : ['Martin', 'Joseph']}
{'Job' : Teacher, 'People' : ['Alex', 'Maria']}
]
</code></pre>
<p>I did create the dictionaries but I can't figure out how to update the value of <code>list_of_jobs['People']</code></p>
<p>Can anybody help me?</p> | 43,060,871 | 3 | 0 | null | 2017-03-28 04:29:19.863 UTC | 3 | 2017-03-28 05:15:13.687 UTC | 2017-03-28 05:15:13.687 UTC | null | 6,760,995 | null | 7,777,625 | null | 1 | 11 | python|list|dictionary | 50,392 | <p>If you have a list of dictionary like this:</p>
<pre><code>list_of_jobs = [
{'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']},
{'Job' : 'Teacher', 'People' : ['Alex', 'Maria']}
]
</code></pre>
<p>You can access the dictionary by index.</p>
<pre><code>list_of_jobs[0]
Output:
{'Job' : 'Sailor', 'People' : ['Martin', 'Joseph']}
</code></pre>
<p>If you want to access 'People' attribute of the first dictionary, you can do it like this:</p>
<pre><code>list_of_jobs[0]['People']
Output:
['Martin', 'Joseph']
</code></pre>
<p>If you want to modify the value of that list of people, you can use append() to add an item or pop() to remove an item from the list.</p>
<pre><code>list_of_jobs[0]['People'].append('Andrew')
list_of_jobs[0]['People'].pop(1)
</code></pre>
<p>Now, list_of_jobs will have this state:</p>
<pre><code>[
{'Job' : 'Sailor', 'People' : ['Martin', 'Andrew']},
{'Job' : 'Teacher', 'People' : ['Alex', 'Maria']}
]
</code></pre> |
8,586,940 | Writing complex custom metadata on images through python | <p>I'm looking to write custom metadata on to images(mostly jpegs, but could be others too). So far I haven't been able to do that through PIL preferably (I'm on centos 5 & I couldn't get pyexiv installed)
I understand that I can update some pre-defined tags, but I need to create custom fields/tags! Can that be done? </p>
<p>This data would be created by users, so I wouldn't know what those tags are before hand or what they contain. I need to allow them to create tags/subtags & then write data for them. For example, someone may want to create this metadata on a particular image :</p>
<pre><code>Category : Human
Physical :
skin_type : smooth
complexion : fair
eye_color: blue
beard: yes
beard_color: brown
age: mid
Location :
city: london
terrain: grass
buildings: old
</code></pre>
<p>I also found that upon saving a jpeg through the PIL JpegImagePlugin, all previous metadata is overwritten with new data that you don't get to edit? Is that a bug?</p>
<p>Cheers,
S</p> | 8,590,271 | 2 | 0 | null | 2011-12-21 08:32:34.377 UTC | 15 | 2020-03-12 22:00:08.81 UTC | null | null | null | null | 799,597 | null | 1 | 17 | python|image|metadata|python-imaging-library | 18,629 | <p>The python <a href="http://tilloy.net/dev/pyexiv2/api.html" rel="noreferrer">pyexiv2 module</a> can read/write metadata.</p>
<p>I think there is a limited set of valid EXIF tags. I don't know how, or if it is possible to create your own custom tags. However, you could use the Exif.Photo.UserComment tag, and fill it with JSON:</p>
<pre><code>import pyexiv2
import json
metadata = pyexiv2.ImageMetadata(filename)
metadata.read()
userdata={'Category':'Human',
'Physical': {
'skin_type':'smooth',
'complexion':'fair'
},
'Location': {
'city': 'london'
}
}
metadata['Exif.Photo.UserComment']=json.dumps(userdata)
metadata.write()
</code></pre>
<p>And to read it back:</p>
<pre><code>import pprint
filename='/tmp/image.jpg'
metadata = pyexiv2.ImageMetadata(filename)
metadata.read()
userdata=json.loads(metadata['Exif.Photo.UserComment'].value)
pprint.pprint(userdata)
</code></pre>
<p>yields</p>
<pre><code>{u'Category': u'Human',
u'Location': {u'city': u'london'},
u'Physical': {u'complexion': u'fair', u'skin_type': u'smooth'}}
</code></pre> |
8,805,538 | How to select N records from a table in mysql | <p>How can I get only 10 records from a table where there are more than 1000 records. I have a test table with rowid, name, cost. </p>
<pre><code> select name, cost from test;
</code></pre>
<p>here I want to select only first 10 rows and dont want to select rowid.</p> | 8,805,558 | 5 | 0 | null | 2012-01-10 15:14:20.82 UTC | 4 | 2020-08-26 14:42:05.937 UTC | null | null | null | null | 1,049,325 | null | 1 | 32 | mysql | 87,107 | <p>To select the first ten records you can use LIMIT followed by the number of records you need:</p>
<pre><code>SELECT name, cost FROM test LIMIT 10
</code></pre>
<p>To select ten records from a specific location, you can use LIMIT 10, 100</p>
<pre><code>SELECT name, cost FROM test LIMIT 100, 10
</code></pre>
<p>This will display records 101-110</p>
<pre><code>SELECT name, cost FROM test LIMIT 10, 100
</code></pre>
<p>This will display records 11-111</p>
<p>To make sure you retrieve the correct results, make sure you ORDER BY the results too, otherwise the returned rows may be random-ish</p>
<p>You can read more @ <a href="http://php.about.com/od/mysqlcommands/g/Limit_sql.htm" rel="noreferrer">http://php.about.com/od/mysqlcommands/g/Limit_sql.htm</a></p> |
48,306,849 | /lib/x86_64-linux-gnu/libz.so.1: version `ZLIB_1.2.9' not found | <p>I'm new to linux and using Eclipse Oxygen.2 Release 4.7.2 on Ubuntu 16.04 </p>
<p>I'm getting the error:</p>
<p>/usr/lib/opencv-2.4.13.5/build/lib/libopencv_java2413.so: /lib/x86_64-linux-gnu/libz.so.1: version `ZLIB_1.2.9' not found (required by /home/mel3/anaconda/lib/libpng16.so.16)</p>
<p>I've tried upgrading and reloading and not sure if there is a path error or what going on. Help much appreciated</p> | 48,579,743 | 6 | 1 | null | 2018-01-17 17:32:15.303 UTC | 9 | 2022-01-25 20:41:48.417 UTC | null | null | null | null | 9,230,929 | null | 1 | 29 | eclipse|opencv | 62,544 | <p><a href="https://sourceforge.net/projects/libpng/files/zlib/1.2.9/zlib-1.2.9.tar.gz/download" rel="noreferrer">Download</a> Zlib 1.2.9
Then run those commands</p>
<pre><code>tar -xvf ~/Downloads/zlib-1.2.9.tar.gz
cd zlib-1.2.9
sudo -s
./configure; make; make install
cd /lib/x86_64-linux-gnu
ln -s -f /usr/local/lib/libz.so.1.2.9/lib libz.so.1
cd ~
rm -rf zlib-1.2.9
</code></pre>
<p>for details visit this <a href="https://github.com/JuliaPy/PyPlot.jl/issues/151" rel="noreferrer">link</a></p> |
27,337,428 | Hibernate Could not obtain transaction-synchronized Session for current thread | <p>I have been having a similar problem as many people have been having, but I can't seem to figure out what is going wrong in my specific case. I am making a simple database call to test the database connection, and Hibernate is throwing the following exception:</p>
<pre><code>Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at boardwalk.computeServer.dao.DbDaoHibernateImpl.getInterpolationJob(DbDaoHibernateImpl.java:73)
at boardwalk.computeServer.ComputeServer.test(ComputeServer.java:39)
at boardwalk.computeServer.ComputeServer.main(ComputeServer.java:32)
</code></pre>
<p>Here is the relevant code and configuration:</p>
<p>pom.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven- 4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>boardwalk</groupId>
<artifactId>computeServer</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>marketserver</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>activesoap</groupId>
<artifactId>jaxp-api</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>5.10.0</version>
<type>xsd</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>net.rforge</groupId>
<artifactId>REngine</artifactId>
<version>0.6-8.1</version>
</dependency>
<dependency>
<groupId>net.rforge</groupId>
<artifactId>Rserve</artifactId>
<version>0.6-8.1</version>
</dependency>
<dependency>
<groupId>org.R</groupId>
<artifactId>RSession</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p>Hibernate DAO (mapping objects have been omitted for clarity, as I don't think they are causing the issue, as the exception is being thrown before any of them can be used):</p>
<pre><code>import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import boardwalk.computeServer.data.InterpolationDesiredPoint;
import boardwalk.computeServer.data.InterpolationJob;
public class DbDaoHibernateImpl implements DbDao {
private final SessionFactory sessionFactory;
public DbDaoHibernateImpl(SessionFactory sessionFactory){
// Save the session factory
this.sessionFactory = sessionFactory;
}
@Override
public InterpolationJob getInterpolationJob(int jobId) {
// Get the session
Session s = sessionFactory.getCurrentSession();
// Load the object from the database and return it
return (InterpolationJob) s.get(InterpolationJob.class, jobId);
}
}
</code></pre>
<p>Main class:</p>
<pre><code>import org.apache.log4j.Logger;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import boardwalk.computeServer.dao.DbDao;
public class ComputeServer {
private static final Logger LOG = Logger.getLogger(ComputeServer.class);
/**
* Runs the server
* @param args none
*/
public static void main(String[] args) {
// Create the application context
@SuppressWarnings("resource")
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/beans.xml");
context.registerShutdownHook();
// Log the server start
LOG.info("Server has started");
test(context);
}
@Transactional
public static void test(ClassPathXmlApplicationContext context){
DbDao dao = (DbDao) context.getBean("dbDao");
System.err.println(dao.getInterpolationJob(1));
}
}
</code></pre>
<p>Spring configuration file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- Load the properties file -->
<context:property-placeholder location="classpath:application.properties" />
<!-- C3PO pooled database connections -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- These are C3P0 properties -->
<property name="acquireIncrement" value="1" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="10" />
</bean>
<!-- Hibernate session factory -->
<bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="boardwalk.computeServer.data" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- The database DAO -->
<bean id="dbDao" class="boardwalk.computeServer.dao.DbDaoHibernateImpl">
<constructor-arg ref="hibernateSessionFactory" />
</bean>
<!-- The transaction manager -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
<context:annotation-config></context:annotation-config>
</beans>
</code></pre>
<p>I should note that the program runs fine when I substitute "getCurrentSession()" with "openSession()". </p>
<p>Thank you in advance!</p> | 27,337,636 | 2 | 2 | null | 2014-12-06 22:42:16.927 UTC | 2 | 2016-06-06 13:26:10.807 UTC | 2016-03-04 04:19:23.12 UTC | null | 5,377,805 | null | 4,332,971 | null | 1 | 13 | java|spring|hibernate|transactions | 45,381 | <p>@Transactional on the test() method is useless, it only works on spring managed bean. That is why there is no transaction context.</p>
<p>as @hiimjames said put @Transactional on your DAO class or method</p> |
30,549,226 | Guzzlehttp - How get the body of a response from Guzzle 6? | <p>I'm trying to write a wrapper around an api my company is developing. It's restful, and using Postman I can send a post request to an endpoint like <code>http://subdomain.dev.myapi.com/api/v1/auth/</code> with a username and password as POST data and I am given back a token. All works as expected. Now, when I try and do the same from PHP I get back a <code>GuzzleHttp\Psr7\Response</code> object, but can't seem to find the token anywhere inside it as I did with the Postman request. </p>
<p>The relevant code looks like: </p>
<pre><code>$client = new Client(['base_uri' => 'http://companysub.dev.myapi.com/']);
$response = $client->post('api/v1/auth/', [
'form_params' => [
'username' => $user,
'password' => $password
]
]);
var_dump($response); //or $resonse->getBody(), etc...
</code></pre>
<p>The output of the code above looks something like (warning, incoming wall of text):</p>
<pre><code>object(guzzlehttp\psr7\response)#36 (6) {
["reasonphrase":"guzzlehttp\psr7\response":private]=>
string(2) "ok"
["statuscode":"guzzlehttp\psr7\response":private]=>
int(200)
["headers":"guzzlehttp\psr7\response":private]=>
array(9) {
["connection"]=>
array(1) {
[0]=>
string(10) "keep-alive"
}
["server"]=>
array(1) {
[0]=>
string(15) "gunicorn/19.3.0"
}
["date"]=>
array(1) {
[0]=>
string(29) "sat, 30 may 2015 17:22:41 gmt"
}
["transfer-encoding"]=>
array(1) {
[0]=>
string(7) "chunked"
}
["content-type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
["allow"]=>
array(1) {
[0]=>
string(13) "post, options"
}
["x-frame-options"]=>
array(1) {
[0]=>
string(10) "sameorigin"
}
["vary"]=>
array(1) {
[0]=>
string(12) "cookie, host"
}
["via"]=>
array(1) {
[0]=>
string(9) "1.1 vegur"
}
}
["headerlines":"guzzlehttp\psr7\response":private]=>
array(9) {
["connection"]=>
array(1) {
[0]=>
string(10) "keep-alive"
}
["server"]=>
array(1) {
[0]=>
string(15) "gunicorn/19.3.0"
}
["date"]=>
array(1) {
[0]=>
string(29) "sat, 30 may 2015 17:22:41 gmt"
}
["transfer-encoding"]=>
array(1) {
[0]=>
string(7) "chunked"
}
["content-type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
["allow"]=>
array(1) {
[0]=>
string(13) "post, options"
}
["x-frame-options"]=>
array(1) {
[0]=>
string(10) "sameorigin"
}
["vary"]=>
array(1) {
[0]=>
string(12) "cookie, host"
}
["via"]=>
array(1) {
[0]=>
string(9) "1.1 vegur"
}
}
["protocol":"guzzlehttp\psr7\response":private]=>
string(3) "1.1"
["stream":"guzzlehttp\psr7\response":private]=>
object(guzzlehttp\psr7\stream)#27 (7) {
["stream":"guzzlehttp\psr7\stream":private]=>
resource(40) of type (stream)
["size":"guzzlehttp\psr7\stream":private]=>
null
["seekable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["readable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["writable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["uri":"guzzlehttp\psr7\stream":private]=>
string(10) "php://temp"
["custommetadata":"guzzlehttp\psr7\stream":private]=>
array(0) {
}
}
}
</code></pre>
<p>The output from Postman was something like:</p>
<pre><code>{
"data" : {
"token" "fasdfasf-asfasdfasdf-sfasfasf"
}
}
</code></pre>
<p>Clearly I'm missing something about working with the response objects in Guzzle. The Guzzle response indicates a 200 status code on the request, so I'm not sure exactly what I need to do to retrieve the returned data.</p> | 30,549,372 | 3 | 1 | null | 2015-05-30 17:29:23.893 UTC | 50 | 2021-03-25 08:51:55.95 UTC | 2016-01-16 12:21:05.1 UTC | null | 711,206 | null | 472,700 | null | 1 | 216 | php|response|guzzle|guzzle6 | 189,219 | <p>Guzzle implements <a href="http://www.php-fig.org/psr/psr-7/">PSR-7</a>. That means that it will by default store the body of a message in a <a href="https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php">Stream</a> that uses PHP temp streams. To retrieve all the data, you can use casting operator:</p>
<pre><code>$contents = (string) $response->getBody();
</code></pre>
<p>You can also do it with</p>
<pre><code>$contents = $response->getBody()->getContents();
</code></pre>
<p>The difference between the two approaches is that <code>getContents</code> returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with <code>rewind</code> or <code>seek</code> .</p>
<pre><code>$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
</code></pre>
<p>Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.</p>
<pre><code>$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
</code></pre>
<p>Documentation: <a href="http://docs.guzzlephp.org/en/latest/psr7.html#responses">http://docs.guzzlephp.org/en/latest/psr7.html#responses</a></p> |
633,051 | Creating mask with CGImageMaskCreate is all black (iphone) | <p>I'm trying to create an image mask that from a composite of two existing images.</p>
<p>First I start with creating the composite which consists of a small image that is the masking image, and a larger image which is the same size as the background:</p>
<pre><code>UIImage *baseTextureImage = [UIImage imageNamed:@"background.png"];
UIImage *maskImage = [UIImage imageNamed:@"my_mask.jpg"];
UIImage *shapesBase = [UIImage imageNamed:@"largerimage.jpg"];
UIImage *maskImageFull;
CGSize finalSize = CGSizeMake(480.0, 320.0);
UIGraphicsBeginImageContext(finalSize);
[shapesBase drawInRect:CGRectMake(0, 0, 480, 320)];
[maskImage drawInRect:CGRectMake(150, 50, 250, 250)];
maskImageFull = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code></pre>
<p>I can output this UIImage (MaskImageFull) and it looks right. It is a full size background size and it has a white background with my mask object in black, in the right place on the screen.</p>
<p>I then pass the MaskImageFull UIImage through this:</p>
<pre><code>CGImageRef maskRef = [maskImage CGImage];
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
UIImage *retImage= [UIImage imageWithCGImage:masked];
</code></pre>
<p>The problem is that the retImage is all black. If I send a pre-made UIImage in as the mask it works fine, it is just when I try to make it from multiple images that it breaks.</p>
<p>I thought it was a colorspace thing but couldn't seem to fix it. Any help is much appreciated!</p> | 634,146 | 3 | 0 | null | 2009-03-11 01:57:46.043 UTC | 17 | 2021-06-17 17:40:54.95 UTC | 2021-06-17 17:38:54.93 UTC | null | 1,058,199 | Patrick | 66,069 | null | 1 | 14 | objective-c|iphone|cocoa-touch|core-graphics|image-manipulation | 23,509 | <p>I tried the same thing with CGImageCreateWithMask, and got the same result. The solution I found was to use CGContextClipToMask instead:</p>
<pre><code>CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;
colorSpace = CGColorSpaceCreateDeviceRGB();
// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
// free the rgb colorspace
CGColorSpaceRelease(colorSpace);
if (mainViewContentContext==NULL)
return NULL;
CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage];
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage);
CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage);
// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
// convert the finished resized image to a UIImage
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
// image is retained by the property setting above, so we can
// release the original
CGImageRelease(mainViewContentBitmapContext);
// return the image
return theImage;
</code></pre> |
471,749 | Can I discover a Java class' declared inner classes using reflection? | <p>In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm? </p> | 471,775 | 3 | 0 | null | 2009-01-23 03:10:13.413 UTC | 5 | 2019-02-07 20:47:54.767 UTC | 2009-01-23 03:17:28.517 UTC | null | 28,946 | null | 28,946 | null | 1 | 44 | java|reflection | 26,150 | <p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaredClasses()" rel="noreferrer"><code>Class.getDeclaredClasses()</code></a> is the answer. </p> |
699,027 | Is there a jQuery selector/method to find a specific parent element n levels up? | <p>Consider the following HTML. If I have a JSON reference to the <button> element, how can I get a reference to the outer <tr> element in both cases</p>
<pre><code><table id="my-table">
<tr>
<td>
<button>Foo</button>
</td>
<td>
<div>
<button>Bar</button>
</div>
</td>
</tr>
</table>
<script type="text/js">
$('#table button').click(function(){
//$(this).parent().parent() will work for the first row
//$(this).parent().parent().parent() will work for the second row
//is there a selector or some magic json one liner that will climb
//the DOM tree until it hits a TR, or do I have to code this myself
//each time?
//$(this).????
});
</script>
</code></pre>
<p>I know I could special case each condition, but I'm more interested "however deep you happen to be, climb the tree until you find element X" style solution. Something like this, but more jQuery like/less-verbose</p>
<pre><code>var climb = function(node, str_rule){
if($(node).is(str_rule)){
return node;
}
else if($(node).is('body')){
return false;
}
else{
return climb(node.parentNode, str_rule);
}
};
</code></pre>
<p>I know about the parent(expr) method, but from what I've seen is allows you filter parents one level up and NOT climb the tree until you find expr (I'd love code example proving me wrong)</p> | 699,036 | 3 | 0 | null | 2009-03-30 21:08:07.787 UTC | 18 | 2019-09-13 07:59:15.31 UTC | 2014-05-19 17:04:08.543 UTC | null | 775,283 | Alan Storm | 4,668 | null | 1 | 61 | javascript|jquery|dom|jquery-selectors | 66,631 | <p>The <a href="https://api.jquery.com/parents/" rel="noreferrer">parents</a> function does what you want:</p>
<pre><code>$(this).parents("tr:first");
</code></pre> |
1,252,529 | Get code line and file that's executing the current function in PHP? | <p>Imagine I have the following situation:</p>
<p>File1.php</p>
<pre><code><?php
include("Function.php");
log("test");
?>
</code></pre>
<p>Function.php</p>
<pre><code><?php
function log($msg)
{
echo "";
}
?>
</code></pre>
<p>I want to change the log function so that it would produce the following:</p>
<blockquote>
<p>test (file: File1.php, line number: 3)</p>
</blockquote>
<p>So, any way to get the file name and the line number of the code that executed the current function in PHP?</p>
<p><strong>EDIT for backlog usage comments:</strong>
When I use backlog in my object oriented way of programming I have the following situation.</p>
<p>Index.php</p>
<pre><code><?php
include("Logger.static.php");
include("TestClass.class.php");
new TestClass();
?>
</code></pre>
<p>TestClass.class.php</p>
<pre><code><?php
class TestClass
{
function __construct()
{
Logger::log("this is a test log message");
}
}
?>
</code></pre>
<p>Logger.static.php</p>
<pre><code><?php
class Logger
{
static public function log($msg)
{
$bt = debug_backtrace();
$caller = array_shift($bt);
echo $caller['file'];
echo $caller['line'];
}
}
?>
</code></pre>
<p>This example will return as file "Index.php" and as line number 4, this is where the class is initiated. However, it is supposed to return the file TestClass.class.php and line number 6. Any idea how to fix this?</p> | 1,252,559 | 3 | 0 | null | 2009-08-09 22:52:21.517 UTC | 17 | 2022-09-08 03:07:48.063 UTC | 2012-12-23 21:39:49.627 UTC | null | 168,868 | null | 45,974 | null | 1 | 76 | php | 60,780 | <p>You can use debug_backtrace().</p>
<p><a href="http://us3.php.net/manual/en/function.debug-backtrace.php" rel="noreferrer">http://us3.php.net/manual/en/function.debug-backtrace.php</a></p>
<p>So, in your log function, you would be able to retrieve the filename and line number from which the log function was called.</p>
<p>I'm using this approach in my logging classes and it has significantly reduced the amount of code required to get meaningful log data. Another benefit would be readability. Magic constants tend to get quite ugly when mixed with strings.</p>
<p>Here's a quick example:</p>
<pre><code>function log($msg)
{
$bt = debug_backtrace();
$caller = array_shift($bt);
// echo $caller['file'];
// echo $caller['line'];
// do your logging stuff here.
}
</code></pre> |
39,826,992 | How can I set a cookie in react? | <p>Orginally, I use the following ajax to set cookie. </p>
<pre><code>function setCookieAjax(){
$.ajax({
url: `${Web_Servlet}/setCookie`,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
headers: { 'Access-Control-Allow-Origin': '*',
'username': getCookie("username"),
'session': getCookie("session")
},
type: 'GET',
success: function(response){
setCookie("username", response.name, 30);
setCookie("session", response.session, 30);}
})
}
function setCookie(cname, cvalue, minutes) {
var d = new Date();
d.setTime(d.getTime() + (minutes*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
export const getUserName = (component) => {
setCookieAjax()
$.ajax({
url: `${Web_Servlet}/displayHeaderUserName`,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
headers: { 'Access-Control-Allow-Origin': '*',
'username': getCookie("username"),
'session': getCookie("session")
},
type: 'GET',
success: function(response){
component.setState({
usernameDisplay: response.message
})
}.bind(component)
})
}
</code></pre>
<p>Now, I want to set the cookie using the servlet's adding cookie function. But I don't know how to achieve my purpose.</p>
<pre><code>Cookie loginCookie = new Cookie("user",user); //setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
loginCookie.setDomain("localhost:4480");
loginCookie.setPath("/");
response.addCookie(loginCookie);
</code></pre>
<p>In order to extend the cookie timelimit, what should I write in the react side to receive the cookie's session time?</p> | 43,684,059 | 10 | 0 | null | 2016-10-03 08:03:54.033 UTC | 34 | 2022-01-18 01:22:22.473 UTC | 2018-09-28 18:57:06.433 UTC | null | 4,333,347 | null | 6,169,793 | null | 1 | 121 | reactjs|cookies | 364,472 | <p>It appears that the functionality previously present in the <code>react-cookie</code> npm package has been moved to <code>universal-cookie</code>. The relevant example from the <a href="https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie" rel="noreferrer" title="universal-cookie repository">universal-cookie repository</a> now is:</p>
<pre><code>import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman
</code></pre> |
67,000,474 | When I start Android Emulator, the audio on my Mac desktop stops | <p>When I start Android Emulator, the audio on my Mac desktop stops. It starts again when I close the emulator.</p> | 67,000,475 | 6 | 0 | null | 2021-04-08 08:50:28.527 UTC | 20 | 2022-08-29 18:40:29.263 UTC | null | null | null | null | 2,298,241 | null | 1 | 46 | android|macos|android-studio|android-emulator | 9,464 | <p>When the emulator is started with enabled audio, sometimes it overrides the audio channel of the Mac machine. This happens even if you disable access to the microphone for Android studio in Security settings. To fix the issue you should start the emulator with disabled audio.</p>
<p><strong>There are two options to start the emulator with disabled audio:</strong></p>
<p><strong>I.</strong> Start the emulator from the console:</p>
<p><code>emulator -avd Pixel_2_API_27 -qemu -no-audio</code></p>
<p><strong>II.</strong> If you want to start the emulator with disabled audio directly from Android studio, you should replace the <code>emulator</code> file with a script that will run <code>emulator</code> with additional parameters:</p>
<p>Android Studio by default uses the binary <code>$ANDROID_SDK/emulator/emulator</code>which is located in: <code>~/Library/Android/sdk/emulator/</code></p>
<p>You have to do the following:</p>
<ol>
<li><p>Rename the <code>emulator</code> binary to <code>emulator-original</code>.</p>
</li>
<li><p>Create a bash script text file with the name <code>emulator</code> that contains:</p>
</li>
</ol>
<blockquote>
<pre><code>#!/bin/bash
~/Library/Android/sdk/emulator/emulator-original $@ -qemu -no-audio
</code></pre>
</blockquote>
<ol start="3">
<li>Set the newly created script permissions with <code>chmod +x emulator</code></li>
</ol>
<p>Now, Android Studio will run your script that will run the original binary with the addtitional parameters to disable emulator's audio.</p>
<p>N.B. Kudos for the script solution to <a href="https://stackoverflow.com/users/2271287/martincr">MartinCR</a> who proposed it <a href="https://stackoverflow.com/questions/39397056/how-to-pass-command-line-options-to-the-emulator-in-android-studio">here</a>.</p> |
22,182,087 | IIS rewrite rule to redirect specific domain url to different url on same domain | <p>I simply want an IIS 7.5 rewrite rule to redirect <a href="http://www.domain.com/url1" rel="nofollow noreferrer">http://www.domain.com/url1</a> to <a href="http://www.domain.com/url2" rel="nofollow noreferrer">http://www.domain.com/url2</a> (same domain). This can be achieved by:</p>
<pre class="lang-xml prettyprint-override"><code><rule name="Redirect url" enabled="true" stopProcessing="true">
<match url="^url1" />
<action type="Redirect" url="http://www.domain.com/url2"
appendQueryString="false" redirectType="Permanent" />
</rule>
</code></pre>
<p>However, this website listens to several domains, thus above becomes a global rule for all domains. How do I make this specific to domain.com? Have tried changing match url and adding conditions but cannot get it to work. Thanks.</p> | 22,206,843 | 2 | 0 | null | 2014-03-04 20:17:53.89 UTC | 2 | 2017-02-10 10:57:15.293 UTC | 2017-02-10 10:55:26.327 UTC | null | 205,245 | null | 1,224,021 | null | 1 | 8 | redirect|iis-7.5|url-rewrite-module | 46,300 | <p>I got it to work this way:</p>
<pre class="lang-xml prettyprint-override"><code><rule name="Redirect url1" stopProcessing="true">
<match url="^url1$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(www.)?domain.com$" />
</conditions>
<action type="Redirect" url="http://www.domain.com/url2"
appendQueryString="false" redirectType="Permanent" />
</rule>
</code></pre> |
2,384,578 | What are CPU registers and how are they used, particularly WRT multithreading? | <p>This question and my answer below are mainly in response to an area of confusion in another question.</p>
<p>At the end of the answer, there are some issues WRT "volatile" and thread synchronisation that I'm not entirely confident about - I welcome comments and alternative answers. The point of the question primarily relates to CPU registers and how they are used, however.</p> | 2,384,596 | 2 | 2 | null | 2010-03-05 04:35:48.713 UTC | 9 | 2015-07-19 06:36:59.683 UTC | null | null | null | user180247 | null | null | 1 | 5 | assembly|code-generation|compiler-construction|cpu-registers | 19,450 | <p>CPU registers are small areas of data storage on the silicon of the CPU. For most architectures, they're the primary place all operations happen (data gets loaded in from memory, operated on, and pushed back out).</p>
<p>Whatever thread is running uses the registers and owns the instruction pointer (which says which instruction comes next). When the OS swaps in another thread, all of the CPU state, including the registers and the instruction pointer, get saved off somewhere, effectively freeze-drying the state of the thread for when it next comes back to life.</p>
<p>Lots more documentation on all of this, of course, all over the place. <a href="http://en.wikipedia.org/wiki/Processor_register" rel="noreferrer">Wikipedia on registers.</a> <a href="http://en.wikipedia.org/wiki/Context_switch" rel="noreferrer">Wikipedia on context switching.</a> for starters. Edit: or read Steve314's answer. :)</p> |
32,648,654 | Web deployment task failed (This access control list is not in canonical form and therefore cannot be modified) | <p>Publishing ASP.NET MVC 4 application to IIS 8 on my machine giving the following error :</p>
<blockquote>
<p>This access control list is not in canonical form and therefore cannot be modified.</p>
</blockquote>
<p>I am under Windows 10 and using VS 2013 Ultimate.<br/>
I installed web deploy 3.5 from web platform installer 5, and I made sure that the services are working </p>
<p><a href="https://i.stack.imgur.com/vHZHM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vHZHM.png" alt="enter image description here"></a></p> | 35,968,313 | 3 | 0 | null | 2015-09-18 09:33:16.567 UTC | 8 | 2019-04-15 04:41:09.997 UTC | 2018-05-16 09:16:31.18 UTC | null | 4,390,133 | null | 4,390,133 | null | 1 | 36 | c#|asp.net-mvc-4|iis|publish | 17,738 | <p><strong>Solution 1</strong></p>
<p>I was able to solve this problem in the following way</p>
<ol>
<li>Go to IIS</li>
<li>Right click on the website that you are publishing to and select <strong>Edit Permissions</strong></li>
<li>Click the <strong>Security</strong> tab.</li>
<li>Click on <strong>Edit</strong> button</li>
<li>A Message box will appear which tell that the Permission was not correctly ordered.</li>
<li>Click <strong>Reorder</strong> on that message box.</li>
</ol>
<p><a href="https://i.stack.imgur.com/Vl9Rg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vl9Rg.png" alt="enter image description here"></a></p>
<p><strong>Solution 2</strong></p>
<p>Open the Command prompt (CMD) and execute the following two statements</p>
<pre><code>icacls.exe C:\inetpub\wwwroot /verify /T /C /L /Q
icacls.exe C:\inetpub\wwwroot /reset /T /C /L /Q
</code></pre>
<p>note : <em>Maybe</em> you will want to open the CMD with Administrator privilege <em>(Maybe I am not sure)</em></p>
<p>Cheers</p> |
41,503,740 | Swift variable name with ` (backtick) | <p>I was browsing Alamofire sources and found a variable name that is backtick escaped in <a href="https://github.com/Alamofire/Alamofire/blob/master/Source/SessionManager.swift" rel="noreferrer">this source file</a></p>
<pre><code>open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
</code></pre>
<p>However in places where variable is used there are no backticks. What's the purpose of backticks?</p>
<p>Removing the backticks results in the error:</p>
<blockquote>
<p>Keyword 'default' cannot be used as an identifier here</p>
</blockquote> | 41,503,795 | 3 | 0 | null | 2017-01-06 10:32:07.95 UTC | 3 | 2021-09-28 03:12:11.687 UTC | 2021-09-28 03:07:24.36 UTC | null | 1,265,393 | null | 3,237,732 | null | 1 | 39 | swift|alamofire | 7,689 | <p>According to the <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#ID412" rel="noreferrer">Swift documentation</a> :</p>
<blockquote>
<p>To use a reserved word as an identifier, put a backtick (<code>`</code>)before and after it. For example, <code>class</code> is not a valid identifier, but <code>`class`</code> is valid. The backticks are not considered part of the identifier; <code>`x`</code> and <code>x</code> have the same meaning.</p>
</blockquote>
<p>In your example, <code>default</code> is a Swift reserved keyword, that's why backticks are needed.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.