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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57,444,207 | How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip | <p>I am trying to install django-heroku using pip, but it keeps running into an error.</p>
<p>I have seen suggestions telling me to make sure my Python version in Heroku is up to date. I have already done that. After pushing to Heroku master, I ran the install command, but it gives me the following errors.</p>
<pre><code>pip install django-heroku
</code></pre>
<p>Error:</p>
<pre class="lang-none prettyprint-override"><code>ERROR: Command errored out with exit status 1:
command: /Users/user/Dev/trydjango/new_env/bin/python -c 'import
sys, setuptools, tokenize; sys.argv[0] =
'"'"'/private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip-
install-xqsix26g/psycopg2/setup.py'"'"';
egg_info --egg-base pip-egg-info
cwd:
/private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip-
install-xqsix26g/psycopg2/
Complete output (23 lines):
running egg_info
creating pip-egg-info/psycopg2.egg-info
writing pip-egg-info/psycopg2.egg-info/PKG-INFO
writing dependency_links to pip-egg-info/psycopg2.egg-
info/dependency_links.txt
writing top-level names to pip-egg-info/psycopg2.egg-
info/top_level.txt
writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'
Error: pg_config executable not found.
pg_config is required to build psycopg2 from source. Please add t . he directory
containing pg_config to the $PATH or specify the full executable
path with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
If you prefer to avoid building psycopg2 from source, please
install the PyPI
'psycopg2-binary' package instead.
For further information please check the 'doc/src/install.rst' file
(also at
<http://initd.org/psycopg/docs/install.html>).
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py
egg_info Check the logs for full command output.
</code></pre> | 57,444,274 | 1 | 2 | null | 2019-08-10 17:20:47.733 UTC | 4 | 2020-06-27 15:34:27.647 UTC | 2020-06-27 15:22:11.227 UTC | null | 63,550 | null | 6,534,681 | null | 1 | 45 | python|django|heroku|pip | 408,573 | <p>You need to add the package containing the executable <em>pg_config</em>.</p>
<p>A prior answer should have details you need: <em><a href="https://stackoverflow.com/questions/11618898/pg-config-executable-not-found">pg_config executable not found</a></em></p> |
21,763,904 | Linux find and grep command together | <p>I am trying to find a command or create a Linux script that can do this two comands and list the otuput</p>
<pre><code>find . -name '*bills*' -print
</code></pre>
<p>this prints all the files</p>
<pre><code>./may/batch_bills_123.log
./april/batch_bills_456.log
..
</code></pre>
<p>from this result I want to do a grep for a word I do this manually right now</p>
<pre><code>grep 'put' ./may/batch_bill_123.log
</code></pre>
<p>and get</p>
<pre><code>sftp > put oldnet_1234.lst
</code></pre>
<p>I would hope to get the file name and its match.</p>
<pre><code>./may/batch_bills_123.log sftp > put oldnet_1234.lst
..
..
and so on...
</code></pre>
<p>any ideas?</p> | 21,765,587 | 4 | 2 | null | 2014-02-13 19:37:38.753 UTC | 17 | 2021-06-17 14:19:31.327 UTC | 2018-01-20 05:03:14.977 UTC | null | 3,848,765 | null | 3,307,574 | null | 1 | 82 | bash|grep|find | 177,499 | <p>You are looking for <code>-H</code> option in gnu grep.</p>
<pre><code>find . -name '*bills*' -exec grep -H "put" {} \;
</code></pre>
<h3>Here is the explanation</h3>
<pre><code> -H, --with-filename
Print the filename for each match.
</code></pre> |
28,477,222 | Python/Pandas calculate Ichimoku chart components | <p>I have Pandas DataFrame object with Date, Open, Close, Low and High daily stock data. I want to calculate components of <a href="https://www.investopedia.com/terms/i/ichimoku-cloud.asp" rel="nofollow noreferrer">Ichimoku</a> chart. I can get my data using the following code:</p>
<pre><code>high_prices = data['High']
close_prices = data['Close']
low_prices = data['Low']
dates = data['Date'] # contains datetime objects
</code></pre>
<p>I need to calculate the following series (Ichimoku calls it Tenkan-Sen line):</p>
<p><strong>(9-period high + 9-period low) / 2</strong></p>
<ul>
<li>9-period high = the highest High value of last 9 days,</li>
<li>9-period low = the lowest Low value of last 9 days,
so both should begin on 9th day.</li>
</ul>
<p><img src="https://i.stack.imgur.com/gadZ2.gif" alt="enter image description here" /></p>
<p>I've found a solution in R language <a href="http://www.r-bloggers.com/ichimoku-clouds-r-code-trading/" rel="nofollow noreferrer">here</a>, but it's difficult for me to translate it to Python/Pandas code.</p>
<p>Ichimoku chart contains of more components, but when I will know how to count Tenkan-Sen line in Pandas, I will be able to count all of them (I will share the code).</p> | 28,477,973 | 8 | 3 | null | 2015-02-12 12:14:23.727 UTC | 13 | 2021-12-22 13:35:00.553 UTC | 2021-01-25 02:31:36.647 UTC | null | 14,148,248 | null | 3,105,499 | null | 1 | 7 | python|pandas | 21,222 | <p>I'm no financial expert or plotting expert but the following shows sample financial data and how to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.rolling_max.html#pandas.rolling_max" rel="nofollow noreferrer"><code>rolling_max</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.rolling_min.html#pandas.rolling_min" rel="nofollow noreferrer"><code>rolling_min</code></a>:</p>
<pre><code>In [60]:
import pandas.io.data as web
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
data=web.DataReader("F", 'yahoo', start, end)
high_prices = data['High']
close_prices = data['Close']
low_prices = data['Low']
dates = data.index
nine_period_high = df['High'].rolling(window=9).max()
nine_period_low = df['Low'].rolling(window=9).min()
ichimoku = (nine_period_high + nine_period_low) /2
ichimoku
Out[60]:
Date
2010-01-04 NaN
2010-01-05 NaN
2010-01-06 NaN
2010-01-07 NaN
2010-01-08 NaN
2010-01-11 NaN
2010-01-12 NaN
2010-01-13 NaN
2010-01-14 11.095
2010-01-15 11.270
2010-01-19 11.635
2010-01-20 11.730
2010-01-21 11.575
2010-01-22 11.275
2010-01-25 11.220
...
2013-01-04 12.585
2013-01-07 12.685
2013-01-08 13.005
2013-01-09 13.030
2013-01-10 13.230
2013-01-11 13.415
2013-01-14 13.540
2013-01-15 13.675
2013-01-16 13.750
2013-01-17 13.750
2013-01-18 13.750
2013-01-22 13.845
2013-01-23 13.990
2013-01-24 14.045
2013-01-25 13.970
Length: 771
</code></pre>
<p>Calling <code>data[['High', 'Low', 'Close', 'ichimoku']].plot()</code> results in the following plot:</p>
<p><img src="https://i.stack.imgur.com/lhOuW.png" alt="enter image description here"></p>
<p><strong>update</strong></p>
<p>After @PedroLobito's comments pointing out the incomplete/incorrect formula I took @chilliq's answer and modified it for pandas versions 0.16.1 and above:</p>
<pre><code>import pandas as pd
from pandas_datareader import data, wb
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
d=data.DataReader("F", 'yahoo', start, end)
high_prices = d['High']
close_prices = d['Close']
low_prices = d['Low']
dates = d.index
nine_period_high = df['High'].rolling(window=9).max()
nine_period_low = df['Low'].rolling(window=9).min()
d['tenkan_sen'] = (nine_period_high + nine_period_low) /2
# Kijun-sen (Base Line): (26-period high + 26-period low)/2))
period26_high = high_prices.rolling(window=26).max()
period26_low = low_prices.rolling(window=26).min()
d['kijun_sen'] = (period26_high + period26_low) / 2
# Senkou Span A (Leading Span A): (Conversion Line + Base Line)/2))
d['senkou_span_a'] = ((d['tenkan_sen'] + d['kijun_sen']) / 2).shift(26)
# Senkou Span B (Leading Span B): (52-period high + 52-period low)/2))
period52_high = high_prices.rolling(window=52).max()
period52_low = low_prices.rolling(window=52).min()
d['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)
# The most current closing price plotted 22 time periods behind (optional)
d['chikou_span'] = close_prices.shift(-22) # 22 according to investopedia
d.plot()
</code></pre>
<p>results in the following plot, unclear because as stated already I'm not a financial expert:</p>
<p><a href="https://i.stack.imgur.com/pV6NY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pV6NY.png" alt="enter image description here"></a></p> |
7,524,262 | Permission denied in tmp | <p>I just deployed a Rails 3 app with Ruby 1.9.2. I have been getting several errors.</p>
<ol>
<li><code>application.css</code> wasn't compiled. so I set pre compilation in <code>production.rb</code> to false;</li>
<li>Then I got: <code>cannot generate tempfile</code>, so I did <code>rake tmp:clear</code>;</li>
<li>And now I get <code>ActionView::Template::Error (Permission denied - /srv/www/appname/tmp/cache/assets):</code> and I haven't been able to fix this one.</li>
</ol>
<p>Please help.</p> | 7,525,481 | 10 | 0 | null | 2011-09-23 04:33:14.413 UTC | 6 | 2019-08-11 06:53:28.15 UTC | 2014-09-12 13:55:05.64 UTC | null | 1,565,597 | null | 912,895 | null | 1 | 26 | ruby-on-rails|ruby | 58,901 | <p>If the <code>user:group</code> running your web server is <code>http:http</code> and it's running on *nix, do this:</p>
<pre><code>sudo chown -R http:http /srv/www/appname/
</code></pre>
<p>Also, silly question, but does /tmp/cache/assets exist?</p>
<p>And, if so, as <a href="https://stackoverflow.com/users/912895/leonel">@leonel</a> points out, you may also need to change the permissions:</p>
<pre><code>chmod 777 /srv/www/appname/tmp/cache
</code></pre>
<p>Be careful setting <code>777</code> permissions on anything. Only do this to verify a permissions issue, then reset to the most minimal permissions necessary.</p> |
13,845,958 | How to get the path coordinates of a shape for use with image-maps? | <p>I am creating an image map using <code>ImageMapster</code> <a href="http://www.outsharked.com/imagemapster/default.aspx?demos.html">from here</a>. </p>
<p>I have created a photoshop image with several images that I have cut out from the original photographs. Each image is on a separate layer.</p>
<p>Now, I need to get the path coordinates of each object, and I don't want to hover over every corner and manually write down each coordinate.</p>
<p>Is there an automated way to get this path?</p>
<p>Maybe there is some application or web service whence I can send my image and get the path in return?</p>
<p>I have tried exporting each layer separately and then importing them into illustrator and vectorizing the shape (it keeps the shape in its original position), but I can't figure out how to get the coordinate path as text. I can export it to svg, but that isn't the same simple code needed for the css image map.</p> | 13,847,787 | 6 | 0 | null | 2012-12-12 18:08:58.57 UTC | 24 | 2017-08-31 06:49:30.327 UTC | 2012-12-12 20:37:13.473 UTC | null | 1,038,866 | null | 1,038,866 | null | 1 | 19 | photoshop|imagemap|adobe-illustrator|imagemapster | 51,514 | <p>Ah! After googling <code>image-map</code>, much thanks to Sven for the idea (he got my +1), I found <a href="https://stackoverflow.com/questions/3833052/illustrator-map-to-imagemap-automatically-or-is-there-a-better-way">this thread here on Stack Overflow</a>.</p>
<p>So here is my process.</p>
<ol>
<li>Prepare the image in Photoshop with each object on a separate layer with a transparent background (this will make it easy for you when you do the tracing).</li>
<li>Save your photoshop file.</li>
<li>Open the Photoshop file in Illustrator using <em>File...Open</em> (works in CS4 and CS5) and make sure to allow the option to import Photoshop's layers as separate objects. After you open the file, make sure NOT to move any of the objects around - you need them to be in the <em>exact same place</em> as they were in the photoshop file so they can superimpose each other when rendered to the imagemap.</li>
<li>Use the <code>Live Trace</code> with custom settings. Use the black & white mode with the threshold all the up (255). This will produce a black silhouette of the shape. (You can also use "ignore white"). Push the <code>Trace</code> button. If you have many layers, you can save this new tracing pattern as a preset - I called mine, <em>Silhouette</em>. Now, I just click on a layer and choose <em>Silhouette</em> from the tracing buttons' dropdown menu.<img src="https://i.stack.imgur.com/516bu.png" alt="Adobe Illustrator Tracing Settings"></li>
<li>Expand the shape and make sure it consists of only a single flat shape:
<ul>
<li>you can use the blob brush in illustrator to blacken over any unwanted white areas</li>
<li><strong>no groups</strong></li>
<li><strong>no compound shapes</strong> (or it won't work) - which means you can't create cutouts.</li>
<li>You can tell the shapes are right when you click on them - you should be able to see the path itself with no "other" shapes involved (perhaps the blob brush additions) - just a single path. An easy method is this:
<ul>
<li><code>select</code> the shape</li>
<li><code>ungroup</code> if necessary</li>
<li><code>release compound path</code></li>
<li><code>unite</code> (shape mode merges all shapes into one)</li>
</ul></li>
<li>Don't <code>crop</code> your image - you want your shape to be in the same place in the image's area as in your original photoshop image.</li>
<li>Don't join all the shapes together, either.</li>
<li>The shapes should all be individual whole shapes, all in their original locations, each on a separate layer.</li>
</ul></li>
<li>Now, open Illustrator's <code>Attributes panel</code>, and make sure to "show options". </li>
<li>Select your shape and in the "Attributes" panel, switch the "Image Map" combo box from <code>None</code> to <code>Polygon</code>. Make sure to add a url (it doesn't matter what you put; you can change it later - I just put "#" and the name of the shape so I can tell which one it belongs to in the image map code) <img src="https://i.stack.imgur.com/euHSn.png" alt="enter image description here"></li>
<li>Do this for each of the objects.</li>
<li>Now, in the <code>File</code> menu, go to "Save for Web and Devices". Skip all the settings here and just push "Save".</li>
<li>In the "Save As" (the title of the window is "Save Optimized As") dialogue box, use "Save As type:" and select <code>HTML Only(*.html)</code> if you just want the code, or <code>HTML and Images</code> if you want the sillouhuette, too (they will appear in a folder called "images") - and note your save location. <img src="https://i.stack.imgur.com/MG6s0.png" alt="enter image description here"></li>
<li>Now go open that html file in notepad!</li>
<li><strong>Voila!</strong> All the shapes will be rendered for you as a pre-made <code>image-map</code> - points path and even html code. Here is what it looks like when you open in notepad the html file you just created: <img src="https://i.stack.imgur.com/CvdgC.png" alt="enter image description here"> For this demo, I chose a particularly complicated image - one which you would never want to estimate by hand, nor have to do twice!</li>
</ol>
<p>Don't forget to place the actual image file somewhere in your site's images folder. You can save the psd file for later and add more "stuff" if you want, and repeat the process.</p>
<p>I was able to create the image map this way for my photoshop picture in just a brief couple of minutes. After you do it once, it gets easier for next time.</p> |
13,917,033 | datatrigger on enum to change image | <p>I've got a button with a fixed background image and would like to show a small overlay image on top of it. Which overlay image to chose depends on a dependency property (<code>LapCounterPingStatus</code>) of the according viewmodel.</p>
<p>This is what I got so far:</p>
<pre><code><Button>
<Grid>
<Image Stretch="None"> <!-- Background Image -->
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="/Images/Pingn.png"/>
</Style>
</Image.Style>
</Image>
<Image Stretch="None" Panel.ZIndex="1"> <!-- Small Overlay Image -->
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_UNKNOWN">
<Setter Property="Source" Value="/Images/RefreshOverlayn.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_FAILURE">
<Setter Property="Source" Value="/Images/ErrorOverlayn.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_SUCCESS">
<Setter Property="Source" Value="/Images/CheckmarkOverlayn.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
</Button>
</code></pre>
<p>Relevant parts of my viewmodel</p>
<pre><code>public class ConfigurationViewModel
{
public enum PingStatus { PING_UNKNOWN, PING_SUCCESS, PING_FAILURE };
public PingStatus LapCounterPingStatus
{
get { return _lapCounterPingStatus; }
set
{
_lapCounterPingStatus = value;
RaisePropertyChanged(LapCounterPingStatusPropertyName);
}
}
}
</code></pre>
<p><strong>Right now, no overlay image at all is displayed. What could be wrong?</strong></p>
<hr>
<p><strong>UPDATE</strong></p>
<p>Trace window of my IDE is showing <code>System.ArgumentException</code> and <code>System.FormatException</code>.
Could the problem source be a unknown type of enumeration <code>PingStatus</code> im the XAML?</p> | 13,917,382 | 3 | 1 | null | 2012-12-17 15:28:43.423 UTC | 21 | 2020-10-28 21:47:52.67 UTC | 2020-02-15 17:28:39.54 UTC | null | 4,728,685 | null | 220,636 | null | 1 | 117 | c#|wpf | 66,728 | <p>You need 2 things to get this working:</p>
<p>1 - Add an <code>xmlns</code> reference in the root element of your XAML file, to the namespace where your Enum is defined:</p>
<pre><code><UserControl ...
xmlns:my="clr-namespace:YourEnumNamespace;assembly=YourAssembly">
</code></pre>
<p>2 - in the <code>Value</code> property of the <code>DataTrigger</code>, use the <code>{x:Static}</code> form:</p>
<pre><code> <DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="{x:Static my:PingStatus.PING_UNKNOWN}">
</code></pre>
<p>Notice that the Enum type must be prefixed with the xmlns prefix you defined above.</p>
<p><strong>Edit:</strong></p>
<p>If your Enum is declared inside a class you need to use the syntax:</p>
<p><code>{x:Static namespace:ClassName+EnumName.EnumValue}</code></p>
<p>for example:</p>
<p><code>{x:Static my:ConfigurationViewModel+PingStatus.PING_UNKNOWN}</code></p> |
9,627,098 | Start Activity with Button Android | <p>Ive got a problem. I want to open an Activity with a Button but it crashes all the time.
So I created 2 Classes and A Button. But it keeps crashing. </p>
<ol>
<li>Class is activity_home class() and second is schedule_act() class.</li>
</ol>
<p><strong>activity_home class:</strong> </p>
<pre><code> package my.action.bat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class activity_home extends Activity {
private Button ScheduleBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ScheduleBtn = (Button) findViewById(R.id.home_btn_schedule);
ScheduleBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent("my.action.bat.schedule_act");
startActivity(myIntent);
}
});
}
}
</code></pre>
<p><strong>schedule_act class:</strong> </p>
<pre><code>package my.action.bat;
import android.app.Activity;
import android.os.Bundle;
public class schedule_act extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.schedule_layout);
}
}
</code></pre>
<p><strong>Android Manifest:</strong> </p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.action.bat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".activity_home" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="@string/app_name"
android:name=".schedule_act" >
<intent-filter >
<action android:name="my.action.bat.SCHEDULE_ACT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>Thank you very much.</p> | 9,627,137 | 5 | 1 | null | 2012-03-09 00:14:07.16 UTC | 2 | 2016-10-04 14:47:17.773 UTC | 2015-06-26 18:28:01.81 UTC | null | 4,626,831 | null | 1,333,975 | null | 1 | 10 | android|android-activity | 40,543 | <p>Intents are case sensitive. Change </p>
<pre><code>"my.action.bat.schedule_act"
</code></pre>
<p>To</p>
<pre><code>"my.action.bat.SCHEDULE_ACT"
</code></pre>
<p>Also, unless you really need to use an intent, I would start your activity like so</p>
<pre><code>startActivity(new Intent(this, schedule_act.class));
</code></pre>
<p>Where <code>this</code> is a <code>Context</code> subclass</p> |
45,722,256 | How do I debug a "[object ErrorEvent] thrown" error in my Karma/Jasmine tests? | <p>I have several failing tests that only output <code>[object ErrorEvent] thrown</code>. I don't see anything in the console that helps me pinpoint the offending code. Is there something I need to do to track these down?</p>
<p>[EDIT]: I'm running Karma v1.70, Jasmine v2.7.0</p> | 46,840,229 | 17 | 6 | null | 2017-08-16 20:14:58.713 UTC | 25 | 2020-10-03 01:52:14.083 UTC | 2018-02-05 23:19:25.463 UTC | null | 415,078 | null | 55,589 | null | 1 | 116 | angular|angular-cli|karma-jasmine | 74,705 | <blockquote>
<p>FYI: you can find the exact error thrown just by open <strong>DevTools Console</strong> once your tests are running.</p>
</blockquote>
<p>As a quickfix you can try to run your <a href="https://angular.io/cli/test" rel="noreferrer">tests without sourcemaps</a>:</p>
<p><strong>CLI v6.0.8 and above</strong><br>
<code>--source-map=false</code></p>
<p><strong>CLI v6.0.x early versions</strong><br>
<code>--sourceMap=false</code></p>
<p><strong>CLI v1.x</strong><br>
<code>--sourcemaps=false</code></p>
<blockquote>
<p>Shortcut <code>ng test -sm=false</code> might also work</p>
</blockquote>
<p>There is an open issue on that <a href="https://github.com/angular/angular-cli/issues/7296" rel="noreferrer">https://github.com/angular/angular-cli/issues/7296</a></p>
<p><strong>UPDATE</strong>:
I had that issue as well, so I just migrated to the latest cli and make sure that all packages are updated in <code>package.json</code> also I fully reinstalled the <code>node_modules</code> so now the issue has gone.</p> |
24,876,673 | Explain JOIN vs. LEFT JOIN and WHERE condition performance suggestion in more detail | <p>In <a href="https://stackoverflow.com/a/24875278/624998">this candidate answer</a> it is asserted that <code>JOIN</code> is better than <code>LEFT JOIN</code> under some circumstances involving some <code>WHERE</code> clauses because it does not confuse the query planner and is not "pointless". The assertion/assumption is that it should be obvious to anyone.</p>
<p>Please explain further or provide link(s) for further reading.</p> | 24,876,947 | 2 | 3 | null | 2014-07-21 23:44:59.21 UTC | 11 | 2021-10-18 12:54:48.787 UTC | 2017-05-23 10:31:35.96 UTC | null | -1 | null | 624,998 | null | 1 | 23 | sql|postgresql|join|left-join|where | 31,783 | <p>Consider the following example. We have two tables, DEPARTMENTS and EMPLOYEES.</p>
<p>Some departments do not yet have any employees.</p>
<p>This query uses an inner join that finds the department employee 999 works at, if any, otherwise it shows nothing (not even the employee or his or her name):</p>
<pre><code>select a.department_id, a.department_desc, b.employee_id, b.employee_name
from departments a
join employees b
on a.department_id = b.department_id
where b.employee_id = '999'
</code></pre>
<p>This next query uses an outer join (left between departments and employees) and finds the department that employee 999 works for. However it too will not show the employee's ID or his or her name, if they do not work at any departments. That is because of the outer joined table being used in the WHERE clause. If there is no matching department, it will be null (not 999, even though 999 exists in employees).</p>
<pre><code>select a.department_id, a.department_desc, b.employee_id, b.employee_name
from departments a
left join employees b
on a.department_id = b.department_id
where b.employee_id = '999'
</code></pre>
<p>But consider this query:</p>
<pre><code>select a.department_id, a.department_desc, b.employee_id, b.employee_name
from departments a
left join employees b
on a.department_id = b.department_id
and b.employee_id= '999'
</code></pre>
<p>Now the criteria is in the on clause. So even if this employee works at no departments, he will still be returned (his ID and name). The department columns will be null, but we get a result (the employee side).</p>
<p>You might think you would never want to use the outer joined table in the WHERE clause, but that is not necessarily the case. Normally it is, for the reason described above, though.</p>
<p>Suppose you want all departments with no employees. Then you could run the following, which does use an outer join, and the outer joined table is used in the where clause:</p>
<pre><code>select a.department_id, a.department_desc, b.employee_id
from departments a
left join employees b
on a.department_id = b.department_id
where b.employee_id is null
</code></pre>
<p>^^ Shows departments with no employees.</p>
<p>The above is likely the only legitimate reason you would want to use an outer joined table in the WHERE clause rather than the ON clause (which I think is what your question is; the difference between inner and outer joins is an entirely different topic).</p>
<p>A good way to look at is this: You use outer joins to allow nulls. Why would you then use an outer join and say that a field should not be null and should be equal to 'XYZ'? If a value has to be 'XYZ' (not null), then why instruct the database to allow nulls to come back? It's like saying one thing and then overriding it later.</p> |
592,160 | static vs extern "C"/"C++" | <p>What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just lucky or...</p>
<pre><code>class X {
public:
static void proxy(int i) {}
}
makecontext(..., (void (*)(void)) X::proxy, ...);
</code></pre>
<p>vs</p>
<pre><code>extern "C" void proxy(int i) {}
makecontext(..., (void (*)(void)) proxy, ...);
</code></pre>
<p>EDIT: Can you show a compiler or architecture where the static member version does not work (and it's not a bug in the compiler) ?</p> | 592,205 | 5 | 3 | null | 2009-02-26 19:58:32.247 UTC | 12 | 2019-02-26 13:16:27.823 UTC | 2017-03-14 06:32:35.147 UTC | Helltone | 55,935 | Helltone | 55,935 | null | 1 | 22 | c++|function-pointers|static-members|linkage|extern-c | 23,617 | <p>Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbersome). </p>
<p>extern "C" tells the compiler that your function is callable by C code. That can, but not must, include the appropriate calling convention and the appropriate C language name mangling (sometimes called "decoration") among other things depending on the implementation. If you have a static member function, the calling convention for it is the one of your C++ compiler. Often they are the same as for the C compiler of that platform - so i said you are just lucky. If you have a C API and you pass a function pointer, better always put one to a function declared with extern "C" like</p>
<pre><code>extern "C" void foo() { ... }
</code></pre>
<p>Even though the function pointer type does not contain the linkage specification but rather looks like</p>
<pre><code>void(*)(void)
</code></pre>
<p>The linkage is an integral part of the type - you just can't express it directly without a typedef:</p>
<pre><code>extern "C" typedef void(*extern_c_funptr_t)();
</code></pre>
<p>The Comeau C++ compiler, in strict mode, will emit an error for example if you try to assign the address of the extern "C" function of above to a <code>(void(*)())</code>, beause this is a pointer to a function with C++ linkage.</p> |
702,510 | jQuery dialog theme and style | <p>How do I change the background color of the title bar of a jQuery dialog?</p>
<p>I have looked at the themeroller but it does not seem to work for me.</p>
<p>Thanks</p> | 1,833,163 | 6 | 1 | null | 2009-03-31 18:48:02.967 UTC | 5 | 2014-04-07 09:56:33.043 UTC | 2012-09-20 21:01:19.487 UTC | null | 128,463 | Picflight | 59,941 | null | 1 | 14 | jquery|dialog|themes|titlebar|background-color | 72,911 | <p>I do this way (adding "ui-state-error" style for header):</p>
<pre><code><script type="text/javascript">
$(function () {
$("#msg").dialog({
open: function () {
$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").addClass("ui-state-error");
}
});
});
</script>
</code></pre> |
660,657 | Parse directory name from a full filepath in C# | <p>If I have a string variable that has:</p>
<pre><code>"C:\temp\temp2\foo\bar.txt"
</code></pre>
<p>and I want to get </p>
<p><strong>"foo"</strong></p>
<p>what is the best way to do this?</p> | 660,666 | 6 | 0 | null | 2009-03-19 00:37:50.417 UTC | 5 | 2016-02-18 15:53:09.303 UTC | 2012-08-23 18:25:13.557 UTC | null | 63,550 | mek | 4,653 | null | 1 | 36 | c#|file | 61,659 | <p>Use:</p>
<pre><code>new FileInfo(@"C:\temp\temp2\foo\bar.txt").Directory.Name
</code></pre> |
628,752 | Why call dispose(false) in the destructor? | <p>What follows is a typical dispose pattern example:</p>
<pre><code> public bool IsDisposed { get; private set; }
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
//perform cleanup here
}
IsDisposed = true;
}
}
~MyObject()
{
Dispose(false);
}
</code></pre>
<p>I understand what dispose does, but what I don't understand is why you would want to call dispose(false) in the destructor? If you look at the definition it would do absolutely nothing, so why would anyone write code like this? Wouldn't it make sense to just <em>not</em> call dispose from the destructor at all?</p> | 628,814 | 6 | 0 | null | 2009-03-10 02:49:04.51 UTC | 32 | 2021-03-21 00:15:52.453 UTC | 2009-03-10 02:55:38.643 UTC | ryeguy | 49,018 | ryeguy | 49,018 | null | 1 | 67 | c#|dispose | 38,144 | <p>The finalizer is used as a fall-back if the object is not disposed properly for some reason. Normally the <code>Dispose()</code> method would be called which removes the finalizer hookup and turns the object into a regular managed object that the garbage collector easily can remove.</p>
<p>Here is an example from MSDN of a class that has managed and unmanaged resources to clean up.</p>
<p>Notice that the managed resources are only cleaned up if <code>disposing</code> is true, but unmanaged resources is always cleaned up.</p>
<pre><code>public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
</code></pre> |
604,883 | Where to put view-specific javascript files in an ASP.NET MVC application? | <p>What is the best place (which folder, etc) to put view-specific javascript files in an ASP.NET MVC application? </p>
<p>To keep my project organized, I'd really love to be able to put them side-by-side with the view's .aspx files, but I haven't found a good way to reference them when doing that without exposing the ~/Views/Action/ folder structure. Is it really a bad thing to let details of that folder structure leak?</p>
<p>The alternative is to put them in the ~/Scripts or ~/Content folders, but is a minor irritation because now I have to worry about filename clashes. It's an irritation I can get over, though, if it is "the right thing."</p> | 6,453,724 | 6 | 2 | null | 2009-03-03 02:30:14.503 UTC | 39 | 2019-01-10 19:07:07.97 UTC | null | null | null | Twisty Maze | 31,910 | null | 1 | 97 | asp.net-mvc | 31,172 | <p>Old question, but I wanted to put my answer incase anyone else comes looking for it.</p>
<p>I too wanted my view specific js/css files under the views folder, and here's how I did it:</p>
<p>In the web.config folder in the root of /Views you need to modify two sections to enable the webserver to serve the files:</p>
<pre><code> <system.web>
<httpHandlers>
<add path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!-- other content here -->
</system.web>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
<!-- other content here -->
</system.webServer>
</code></pre>
<p>Then from your view file you can reference the urls like you expect:</p>
<pre><code>@Url.Content("~/Views/<ControllerName>/somefile.css")
</code></pre>
<p>This will allow serving of .js and .css files, and will forbid serving of anything else.</p> |
69,041,454 | Error: require() of ES modules is not supported when importing node-fetch | <p>I'm creating a program to analyze security camera streams and got stuck on the very first line. At the moment my .js file has nothing but the import of node-fetch and it gives me an error message. What am I doing wrong?</p>
<p>Running Ubuntu 20.04.2 LTS in Windows Subsystem for Linux.</p>
<p>Node version:</p>
<pre><code>user@MYLLYTIN:~/CAMSERVER$ node -v
v14.17.6
</code></pre>
<p>node-fetch package version:</p>
<pre><code>user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
[email protected] | MIT | deps: 2 | versions: 63
A light-weight module that brings Fetch API to node.js
https://github.com/node-fetch/node-fetch
keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
dist
.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
.unpackedSize: 75.9 kB
dependencies:
data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2
maintainers:
- endless <[email protected]>
- bitinn <[email protected]>
- timothygu <[email protected]>
- akepinski <[email protected]>
dist-tags:
latest: 3.0.0 next: 3.0.0-beta.10
published 3 days ago by endless <[email protected]>
</code></pre>
<p>esm package version:</p>
<pre><code>user@MYLLYTIN:~/CAMSERVER$ npm v esm
[email protected] | MIT | deps: none | versions: 140
Tomorrow's ECMAScript modules today!
https://github.com/standard-things/esm#readme
keywords: commonjs, ecmascript, export, import, modules, node, require
dist
.tarball: https://registry.npmjs.org/esm/-/esm-3.2.25.tgz
.shasum: 342c18c29d56157688ba5ce31f8431fbb795cc10
.integrity: sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==
.unpackedSize: 308.6 kB
maintainers:
- jdalton <[email protected]>
dist-tags:
latest: 3.2.25
published over a year ago by jdalton <[email protected]>
</code></pre>
<p>Contents of the .js file (literally nothing but the import):</p>
<pre><code>user@MYLLYTIN:~/CAMSERVER$ cat server.js
import fetch from "node-fetch";
</code></pre>
<p>Result:</p>
<pre><code>user@MYLLYTIN:~/CAMSERVER$ node -r esm server.js
/home/user/CAMSERVER/node_modules/node-fetch/src/index.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/user/CAMSERVER/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /home/user/CAMSERVER/node_modules/node-fetch/src/index.js from /home/user/CAMSERVER/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/user/CAMSERVER/node_modules/node-fetch/package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13) {
code: 'ERR_REQUIRE_ESM'
}
user@MYLLYTIN:~/CAMSERVER$
</code></pre> | 69,329,950 | 7 | 11 | null | 2021-09-03 08:01:10.423 UTC | 9 | 2022-05-23 06:29:26.827 UTC | 2021-09-03 08:07:17.1 UTC | null | 16,821,219 | null | 16,821,219 | null | 1 | 79 | javascript|node.js|node-fetch | 88,407 | <p><code>node-fetch</code> v3 is ESM-only: <a href="https://github.com/node-fetch/node-fetch#loading-and-configuring-the-module" rel="noreferrer">https://github.com/node-fetch/node-fetch#loading-and-configuring-the-module</a>. The <code>esm</code> module you’re adding is for adding ESM compatibility, but it’s unnecessary now that Node 12+ supports ESM natively; and it doesn’t work with ESM-only packages like <code>node-fetch</code> 3+.</p>
<p>To fix your issue:</p>
<ol>
<li>Remove the <code>esm</code> package.</li>
<li>Add <code>"type": "module"</code> to your <code>package.json</code>.</li>
</ol>
<p>And that’s it. Then when you run <code>node server.js</code> it should work.</p> |
30,894,045 | Recordset.Edit or Update sql vba statement fastest way to update? | <p>I recently came across vba update statements and I have been using <code>Recordset.Edit</code> and <code>Recordset.Update</code> to not only edit my existing data but to update it. </p>
<p>I want to know the difference between the two: <code>recordset.update</code> and <code>Update sql Vba</code> statement. I think they all do the same but I can't figure which one is more efficient and why. </p>
<p>Example code below:</p>
<pre class="lang-vb prettyprint-override"><code>'this is with sql update statement
dim someVar as string, anotherVar as String, cn As New ADODB.Connection
someVar = "someVar"
anotherVar = "anotherVar"
sqlS = "Update tableOfRec set columna = " &_
someVar & ", colunmb = " & anotherVar &_
" where columnc = 20";
cn.Execute stSQL
</code></pre>
<p>This is for recordset (update and Edit): </p>
<pre class="lang-vb prettyprint-override"><code>dim thisVar as String, someOthVar as String, rs as recordset
thisVar = "thisVar"
someOthVar = "someOtherVar"
set rs = currentDb.openRecordset("select columna, columnb where columnc = 20")
do While not rs.EOF
rs.Edit
rs!columna = thisVar
rs!columnb = someOthvar
rs.update
rs.MoveNext
loop
</code></pre> | 30,895,088 | 4 | 2 | null | 2015-06-17 14:09:29.347 UTC | 1 | 2020-07-12 07:53:57.09 UTC | 2020-07-12 07:53:57.09 UTC | null | 8,422,953 | null | 4,331,334 | null | 1 | 9 | sql|vba|ms-access | 42,237 | <p>Assuming <code>WHERE columnc = 20</code> selects 1000+ rows, as you mentioned in a comment, executing that <code>UPDATE</code> statement should be noticeably faster than looping through a recordset and updating its rows one at a time.</p>
<p>The latter strategy is a RBAR (Row By Agonizing Row) approach. The first strategy, executing a single (valid) <code>UPDATE</code>, is a "set-based" approach. In general, set-based trumps RBAR with respect to performance.</p>
<p>However your 2 examples raise other issues. My first suggestion would be to use DAO instead of ADO to execute your <code>UPDATE</code>:</p>
<pre class="lang-vb prettyprint-override"><code>CurrentDb.Execute stSQL, dbFailonError
</code></pre>
<p>Whichever of those strategies you choose, make sure <em>columnc</em> is indexed.</p> |
31,135,368 | Display date picker below input field | <p>I am using bootstrap datepicker when I click on input field calendar display above the input field. I want to display it bellow input field.</p>
<p><strong>JS</strong></p>
<pre><code>$(function () {
$("#fFYear").datepicker({
dateFormat: "mm/dd/yy",
showOtherMonths: true,
selectOtherMonths: true,
autoclose: true,
changeMonth: true,
changeYear: true,
//gotoCurrent: true,
}).datepicker("setDate", new Date());
//alert("#FirstFiscalTo");
});
</code></pre>
<p><strong>Input Field</strong></p>
<pre><code><input class="textboxCO input-sm form-control datePickerPickcer" id="fiscalYear" name="FiscalYear" type="text" value="6/30/2015 7:12:21 AM">
</code></pre> | 31,135,707 | 5 | 3 | null | 2015-06-30 10:07:50.817 UTC | 3 | 2021-05-17 08:19:26.343 UTC | null | null | null | null | 4,557,690 | null | 1 | 7 | javascript|jquery|twitter-bootstrap|datepicker | 48,818 | <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function () {
$("#fiscalYear").datepicker({
dateFormat: "mm/dd/yy",
showOtherMonths: true,
selectOtherMonths: true,
autoclose: true,
changeMonth: true,
changeYear: true,
//gotoCurrent: true,
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input id="fiscalYear" name="FiscalYear" type="text" value="6/30/2015 7:12:21 AM"></code></pre>
</div>
</div>
</p> |
39,404,922 | 'tsc command not found' in compiling typescript | <p>I want to install typescript, so I used the following command:</p>
<pre><code>npm install -g typescript
</code></pre>
<p>and test <code>tsc --version</code>, but it just show 'tsc command not found'. I have tried many ways as suggested in stackoverflow, github and other sites. but it doesn't work. How could I know typescript is installed and where it is.</p>
<p>my OS is Unix, OS X El Capitan 10.11.6,
node version is 4.4.3,
npm version is 3.10.5</p> | 39,413,342 | 25 | 6 | null | 2016-09-09 06:13:02.03 UTC | 18 | 2022-09-24 05:02:36.043 UTC | 2016-09-09 06:32:48.167 UTC | null | 3,152,790 | null | 3,152,790 | null | 1 | 197 | typescript|npm|tsc | 308,874 | <p>A few tips in order</p>
<ul>
<li>restart the terminal </li>
<li>restart the machine</li>
<li>reinstall nodejs + then run <code>npm install typescript -g</code></li>
</ul>
<p>If it still doesn't work run <code>npm config get prefix</code> to see where npm install -g is putting files (append <code>bin</code> to the output) and make sure that they are in the path (the node js setup does this. Maybe you forgot to tick that option).</p> |
63,277,123 | What does the error message about pip --use-feature=2020-resolver mean? | <p>I'm trying to install jupyter on Ubuntu 16.04.6 x64 on DigitalOcean droplet. It is giving me the following error message, and I can't understand what this means.</p>
<blockquote>
<p>ERROR: After October 2020 you may experience errors when installing or
updating packages. This is because pip will change the way that it
resolves dependency conflicts.</p>
<p>We recommend you use --use-feature=2020-resolver to test your packages
with the new resolver before it becomes the default.</p>
<p>jsonschema 3.2.0 requires six>=1.11.0, but you'll have six 1.10.0 which is incompatible</p>
</blockquote>
<p>Any help would be greatly appreciated!</p> | 63,280,415 | 2 | 1 | null | 2020-08-06 05:00:22.97 UTC | 16 | 2022-08-03 13:12:40.7 UTC | 2022-08-03 13:12:40.7 UTC | null | 2,745,495 | null | 9,325,875 | null | 1 | 82 | python|pip | 86,773 | <p>According to <a href="https://discuss.python.org/t/announcement-pip-20-2-release/4863" rel="noreferrer">this announcement</a>, pip will introduce a new dependency resolver in October 2020, which will be more robust but might break some existing setups. Therefore they are suggesting users to try running their pip install scripts at least once (in dev mode) with this option: <code>--use-feature=2020-resolver</code>
to anticipate any potential issue before the new resolver becomes the default in October 2020 with pip version 20.3.</p>
<blockquote>
<p>On behalf of the PyPA, I am pleased to announce that we have just released pip 20.2, a new version of pip. You can install it by running python -m pip install --upgrade pip.</p>
<p>The highlights for this release are:</p>
<ul>
<li>The beta of the next-generation dependency resolver is available</li>
<li>Faster installations from wheel files</li>
<li>Improved handling of wheels containing non-ASCII file contents</li>
<li>Faster pip list using parallelized network operations</li>
<li>Installed packages now contain metadata about whether they were directly
requested by the user (PEP 376’s REQUESTED file)</li>
</ul>
<p>The new dependency resolver is off by default because it is not yet ready for everyday use.</p>
<p>The new dependency resolver is significantly stricter and more consistent when it receives incompatible instructions, and reduces support for certain kinds of constraints files, so some workarounds and workflows may break. Please test it with the --use-feature=2020-resolver flag. Please see <a href="https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-2-2020" rel="noreferrer">our guide on how to test and migrate</a>, and how to report issues . We are preparing to change the default dependency resolution behavior and make the new resolver the default in pip 20.3 (in October 2020).</p>
</blockquote> |
2,200,409 | What is the difference between copying and cloning? | <p>Is there a definitive reference on this in programming? </p>
<p>I see a lot of people refer to deep copying and cloning as the same thing. Is this true? </p>
<p>Is it language dependent?</p>
<p>A small point, but it was bothering me...</p> | 2,200,510 | 5 | 1 | null | 2010-02-04 14:36:27.783 UTC | 5 | 2015-05-26 18:25:38.5 UTC | 2014-02-25 13:50:15.6 UTC | user195488 | 1,559,219 | null | 94,777 | null | 1 | 32 | c#|oop | 45,730 | <p>Yes, there is a difference. As far as language dependencies, some languages can do all Shallow, Deep, Lazy copying. Some only do Shallow copies. So yes, it is language dependent sometimes. </p>
<p>Now, take for instance an Array:</p>
<pre><code>int [] numbers = { 2, 3, 4, 5};
int [] numbersCopy = numbers;
</code></pre>
<p>The “numbersCopy” array now contains the same values, but more importantly the array object itself points to the same object reference as the “numbers” array.</p>
<p>So if I were to do something like:</p>
<pre><code> numbersCopy[2] = 0;
</code></pre>
<p>What would be the output for the following statements?</p>
<pre><code> System.out.println(numbers[2]);
System.out.println(numbersCopy[2]);
</code></pre>
<p>Considering both arrays point to the same reference we would get:</p>
<p>0</p>
<p>0</p>
<p>But what if we want to make a distinct copy of the first array with its own reference? Well in that case we would want to clone the array. In doing so each array will now have its own object reference. Let’s see how that will work.</p>
<pre><code> int [] numbers = { 2, 3, 4, 5};
int [] numbersClone = (int[])numbers.clone();
</code></pre>
<p>The “numbersClone” array now contains the same values, but in this case the array object itself points a different reference than the “numbers” array.</p>
<p>So if I were to do something like:</p>
<pre><code> numbersClone[2] = 0;
</code></pre>
<p>What would be the output now for the following statements?</p>
<pre><code> System.out.println(numbers[2]);
System.out.println(numbersClone[2]);
</code></pre>
<p>You guessed it:</p>
<p>4</p>
<p>0</p>
<p><a href="http://geekswithblogs.net/dforhan/archive/2005/12/01/61852.aspx" rel="noreferrer">Source</a></p> |
1,698,076 | What is the difference between <pubDate> and <lastBuildDate> in RSS? | <p>I have the feeling, in every RSS.xml file, both the pubDate and the lastBuildDate match.</p>
<p>I am sure that this one, is not always true... </p>
<p>So firstly, what is the difference between those two above?</p>
<p>Secondly, the RSS readers, sort the content by Date, based on the pubDate or the lastBuildDate?</p> | 1,698,108 | 5 | 1 | null | 2009-11-08 22:01:01.077 UTC | 1 | 2017-02-17 19:55:00.563 UTC | 2012-01-08 16:16:19.613 UTC | null | 71,515 | null | 59,314 | null | 1 | 40 | rss|feed | 24,639 | <p><strong>pubDate:</strong></p>
<p>The original publication date for the channel or item. (optional)</p>
<p><strong>lastBuildDate:</strong></p>
<p>The most recent time the content of the channel was modified. (optional)</p>
<hr>
<p>Here are some docs for the <a href="http://cyber.law.harvard.edu/rss/rss.html#optionalChannelElements" rel="noreferrer">optional items in the RSS 2.0 spec</a>.</p> |
1,414,125 | How do I run all my PHPUnit tests? | <p>I have script called Script.php and tests for it in Tests/Script.php, but when I run phpunit Tests it does not execute any tests in my test file. How do I run all my tests with phpunit?</p>
<p>PHPUnit 3.3.17, PHP 5.2.6-3ubuntu4.2, latest Ubuntu</p>
<p><strong>Output:</strong></p>
<pre><code>$ phpunit Tests
PHPUnit 3.3.17 by Sebastian Bergmann.
Time: 0 seconds
OK (0 tests, 0 assertions)
</code></pre>
<p>And here are my script and test files:</p>
<p><strong>Script.php</strong></p>
<pre><code><?php
function returnsTrue() {
return TRUE;
}
?>
</code></pre>
<p><strong>Tests/Script.php</strong></p>
<pre><code><?php
require_once 'PHPUnit/Framework.php';
require_once 'Script.php'
class TestingOne extends PHPUnit_Framework_TestCase
{
public function testTrue()
{
$this->assertEquals(TRUE, returnsTrue());
}
public function testFalse()
{
$this->assertEquals(FALSE, returnsTrue());
}
}
class TestingTwo extends PHPUnit_Framework_TestCase
{
public function testTrue()
{
$this->assertEquals(TRUE, returnsTrue());
}
public function testFalse()
{
$this->assertEquals(FALSE, returnsTrue());
}
}
?>
</code></pre> | 1,415,258 | 5 | 0 | null | 2009-09-12 02:54:32.84 UTC | 13 | 2013-04-13 08:56:41.977 UTC | null | null | null | null | 172,365 | null | 1 | 51 | php|linux|unit-testing|ubuntu|phpunit | 58,301 | <p>I created following <strong>phpunit.xml</strong> and now atleast I can do <em>phpunit --configuration phpunit.xml</em> in my root directory to run the tests located in Tests/</p>
<pre><code><phpunit backupGlobals="false"
backupStaticAttributes="false"
syntaxCheck="false">
<testsuites>
<testsuite name="Tests">
<directory suffix=".php">Tests</directory>
</testsuite>
</testsuites>
</phpunit>
</code></pre> |
1,928,675 | ServletRequest.getParameterMap() returns Map<String, String[]> and ServletRequest.getParameter() returns String? | <p>Can someone explain to me why <code>ServletRequest.getParameterMap()</code> returns type </p>
<pre><code>Map<String, String[]>
</code></pre>
<p><code>ServletRequest.getParameter()</code> just returns type <code>String</code></p>
<p>I'm don't understand why the map would ever map to more then one value. TIA.</p> | 1,928,707 | 5 | 0 | null | 2009-12-18 14:54:49.78 UTC | 8 | 2012-04-24 05:20:56.743 UTC | null | null | null | null | 227,986 | null | 1 | 51 | java|servlets | 49,710 | <p>It returns all parameter values for controls with the <strong>same</strong> name. </p>
<p>For example:</p>
<pre class="lang-html prettyprint-override"><code><input type="checkbox" name="cars" value="audi" /> Audi
<input type="checkbox" name="cars" value="ford" /> Ford
<input type="checkbox" name="cars" value="opel" /> Opel
</code></pre>
<p>or</p>
<pre class="lang-html prettyprint-override"><code><select name="cars" multiple>
<option value="audi">Audi</option>
<option value="ford">Ford</option>
<option value="opel">Opel</option>
</select>
</code></pre>
<p>Any checked/selected values will come in as:</p>
<pre><code>String[] cars = request.getParameterValues("cars");
</code></pre>
<p>It's also useful for multiple selections in tables:</p>
<pre class="lang-html prettyprint-override"><code><table>
<tr>
<th>Delete?</th>
<th>Foo</th>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td><input type="checkbox" name="delete" value="${item.id}"></td>
<td>${item.foo}</td>
</tr>
</c:forEach>
</table>
</code></pre>
<p>in combination with</p>
<pre><code>itemDAO.delete(request.getParameterValues("delete"));
</code></pre> |
1,493,913 | How to set the maximum memory usage for JVM? | <p>I want to limit the maximum memory used by the JVM. Note, this is not just the heap, I want to limit the total memory used by this process.</p> | 1,493,951 | 5 | 0 | null | 2009-09-29 17:24:55.137 UTC | 25 | 2021-10-29 22:48:36.263 UTC | null | null | null | null | 56,952 | null | 1 | 158 | java|memory|memory-management|memory-leaks|profiling | 348,085 | <p>use the arguments <code>-Xms<memory></code> <code>-Xmx<memory></code>. Use <code>M</code> or <code>G</code> after the numbers for indicating Megs and Gigs of bytes respectively. <code>-Xms</code> indicates the minimum and <code>-Xmx</code> the maximum.</p> |
1,907,993 | Autoreload of modules in IPython | <p>Is there a way to have IPython automatically reload all changed code? Either before each line is executed in the shell or failing that when it is specifically requested to. I'm doing a lot of exploratory programming using IPython and SciPy and it's quite a pain to have to manually reload each module whenever I change it.</p> | 10,472,712 | 6 | 2 | null | 2009-12-15 14:55:51.017 UTC | 155 | 2021-12-07 04:37:29.82 UTC | 2019-07-03 10:51:02.977 UTC | null | 6,866,692 | null | 65,130 | null | 1 | 271 | python|jupyter-notebook|ipython | 223,115 | <p>For IPython version 3.1, 4.x, and 5.x</p>
<pre><code>%load_ext autoreload
%autoreload 2
</code></pre>
<p>Then your module will be <strong>auto-reloaded</strong> by default. This is the doc:</p>
<pre><code>File: ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py
Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.
This makes for example the following workflow possible:
.. sourcecode:: ipython
In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: from foo import some_function
In [4]: some_function()
Out[4]: 42
In [5]: # open foo.py in an editor and change some_function to return 43
In [6]: some_function()
Out[6]: 43
The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.
</code></pre>
<p>There is a trick: when you <strong>forget all</strong> of the above when using <code>ipython</code>, just try:</p>
<pre><code>import autoreload
?autoreload
# Then you get all the above
</code></pre> |
1,907,565 | C and Python - different behaviour of the modulo (%) operation | <p>I have found that the same mod operation produces different results depending on what language is being used.</p>
<p>In Python:</p>
<pre><code>-1 % 10
</code></pre>
<p>produces <strong>9</strong></p>
<p>In C it produces <strong>-1</strong> !</p>
<ol>
<li>Which one is the right modulo? <br></li>
<li>How to make mod operation in C to be the same like in Python?</li>
</ol> | 1,907,585 | 6 | 0 | null | 2009-12-15 13:46:07.003 UTC | 36 | 2018-06-20 22:54:56.433 UTC | 2018-05-07 21:16:47.297 UTC | null | 12,892 | null | 215,571 | null | 1 | 73 | python|c|math|modulo | 22,465 | <ol>
<li>Both variants are correct, however in mathematics (number theory in particular), Python's <a href="http://en.wikipedia.org/wiki/Modulo_operation" rel="noreferrer">modulo</a> is most commonly used.</li>
<li>In C, you do <code>((n % M) + M) % M</code> to get the same result as in Python. E. g. <code>((-1 % 10) + 10) % 10</code>. Note, how it still works for positive integers: <code>((17 % 10) + 10) % 10 == 17 % 10</code>, as well as for both variants of C implementations (positive or negative remainder).</li>
</ol> |
1,953,377 | How to determine programmatically whether a particular process is 32-bit or 64-bit | <p>How can my C# application check whether a particular application/process (note: not the current process) is running in 32-bit or 64-bit mode? </p>
<p>For example, I might want to query a particular process by name, i.e, 'abc.exe', or based on the process ID number.</p> | 1,953,411 | 7 | 3 | null | 2009-12-23 15:18:31.177 UTC | 27 | 2021-03-19 22:13:07.05 UTC | 2015-10-19 03:05:57.737 UTC | null | 886,887 | null | 448,430 | null | 1 | 108 | c#|process|32bit-64bit | 92,745 | <p>One of the more interesting ways I've seen is this:</p>
<pre><code>if (IntPtr.Size == 4)
{
// 32-bit
}
else if (IntPtr.Size == 8)
{
// 64-bit
}
else
{
// The future is now!
}
</code></pre>
<p>To find out if OTHER processes are running in the 64-bit emulator (WOW64), use this code:</p>
<pre><code>namespace Is64Bit
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static class Program
{
private static void Main()
{
foreach (var p in Process.GetProcesses())
{
try
{
Console.WriteLine(p.ProcessName + " is " + (p.IsWin64Emulator() ? string.Empty : "not ") + "32-bit");
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode != 0x00000005)
{
throw;
}
}
}
Console.ReadLine();
}
private static bool IsWin64Emulator(this Process process)
{
if ((Environment.OSVersion.Version.Major > 5)
|| ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1)))
{
bool retVal;
return NativeMethods.IsWow64Process(process.Handle, out retVal) && retVal;
}
return false; // not on 64-bit Windows Emulator
}
}
internal static class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
}
}
</code></pre> |
1,532,133 | VBScript : checking if the user input is an integer | <p>Within a VBScript, I need to make sure the user inputs a integer.</p>
<p>Here is what I have now :</p>
<pre><code>WScript.Echo "Enter an integer number : "
Number = WScript.StdIn.ReadLine
If IsNumeric(Number) Then
' Here, it still could be an integer or a floating point number
If CLng(Number) Then
WScript.Echo "Integer"
Else
WScript.Echo "Not an integer"
End If
End if
</code></pre>
<p>The problem is that CLng() doesn't test if my number is an integer : the number is converted anyway.</p>
<p>Is there a way to check if a number is an integer ?</p>
<p><strong>EDIT :</strong></p>
<p>The suggested answer doesn't work as well for me. Here is a new version of my code :</p>
<pre><code>WScript.Echo "Enter an integer number : "
Number = WScript.StdIn.ReadLine
If IsNumeric(Number) Then
' Here, it still could be an integer or a floating point number
If Number = CLng(Number) Then
WScript.Echo "Integer"
Else
WScript.Echo "Not an integer"
End If
End if
</code></pre>
<p>and here is the output :</p>
<pre><code>U:\>cscript //nologo test.vbs
Enter an integer number :
12
Not an integer
U:\>cscript //nologo test.vbs
Enter an integer number :
3.45
Not an integer
</code></pre> | 1,532,392 | 8 | 0 | null | 2009-10-07 14:50:16.737 UTC | 1 | 2022-02-24 21:37:41.103 UTC | 2009-10-08 06:44:37.343 UTC | null | 2,796 | null | 2,796 | null | 1 | 21 | vbscript | 88,019 | <p>This is very similar to your code:</p>
<pre><code>WScript.Echo "Enter an integer number : "
Number = WScript.StdIn.ReadLine
If IsNumeric(Number) Then
' Here, it still could be an integer or a floating point number
If CLng(Number) = Number Then
WScript.Echo "Integer"
Else
WScript.Echo "Not an integer"
End If
End If
</code></pre> |
1,417,346 | iPhone - UILabel containing text with multiple fonts at the same time | <p>I am looking for a way to use a UILabel (or something similar) to display something like this:</p>
<p><strong>Tom:</strong> Some message.</p>
<p>It is like how it's done in for example the Facebook app to display the "what's on your mind?" messages. Does anyone have any suggestions how to approach this?</p> | 1,417,365 | 10 | 3 | null | 2009-09-13 10:02:21.06 UTC | 37 | 2018-10-27 16:47:56.943 UTC | null | null | null | null | 109,774 | null | 1 | 68 | iphone|objective-c|uilabel | 74,077 | <p>Use two UILabel IBOutlets, each with a different format (font/color/etc), as you desire.. Move the second one over the first based on where the first one's text ends. You can get that via sizeWithFont:forWidth:lineBreakMode:</p>
<p>Alternatively, you can subclass UILabel, and draw the text yourself in drawRect. If you do it this way, just add an instance variable to tell you how much of the string to draw in one format, and draw the rest in another.</p>
<p>Update: Please see @Akshay's response below. As of iOS6 UILabel's can contain NSMutableAttributedString. When I wrote this, this was not available.</p> |
1,422,003 | SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6) | <p>Some weird error cropped up suddenly outta nowhere and is preventing me from checking in my code via TortoiseSVN. I'm using a free account on myversioncontrol.com</p>
<p>This is on a Windows Vista system. It was working fine till earlier in the day. Any clue how to get things back to normal?</p>
<p>The Tortoise window shows this</p>
<pre><code>Command: Commit
Modified: ...\edit.php
Sending content: ...\edit.php
Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: n/a (6).
Finished!:
</code></pre> | 1,422,018 | 12 | 0 | null | 2009-09-14 14:43:19.857 UTC | 3 | 2018-11-19 12:57:50.59 UTC | 2015-03-02 11:31:34.583 UTC | null | 761,095 | null | 128,500 | null | 1 | 25 | svn|tortoisesvn|pre-commit | 109,150 | <p>Sounds like myversioncontrol.com have added a pre-commit hook, or have one that is now failing. If it's a free account, it might be you've exceeded some sort of monthly commit or bandwidth limit. Check their terms of service and/or contact them to see what's up.</p>
<p>UPDATE:<br>
I've just checked their website, and it looks like the free account is only valid for 30 days, so you might've exceeded that. You may need to pony up the £3.50pcm or find somewhere else (Google Code is one suggestion, though there are others).</p>
<p>Simon Groenewolt makes a good point that you may have changed something in the control panel on their website that has turned on a pre-commit hook but where it's configured incorrectly.</p> |
1,657,232 | How can I calculate an MD5 checksum of a directory? | <p>I need to calculate a summary MD5 checksum for all files of a particular type (<code>*.py</code> for example) placed under a directory and all sub-directories.</p>
<p>What is the best way to do that?</p>
<hr/>
<p>The proposed solutions are very nice, but this is not exactly what I need. I'm looking for a solution to get a <strong>single summary</strong> checksum which will uniquely identify the directory as a whole - including content of all its subdirectories.</p> | 1,658,554 | 16 | 6 | null | 2009-11-01 14:00:33.507 UTC | 77 | 2022-06-29 08:09:52.1 UTC | 2021-11-01 17:54:42.4 UTC | null | 63,550 | null | 140,995 | null | 1 | 145 | linux|directory|md5sum | 161,234 | <pre><code>find /path/to/dir/ -type f -name "*.py" -exec md5sum {} + | awk '{print $1}' | sort | md5sum
</code></pre>
<p>The <em><a href="https://linux.die.net/man/1/find" rel="nofollow noreferrer">find</a></em> command lists all the files that end in .py.
The MD5 hash value is computed for each .py file. AWK is used to pick off the MD5 hash values (ignoring the filenames, which may not be unique).
The MD5 hash values are sorted. The MD5 hash value of this sorted list is then returned.</p>
<p>I've tested this by copying a test directory:</p>
<pre><code>rsync -a ~/pybin/ ~/pybin2/
</code></pre>
<p>I renamed some of the files in <em>~/pybin2</em>.</p>
<p>The <code>find...md5sum</code> command returns the same output for both directories.</p>
<pre><code>2bcf49a4d19ef9abd284311108d626f1 -
</code></pre>
<p>To take into account the file layout (paths), so the checksum changes if a file is renamed or moved, the command can be simplified:</p>
<pre><code>find /path/to/dir/ -type f -name "*.py" -exec md5sum {} + | md5sum
</code></pre>
<p>On macOS with <code>md5</code>:</p>
<pre><code>find /path/to/dir/ -type f -name "*.py" -exec md5 {} + | md5
</code></pre> |
33,820,979 | Calculate & Display percentage of progress of page load | <p>I have a loader which loads when page loads at the starting. I need to show the percentage of completion in it.</p>
<p>My application has lots of jquery and css included in it and it also include a ajax call.</p>
<p>As of now, I have displayed the progress bar when page load starts and hided it when the ajax completed successfully.</p>
<p>Also, I have displayed the percentage but increased it manually using the below code:</p>
<pre><code>function timeout_trigger() {
$(".progress").css("max-width", p + "%");
$(".progress-view").text(p + "%");
if (p != 100) {
setTimeout('timeout_trigger()', 50);
}
p++;
}
timeout_trigger();
</code></pre>
<p>The problem here is, before the progress reaches 100, the page loads and the content is displayed and hence the loader is hided in between let say - at 60% - the loader is hided.</p>
<p>I want to calculate the percentage of page load completion (ie. jquery loading time, css loading time etc) dynamically and increase the progress accordingly.</p>
<p>Please help to get through this..</p> | 33,821,091 | 2 | 3 | null | 2015-11-20 07:16:39.38 UTC | 10 | 2017-05-02 00:39:49.927 UTC | 2017-05-02 00:39:49.927 UTC | null | 2,323,059 | null | 3,211,705 | null | 1 | 13 | javascript|jquery|html|css|ajax | 63,368 | <pre><code>function timeout_trigger() {
$(".progress").css("max-width",p+"%");
$(".progress-view").text(p+"%");
if(p!=100) {
setTimeout('timeout_trigger()', 50);
}
p++;
}
timeout_trigger();
</code></pre>
<p>This code will work only when you download 1% per 50ms, if download goes faster - if will fail.</p>
<p>It must be something like this:</p>
<pre><code>var size = file.getsize(); // file size
function timeout_trigger() {
var loaded = file.getLoaded(); // loaded part
p = parseInt(loaded / size);
$(".progress").css("max-width",p+"%");
$(".progress-view").text(p+"%");
if(p!=100) {
setTimeout('timeout_trigger()', 20);
}
}
timeout_trigger();
</code></pre>
<p>To realise method <code>getLoaded()</code> you can use AJAX event <code>onprogress</code> (I hope you are loading files async). Check <strong>Monitoring Progress</strong> part here <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest</a></p> |
8,577,627 | ScintillaNET vs AvalonEdit for providing scripting interface for a WPF Application | <p>I am working on a project which includes implementing a scripting interface for my WPF (.Net4) windows Application. I am curious if anyone can suggest a preferred editor, <a href="http://wiki.sharpdevelop.net/AvalonEdit.ashx" rel="noreferrer">AvalonEdit</a> vs <a href="http://scintillanet.codeplex.com/" rel="noreferrer">ScintillaNET</a>. Any pitfalls and advantages of one over the other. We need to support both C# and IronPython as scripting languages. (At least that is the initial plan. We might finalize on one of it though).</p>
<p>One of the downsides of ScintillaNET is that it is just a managed wrapper around the native (unmanaged) Scintilla. Is this going to cause any issues when used with WPF4.</p>
<p>Any pointers and suggestions are appreciated.</p> | 8,711,597 | 1 | 2 | null | 2011-12-20 15:17:25.707 UTC | 9 | 2012-01-03 11:29:16.94 UTC | null | null | null | null | 249,198 | null | 1 | 16 | c#|scripting|ironpython|scintilla|avalonedit | 9,077 | <p>I think this depends on how many features you want to implement in the editor. Also how much work you are willing to put in to extend it and how much of a learning curve you are willing to deal with.</p>
<p>If you are targetting Win32 and you don't mind the unmanaged dll then I think Scintilla.NET won't be a problem. Also you can easily host it in WPF as <a href="http://msdn.microsoft.com/en-us/library/ms751761.aspx">this</a> page suggests.</p>
<p>Personally I felt that Scintilla performs better than AvalonEdit. It also is easier to get started with a basic editor, and provides a lot out of the box, for instance Scintilla provides code folding out of the box.</p>
<p>With AvalonEdit you have to create a folding strategy and parse the document yourself, This is what I had to do to support IronPython for AvalonEdit which I haven't implemented yet.</p>
<p>All I needed to support an IronPython editor in scintilla was the SciLexer.dll in the search path and the Scintilla.net assembly and the following configuration:</p>
<pre><code>private void Form1_Load(object sender, EventArgs e)
{
this.scintilla1 = new ScintillaNet.Scintilla();
this.scintilla1.ConfigurationManager.Language = "python";
this.scintilla1.Indentation.ShowGuides = true;
this.scintilla1.Indentation.SmartIndentType = ScintillaNet.SmartIndent.Simple;
this.scintilla1.Location = new System.Drawing.Point(0, 0);
this.scintilla1.Margins.Margin0.Width = 40;
this.scintilla1.Margins.Margin2.Width = 20;
this.scintilla1.Name = "scintilla1";
this.scintilla1.TabIndex = 4;
this.scintilla1.Whitespace.Mode = ScintillaNet.WhitespaceMode.VisibleAfterIndent;
this.scintilla1.Dock = DockStyle.Fill;
this.Controls.Add(this.scintilla1);
}
</code></pre>
<p>For AvalonEdit you have to load an external highlighter file, you can see the <a href="http://jonsblogat.blogspot.com/2011/06/adding-scripting-support-to-wpf.html">this</a> blog post for more info. So if you want the basics (highlighting, folding for python+c#) my conclusion is schintilla is easier and performs better. Although with AvalonEdit you might be able to do more in the end if you are willing to put in the effort and deal with the learning curve. At the moment I am using Scintilla as my stable editor and am experimenting with Avalon as a proof of concept. Perhaps I will form new opinions too as I learn more about the editor.</p>
<p>Good luck</p> |
8,614,423 | How to change one element while hovering over another | <p>I have looked at several other questions but I can't seem to figure any of them out, so here is my problem: I would like to have a <code>div</code> or a <code>span</code>, when you hover over it an area would appear and would be like a drop down.</p>
<p>Such as I have an <code>div</code>, and I want to hover over it and have it show some info about the item I hovered over</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Question1</title>
<styles type="css/text">
#cheetah {
background-color: red;
color: yellow;
text-align: center;
}
a {
color: blue;
}
#hidden {
background-color: black;
}
a:hover > #hidden {
background-color: orange;
color: orange;
}
</styles>
</head>
<body>
<div id="cheetah">
<p><a href="#">Cheetah</a></p>
</div>
<div id="hidden">
<p>A cheetah is a land mammal that can run up 2 60mph!!!</p>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>But this ^ doesn't seem to work, I don't know why... and if there is a way to do that in CSS, I would like to know, but I want any and all suggestions.</p> | 8,614,540 | 4 | 2 | null | 2011-12-23 09:43:18.487 UTC | 6 | 2021-04-23 12:06:52.13 UTC | 2021-04-23 12:06:52.13 UTC | null | 6,364,190 | null | 1,113,135 | null | 1 | 31 | html|css | 58,044 | <p>You can achieve this in CSS only if the hidden div is a child of the element you use for hovering:</p>
<p><a href="http://jsfiddle.net/LgKkU/">http://jsfiddle.net/LgKkU/</a></p> |
17,990,647 | npm install errors with Error: ENOENT, chmod | <p>I am trying to globally install an npm module I just published. Every time I try to install, either from npm or the folder, I get this error.</p>
<pre><code>npm ERR! Error: ENOENT, chmod '/usr/local/lib/node_modules/takeapeek/lib/cmd.js'
npm ERR! If you need help, you may report this log at:
npm ERR! <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR! <[email protected]>
npm ERR! System Linux 3.8.0-19-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "takeapeek"
npm ERR! cwd /home/giodamlio
npm ERR! node -v v0.10.6
npm ERR! npm -v 1.3.6
npm ERR! path /usr/local/lib/node_modules/takeapeek/lib/cmd.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/giodamlio/npm-debug.log
npm ERR! not ok code 0
</code></pre>
<p>I am using sudo and I have triple checked everything in the package everything should work. I did some searching around, and saw a couple of similer cases none of which have been resolved. Here is what I tried.</p>
<ul>
<li>Upgrade npm (<code>sudo npm install -g npm</code>)</li>
<li>Clear the global npm cache (<code>sudo npm cache clear</code>)</li>
<li>Clear the user npm cache (<code>npm cache clear</code>)</li>
</ul>
<p>I noticed that the error had to do with the file I am linking to the path, specifically when npm tried to do a chmod. That shouldn't be a problem, my <code>lib/cli.js</code> has normal permissions, and npm has superuser permissions during this install.</p>
<p>After digging through the npm docs I found an option that would stop npm from making the bin links(<code>--no-bin-links</code>), when I tried the install with it, it worked fine.</p>
<p>So what's the deal? Is this some <a href="https://github.com/isaacs/npm/issues/3311#issuecomment-16011860" rel="noreferrer">weird fringe case bug</a> that has no solution yet?</p>
<p><strong>Edit: For reference, <a href="https://github.com/giodamelio/takeapeek" rel="noreferrer">here</a> is the module I uploaded</strong></p> | 18,020,195 | 44 | 9 | null | 2013-08-01 09:49:10.76 UTC | 42 | 2022-09-10 11:04:53.48 UTC | 2015-12-16 18:08:49.327 UTC | null | 123,671 | null | 375,847 | null | 1 | 173 | node.js|permissions|installation|npm|sudo | 472,248 | <p>Ok it looks like NPM is using your <code>.gitignore</code> as a base for the <code>.npmignore</code> file, and thus ignores <code>/lib</code>. If you add a blank <code>.npmignore</code> file into the root of your application, everything should work.</p>
<p>A better, more explicit approach is to use an allow-list rather than a disallow-list, and use the "files" field in package.json to specify the files in your package.</p>
<p>[edit] - more info on this behaviour here: <a href="https://docs.npmjs.com/cli/v7/using-npm/developers#keeping-files-out-of-your-package" rel="noreferrer">https://docs.npmjs.com/cli/v7/using-npm/developers#keeping-files-out-of-your-package</a></p> |
44,821,561 | How to set proxy host on HttpClient request in Java | <p>I want to set proxy before sending <code>HttpClient</code> request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that. </p>
<p>Curl command:</p>
<pre><code>**curl -I -x IP:80 URL**
</code></pre>
<p>Code change done in java file:</p>
<pre><code>HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
</code></pre>
<p>With above code changes in my java file I am getting below error :</p>
<pre><code>java.net.ConnectException: Connection refused (Connection refused)
</code></pre>
<p>Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.</p> | 44,891,163 | 4 | 7 | null | 2017-06-29 09:39:23.343 UTC | 2 | 2020-04-06 12:08:58.19 UTC | 2020-04-06 12:08:58.19 UTC | null | 7,917,574 | null | 2,618,323 | null | 1 | 9 | java|http|apache-commons-httpclient | 59,534 | <p>I think this could be helpful:</p>
<pre><code>HttpClient client = new HttpClient();
HostConfiguration config = client.getHostConfiguration();
config.setProxy("someProxyURL", "someProxyPort");
Credentials credentials = new UsernamePasswordCredentials("username", "password");
AuthScope authScope = new AuthScope("someProxyURL", "someProxyPort");
client.getState().setProxyCredentials(authScope, credentials);
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
</code></pre> |
6,389,039 | How Google Voice Search works? Is there an API for that? | <p>I'm not sure if this is the right site for this question, but I was wondering how the voice activated search on Google's homepage works. Does it use Flash, some kind of plugin built into Google Chrome, or how does it use the microphone? This could be a dangerous privacy invasion if it is allowed to work the same way on any website, because no dialog asking for permission comes up, and I find this startling that Google (and who knows what other sites) can use my microphone without my permission. How is Google doing this? Javascript? Actionscript? Some custom plugin?</p> | 6,391,490 | 3 | 6 | null | 2011-06-17 16:47:11.977 UTC | 15 | 2015-02-25 21:44:51.71 UTC | null | null | null | null | 435,224 | null | 1 | 30 | javascript|html|voice-recognition | 27,045 | <p>It's available to anyone. There's more information here:</p>
<p><a href="http://chrome.blogspot.com/2011/04/everybodys-talking-and-translating-with.html" rel="noreferrer">http://chrome.blogspot.com/2011/04/everybodys-talking-and-translating-with.html</a></p>
<p>and an example here:
<a href="http://www.web2voice.com/chrome-speech-input.html" rel="noreferrer">http://www.web2voice.com/chrome-speech-input.html</a></p>
<p>I'm glad I'm not the only one who thinks the lack of a permissions prompt feels a little bit big-brother-esque. </p> |
6,554,805 | Getting a callback when a Tkinter Listbox selection is changed? | <p>There are a number of ways of getting callbacks when <code>Text</code> or <code>Entry</code> widgets are changed in Tkinter, but I haven't found one for <code>Listbox</code>'s (it doesn't help that much of the event documentation I can find is old or incomplete). Is there some way of generating an event for this?</p> | 6,557,251 | 3 | 1 | null | 2011-07-02 02:45:06.727 UTC | 14 | 2022-03-29 16:06:30.38 UTC | null | null | null | null | 417,803 | null | 1 | 57 | python|events|tkinter | 72,226 | <p>You can bind to the <code><<ListboxSelect>></code> event. This event will be generated whenever the selection changes, whether it changes from a button click, via the keyboard, or any other method.</p>
<p>Here's a simple example which updates a label whenever you select something from the listbox:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
label = tk.Label(root)
listbox = tk.Listbox(root)
label.pack(side="bottom", fill="x")
listbox.pack(side="top", fill="both", expand=True)
listbox.insert("end", "one", "two", "three", "four", "five")
def callback(event):
selection = event.widget.curselection()
if selection:
index = selection[0]
data = event.widget.get(index)
label.configure(text=data)
else:
label.configure(text="")
listbox.bind("<<ListboxSelect>>", callback)
root.mainloop()
</code></pre>
<p><a href="https://i.stack.imgur.com/MlsPy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MlsPy.png" alt="screenshot" /></a></p>
<p>This event is mentioned in the canonical <a href="http://tcl.tk/man/tcl8.5/TkCmd/listbox.htm#M50" rel="noreferrer">man page for listbox</a>. All predefined virtual events can be found on the <a href="http://www.tcl.tk/man/tcl8.5/TkCmd/event.htm#M41" rel="noreferrer">bind man page</a>.</p> |
56,899,871 | Unable to start embedded Tomcat org.springframework.context.ApplicationContextException | <p>Started working with spring boot recently. Trying to create a simple login so I can start to migrate my spring mvc project to spring boot. However keep getting the error :</p>
<blockquote>
<p>unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat.</p>
</blockquote>
<p>I have gone through all of the stackoverflow and articles related to Unable to start embedded tomcat. For example, I have tried changing the <code>pom.xml</code> to older versions, I have tried changing the port as some said that may be the problem and I have tried changing the annotated call at the start of the spring boot controller to <code>@EnableAutoConfiguration</code> and <code>@SpringBootApplication</code> this doesn't seem to change the error log at all.</p>
<p>I have also tried changing the java version and have tried it by using both java 8 and 10.</p>
<p><code>POM.XML</code> - From <a href="https://start.spring.io/" rel="noreferrer">https://start.spring.io/</a></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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bottomline</groupId>
<artifactId>flashcards</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>flashcards</name>
<description>Test</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>MainController.java</p>
<pre><code>package com.bottomline.flashcards.controller;
import java.security.Principal;
import com.bottomline.flashcards.utils.WebUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@EnableAutoConfiguration
@Controller
public class MainController {
@RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public String welcomePage(Model model) {
model.addAttribute("title", "Welcome");
model.addAttribute("message", "This is welcome page!");
return "welcomePage";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model, Principal principal) {
User loginedUser = (User) ((Authentication) principal).getPrincipal();
String userInfo = WebUtils.toString(loginedUser);
model.addAttribute("userInfo", userInfo);
return "adminPage";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model) {
return "loginPage";
}
@RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
public String logoutSuccessfulPage(Model model) {
model.addAttribute("title", "Logout");
return "logoutSuccessfulPage";
}
@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
public String userInfo(Model model, Principal principal) {
// (1) (en)
// After user login successfully.
// (vi)
// Sau khi user login thanh cong se co principal
String userName = principal.getName();
System.out.println("User Name: " + userName);
User loginedUser = (User) ((Authentication) principal).getPrincipal();
String userInfo = WebUtils.toString(loginedUser);
model.addAttribute("userInfo", userInfo);
return "userInfoPage";
}
@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(Model model, Principal principal) {
if (principal != null) {
User loginedUser = (User) ((Authentication) principal).getPrincipal();
String userInfo = WebUtils.toString(loginedUser);
model.addAttribute("userInfo", userInfo);
String message = "Hi " + principal.getName() //
+ "<br> You do not have permission to access this page!";
model.addAttribute("message", message);
}
return "403Page";
}
}
</code></pre>
<pre><code>SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
Jul 05, 2019 9:44:54 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
Jul 05, 2019 9:44:54 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.21]
Jul 05, 2019 9:44:54 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring embedded WebApplicationContext
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 05, 2019 9:45:04 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Tomcat]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
at com.bottomline.flashcards.FlashcardsApplication.main(FlashcardsApplication.java:11)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:124)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:86)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:414)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:178)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:179)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152)
... 8 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]: Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:211)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:202)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:96)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:85)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:252)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:226)
at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:53)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5132)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:456)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:105)
... 13 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:676)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:392)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
... 53 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:668)
... 76 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:224)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:411)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:344)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:337)
at org.springframework.orm.jpa.EntityManagerFactoryUtils.findEntityManagerFactory(EntityManagerFactoryUtils.java:120)
at org.springframework.orm.jpa.JpaTransactionManager.setBeanFactory(JpaTransactionManager.java:313)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1800)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1765)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
... 85 more
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
... 100 more
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 117 more
</code></pre>
<p>Any help would be great, please let me know if there isn't enough information.</p> | 56,903,229 | 5 | 7 | null | 2019-07-05 09:01:10.953 UTC | 3 | 2021-07-01 13:13:52.653 UTC | 2019-07-05 09:15:11.06 UTC | null | 2,226,388 | null | 8,875,041 | null | 1 | 19 | java|spring|maven|spring-boot | 148,441 | <p>First, you usually can find the root cause on <strong>last</strong> <code>Caused by</code> statement for debugging. </p>
<p>Therefore, according to the error log you posted, <code>Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set</code> should be key! </p>
<p>Although Hibernate is database agnostic, we can specify the current database dialect to let it generate better SQL queries for that database. Therefore, this exception can be solved by simply identifying <code>hibernate.dialect</code> in your properties file as follows: </p>
<p>For application.properties: </p>
<pre><code>spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
</code></pre>
<p>For application.yml: </p>
<pre><code>spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
</code></pre> |
45,836,397 | Coding pattern for random percentage branching? | <p>So let's say we have a code block that we want to execute 70% of times and another one 30% of times.</p>
<pre><code>if(Math.random() < 0.7)
70percentmethod();
else
30percentmethod();
</code></pre>
<p>Simple enough. But what if we want it to be easily expandable to say, 30%/60%/10% etc.?
Here it would require adding and changing all the if statements on change which isn't exactly great to use, slow and mistake inducing.</p>
<p>So far I've found large switches to be decently useful for this use case, for example:</p>
<pre><code>switch(rand(0, 10)){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:70percentmethod();break;
case 8:
case 9:
case 10:30percentmethod();break;
}
</code></pre>
<p>Which can be very easily changed to:</p>
<pre><code>switch(rand(0, 10)){
case 0:10percentmethod();break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:60percentmethod();break;
case 8:
case 9:
case 10:30percentmethod();break;
}
</code></pre>
<p>But these have their drawbacks as well, being cumbersome and split onto a predetermined amount of divisions.</p>
<p>Something ideal would be based on a "frequency number" system I guess, like so:</p>
<pre><code>(1,a),(1,b),(2,c) -> 25% a, 25% b, 50% c
</code></pre>
<p>then if you added another one:</p>
<pre><code>(1,a),(1,b),(2,c),(6,d) -> 10% a, 10% b, 20% c, 60% d
</code></pre>
<p>So simply adding up the numbers, making the sum equal 100% and then split that.</p>
<p>I suppose it wouldn't be that much trouble to make a handler for it with a customized hashmap or something, but I'm wondering if there's some established way/pattern or lambda for it before I go all spaghetti on this.</p> | 45,836,917 | 7 | 9 | null | 2017-08-23 09:52:21.973 UTC | 7 | 2017-12-21 13:28:32.553 UTC | 2017-08-23 19:21:04.573 UTC | null | 3,357,935 | null | 4,012,132 | null | 1 | 53 | java|design-patterns|random | 5,536 | <p><strong>EDIT:</strong> See edit at end for more elegant solution. I'll leave this in though.</p>
<p>You can use a <code>NavigableMap</code> to store these methods mapped to their percentages.</p>
<pre><code>NavigableMap<Double, Runnable> runnables = new TreeMap<>();
runnables.put(0.3, this::30PercentMethod);
runnables.put(1.0, this::70PercentMethod);
public static void runRandomly(Map<Double, Runnable> runnables) {
double percentage = Math.random();
for (Map.Entry<Double, Runnable> entry : runnables){
if (entry.getKey() < percentage) {
entry.getValue().run();
return; // make sure you only call one method
}
}
throw new RuntimeException("map not filled properly for " + percentage);
}
// or, because I'm still practicing streams by using them for everything
public static void runRandomly(Map<Double, Runnable> runnables) {
double percentage = Math.random();
runnables.entrySet().stream()
.filter(e -> e.getKey() < percentage)
.findFirst().orElseThrow(() ->
new RuntimeException("map not filled properly for " + percentage))
.run();
}
</code></pre>
<p>The <code>NavigableMap</code> is <em>sorted</em> (e.g. <code>HashMap</code> gives no guarantees of the entries) by keys, so you get the entries ordered by their percentages. This is relevant because if you have two items <em>(3,r1)</em>,<em>(7,r2)</em>, they result in the following entries: <code>r1 = 0.3</code> and <code>r2 = 1.0</code> and they need to be evaluated in this order (e.g. if they are evaluated in the reverse order the result would <em>always</em> be <code>r2</code>).</p>
<p>As for the splitting, it should go something like this:
With a Tuple class like this</p>
<pre><code>static class Pair<X, Y>
{
public Pair(X f, Y s)
{
first = f;
second = s;
}
public final X first;
public final Y second;
}
</code></pre>
<p><strong>You can create a map like this</strong></p>
<pre><code>// the parameter contains the (1,m1), (1,m2), (3,m3) pairs
private static Map<Double,Runnable> splitToPercentageMap(Collection<Pair<Integer,Runnable>> runnables)
{
// this adds all Runnables to lists of same int value,
// overall those lists are sorted by that int (so least probable first)
double total = 0;
Map<Integer,List<Runnable>> byNumber = new TreeMap<>();
for (Pair<Integer,Runnable> e : runnables)
{
total += e.first;
List<Runnable> list = byNumber.getOrDefault(e.first, new ArrayList<>());
list.add(e.second);
byNumber.put(e.first, list);
}
Map<Double,Runnable> targetList = new TreeMap<>();
double current = 0;
for (Map.Entry<Integer,List<Runnable>> e : byNumber.entrySet())
{
for (Runnable r : e.getValue())
{
double percentage = (double) e.getKey() / total;
current += percentage;
targetList.put(current, r);
}
}
return targetList;
}
</code></pre>
<p><strong>And all of this added to a class</strong></p>
<pre><code>class RandomRunner {
private List<Integer, Runnable> runnables = new ArrayList<>();
public void add(int value, Runnable toRun) {
runnables.add(new Pair<>(value, toRun));
}
public void remove(Runnable toRemove) {
for (Iterator<Pair<Integer, Runnable>> r = runnables.iterator();
r.hasNext(); ) {
if (toRemove == r.next().second) {
r.remove();
break;
}
}
}
public void runRandomly() {
// split list, use code from above
}
}
</code></pre>
<p><strong>EDIT :</strong><br>
Actually, the above is what you get if you get an idea stuck in your head and don't question it properly.
Keeping the <code>RandomRunner</code> class interface, this is much easier:</p>
<pre><code>class RandomRunner {
List<Runnable> runnables = new ArrayList<>();
public void add(int value, Runnable toRun) {
// add the methods as often as their weight indicates.
// this should be fine for smaller numbers;
// if you get lists with millions of entries, optimize
for (int i = 0; i < value; i++) {
runnables.add(toRun);
}
}
public void remove(Runnable r) {
Iterator<Runnable> myRunnables = runnables.iterator();
while (myRunnables.hasNext()) {
if (myRunnables.next() == r) {
myRunnables.remove();
}
}
public void runRandomly() {
if (runnables.isEmpty()) return;
// roll n-sided die
int runIndex = ThreadLocalRandom.current().nextInt(0, runnables.size());
runnables.get(runIndex).run();
}
}
</code></pre> |
19,053,707 | Converting Snake Case to Lower Camel Case (lowerCamelCase) | <p>What would be a good way to convert from snake case (<code>my_string</code>) to lower camel case (myString) in Python 2.7?</p>
<p>The obvious solution is to split by underscore, capitalize each word except the first one and join back together.</p>
<p>However, I'm curious as to other, more idiomatic solutions or a way to use <code>RegExp</code> to achieve this (with some case modifier?)</p> | 19,053,800 | 16 | 3 | null | 2013-09-27 14:48:06.153 UTC | 10 | 2022-04-13 07:27:57.81 UTC | 2015-12-14 07:21:02.433 UTC | null | 3,093,387 | null | 120,496 | null | 1 | 100 | python|python-2.7 | 65,051 | <pre><code>def to_camel_case(snake_str):
components = snake_str.split('_')
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + ''.join(x.title() for x in components[1:])
</code></pre>
<p>Example:</p>
<pre><code>In [11]: to_camel_case('snake_case')
Out[11]: 'snakeCase'
</code></pre> |
40,143,528 | hdfs dfs -mkdir, No such file or directory | <p>Hi I am new to hadoop and trying to create directory in hdfs called twitter_data.
I have set up my vm on softlayer, installed & started hadoop successfully. </p>
<p>This is the commend I am trying to run:</p>
<blockquote>
<p>hdfs dfs -mkdir hdfs://localhost:9000/user/Hadoop/twitter_data</p>
</blockquote>
<p>And it keeps returning this error message: </p>
<pre><code> /usr/local/hadoop/etc/hadoop/hadoop-env.sh: line 2: ./hadoop-env.sh: Permission denied
16/10/19 19:07:03 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
mkdir: `hdfs://localhost:9000/user/Hadoop/twitter_data': No such file or directory
</code></pre>
<p>Why does it say there is no such file and directory? I am ordering it to make directory, shouldn't it just create one? I am guessing it must be the permission issue, but I cant resolve it. Please help me hdfs experts. I have been spending too much time on what seems to be a simple matter.</p>
<p>Thanks in advance. </p> | 40,143,627 | 2 | 3 | null | 2016-10-20 00:18:37.57 UTC | 8 | 2017-03-12 09:20:01.147 UTC | null | null | null | null | 5,214,063 | null | 1 | 34 | hadoop|hdfs | 51,036 | <p>It is because the parent directories do not exist yet either. Try <code>hdfs dfs -mkdir -p /user/Hadoop/twitter_data</code>. The <code>-p</code> flag indicates that all nonexistent directories leading up to the given directory are to be created as well. </p>
<p>As for the question you posed in the comments, simply type into your browser <code>http://<host name of the namenode>:<port number>/</code>. </p> |
57,562,606 | Why does sync.Mutex largely drop performance when goroutine contention is more than 3400? | <p>I am comparing the performance regarding sync.Mutex and Go channels. Here is my benchmark:</p>
<pre><code>// go playground: https://play.golang.org/p/f_u9jHBq_Jc
const (
start = 300 // actual = start * goprocs
end = 600 // actual = end * goprocs
step = 10
)
var goprocs = runtime.GOMAXPROCS(0) // 8
// https://perf.golang.org/search?q=upload:20190819.3
func BenchmarkChanWrite(b *testing.B) {
var v int64
ch := make(chan int, 1)
ch <- 1
for i := start; i < end; i += step {
b.Run(fmt.Sprintf("goroutines-%d", i*goprocs), func(b *testing.B) {
b.SetParallelism(i)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
<-ch
v += 1
ch <- 1
}
})
})
}
}
// https://perf.golang.org/search?q=upload:20190819.2
func BenchmarkMutexWrite(b *testing.B) {
var v int64
mu := sync.Mutex{}
for i := start; i < end; i += step {
b.Run(fmt.Sprintf("goroutines-%d", i*goprocs), func(b *testing.B) {
b.SetParallelism(i)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
mu.Lock()
v += 1
mu.Unlock()
}
})
})
}
}
</code></pre>
<p>The performance comparison visualization is as follows:</p>
<p><a href="https://i.stack.imgur.com/Mt8Fh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mt8Fh.png" alt="enter image description here"></a></p>
<p>What are the reasons that </p>
<ol>
<li>sync.Mutex encounters a large performance drop when the number of goroutines goes higher than roughly 3400?</li>
<li>Go channels are pretty stable but slower than sync.Mutex before?</li>
</ol>
<p>Raw bench data by benchstat (go test -bench=. -count=5) <code>go version go1.12.4 linux/amd64</code>:</p>
<pre><code>MutexWrite/goroutines-2400-8 48.6ns ± 1%
MutexWrite/goroutines-2480-8 49.1ns ± 0%
MutexWrite/goroutines-2560-8 49.7ns ± 1%
MutexWrite/goroutines-2640-8 50.5ns ± 3%
MutexWrite/goroutines-2720-8 50.9ns ± 2%
MutexWrite/goroutines-2800-8 51.8ns ± 3%
MutexWrite/goroutines-2880-8 52.5ns ± 2%
MutexWrite/goroutines-2960-8 54.1ns ± 4%
MutexWrite/goroutines-3040-8 54.5ns ± 2%
MutexWrite/goroutines-3120-8 56.1ns ± 3%
MutexWrite/goroutines-3200-8 63.2ns ± 5%
MutexWrite/goroutines-3280-8 77.5ns ± 6%
MutexWrite/goroutines-3360-8 141ns ± 6%
MutexWrite/goroutines-3440-8 239ns ± 8%
MutexWrite/goroutines-3520-8 248ns ± 3%
MutexWrite/goroutines-3600-8 254ns ± 2%
MutexWrite/goroutines-3680-8 256ns ± 1%
MutexWrite/goroutines-3760-8 261ns ± 2%
MutexWrite/goroutines-3840-8 266ns ± 3%
MutexWrite/goroutines-3920-8 276ns ± 3%
MutexWrite/goroutines-4000-8 278ns ± 3%
MutexWrite/goroutines-4080-8 286ns ± 5%
MutexWrite/goroutines-4160-8 293ns ± 4%
MutexWrite/goroutines-4240-8 295ns ± 2%
MutexWrite/goroutines-4320-8 280ns ± 8%
MutexWrite/goroutines-4400-8 294ns ± 9%
MutexWrite/goroutines-4480-8 285ns ±10%
MutexWrite/goroutines-4560-8 290ns ± 8%
MutexWrite/goroutines-4640-8 271ns ± 3%
MutexWrite/goroutines-4720-8 271ns ± 4%
ChanWrite/goroutines-2400-8 158ns ± 3%
ChanWrite/goroutines-2480-8 159ns ± 2%
ChanWrite/goroutines-2560-8 161ns ± 2%
ChanWrite/goroutines-2640-8 161ns ± 1%
ChanWrite/goroutines-2720-8 163ns ± 1%
ChanWrite/goroutines-2800-8 166ns ± 3%
ChanWrite/goroutines-2880-8 168ns ± 1%
ChanWrite/goroutines-2960-8 176ns ± 4%
ChanWrite/goroutines-3040-8 176ns ± 2%
ChanWrite/goroutines-3120-8 180ns ± 1%
ChanWrite/goroutines-3200-8 180ns ± 1%
ChanWrite/goroutines-3280-8 181ns ± 2%
ChanWrite/goroutines-3360-8 183ns ± 2%
ChanWrite/goroutines-3440-8 188ns ± 3%
ChanWrite/goroutines-3520-8 190ns ± 2%
ChanWrite/goroutines-3600-8 193ns ± 2%
ChanWrite/goroutines-3680-8 196ns ± 3%
ChanWrite/goroutines-3760-8 199ns ± 2%
ChanWrite/goroutines-3840-8 206ns ± 2%
ChanWrite/goroutines-3920-8 209ns ± 2%
ChanWrite/goroutines-4000-8 206ns ± 2%
ChanWrite/goroutines-4080-8 209ns ± 2%
ChanWrite/goroutines-4160-8 208ns ± 2%
ChanWrite/goroutines-4240-8 209ns ± 3%
ChanWrite/goroutines-4320-8 213ns ± 2%
ChanWrite/goroutines-4400-8 209ns ± 2%
ChanWrite/goroutines-4480-8 211ns ± 1%
ChanWrite/goroutines-4560-8 213ns ± 2%
ChanWrite/goroutines-4640-8 215ns ± 1%
ChanWrite/goroutines-4720-8 218ns ± 3%
</code></pre>
<p>Go 1.12.4. Hardware:</p>
<pre><code>CPU: Quad core Intel Core i7-7700 (-MT-MCP-) cache: 8192 KB
clock speeds: max: 4200 MHz 1: 1109 MHz 2: 3641 MHz 3: 3472 MHz 4: 3514 MHz 5: 3873 MHz 6: 3537 MHz
7: 3410 MHz 8: 3016 MHz
CPU Flags: 3dnowprefetch abm acpi adx aes aperfmperf apic arat arch_perfmon art avx avx2 bmi1 bmi2
bts clflush clflushopt cmov constant_tsc cpuid cpuid_fault cx16 cx8 de ds_cpl dtes64 dtherm dts epb
ept erms est f16c flexpriority flush_l1d fma fpu fsgsbase fxsr hle ht hwp hwp_act_window hwp_epp
hwp_notify ibpb ibrs ida intel_pt invpcid invpcid_single lahf_lm lm mca mce md_clear mmx monitor
movbe mpx msr mtrr nonstop_tsc nopl nx pae pat pbe pcid pclmulqdq pdcm pdpe1gb pebs pge pln pni
popcnt pse pse36 pti pts rdrand rdseed rdtscp rep_good rtm sdbg sep smap smep smx ss ssbd sse sse2
sse4_1 sse4_2 ssse3 stibp syscall tm tm2 tpr_shadow tsc tsc_adjust tsc_deadline_timer tsc_known_freq
vme vmx vnmi vpid x2apic xgetbv1 xsave xsavec xsaveopt xsaves xtopology xtpr
</code></pre>
<hr>
<p>Update: I tested on different hardware. It seems the problem still exists:</p>
<p><a href="https://i.stack.imgur.com/lSVrQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lSVrQ.png" alt="enter image description here"></a></p>
<p>bench: <a href="https://play.golang.org/p/HnQ44--E4UQ" rel="noreferrer">https://play.golang.org/p/HnQ44--E4UQ</a></p>
<hr>
<p>Update:</p>
<p>My full benchmark that tested from 8 goroutines to 15000 goroutines, including a comparison on chan/sync.Mutex/atomic:</p>
<p><a href="https://i.stack.imgur.com/1gv21.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1gv21.png" alt="enter image description here"></a></p> | 57,670,078 | 2 | 4 | null | 2019-08-19 19:07:42.79 UTC | 16 | 2019-08-27 07:56:19.213 UTC | 2019-08-21 21:14:51.46 UTC | null | 3,819,460 | null | 3,819,460 | null | 1 | 26 | performance|go | 8,845 | <p>sync.Mutex 's implementation is based on runtime semaphore. The reason why it encounters massive performance decreases is that the implementation of <code>runtime.semacquire1</code>.</p>
<p>Now, let's sample two representative points, we use <code>go tool pprof</code> when the number of goroutines was equal to 2400 and 4800:</p>
<pre><code>goos: linux
goarch: amd64
BenchmarkMutexWrite/goroutines-2400-8 50000000 46.5 ns/op
PASS
ok 2.508s
BenchmarkMutexWrite/goroutines-4800-8 50000000 317 ns/op
PASS
ok 16.020s
</code></pre>
<p>2400:</p>
<p><a href="https://i.stack.imgur.com/gvbeD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gvbeD.png" alt="enter image description here"></a></p>
<p>4800:</p>
<p><a href="https://i.stack.imgur.com/hyUH1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hyUH1.png" alt="enter image description here"></a></p>
<p>As we can see, when the number of goroutines increased to 4800, the overhead of <code>runtime.gopark</code> becomes dominant. Let's dig more in the runtime source code and see who exactly calls <code>runtime.gopark</code>. In the <code>runtime.semacquire1</code>:</p>
<pre><code>func semacquire1(addr *uint32, lifo bool, profile semaProfileFlags, skipframes int) {
// fast path
if cansemacquire(addr) {
return
}
s := acquireSudog()
root := semroot(addr)
...
for {
lock(&root.lock)
atomic.Xadd(&root.nwait, 1)
if cansemacquire(addr) {
atomic.Xadd(&root.nwait, -1)
unlock(&root.lock)
break
}
// slow path
root.queue(addr, s, lifo)
goparkunlock(&root.lock, waitReasonSemacquire, traceEvGoBlockSync, 4+skipframes)
if s.ticket != 0 || cansemacquire(addr) {
break
}
}
...
}
</code></pre>
<p>Based on the pprof graph we presented above, we can conclude that:</p>
<ol>
<li><p>Observation: <code>runtime.gopark</code> calls rarely when 2400 #goroutines, and <code>runtime.mutex</code> calls heavily. We infer that most of the code is done before the slow path.</p></li>
<li><p>Observation: <code>runtime.gopark</code> calls heavily when 4800 #goroutines. We infer that most of the code was entering the slow path, and when we start using <code>runtime.gopark</code>, the runtime scheduler context switching costs must be considered.</p></li>
</ol>
<p>Considering channels in Go is implemented based on OS synchronization primitives without involving runtime scheduler, eg. Futex on Linux. Therefore its performance decreases linearly with the increasing of problem size.</p>
<p>The above explains the reason why we see a massive performance decrease in <code>sync.Mutex</code>.</p> |
57,592,530 | Latest Update brings Github error on pull, push, or sync | <p>In Visual Studio 2019, we have been using the GitHub extension successfully since before release. Now, all of the sudden, when we push, pull, or sync, we receive the following in the Output window:</p>
<pre><code>Warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
For security reasons, it is therefore ignored.
To fix this, please transfer ownership to an admininstrator.
</code></pre> | 57,624,911 | 11 | 5 | null | 2019-08-21 13:13:40.357 UTC | 10 | 2020-08-18 06:43:45.643 UTC | 2019-08-21 13:16:57.267 UTC | null | 9,020,340 | null | 3,487,602 | null | 1 | 36 | git|visual-studio|github|visual-studio-2019 | 30,295 | <p>You should check if 'C:\ProgramData/Git/config' actually exists. If it doesn't you can just create it and paste the following into the file:</p>
<pre><code>[core]
symlinks = false
autocrlf = true
fscache = true
[color]
diff = auto
status = auto
branch = auto
interactive = true
[help]
format = html
[rebase]
autosquash = true
</code></pre>
<p>This worked for me.</p> |
1,082,216 | GMail SMTP via C# .Net errors on all ports | <p>I've been trying for a whlie on this, and have so far been failing miserably. My most recent attempt was lifted from this stack code here: <a href="https://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-with-c">Sending email through Gmail SMTP server with C#</a>, but I've tried all the syntax I could find here on stack and elsewhere. My code currently is:</p>
<pre><code>var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "mypass"),
EnableSsl = true
};
client.Send("[email protected]","[email protected]","Test", "test message");
</code></pre>
<p>Running that code gives me an immediate exception "Failure sending mail" that has an innerexeption "unable to connect to the remote server".</p>
<p>If I change the port to 465 (as gmail docs suggest), I get a timeout every time.</p>
<p>I've read that 465 isn't a good port to use, so I'm wondering what the deal is w/ 587 giving me failure to connect. My user and pass are right. I've read that I have to have POP service setup on my gmail account, so I did that. No avail.</p>
<p>I was originally trying to get this working for my branded GMail account, but after running into the same problems w/ that I <em>thought</em> going w/ my regular gmail account would be easier... so far that's not the case.</p> | 1,082,251 | 7 | 1 | null | 2009-07-04 13:30:29.433 UTC | 11 | 2018-02-06 10:43:25.573 UTC | 2018-02-06 10:43:25.573 UTC | null | 206,730 | null | 53,788 | null | 1 | 12 | c#|.net|gmail | 34,298 | <p>I tried your code, and it works prefectly with port 587, but not with 465. </p>
<p>Have you checked the fire wall? Try from the command line "Telnet smtp.gmail.com 587"
If you get "220 mx.google.com ESMTP...." back, then the port is open. If not, it is something that blocks you call.</p>
<p>Daniel</p> |
1,333,813 | Recursively read folders and executes command on each of them | <p>I am trying to recurse into folders and then run commands on them, using bash script. Any suggestions?</p> | 1,333,837 | 7 | 3 | null | 2009-08-26 10:44:14.143 UTC | 18 | 2020-05-17 20:50:04.447 UTC | 2020-05-17 20:50:04.447 UTC | null | 1,892,051 | null | 158,997 | null | 1 | 44 | bash|shell | 73,075 | <p>If you want to recurse into directories, executing a command on each file found in those, I would use the <code>find</code> command, instead of writing anything using shell-script, I think.</p>
<p>That command can receive lots of parameters, like <code>type</code> to filter the types of files returned, or <code>exec</code> to execute a command on each result.</p>
<p><br>
For instance, to find directories that are under the one I'm currently in :</p>
<pre><code>find . -type d -exec echo "Hello, '{}'" \;
</code></pre>
<p>Which will get me somehthing like :</p>
<pre><code>Hello, '.'
Hello, './.libs'
Hello, './include'
Hello, './autom4te.cache'
Hello, './build'
Hello, './modules'
</code></pre>
<p><br>
Same to find the files under the current directory :</p>
<pre><code>find . -type f -exec echo "Hello, '{}'" \;
</code></pre>
<p>which will get me something like this :</p>
<pre><code>Hello, './config.guess'
Hello, './config.sub'
Hello, './.libs/memcache_session.o'
Hello, './.libs/memcache_standard_hash.o'
Hello, './.libs/memcache_consistent_hash.o'
Hello, './.libs/memcache.so'
Hello, './.libs/memcache.lai'
Hello, './.libs/memcache.o'
Hello, './.libs/memcache_queue.o'
Hello, './install-sh'
Hello, './config.h.in'
Hello, './php_memcache.h'
...
</code></pre>
<p><br>
Some would say "it's not shell"... But why re-invent the wheel ?
<br><em>(And, in a way, it is shell ^^ )</em></p>
<p><br>
For more informations, you can take a look at :</p>
<ul>
<li><code>man find</code></li>
<li>lots of tutorials found with google, like, for instance, <a href="http://www.softpanorama.org/Tools/Find/find_mini_tutorial.shtml" rel="noreferrer">Unix Find Command Tutorial</a></li>
</ul> |
126,279 | C99 stdint.h header and MS Visual Studio | <p>To my amazement I just discovered that the C99 stdint.h is missing from MS Visual Studio 2003 upwards. I'm sure they have their reasons, but does anyone know where I can download a copy? Without this header I have no definitions for useful types such as uint32_t, etc.</p> | 126,285 | 7 | 2 | null | 2008-09-24 09:53:01.89 UTC | 31 | 2022-02-12 23:07:43.12 UTC | null | null | null | Rob | 9,236 | null | 1 | 117 | c++|c|visual-studio|c99 | 142,551 | <p>Turns out you can download a MS version of this header from:</p>
<p><a href="https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h" rel="nofollow noreferrer">https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h</a></p>
<p>A portable one can be found here:</p>
<p><a href="http://www.azillionmonkeys.com/qed/pstdint.h" rel="nofollow noreferrer">http://www.azillionmonkeys.com/qed/pstdint.h</a></p>
<p>Thanks to the <a href="http://stephendoyle.blogspot.com/2008/03/c-tr1-stdinth-still-missing-from-visual.html" rel="nofollow noreferrer">Software Rambling</a>s blog.</p>
<p><em>NB:</em> The Public Domain version of the header, mentioned by <a href="https://stackoverflow.com/users/12711/michael-burr">Michael Burr</a> in a comment, can be find as an archived copy <a href="https://web.archive.org/web/20101104120614/http://snipplr.com/view/18199/stdinth/" rel="nofollow noreferrer">here</a>. An updated version can be found in <a href="https://android.googlesource.com/platform/external/libusb_aah/+/master/msvc/stdint.h" rel="nofollow noreferrer">the Android source tree for libusb_aah</a>.</p> |
508,639 | Why must delegation to a different constructor happen first in a Java constructor? | <p>In a constructor in Java, if you want to call another constructor (or a super constructor), it has to be the first line in the constructor. I assume this is because you shouldn't be allowed to modify any instance variables before the other constructor runs. But why can't you have statements before the constructor delegation, in order to compute the complex value to the other function? I can't think of any good reason, and I have hit some real cases where I have written some ugly code to get around this limitation.</p>
<p>So I'm just wondering:</p>
<ol>
<li>Is there a good reason for this limitation?</li>
<li>Are there any plans to allow this in future Java releases? (Or has Sun definitively said this is not going to happen?)</li>
</ol>
<hr>
<p>For an example of what I'm talking about, consider some code I wrote which I gave in <a href="https://stackoverflow.com/questions/474535/best-way-to-represent-a-fraction-in-java/474612#474612">this StackOverflow answer</a>. In that code, I have a BigFraction class, which has a BigInteger numerator and a BigInteger denominator. The "canonical" constructor is the <code>BigFraction(BigInteger numerator, BigInteger denominator)</code> form. For all the other constructors, I just convert the input parameters to BigIntegers, and call the "canonical" constructor, because I don't want to duplicate all the work.</p>
<p>In some cases this is easy; for example, the constructor that takes two <code>long</code>s is trivial:</p>
<pre><code> public BigFraction(long numerator, long denominator)
{
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
</code></pre>
<p>But in other cases, it is more difficult. Consider the constructor which takes a BigDecimal:</p>
<pre><code> public BigFraction(BigDecimal d)
{
this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
}
</code></pre>
<p>I find this pretty ugly, but it helps me avoid duplicating code. The following is what I'd like to do, but it is illegal in Java:</p>
<pre><code> public BigFraction(BigDecimal d)
{
BigInteger numerator = null;
BigInteger denominator = null;
if(d.scale() < 0)
{
numerator = d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
denominator = BigInteger.ONE;
}
else
{
numerator = d.unscaledValue();
denominator = BigInteger.TEN.pow(d.scale());
}
this(numerator, denominator);
}
</code></pre>
<hr>
<p><strong>Update</strong></p>
<p>There have been good answers, but thus far, no answers have been provided that I'm completely satisfied with, but I don't care enough to start a bounty, so I'm answering my own question (mainly to get rid of that annoying "have you considered marking an accepted answer" message).</p>
<p>Workarounds that have been suggested are:</p>
<ol>
<li>Static factory.
<ul>
<li>I've used the class in a lot of places, so that code would break if I suddenly got rid of the public constructors and went with valueOf() functions.</li>
<li>It feels like a workaround to a limitation. I wouldn't get any other benefits of a factory because this cannot be subclassed and because common values are not being cached/interned.</li>
</ul></li>
<li>Private static "constructor helper" methods.
<ul>
<li>This leads to lots of code bloat.</li>
<li>The code gets ugly because in some cases I really need to compute both numerator and denominator at the same time, and I can't return multiple values unless I return a <code>BigInteger[]</code> or some kind of private inner class.</li>
</ul></li>
</ol>
<p>The main argument against this functionality is that the compiler would have to check that you didn't use any instance variables or methods before calling the superconstructor, because the object would be in an invalid state. I agree, but I think this would be an easier check than the one which makes sure all final instance variables are always initialized in every constructor, no matter what path through the code is taken. The other argument is that you simply can't execute code beforehand, but this is clearly false because the code to compute the parameters to the superconstructor is getting executed <em>somewhere</em>, so it must be allowed at a bytecode level.</p>
<p>Now, what I'd like to see, is some <em>good</em> reason why the compiler couldn't let me take this code:</p>
<pre><code>public MyClass(String s) {
this(Integer.parseInt(s));
}
public MyClass(int i) {
this.i = i;
}
</code></pre>
<p>And rewrite it like this (the bytecode would be basically identical, I'd think):</p>
<pre><code>public MyClass(String s) {
int tmp = Integer.parseInt(s);
this(tmp);
}
public MyClass(int i) {
this.i = i;
}
</code></pre>
<p>The only real difference I see between those two examples is that the "<code>tmp</code>" variable's scope allows it to be accessed after calling <code>this(tmp)</code> in the second example. So maybe a special syntax (similar to <code>static{}</code> blocks for class initialization) would need to be introduced:</p>
<pre><code>public MyClass(String s) {
//"init{}" is a hypothetical syntax where there is no access to instance
//variables/methods, and which must end with a call to another constructor
//(using either "this(...)" or "super(...)")
init {
int tmp = Integer.parseInt(s);
this(tmp);
}
}
public MyClass(int i) {
this.i = i;
}
</code></pre> | 508,910 | 8 | 2 | null | 2009-02-03 19:52:06.54 UTC | 10 | 2016-01-11 14:30:30.773 UTC | 2017-05-23 12:10:13.95 UTC | Kip | -1 | Kip | 18,511 | null | 1 | 39 | java|syntax | 15,567 | <blockquote>
<p>I find this pretty ugly, but it helps
me avoid duplicating code. The
following is what I'd like to do, but
it is illegal in Java ...</p>
</blockquote>
<p>You could also work around this limitation by using a static factory method that returns a new object:</p>
<pre><code>public static BigFraction valueOf(BigDecimal d)
{
// computate numerator and denominator from d
return new BigFraction(numerator, denominator);
}
</code></pre>
<p>Alternatively, you could cheat by calling a private static method to do the computations for your constructor:</p>
<pre><code>public BigFraction(BigDecimal d)
{
this(computeNumerator(d), computeDenominator(d));
}
private static BigInteger computeNumerator(BigDecimal d) { ... }
private static BigInteger computeDenominator(BigDecimal d) { ... }
</code></pre> |
1,221,447 | What do I need to store in the php session when user logged in? | <p>Currently when user logged in, i created 2 sessions.</p>
<pre><code>$_SESSION['logged_in'] = 1;
$_SESSION['username'] = $username; // user's name
</code></pre>
<p>So that, those page which requires logged in, i just do this:</p>
<pre><code>if(isset($_SESSION['logged_id'])){
// Do whatever I want
}
</code></pre>
<p>Is there any security loopholes? I mean, is it easy to hack my session? How does people hack session? and how do I prevent it??</p>
<p>EDIT:</p>
<p>Just found this: </p>
<p><a href="http://www.xrvel.com/post/353/programming/make-a-secure-session-login-script" rel="noreferrer">http://www.xrvel.com/post/353/programming/make-a-secure-session-login-script</a></p>
<p><a href="http://net.tutsplus.com/tutorials/php/secure-your-forms-with-form-keys/" rel="noreferrer">http://net.tutsplus.com/tutorials/php/secure-your-forms-with-form-keys/</a></p>
<p>Just found the links, are those methods good enough?? Please give your opinions. I still have not get the best answer yet.</p> | 1,225,668 | 9 | 0 | null | 2009-08-03 09:39:49.007 UTC | 27 | 2012-08-01 12:09:08.483 UTC | 2009-08-04 03:19:56.047 UTC | null | 146,128 | null | 146,128 | null | 1 | 18 | php|security|session | 9,928 | <h1>Terminology</h1>
<ul>
<li><strong>User:</strong> A visitor.</li>
<li><strong>Client:</strong> A particular web-capable software installed on a particular machine.</li>
</ul>
<hr>
<h1>Understanding Sessions</h1>
<p>In order to understand how to make your session secure, you must first understand how sessions work.</p>
<p>Let's see this piece of code:</p>
<pre><code>session_start();
</code></pre>
<p>As soon as you call that, PHP will look for a cookie called <code>PHPSESSID</code> (by default). If it is not found, it will create one:</p>
<pre><code>PHPSESSID=h8p6eoh3djplmnum2f696e4vq3
</code></pre>
<p>If it is found, it takes the value of <code>PHPSESSID</code> and then loads the corresponding session. That value is called a <code>session_id</code>.</p>
<p>That is the only thing the client will know. Whatever you add into the session variable stays on the server, and is never transfered to the client. That variable doesn't change if you change the content of <code>$_SESSION</code>. It always stays the same until you destroy it or it times out. Therefore, it is useless to try to obfuscate the contents of <code>$_SESSION</code> by hashing it or by other means as the client never receives or sends that information.</p>
<p>Then, in the case of a new session, you will set the variables:</p>
<pre><code>$_SESSION['user'] = 'someuser';
</code></pre>
<p>The client will never see that information.</p>
<hr>
<h1>The Problem</h1>
<p>A security issue may arise when a malicious user steals the <code>session_id</code> of an other user. Without some kind of check, he will then be free to impersonate that user. We need to find a way to uniquely identify the client (not the user).</p>
<p>One strategy (the most effective) involves checking if the IP of the client who started the session is the same as the IP of the person using the session.</p>
<pre><code>if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
// The Check on subsequent load
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) {
die('Session MAY have been hijacked');
}
</code></pre>
<p>The problem with that strategy is that if a client uses a load-balancer, or (on long duration session) the user has a dynamic IP, it will trigger a false alert.</p>
<p>Another strategy involves checking the user-agent of the client:</p>
<pre><code>if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT'];
}
// The Check on subsequent load
if($_SESSION['agent'] != $_SERVER['HTTP_USER_AGENT']) {
die('Session MAY have been hijacked');
}
</code></pre>
<p>The downside of that strategy is that if the client upgrades it's browser or installs an addon (some adds to the user-agent), the user-agent string will change and it will trigger a false alert.</p>
<p>Another strategy is to rotate the <code>session_id</code> on each 5 requests. That way, the <code>session_id</code> theoretically doesn't stay long enough to be hijacked.</p>
<pre><code>if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['count'] = 5;
}
// The Check on subsequent load
if(($_SESSION['count'] -= 1) == 0) {
session_regenerate_id();
$_SESSION['count'] = 5;
}
</code></pre>
<p>You may combine each of these strategies as you wish, but you will also combine the downsides.</p>
<p>Unfortunately, no solution is fool-proof. If your <code>session_id</code> is compromised, you are pretty much done for. The above strategies are just stop-gap measures.</p> |
19,766 | How do I make a list with checkboxes in Java Swing? | <p>What would be the best way to have a list of items with a checkbox each in Java Swing?</p>
<p>I.e. a JList with items that have some text and a checkbox each?</p> | 19,804 | 9 | 2 | null | 2008-08-21 12:49:12.4 UTC | 6 | 2015-09-22 08:26:18.81 UTC | 2015-05-04 08:19:55.423 UTC | null | 785,593 | null | 1,827 | null | 1 | 33 | java|swing|jcheckbox | 85,310 | <p>Create a custom <code>ListCellRenderer</code> and asign it to the <code>JList</code>.</p>
<p>This custom <code>ListCellRenderer</code> must return a <code>JCheckbox</code> in the implementantion of <code>getListCellRendererComponent(...)</code> method.</p>
<p>But this <code>JCheckbox</code> will not be editable, is a simple paint in the screen is up to you to choose when this <code>JCheckbox</code> must be 'ticked' or not, </p>
<p>For example, show it ticked when the row is selected (parameter <code>isSelected</code>), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the <code>ListModel</code>, but then is up to you to implement the method who changes the check status of the data, and notify the change to the <code>JList</code> to be repainted.</p>
<p>I Will post sample code later if you need it</p>
<p><a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html" rel="noreferrer">ListCellRenderer</a></p> |
773,843 | iPhone UIWebview: How to force a numeric keyboard? Is it possible? | <p>I'm experimenting with PhoneGap to develop some iPhone apps. PhoneGap basically wraps a UIWebView - it works well. The problem is the my app has several input fields that only take numeric input. I really need to force the numeric keypad instead of accepting the default standard keyboard, which then forces the user to switch to the numeric on every field. Does anyone know if this is possible? How?</p>
<p>Clarification:
I know that Apple doesn't currently provide any API to allow this. I'm wondering if creating a custom class that inherited from UIWebView might help, or maybe creating a custom keyboard would open up some possibilities?</p>
<p>Update 6 Nov, 2009 - As noted below, Apple has recently updated safari functionality so that this is, once again, supported. So the accepted answer was changed to reflect that.</p>
<pre><code> <html>
<input type='tel'/>
<input type='number'/>
<input type='email'/>
<input />
</html>
</code></pre> | 1,505,805 | 9 | 3 | null | 2009-04-21 18:06:17.257 UTC | 19 | 2017-12-10 15:59:36.85 UTC | 2017-12-10 15:59:36.85 UTC | null | 4,447,772 | null | 93,933 | null | 1 | 61 | iphone|keyboard|uiwebview|cordova | 63,595 | <p>It looks like Mobile Safari supports the new HTML5 input type attributes of <em>email</em>, <em>number</em>, <em>search</em>, <em>tel</em>, and <em>url</em>. These will switch the keyboard that is displayed. See <a href="http://www.whatwg.org/specs/web-apps/current-work/#attr-input-type" rel="noreferrer">the type attribute</a>.</p>
<p>So for example, you could do this:</p>
<pre><code><input type="number" />
</code></pre>
<p>And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.</p>
<p>If you really only want numbers, you could specify:</p>
<pre><code><input type="tel" />
</code></pre>
<p>And then the user would get the phone number dialing keypad.</p>
<p>I know this works with Mobile Safari -- I only assume it will work with UIWebView.</p> |
306,668 | Are Parameters really enough to prevent Sql injections? | <p>I've been preaching both to my colleagues and here on SO about the goodness of using parameters in SQL queries, especially in .NET applications. I've even gone so far as to promise them as giving immunity against SQL injection attacks.</p>
<p>But I'm starting to wonder if this really is true. Are there any known SQL injection attacks that will be successfull against a parameterized query? Can you for example send a string that causes a buffer overflow on the server?</p>
<p>There are of course other considerations to make to ensure that a web application is safe (like sanitizing user input and all that stuff) but now I am thinking of SQL injections. I'm especially interested in attacks against MsSQL 2005 and 2008 since they are my primary databases, but all databases are interesting. </p>
<p>Edit: To clarify what I mean by parameters and parameterized queries. By using parameters I mean using "variables" instead of building the sql query in a string.<br>
So instead of doing this: </p>
<pre><code>SELECT * FROM Table WHERE Name = 'a name'
</code></pre>
<p>We do this:</p>
<pre><code>SELECT * FROM Table WHERE Name = @Name
</code></pre>
<p>and then set the value of the @Name parameter on the query / command object.</p> | 306,675 | 9 | 3 | null | 2008-11-20 20:06:43.94 UTC | 32 | 2011-04-12 14:47:07.523 UTC | 2009-09-18 17:40:01.967 UTC | coldice | 21,632 | Rune | 30,366 | null | 1 | 86 | asp.net|sql|database|sql-injection | 28,919 | <p><strong>Placeholders</strong> are enough to prevent injections. You might still be open to buffer overflows, but that is a completely different flavor of attack from an SQL injection (the attack vector would not be SQL syntax but binary). Since the parameters passed will all be escaped properly, there isn't any way for an attacker to pass data that will be treated like "live" SQL. </p>
<p>You can't use functions inside placeholders, and you can't use placeholders as column or table names, because they are escaped and quoted as string literals.</p>
<p>However, if you use <strong>parameters</strong> as part of a <strong>string concatenation</strong> inside your dynamic query, you are still vulnerable to injection, because your strings will not be escaped but will be literal. Using other types for parameters (such as integer) is safe.</p>
<p>That said, if you're using use input to set the value of something like <code>security_level</code>, then someone could just make themselves administrators in your system and have a free-for-all. But that's just basic input validation, and has nothing to do with SQL injection.</p> |
115,548 | Why is isNaN(null) == false in JS? | <p>This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if (isNaN(null)) {
alert("null is not a number");
} else {
alert("i think null is a number");
}</code></pre>
</div>
</div>
</p>
<p>I'm using Firefox 3. Is that a browser bug?</p>
<p>Other tests:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(null == NaN); // false
console.log(isNaN("text")); // true
console.log(NaN == "text"); // false</code></pre>
</div>
</div>
</p>
<p>So, the problem seems not to be an exact comparison with NaN?</p>
<p><i><b>Edit:</b> Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:</p>
<ul>
<li>Removed a note saying that I had screwed up the headline in the first place by reverting its meaning</li>
<li>Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
</i></li>
</ul> | 115,696 | 9 | 3 | null | 2008-09-22 15:32:26.537 UTC | 19 | 2022-02-07 22:04:17.317 UTC | 2019-08-29 06:28:26.147 UTC | Hanno | 4,551,041 | Hanno | 2,077 | null | 1 | 155 | javascript | 61,906 | <p>I believe the code is trying to ask, "is <code>x</code> numeric?" with the specific case here of <code>x = null</code>. The function <code>isNaN()</code> can be used to answer this question, but semantically it's referring specifically to the value <code>NaN</code>. From Wikipedia for <a href="http://en.wikipedia.org/wiki/NaN" rel="noreferrer"><code>NaN</code></a>: </p>
<blockquote>
<p>NaN (<b>N</b>ot <b>a</b> <b>N</b>umber) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.</p>
</blockquote>
<p>In most cases we think the answer to "is null numeric?" should be no. However, <code>isNaN(null) == false</code> is semantically correct, because <code>null</code> is not <code>NaN</code>.</p>
<p>Here's the algorithmic explanation:</p>
<p>The function <code>isNaN(x)</code> attempts to convert the passed parameter to a number<sup><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN" rel="noreferrer">1</a></sup> (equivalent to <code>Number(x)</code>) and then tests if the value is <code>NaN</code>. If the parameter can't be converted to a number, <code>Number(x)</code> will return <code>NaN</code><sup><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number" rel="noreferrer">2</a></sup>. Therefore, if the conversion of parameter <code>x</code> to a number results in <code>NaN</code>, it returns true; otherwise, it returns false. </p>
<p>So in the specific case <code>x = null</code>, <code>null</code> is converted to the number 0, (try evaluating <code>Number(null)</code> and see that it returns 0,) and <code>isNaN(0)</code> returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. <code>'abcd'</code>) that cannot be converted to a number will cause <code>isNaN('abcd')</code> to return true, specifically because <code>Number('abcd')</code> returns <code>NaN</code>.</p>
<p>In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0.</p>
<p>As for the seemingly inconsistent tests for equality shown in the question, the behavior of <code>NaN</code> is specified such that any comparison <code>x == NaN</code> is false, regardless of the other operand, including <code>NaN</code> itself<sup><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN" rel="noreferrer">1</a></sup>.</p> |
701,882 | What is ANSI format? | <p>What is ANSI encoding format? Is it a system default format?
In what way does it differ from ASCII?</p> | 701,920 | 10 | 0 | null | 2009-03-31 16:26:45.32 UTC | 75 | 2019-11-15 12:29:18.433 UTC | 2015-05-14 12:26:38.003 UTC | Alan M | 617,450 | BALAMURUGAN | 79,631 | null | 1 | 257 | character-encoding|ascii|ansi|codepages | 407,713 | <p>ANSI encoding is a slightly generic term used to refer to the standard code page on a system, usually Windows. It is more properly referred to as <a href="http://en.wikipedia.org/wiki/Windows-1252" rel="noreferrer">Windows-1252</a> on Western/U.S. systems. (It can represent certain other <a href="http://en.wikipedia.org/wiki/Windows_code_page" rel="noreferrer">Windows code pages</a> on other systems.) This is essentially an <a href="http://en.wikipedia.org/wiki/Extended_ASCII" rel="noreferrer">extension of the ASCII character set</a> in that it includes all the ASCII characters with an additional 128 character codes. This difference is due to the fact that "ANSI" encoding is 8-bit rather than 7-bit as ASCII is (ASCII is almost always encoded nowadays as 8-bit bytes with the <a href="https://en.wikipedia.org/wiki/Most_significant_bit" rel="noreferrer">MSB</a> set to 0). See the article for an explanation of why this encoding is usually referred to as ANSI.</p>
<p>The name "ANSI" is a misnomer, since it doesn't correspond to any actual ANSI standard, but the name has stuck. ANSI is not the same as UTF-8.</p> |
531,199 | how to destroy a Static Class in C# | <p>I am using .net 1.1. I have a session class in which I have stored many static variables that hold some data to be used by many classes.</p>
<p>I want to find a simple way of destroying this class instead of resetting every variable one by one. For example if there is a static class MyStatic, I would have liked to destroy/remove this class from the memory by writing MyStatic = null, which is not currently possible,</p>
<h2>Additional question.</h2>
<p>The idea of singleton is good, but I have the following questions:</p>
<p>If singleton is implemented, the 'single' object will still remain in the memory. In singleton, we are only checking if an instance is already existing. how can i make sure that this instance variable also gets destroyed. </p>
<p>I have a main class which initializes the variable in the static class. Even if I plan to implement a Rest() method, I need to call it from a method, for eg, the destructor in the main class. But this destructor gets called only when GC collects this main class object in the memory, which means the Reset() gets called very late</p>
<p>thanks
pradeep</p> | 531,204 | 10 | 0 | null | 2009-02-10 06:05:23.48 UTC | 6 | 2017-02-05 07:02:09.983 UTC | 2009-02-10 07:27:46.167 UTC | pradeeptp | 20,933 | pradeeptp | 20,933 | null | 1 | 18 | c# | 39,399 | <p>Don't use a static class to store your variables. Use an instance (and make it a singleton if you only want one instance at any given time.) You can then implement IDisposible, and just call Dispose() when you want to destroy it.</p>
<p>For more information check out this site: <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="noreferrer">http://csharpindepth.com/Articles/General/Singleton.aspx</a></p>
<p><b> EDIT</b> </p>
<p>The object is still subject to garbage collection, so unless you are using lots of unmanaged resources, you should be fine. You can implement IDisposible to clean up any resources that need to be cleaned up as well.</p> |
174,600 | Is there a way to disable a SQL Server trigger for just a particular scope of execution? | <p>In SQL Server 2005, is there a way for a trigger to find out what object is responsible for firing the trigger? I would like to use this to disable the trigger for one stored procedure.</p>
<p>Is there any other way to disable the trigger only for the current transaction? I could use the following code, but if I'm not mistaken, it would affect concurrent transactions as well - which would be a bad thing.</p>
<pre><code>DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ]
</code></pre>
<p>If possible, I would like to avoid the technique of having a "NoTrigger" field in my table and doing a <code>NoTrigger = null</code>, because I would like to keep the table as small as possible.</p>
<p>The reason I would like to avoid the trigger is because it contains logic that is important for manual updates to the table, but my stored procedure will take care of this logic. Because this will be a highly used procedure, I want it to be fast.</p>
<blockquote>
<p>Triggers impose additional overhead on the server because they initiate an implicit transaction. As soon as a trigger is executed, a new implicit transaction is started, and any data retrieval within a transaction will hold locks on affected tables.</p>
</blockquote>
<p>From: <a href="http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger" rel="nofollow noreferrer">http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger</a></p> | 178,192 | 11 | 1 | null | 2008-10-06 14:48:39.173 UTC | 17 | 2019-09-13 10:29:07.637 UTC | 2019-09-13 10:29:07.637 UTC | Terrapin | 13,302 | Terrapin | 357 | null | 1 | 36 | sql-server|tsql|triggers | 44,579 | <p>I just saw this article recently highlighted on the SQL Server Central newsletter and it appears to offer a way which you may find useful using the Context_Info on the connection:</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1591" rel="noreferrer">http://www.mssqltips.com/tip.asp?tip=1591</a></p>
<hr>
<p>EDIT by Terrapin:</p>
<p>The above link includes the following code:</p>
<pre><code>USE AdventureWorks;
GO
-- creating the table in AdventureWorks database
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
GO
CREATE TABLE dbo.Table1(ID INT)
GO
-- Creating a trigger
CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE
AS
DECLARE @Cinfo VARBINARY(128)
SELECT @Cinfo = Context_Info()
IF @Cinfo = 0x55555
RETURN
PRINT 'Trigger Executed'
-- Actual code goes here
-- For simplicity, I did not include any code
GO
</code></pre>
<p>If you want to prevent the trigger from being executed you can do the following:</p>
<pre><code>SET Context_Info 0x55555
INSERT dbo.Table1 VALUES(100)
</code></pre> |
520,640 | Google's Imageless Buttons | <p>There have been a few articles recently about Google's new imageless buttons:</p>
<ul>
<li><a href="http://stopdesign.com/archive/2009/02/04/recreating-the-button.html" rel="noreferrer">http://stopdesign.com/archive/2009/02/04/recreating-the-button.html</a></li>
<li><a href="http://stopdesign.com/eg/buttons/3.0/code.html" rel="noreferrer">http://stopdesign.com/eg/buttons/3.0/code.html</a></li>
<li><a href="http://stopdesign.com/eg/buttons/3.1/code.html" rel="noreferrer">http://stopdesign.com/eg/buttons/3.1/code.html</a></li>
<li><a href="http://gmailblog.blogspot.com/2009/02/new-ways-to-label-with-move-to-and-auto.html" rel="noreferrer">http://gmailblog.blogspot.com/2009/02/new-ways-to-label-with-move-to-and-auto.html</a></li>
</ul>
<p>I really like how these new buttons work in Gmail. How can I use these or similar buttons on my site? Are there any open source projects with a similar look & feel?</p>
<p>If I wanted to roll my own button package like this using JQuery/XHTML/CSS, what elements could I use? My initial thoughts are:</p>
<ol>
<li><p>Standard <code><input type="button"></code> with css to improve the look (the design article talked mostly about the css/imges involves.)</p></li>
<li><p>Jquery javascript to bring up a custom dialog rooted to the button on the "onclick" event which would have <code><a></code> tags in them and a search bar for filtering? Would a table layout for that popup be sane?</p></li>
</ol>
<p>I'm terrible at reverse engineering things on the web, what are some of the tools that I could use to help reverse engineer these buttons? Using Firefox's web developer toolbar I can't really see the css or javascript (even if it is minified) that is used on the buttons popup dialogs. What browser tool or other method could I use to peek at them and get some ideas?</p>
<p>I'm not looking to steal any of Google's IP, just get an idea of how I could create similar button functionality.</p> | 540,316 | 11 | 0 | null | 2009-02-06 15:12:31.98 UTC | 98 | 2011-07-24 09:57:31.467 UTC | 2009-06-27 17:28:31.1 UTC | Jeff Atwood | 54,680 | MikeN | 36,680 | null | 1 | 90 | javascript|html|css|gmail|reverse-engineering | 25,450 | <p>-- EDIT -- I didn't see the link in the original post. Sorry! Will try and re-write to reflect actual question</p>
<p>StopDesign has an excellent post on this <a href="http://stopdesign.com/archive/2009/02/04/recreating-the-button.html" rel="nofollow noreferrer">here</a>. <strong>[edit 20091107] These were released as part of the <a href="http://code.google.com/closure/" rel="nofollow noreferrer">closure library</a>: see the <a href="http://closure-library.googlecode.com/svn/trunk/closure/goog/demos/button.html" rel="nofollow noreferrer">button demo</a>.</strong></p>
<p>Basically the custom buttons he <a href="http://stopdesign.com/eg/buttons/3.0/code.html" rel="nofollow noreferrer">shows</a> are created using a simple bit of CSS.</p>
<p>He originally used 9 tables to get the effect: <img src="https://stopdesign.com/img/archive/2009/02/9-cell.png" alt="9 Tables"></p>
<p>But later he used a simple 1px left and right margin on the top and bottom borders to achieve the same effect.</p>
<p>The gradient is faked by using three layers: <img src="https://stopdesign.com/img/archive/2009/02/bands-spec.png" alt="Button Gradient"></p>
<p>All of the code can be found at the <a href="http://stopdesign.com/eg/buttons/3.1/code.html" rel="nofollow noreferrer">Custom Buttons 3.1</a> page. (although the gradient without the image is only working in Firefox and Safari)</p>
<h2>Step by Step Instructions</h2>
<p>1 - Insert the following CSS:</p>
<pre><code>/* Start custom button CSS here
---------------------------------------- */
.btn {
display:inline-block;
background:none;
margin:0;
padding:3px 0;
border-width:0;
overflow:visible;
font:100%/1.2 Arial,Sans-serif;
text-decoration:none;
color:#333;
}
* html button.btn {
padding-bottom:1px;
}
/* Immediately below is a temporary hack to serve the
following margin values only to Gecko browsers
Gecko browsers add an extra 3px of left/right
padding to button elements which can't be overriden.
Thus, we use -3px of left/right margin to overcome this. */
html:not([lang*=""]) button.btn {
margin:0 -3px;
}
.btn span {
background:#f9f9f9;
z-index:1;
margin:0;
padding:3px 0;
border-left:1px solid #ccc;
border-right:1px solid #bbb;
}
* html .btn span {
padding-top:0;
}
.btn span span {
background:none;
position:relative;
padding:3px .4em;
border-width:0;
border-top:1px solid #ccc;
border-bottom:1px solid #bbb;
}
.btn b {
background:#e3e3e3;
position:absolute;
z-index:2;
bottom:0;
left:0;
width:100%;
overflow:hidden;
height:40%;
border-top:3px solid #eee;
}
* html .btn b {
top:1px;
}
.btn u {
text-decoration:none;
position:relative;
z-index:3;
}
/* pill classes only needed if using pill style buttons ( LEFT | CENTER | RIGHT ) */
button.pill-l span {
border-right-width:0;
}
button.pill-l span span {
border-right:1px solid #ccc;
}
button.pill-c span {
border-right-style:none;
border-left-color:#fff;
}
button.pill-c span span {
border-right:1px solid #ccc;
}
button.pill-r span {
border-left-color:#fff;
}
/* only needed if implementing separate hover state for buttons */
.btn:hover span, .btn:hover span span {
cursor:pointer;
border-color:#9cf !important;
color:#000;
}
/* use if one button should be the 'primary' button */
.primary {
font-weight:bold;
color:#000;
}
</code></pre>
<p>2 - Use one of the following ways to call it (more can be found in the links above)</p>
<pre><code><a href="#" class="btn"><span><span><b>&nbsp;</b><u>button</u></span></span></a>
</code></pre>
<p>or </p>
<pre><code><button type="button" class="btn"><span><span><b>&nbsp;</b><u>button</u></span></span></button>
</code></pre> |
299,802 | How do you check if a selector matches something in jQuery? | <p>In Mootools, I'd just run <code>if ($('target')) { ... }</code>. Does <code>if ($('#target')) { ... }</code> in jQuery work the same way?</p> | 299,821 | 11 | 1 | null | 2008-11-18 19:13:31.13 UTC | 71 | 2014-01-29 22:25:24.18 UTC | 2012-08-11 19:52:31.667 UTC | null | 106,224 | One Crayon | 38,666 | null | 1 | 506 | javascript|jquery|jquery-selectors | 305,423 | <p>As the other commenters are suggesting the most efficient way to do it seems to be: </p>
<pre><code>if ($(selector).length ) {
// Do something
}
</code></pre>
<p>If you absolutely must have an exists() function - which will be slower- you can do:</p>
<pre><code>jQuery.fn.exists = function(){return this.length>0;}
</code></pre>
<p>Then in your code you can use</p>
<pre><code>if ($(selector).exists()) {
// Do something
}
</code></pre>
<p>As answered <a href="https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery">here</a></p> |
726,549 | Algorithm for Additive Color Mixing for RGB Values | <p>I'm looking for an algorithm to do additive color mixing for RGB values.</p>
<p>Is it as simple as adding the RGB values together to a max of 256?</p>
<pre><code>(r1, g1, b1) + (r2, g2, b2) =
(min(r1+r2, 256), min(g1+g2, 256), min(b1+b2, 256))
</code></pre> | 726,564 | 13 | 4 | null | 2009-04-07 16:25:27.677 UTC | 56 | 2020-11-03 12:43:42.193 UTC | 2012-10-08 19:15:07.957 UTC | null | 50,776 | null | 88,191 | null | 1 | 86 | algorithm|colors | 100,470 | <p>It depends on what you want, and it can help to see what the results are of different methods.</p>
<p>If you want </p>
<pre>
Red + Black = Red
Red + Green = Yellow
Red + Green + Blue = White
Red + White = White
Black + White = White
</pre>
<p>then adding with a clamp works (e.g. <code>min(r1 + r2, 255)</code>) This is more like the light model you've referred to.</p>
<p>If you want </p>
<pre>
Red + Black = Dark Red
Red + Green = Dark Yellow
Red + Green + Blue = Dark Gray
Red + White = Pink
Black + White = Gray
</pre>
<p>then you'll need to average the values (e.g. <code>(r1 + r2) / 2</code>) This works better for lightening/darkening colors and creating gradients.</p> |
359,821 | Styling the last td in a table with css | <p>I want to style the last TD in a table without using a CSS class on the particular TD.</p>
<pre><code><table>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<td>Five</td>
</tr>
</tbody>
</table>
table td
{
border: 1px solid black;
}
</code></pre>
<p>I want the TD containing the text "Five" to not have a border but again, I do not want to use a class.</p> | 359,838 | 15 | 3 | null | 2008-12-11 15:56:04.813 UTC | 14 | 2020-07-02 11:25:37.483 UTC | 2016-09-15 15:25:57.607 UTC | Gortok | 4,370,109 | vchoke | null | null | 1 | 71 | html|css|html-table | 179,097 | <p>You can use relative rules:</p>
<pre><code>table td + td + td + td + td {
border: none;
}
</code></pre>
<p>This only works if the number of columns isn't determined at runtime.</p> |
382,603 | In what contexts do programming languages make real use of an Infinity value? | <p>So in Ruby there is a trick to specify infinity:</p>
<pre><code>1.0/0
=> Infinity
</code></pre>
<p>I believe in Python you can do something like this</p>
<pre><code>float('inf')
</code></pre>
<p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p>
<pre><code>(0..1.0/0).include?(number) == (number >= 0) # True for all values of number
=> true
</code></pre>
<p>To summarize, what I'm looking for is a real world reason to use Infinity.</p>
<p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p> | 382,674 | 24 | 2 | 2009-01-20 00:48:55.2 UTC | 2008-12-19 23:54:04.747 UTC | 7 | 2015-04-11 13:28:24.82 UTC | 2015-04-11 13:28:24.82 UTC | Chris Lloyd | 1,593,077 | Chris Lloyd | 42,413 | null | 1 | 28 | python|ruby|language-agnostic|idioms|infinity | 28,504 | <p>Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't <em>have</em> to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.</p> |
284,325 | How to make child process die after parent exits? | <p>Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?</p>
<hr>
<p>Some similar question on stackoverflow:</p>
<ul>
<li>(asked earlier) <a href="https://stackoverflow.com/questions/269494/how-can-i-cause-a-child-process-to-exit-when-the-parent-does">How can I cause a child process to exit when the parent does?</a></li>
<li>(asked later) <a href="https://stackoverflow.com/questions/395877/are-child-processes-created-with-fork-automatically-killed-when-the-parent-is-k">Are child processes created with fork() automatically killed when the parent is killed?</a></li>
</ul>
<hr>
<p>Some similar question on stackoverflow for <strong>Windows</strong>: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows">How do I automatically destroy child processes in Windows?</a> </li>
<li><a href="https://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed">Kill child process when parent process is killed</a></li>
</ul> | 284,443 | 24 | 0 | null | 2008-11-12 15:37:51.153 UTC | 130 | 2022-09-04 04:35:35.597 UTC | 2017-05-23 12:03:02.377 UTC | dmckee | -1 | phjr | 9,403 | null | 1 | 236 | c|linux|unix|process|fork | 199,867 | <p>Child can ask kernel to deliver <code>SIGHUP</code> (or other signal) when parent dies by specifying option <code>PR_SET_PDEATHSIG</code> in <code>prctl()</code> syscall like this:</p>
<p><code>prctl(PR_SET_PDEATHSIG, SIGHUP);</code></p>
<p>See <code>man 2 prctl</code> for details.</p>
<p>Edit: This is Linux-only</p> |
584,507 | What is the purpose of null? | <p>I am in a compilers class and we are tasked with creating our own language, from scratch. Currently our dilemma is whether to include a 'null' type or not. What purpose does null provide? Some of our team is arguing that it is not strictly necessary, while others are pro-null just for the extra flexibility it can provide.</p>
<p>Do you have any thoughts, especially for or against null?
Have you ever created functionality that required null?</p> | 584,510 | 25 | 2 | null | 2009-02-25 02:30:35.8 UTC | 14 | 2013-10-12 10:00:56.81 UTC | 2012-09-15 02:39:32.903 UTC | Nikhil Chelliah | 1,288 | Allyn | 57,414 | null | 1 | 42 | language-agnostic|compiler-construction|null|language-design | 7,546 | <p><a href="http://dow.ngra.de/2009/02/01/correcting-the-billion-dollar-mistake/" rel="noreferrer">Null: The Billion Dollar Mistake</a>. Tony Hoare:</p>
<blockquote>
<p>I call it my billion-dollar mistake.
It was the invention of the null
reference in 1965. At that time, I was
designing the first comprehensive type
system for references in an object
oriented language (ALGOL W). My goal
was to ensure that all use of
references should be absolutely safe,
with checking performed automatically
by the compiler. <strong>But I couldn't resist
the temptation to put in a null
reference, simply because it was so
easy to implement. This has led to
innumerable errors, vulnerabilities,
and system crashes, which have
probably caused a billion dollars of
pain and damage in the last forty
years. In recent years, a number of
program analysers like PREfix and
PREfast in Microsoft have been used to
check references, and give warnings if
there is a risk they may be non-null.</strong>
More recent programming languages like
Spec# have introduced declarations for
non-null references. This is the
solution, which I rejected in 1965.</p>
</blockquote> |
716,597 | Array or List in Java. Which is faster? | <p>I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?</p>
<p>Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?</p> | 716,619 | 32 | 8 | null | 2009-04-04 05:57:28.337 UTC | 138 | 2022-06-28 23:01:11.12 UTC | 2019-11-13 19:37:45.097 UTC | euphoria83 | 213,269 | euphoria83 | 78,351 | null | 1 | 387 | java|arrays|list|performance | 321,082 | <p>I suggest that you use a profiler to test which is faster.</p>
<p>My personal opinion is that you should use Lists.</p>
<p>I work on a large codebase and a previous group of developers used arrays <strong>everywhere</strong>. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.</p> |
6,358,799 | ASP.net programmatically bind dataset to gridview | <p>I have a data set with about 15 columns, and I also have an ASP.net gridview. I was wondering if any one knew how I can populate the gridview with the dataset, but the issue is I just want a few of the columns from the dataset.</p>
<p>at the moment I'm just doing </p>
<pre><code> GridView1.DataSource = ds;
GridView1.DataBind();
</code></pre>
<p>but this obviously binds all the columns from the dataset to the gridview.</p> | 6,358,907 | 5 | 1 | null | 2011-06-15 13:54:05.983 UTC | 3 | 2019-01-21 12:12:41.313 UTC | 2019-01-21 12:12:41.313 UTC | null | 1,033,581 | null | 276,595 | null | 1 | 6 | c#|asp.net|data-binding|gridview | 65,830 | <p>So you are looking to create columns at runtime? Try this: </p>
<p><a href="http://www.codeproject.com/KB/aspnet/dynamic_Columns_in_Grid.aspx" rel="noreferrer">http://www.codeproject.com/KB/aspnet/dynamic_Columns_in_Grid.aspx</a></p>
<p>Alternatively, you can configure your gridview ahead of time in the aspx: </p>
<pre><code><Columns>
<asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price" HtmlEncode="False" SortExpression="UnitPrice" />
</Columns>
</code></pre>
<p>And make sure you set <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogeneratecolumns.aspx" rel="noreferrer">AutoGenerateColumns</a> to false. </p> |
6,766,722 | How to modify parent scope variable using Powershell | <p>I'm fairly new to powershell, and I'm just not getting how to modify a variable in a parent scope:</p>
<pre><code>$val = 0
function foo()
{
$val = 10
}
foo
write "The number is: $val"
</code></pre>
<p>When I run it I get:</p>
<pre class="lang-none prettyprint-override"><code>The number is: 0
</code></pre>
<p>I would like it to be 10. But powershell is creating a new variable that hides the one in the parent scope.</p>
<p>I've tried these, with no success (as per the documentation):</p>
<pre><code>$script:$val = 10
$global:$val = 10
$script:$val = 10
</code></pre>
<p>But these don't even 'compile' so to speak.
What am I missing?</p> | 6,767,219 | 5 | 0 | null | 2011-07-20 18:33:21.817 UTC | 3 | 2022-07-06 08:26:58.803 UTC | 2015-10-09 22:37:46.337 UTC | null | 1,743,811 | null | 321,866 | null | 1 | 32 | powershell | 20,819 | <p>You don't need to use the global scope. A variable with the same name could have been already exist in the shell console and you may update it instead. Use the script scope modifier. When using a scope modifier you don't include the $ sign in the variable name.</p>
<p>$script:val=10 </p> |
6,821,883 | Set httpOnly and secure on PHPSESSID cookie in PHP | <p>Whats the recommended way to set httponly and secure flags on the PHPSESSID cookie?</p>
<p>I found <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly</a>. Any better suggestions?</p>
<p>thanks</p> | 6,822,303 | 8 | 2 | null | 2011-07-25 20:23:06.79 UTC | 4 | 2020-04-23 15:40:04.237 UTC | null | null | null | null | 117,647 | null | 1 | 32 | php|security|session-cookies | 87,398 | <p>In my opinion the best would be: <a href="http://www.php.net/manual/en/function.session-set-cookie-params.php" rel="noreferrer">http://www.php.net/manual/en/function.session-set-cookie-params.php</a></p>
<pre><code>void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
</code></pre> |
6,554,492 | error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere | <p>So I have a class included in another class that keeps throwing a compile error of the form "error: 'ProblemClass' has not been declared. The files are set up thusly:</p>
<pre><code>#ifndef PROBLEMCLASS_H
#define PROBLEMCLASS_H
#include <iostream>
#include <cmath>
class ProblemClass
{
public:
virtual void Init() = 0;
};
#endif
</code></pre>
<p>and the class where the error occurs looks like this:</p>
<pre><code>#ifndef ACLASS_H
#define ACLASS_H
#include "problemclass.h"
class AClass : public Base
{
public:
void DoSomething(ProblemClass* problem);
};
#endif
</code></pre>
<p>The compile error occurs at void Dosomething();</p>
<p>I'm aware the code here isn't enough to solve the problem. I've been unable to create a minimal example that can reproduce it. So my question is much more general; what sort of things might cause this? Is there anything in particular I should look for, or some line of enquiry I should be following to track it down?</p>
<p>This code compiles fine in an almost identical version of the project.</p>
<p>Help of any sort would be greatly appreciated, no matter how vague. I'm using codeblocks 10.05 with mingw4.4.1 in win 7 64 bit.</p> | 6,555,232 | 9 | 9 | null | 2011-07-02 01:02:44.083 UTC | 14 | 2021-10-27 09:26:53.45 UTC | 2014-11-04 07:07:20.03 UTC | null | 2,365,624 | null | 825,677 | null | 1 | 54 | c++|compiler-errors|header | 110,165 | <p>You seem to be saying that the code you are showing doesn't actually produce the compiler error that you are having a problem with. So we can only guess. Here are some possibilities:</p>
<ul>
<li>You could have forgot to include <code>problemclass.h</code> from the file where you are using <code>ProblemClass</code>.</li>
<li>You could have misspelled the name of <code>ProblemClass</code> either in its own header file or in the place where you are using it. This can be hard to spot if it is a capitalization error such as writing <code>Problemclass</code> or <code>problemClass</code> instead of <code>ProblemClass</code>.</li>
<li>You could have copy-pasted your inclusion guard <code>#defines</code> from one header file to another and then forgot to change the defined names. Then only the first of those two included header files would take effect.</li>
<li>You could have placed <code>ProblemClass</code> in a namespace <code>A</code>, in which case you must refer to <code>ProblemClass</code> as <code>A::ProblemClass</code> if you are referring to it from outside the namespace <code>A</code>.</li>
<li>You may be using templates and not expecting two-phase lookup to work the way <a href="http://clang.llvm.org/compatibility.html#dep_lookup" rel="noreferrer">it does</a>.</li>
<li>You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old version of that file under the misspelled name.</li>
<li>You could have made <code>ProblemClass</code> a macro that only gets defined after you include <code>problemclass.h</code>, in which case what you see as <code>ProblemClass</code> gets replaced by something else by the macro preprocessor.</li>
<li>You could have defined <code>ProblemClass</code> in a header file other than <code>problemclass.h</code> and then <code>problemclass.h</code> actually defines something else.</li>
</ul> |
6,712,034 | Sort array by firstname (alphabetically) in JavaScript | <p>I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript.
How can I do it?</p>
<pre><code>var user = {
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
</code></pre> | 6,712,080 | 23 | 0 | null | 2011-07-15 19:10:55.933 UTC | 199 | 2022-07-07 18:28:04.54 UTC | 2022-06-21 18:56:59.813 UTC | null | 1,145,388 | null | 261,694 | null | 1 | 1,053 | javascript | 1,170,289 | <p>Suppose you have an array <code>users</code>. You may use <code>users.sort</code> and pass a function that takes two arguments and compare them (comparator)</p>
<p>It should return</p>
<ul>
<li>something negative if first argument is less than second (should be placed before the second in resulting array)</li>
<li>something positive if first argument is greater (should be placed after second one)</li>
<li>0 if those two elements are equal.</li>
</ul>
<p>In our case if two elements are <code>a</code> and <code>b</code> we want to compare <code>a.firstname</code> and <code>b.firstname</code></p>
<p>Example:</p>
<pre><code>users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
</code></pre>
<p>This code is going to work with any type.</p>
<p>Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc. when you compare strings, so you may want to use <code>localeCompare</code>. See other answers for clarity.</p> |
38,498,258 | Typescript difference between two arrays | <p>Is there a way to return the missing values of list_a from list_b in TypeScrpit?</p>
<p>For example:</p>
<pre><code>var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
</code></pre>
<p>The result value is</p>
<pre><code>['e', 'f', 'g'].
</code></pre> | 38,498,350 | 5 | 2 | null | 2016-07-21 07:55:27.053 UTC | 6 | 2022-03-29 15:46:50.973 UTC | 2021-06-01 21:16:52.887 UTC | null | 285,795 | null | 3,667,920 | null | 1 | 46 | arrays|typescript|difference | 85,634 | <p>There are probably a lot of ways, for example using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer">Array.prototype.filter()</a>:</p>
<pre><code>var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd'];
let missing = a1.filter(item => a2.indexOf(item) < 0);
console.log(missing); // ["e", "f", "g"]
</code></pre>
<p>(<a href="https://www.typescriptlang.org/play/#src=var%20a1%20%3D%20%5B'a'%2C%20'b'%2C%20'c'%2C%20'd'%2C%20'e'%2C%20'f'%2C%20'g'%5D%3B%0D%0Avar%20a2%20%3D%20%5B'a'%2C%20'b'%2C%20'c'%2C%20'd'%5D%3B%0D%0A%0D%0Alet%20missing%20%3D%20a1.filter(item%20%3D%3E%20a2.indexOf(item)%20%3C%200)%3B%0D%0Aconsole.log(missing)%3B%20%2F%2F%20%5B%22e%22%2C%20%22f%22%2C%20%22g%22%5D" rel="noreferrer">code in playground</a>)</p>
<hr>
<h3>Edit</h3>
<p>The <code>filter</code> function runs over the elements of <code>a1</code> and it reduce it (but in a new array) to elements who are in <code>a1</code> (because we're iterating over it's elements) and are missing in <code>a2</code>. </p>
<p>Elements in <code>a2</code> which are missing in <code>a1</code> won't be included in the result array (<code>missing</code>) as the filter function doesn't iterate over the <code>a2</code> elements:</p>
<pre><code>var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z', 'hey', 'there'];
let missing = a1.filter(item => a2.indexOf(item) < 0);
console.log(missing); // still ["e", "f", "g"]
</code></pre>
<p>(<a href="https://www.typescriptlang.org/play/#src=var%20a1%20%3D%20%5B'a'%2C%20'b'%2C%20'c'%2C%20'd'%2C%20'e'%2C%20'f'%2C%20'g'%5D%3B%0D%0Avar%20a2%20%3D%20%5B'a'%2C%20'b'%2C%20'c'%2C%20'd'%2C%20'z'%2C%20'hey'%2C%20'there'%5D%3B%0D%0A%0D%0Alet%20missing%20%3D%20a1.filter(item%20%3D%3E%20a2.indexOf(item)%20%3C%200)%3B%0D%0Aconsole.log(missing)%3B%20%2F%2F%20%5B%22e%22%2C%20%22f%22%2C%20%22g%22%5D" rel="noreferrer">code in playground</a>)</p> |
45,659,742 | Angular4 - No value accessor for form control | <p>I have a custom element :</p>
<pre class="lang-html prettyprint-override"><code><div formControlName="surveyType">
<div *ngFor="let type of surveyTypes"
(click)="onSelectType(type)"
[class.selected]="type === selectedType">
<md-icon>{{ type.icon }}</md-icon>
<span>{{ type.description }}</span>
</div>
</div>
</code></pre>
<p>When I try to add the formControlName, I get an error message:</p>
<blockquote>
<p>ERROR Error: No value accessor for form control with name:
'surveyType'</p>
</blockquote>
<p>I tried to add <code>ngDefaultControl</code> without success.
It seems it's because there is no input/select... and I dont know what to do.</p>
<p>I would like to bind my click to this formControl in order that when someone clicks on the entire card that would push my 'type' into the formControl. Is it possible?</p> | 45,660,571 | 4 | 5 | null | 2017-08-13 11:13:43.837 UTC | 33 | 2020-11-13 13:36:19.707 UTC | 2019-07-27 14:31:45.773 UTC | null | 5,468,463 | null | 8,457,760 | null | 1 | 185 | javascript|angular|typescript|angular4-forms | 285,514 | <p>You can use <code>formControlName</code> only on directives which implement <a href="https://angular.io/api/forms/ControlValueAccessor" rel="noreferrer"><code>ControlValueAccessor</code></a>.</p>
<h1>Implement the interface</h1>
<p>So, in order to do what you want, you have to create a component which implements <a href="https://angular.io/api/forms/ControlValueAccessor" rel="noreferrer"><code>ControlValueAccessor</code></a>, which means <strong>implementing the following three functions</strong>:</p>
<ul>
<li><code>writeValue</code> (tells Angular how to write value from model into view)</li>
<li><code>registerOnChange</code> (registers a handler function that is called when the view changes)</li>
<li><code>registerOnTouched</code> (registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).</li>
</ul>
<h1>Register a provider</h1>
<p>Then, you have to tell Angular that this directive is a <code>ControlValueAccessor</code> (interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by <strong>registering a provider</strong>. </p>
<p>The provider should provide <a href="https://angular.io/api/forms/NG_VALUE_ACCESSOR" rel="noreferrer"><code>NG_VALUE_ACCESSOR</code></a> and <a href="https://angular.io/guide/dependency-injection-in-action#useexistingthe-alias-provider" rel="noreferrer">use an existing value</a>. You'll also need a <a href="https://angular.io/guide/dependency-injection-in-action#forwardref" rel="noreferrer"><code>forwardRef</code></a> here. Note that <code>NG_VALUE_ACCESSOR</code> should be a <a href="https://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html" rel="noreferrer">multi provider</a>.</p>
<p>For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to <code>@Component</code> decorator:</p>
<pre class="lang-json prettyprint-override"><code>providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyControlComponent),
}
]
</code></pre>
<h1>Usage</h1>
<p>Your component is ready to be used. With <a href="https://angular.io/guide/forms#template-driven-forms" rel="noreferrer">template-driven forms</a>, <code>ngModel</code> binding will now work properly.</p>
<p>With <a href="https://angular.io/guide/reactive-forms" rel="noreferrer">reactive forms</a>, you can now properly use <code>formControlName</code> and the form control will behave as expected.</p>
<h1>Resources</h1>
<ul>
<li><a href="https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html" rel="noreferrer"><strong>Custom Form Controls in Angular</strong> by Thoughtram</a></li>
<li><a href="https://coryrylan.com/blog/angular-custom-form-controls-with-reactive-forms-and-ngmodel" rel="noreferrer"><strong>Angular Custom Form Controls with Reactive Forms and NgModel</strong> by Cory Rylan</a></li>
</ul> |
57,340,308 | How does Rust's 128-bit integer `i128` work on a 64-bit system? | <p>Rust has 128-bit integers, these are denoted with the data type <code>i128</code> (and <code>u128</code> for unsigned ints):</p>
<pre><code>let a: i128 = 170141183460469231731687303715884105727;
</code></pre>
<p>How does Rust make these <code>i128</code> values work on a 64-bit system; e.g. how does it do arithmetic on these?</p>
<p>Since, as far as I know, the value cannot fit in one register of a x86-64 CPU, does the compiler somehow use two registers for one <code>i128</code> value? Or are they instead using some kind of big integer struct to represent them?</p> | 57,340,670 | 4 | 14 | null | 2019-08-03 16:44:06.097 UTC | 21 | 2021-11-30 08:28:03.493 UTC | 2021-11-30 08:28:03.493 UTC | null | 9,835,872 | null | 9,835,872 | null | 1 | 168 | rust|x86-64|bigint|int128|llvm-codegen | 25,503 | <p>All Rust's integer types are compiled to <a href="https://llvm.org/docs/LangRef.html#integer-type" rel="noreferrer">LLVM integers</a>. The LLVM abstract machine allows integers of any bit width from 1 to 2^23 - 1.* LLVM <a href="https://llvm.org/docs/LangRef.html#binary-operations" rel="noreferrer">instructions</a> typically work on integers of any size.</p>
<p>Obviously, there aren't many 8388607-bit architectures out there, so when the code is compiled to native machine code, LLVM has to decide how to implement it. The semantics of an abstract instruction like <a href="https://llvm.org/docs/LangRef.html#add-instruction" rel="noreferrer"><code>add</code></a> are defined by LLVM itself. Typically, abstract instructions that have a single-instruction equivalent in native code will be compiled to that native instruction, while those that don't will be emulated, possibly with multiple native instructions. <a href="https://stackoverflow.com/a/57340591/3650362">mcarton's answer</a> demonstrates how LLVM compiles both native and emulated instructions.</p>
<p>(This doesn't only apply to integers that are larger than the native machine can support, but also to those that are smaller. For example, modern architectures might not support native 8-bit arithmetic, so an <code>add</code> instruction on two <code>i8</code>s may be emulated with a wider instruction, the extra bits discarded.)</p>
<blockquote>
<p>Does the compiler somehow use 2 registers for one <code>i128</code> value? Or are they using some kind of big integer struct to represent them?</p>
</blockquote>
<p>At the level of LLVM IR, the answer is neither: <code>i128</code> fits in a single register, just like every other <a href="https://llvm.org/docs/LangRef.html#single-value-types" rel="noreferrer">single-valued type</a>. On the other hand, once translated to machine code, there isn't really a difference between the two, because structs may be decomposed into registers just like integers. When doing arithmetic, though, it's a pretty safe bet that LLVM will just load the whole thing into two registers.</p>
<hr>
<p>* However, not all LLVM backends are created equal. This answer relates to x86-64. I understand that backend support for sizes larger than 128 and non-powers of two is spotty (which may partly explain why Rust only exposes 8-, 16-, 32-, 64-, and 128-bit integers). <a href="https://www.reddit.com/r/rust/comments/cm4qf9/how_does_rusts_128bit_integer_i128_work_on_a/ew0bpwt/" rel="noreferrer">According to est31 on Reddit</a>, rustc implements 128 bit integers in software when targeting a backend that doesn't support them natively.</p> |
15,610,887 | binding to a property of an object | <p>I want to <strong>bind</strong> a <strong>series of TextBoxes</strong> in a grid into <strong>properties of an object</strong> which is itself another property in my ViewModel (the DataContext).</p>
<p><code>CurrentPerson</code> consists of <code>Name</code> and <code>Age</code> properties</p>
<p><strong>Inside the ViewModel:</strong></p>
<pre><code>public Person CurrentPerson { get; set ... (with OnPropertyChanged)}
</code></pre>
<p>Xaml :</p>
<pre><code><TextBox Text="{Binding Name}" >
<TextBox Text="{Binding Age}" >
</code></pre>
<p>I wasn't sure on the approach to use, I set another DataContext in the grid scope, without any result, Also tried setting the source and path like Source=CurrentPerson, Path=Age again without any result, these were for trial and see if there would be any change or not.</p>
<p>How should I achieve this ?</p> | 15,613,446 | 2 | 0 | null | 2013-03-25 08:54:59.233 UTC | 6 | 2020-03-10 08:24:01.547 UTC | 2017-05-22 20:02:37.24 UTC | null | 1,194,402 | null | 50,506 | null | 1 | 19 | c#|wpf|mvvm|binding | 58,953 | <p>Does your <code>Person</code> class members <code>Name</code> and <code>Age</code> raise INPC themselves?</p>
<p>If you want to update the value of either <code>Name</code> or <code>Age</code> in the <code>ViewModel</code> and have it reflect in the view, you need them to raise property changed individually inside <code>Person</code> class as well.</p>
<p>The bindings are fine, but the view is not notified of changes from the view model. Also remember <code>UpdateSourceTrigger</code> for a <code>TextBox</code> by default is <code>LostFocus</code>, so setting that to <code>PropertyChanged</code> will update your string in the <code>ViewModel</code> as you're typing.</p>
<p>Simple example:</p>
<pre><code>public class Person : INotifyPropertyChanged {
private string _name;
public string Name {
get {
return _name;
}
set {
if (value == _name)
return;
_name = value;
OnPropertyChanged(() => Name);
}
}
// Similarly for Age ...
}
</code></pre>
<p>Now your xaml would be:</p>
<pre><code><StackPanel DataContext="{Binding CurrentPerson}">
<TextBox Text="{Binding Name}" />
<TextBox Margin="15"
Text="{Binding Age}" />
</StackPanel>
</code></pre>
<p>or you can also bind as suggested by @Kshitij:</p>
<pre><code><StackPanel>
<TextBox Text="{Binding CurrentPerson.Name}" />
<TextBox Margin="15"
Text="{Binding CurrentPerson.Age}" />
</StackPanel>
</code></pre>
<p>and to update view model as you're typing:</p>
<pre><code><StackPanel DataContext="{Binding CurrentPerson}">
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Margin="15"
Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</code></pre> |
15,560,007 | Declaring a long constant byte array | <p>I have a long byte array that I need to declare in my C# code. I do something like this:</p>
<pre><code>public static class Definitions
{
public const byte[] gLongByteArray = new byte[] {
1, 2, 3,
//and so on
};
}
</code></pre>
<p>But I get an error that the const array may be initialized only with nulls.</p>
<p>If I change <code>const</code> to <code>static</code> it compiles, but the question I have is this -- when I declare it as <code>public static byte[] gLongByteArray</code> it won't be initialized every time my app loads, right? In that case the <code>gLongByteArray</code> variable will simply point to an array that is defined in the compiled exe/dll file that loads into memory. The reason I'm asking is because this array is pretty long and I don't want my program to waste CPU cycles on loading it every time the app starts, or worse, this class is referenced...</p> | 15,560,041 | 4 | 11 | null | 2013-03-21 23:23:19.59 UTC | null | 2016-09-26 14:28:06.583 UTC | 2013-03-24 12:16:11.63 UTC | null | 41,071 | null | 670,017 | null | 1 | 22 | c#|arrays|constants | 40,954 | <p><em>Compile-time constants</em> (those declared with the <code>const</code> keyword) are severely restricted. No code must be executed to get such a constant, or otherwise it could not be a compile-time constant. <code>const</code> constants are <code>static</code> by default.</p>
<p>If you want to create a constant and you cannot use a compile-time constant, you can use <code>static readonly</code> instead:</p>
<pre><code>public static readonly byte[] longByteArray = new byte[] { 1, 2, 3, 4, 5 };
</code></pre>
<p>The <code>static</code> keyword ensures it is initialized only once, and part of the declaring type (and not each instance). The <code>readonly</code> keyword ensures the <code>longByteArray</code> <em>variable</em> cannot be changed afterwards.</p>
<pre><code>Definitions.longByteArray = new byte[] { 4, 5, 6 }; // Not possible.
</code></pre>
<p><strong>Warning</strong>: An array is mutable, so in the above code I <em>can</em> still do this:</p>
<pre><code>Definitions.longByteArray[3] = 82; // Allowed.
</code></pre>
<p>To prevent that, make the type not an array but a read-only collection interface, such as <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="noreferrer"><code>IEnumerable<T></code></a> or <a href="http://msdn.microsoft.com/en-us/library/hh192385.aspx" rel="noreferrer"><code>IReadOnlyList<T></code></a>, or even better a read-only collection type such as <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx" rel="noreferrer"><code>ReadOnlyCollection<T></code></a> which doesn't even allow modification through casting.</p>
<pre><code>public static readonly IReadOnlyList<byte> longByteArray = new byte[] { 1, 2, 3, 4, 5 };
</code></pre> |
15,492,481 | Context-free grammar for C | <p>I'm working on a parser for C. I'm trying to find a list of all of the context-free derivations for C. Ideally it would be in BNF or similar. I'm sure such a thing is out there, but googling around hasn't given me much. </p>
<p>Reading the source code for existing parsers/compilers has proven to be far more confusing than helpful, as most that I've found are much more ambitious and complicated than the one I'm building.</p> | 16,247,692 | 2 | 7 | null | 2013-03-19 06:00:15.823 UTC | 9 | 2020-08-22 20:40:01.05 UTC | 2017-03-01 19:40:43.23 UTC | null | 3,924,118 | null | 1,467,997 | null | 1 | 25 | c|context-free-grammar|bnf | 25,830 | <p>You could always use Annex A of the C11 standard itself. The freely available draft standard will work for your purposes, at <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf</a> .</p> |
15,949,319 | ruby on rails how to render a page without layout and other head field | <pre><code>else
respond_to do |format|
format.html { render "tabelle/show" }
end
end
</code></pre>
<p>I want to render the page ...with only the code in that page....not add <code><head></code>...layout and <code><body></code> field in ruby on rails.
I only want to show the result of code in the page tabelle/show.html.haml</p> | 15,949,416 | 4 | 2 | null | 2013-04-11 12:53:56.147 UTC | 5 | 2018-01-29 23:35:04.267 UTC | 2013-04-12 07:49:27.477 UTC | null | 274,008 | null | 2,265,394 | null | 1 | 34 | ruby-on-rails|ruby|render | 26,337 | <p>You can do it like this:</p>
<pre><code>format.html { render "tabelle/show", :layout => false }
</code></pre> |
15,823,991 | IOS - remove ALL padding from UITextView | <p>There are many great examples on SO to remove the left padding of a UITextView.</p>
<p><a href="https://stackoverflow.com/questions/746670/how-to-lose-margin-padding-in-uitextview">How to lose margin/padding in UITextView?</a></p>
<p>However, I need to remove the right padding too.</p>
<p>I have tried...</p>
<pre><code>[tv setContentInset: UIEdgeInsetsMake(-4,-8,-8,-X)];//where X is any integer
</code></pre>
<p>and just about every other permutation of the last two values to remove the padding and nothing seems to work. Have also tried</p>
<pre><code>[tv sizeToFit];
[tv setTextAlignment:[NSTextAlignmentRight]];
</code></pre>
<p>The following Text in the Textview says "00"</p>
<p><img src="https://i.stack.imgur.com/3kOp8.png" alt="enter image description here"></p> | 20,269,793 | 6 | 6 | null | 2013-04-05 00:26:54.08 UTC | 20 | 2021-12-12 10:55:35.75 UTC | 2017-05-23 12:02:47.733 UTC | null | -1 | null | 1,296,896 | null | 1 | 86 | ios|uitextview|padding | 42,593 | <p>Although it is iOS 7 only, an extremely clean solution is to set the textView's textContainerInsets as such:</p>
<pre><code>[textView setTextContainerInset:UIEdgeInsetsZero];
textView.textContainer.lineFragmentPadding = 0; // to remove left padding
</code></pre>
<p>This will effectively remove all padding (insets) around the text inside the text view. If your deployment target is iOS 7+ then this is the best solution thus far.</p> |
33,645,037 | While loop with empty body checking volatile ints - what does this mean? | <p>I am looking at a C++ class which has the following lines:</p>
<pre><code>while( x > y );
return x - y;
</code></pre>
<p><code>x</code> and <code>y</code> are member variables of type <code>volatile int</code>. I do not understand this construct. </p>
<p>I found the code stub here: <a href="https://gist.github.com/r-lyeh/cc50bbed16759a99a226" rel="noreferrer">https://gist.github.com/r-lyeh/cc50bbed16759a99a226</a>. I guess it is not guaranteed to be correct or even work.</p> | 33,645,206 | 4 | 16 | null | 2015-11-11 05:59:37.55 UTC | 3 | 2015-11-12 13:01:32.63 UTC | 2015-11-11 22:16:53.137 UTC | null | 43,681 | null | 2,713,740 | null | 1 | 34 | c++|while-loop|volatile | 6,326 | <p>Since <code>x</code> and <code>y</code> have been declared as volatile, the programmer expects that they will be changed from outside the program.</p>
<p>In that case, your code will remain in the loop</p>
<pre><code> while(x>y);
</code></pre>
<p>and will return the value <code>x-y</code> after the values are changed from outside such that <code>x <= y</code>. The exact reason why this is written can be guessed after you tell us more about your code and where you saw it. The <code>while</code> loop in this case is a waiting technique for some other event to occur.</p> |
35,537,619 | Why are ES6 classes not hoisted? | <p>Since ES6 classes are just a <em>syntactical sugar over JavaScript's existing prototype-based inheritance</em> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes" rel="noreferrer">[1]</a> it would (IMO) make sense to hoist it's definition:</p>
<pre><code>var foo = new Foo(1, 2); //this works
function Foo(x, y) {
this.x = x;
this.y = y;
}
</code></pre>
<p>But the following won't work:</p>
<pre><code>var foo = new Foo(1, 2); //ReferenceError
class Foo {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
</code></pre>
<p>Why are ES6 classes not hoisted?</p> | 35,537,963 | 4 | 7 | null | 2016-02-21 14:53:23.2 UTC | 11 | 2021-01-12 14:02:52.143 UTC | null | null | null | null | 190,438 | null | 1 | 70 | javascript|ecmascript-6 | 14,666 | <blockquote>
<p>Why are ES6 classes not hoisted?</p>
</blockquote>
<p>Actually they <em>are</em> hoisted (the variable binding is available in the whole scope) just like <a href="https://stackoverflow.com/a/31222689/157247"><code>let</code> and <code>const</code> are</a> - they only are not initialised.</p>
<blockquote>
<p>It would make sense to hoist its definition</p>
</blockquote>
<p>No. It's never a good idea to use a class before its definition. Consider the example</p>
<pre><code>var foo = new Bar(); // this appears to work
console.log(foo.x) // but doesn't
function Bar(x) {
this.x = x || Bar.defaultX;
}
Bar.defaultX = 0;
</code></pre>
<p>and compare it to</p>
<pre><code>var foo = new Bar(); // ReferenceError
console.log(foo.x);
class Bar {
constructor (x = Bar.defaultX) {
this.x = x;
}
}
Bar.defaultX = 0;
</code></pre>
<p>which throws an error as you would expect. This is a problem for static properties, prototype mixins, decorators and everything. Also it is quite important for subclassing, which broke entirely in ES5 when you used a class with its non-adjusted prototype, but now throws an error if an <code>extend</code>ed class is not yet initialised.</p> |
13,655,540 | Read resource bundle properties in a managed bean | <p>Using <code><resource-bundle></code> files I'm able to have i18n text in my JSF pages. </p>
<p>But is it possible to access these same properties in my managed bean so I can set faces messages with i18n values?</p> | 13,656,194 | 3 | 0 | null | 2012-12-01 01:43:39.793 UTC | 9 | 2016-06-07 13:51:35.33 UTC | 2016-06-07 13:49:11.38 UTC | null | 157,882 | null | 884,123 | null | 1 | 13 | jsf|internationalization|managed-bean | 24,673 | <p>Assuming that you've configured it as follows:</p>
<pre><code><resource-bundle>
<base-name>com.example.i18n.text</base-name>
<var>text</var>
</resource-bundle>
</code></pre>
<p>If your bean is request scoped, you can just inject the <code><resource-bundle></code> as <code>@ManagedProperty</code> by its <code><var></code>:</p>
<pre><code>@ManagedProperty("#{text}")
private ResourceBundle text;
public void someAction() {
String someKey = text.getString("some.key");
// ...
}
</code></pre>
<p>Or if you just need some specific key:</p>
<pre><code>@ManagedProperty("#{text['some.key']}")
private String someKey;
public void someAction() {
// ...
}
</code></pre>
<hr>
<p>If your bean is however in a broader scope, then evaluate <code>#{text}</code> programmatically in method local scope:</p>
<pre><code>public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle text = context.getApplication().evaluateExpressionGet(context, "#{text}", ResourceBundle.class);
String someKey = text.getString("some.key");
// ...
}
</code></pre>
<p>Or if you only need some specific key:</p>
<pre><code>public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
String someKey = context.getApplication().evaluateExpressionGet(context, "#{text['some.key']}", String.class);
// ...
}
</code></pre>
<hr>
<p>You can even just get it by the standard <code>ResourceBundle</code> API the same way as JSF itself is already doing under the covers, you'd only need to repeat the base name in code:</p>
<pre><code>public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle text = ResourceBundle.getBundle("com.example.i18n.text", context.getViewRoot().getLocale());
String someKey = text.getString("some.key");
// ...
}
</code></pre>
<hr>
<p>Or if you're managing beans by CDI instead of JSF, then you can create a <code>@Producer</code> for that:</p>
<pre><code>public class BundleProducer {
@Produces
public PropertyResourceBundle getBundle() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{text}", PropertyResourceBundle.class);
}
}
</code></pre>
<p>And inject it as below:</p>
<pre><code>@Inject
private PropertyResourceBundle text;
</code></pre>
<hr>
<p>Alternatively, if you're using the <code>Messages</code> class of the JSF utility library <a href="http://omnifaces.org" rel="noreferrer">OmniFaces</a>, then you can just set its resolver once to let all <code>Message</code> methods utilize the bundle.</p>
<pre><code>Messages.setResolver(new Messages.Resolver() {
public String getMessage(String message, Object... params) {
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", Faces.getLocale());
if (bundle.containsKey(message)) {
message = bundle.getString(message);
}
return MessageFormat.format(message, params);
}
});
</code></pre>
<p>See also the example in the <a href="http://omnifaces.org/docs/javadoc/current/org/omnifaces/util/Messages.html" rel="noreferrer">javadoc</a> and the <a href="http://showcase.omnifaces.org/utils/Messages" rel="noreferrer">showcase page</a>.</p> |
13,647,346 | Calling async method in controller | <p>I have a controller with something like the following:</p>
<pre><code>public MyController : Controller
{
public ActionResult DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
</code></pre>
<p>When calling my controller I get the following error:</p>
<blockquote>
<p>An asynchronous operation cannot be started at this time. Asynchronous operations
may only be started within an asynchronous handler or module or during certain
events in the Page lifecycle. If this exception occurred while executing a Page,
ensure that the Page is marked <code><%@ Page Async="true" %></code>.</p>
</blockquote>
<p>Now I dont have control over <code>CallSomeMethodWhichDoesAsyncOperations</code> and the method itself is not async but internally does some async fire and forget. What can I do to fix it? Have tried to change the controller to an <code>AsyncController</code> and/or making the method in the controller async.</p>
<p>Edit:</p>
<p>When I attempted to use an AsyncController I first tried, with the same result</p>
<pre><code>public MyController : AsyncController
{
public ActionResult DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
</code></pre>
<p>And then </p>
<pre><code>public MyController : AsyncController
{
public async Task<ActionResult> DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
</code></pre>
<p>Which did change the exception to the following "An asynchronous module or handler completed while an asynchronous operation was still pending."</p> | 13,648,083 | 1 | 7 | null | 2012-11-30 14:41:30.21 UTC | 7 | 2014-07-09 23:12:15.317 UTC | 2014-07-09 23:12:15.317 UTC | null | 41,956 | null | 865,337 | null | 1 | 26 | c#|asp.net-mvc-4|async-await | 50,908 | <blockquote>
<p>Now I dont have control over CallSomeMethodWhichDoesAsyncOperations and the method itself is not async but internally does some async fire and forget. What can I do to fix it?</p>
</blockquote>
<p>Contact the person who wrote it and make <em>them</em> fix it.</p>
<p>Seriously, that's the best option. There's no good fix for this - only a hack.</p>
<p>You can hack it to work like this:</p>
<pre><code>public MyController : Controller
{
public async Task<ActionResult> DoSomething()
{
await Task.Run(() => CallSomeMethodWhichDoesAsyncOperations());
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}
</code></pre>
<p><strong>This is not recommended.</strong> This solution pushes off work to a background thread, so when the <code>async</code> operations resume, they will not have an <code>HttpContext</code>, etc. This solution completes the request while there is still processing to be done. This solution will not behave correctly if the server is stopped/recycled at just the wrong time.</p>
<p>There is only one proper solution: change <code>CallSomeMethodWhichDoesAsyncOperations</code>.</p> |
13,754,694 | What is the correct way to read a serial port using .NET framework? | <p>I've read a lot of questions here about how to read data from serial ports using the .NET SerialPort class but none of the recommended approaches have proven completely efficient for me.</p>
<p>Here is the code I am using for now:</p>
<pre><code>SerialPort port = new SerialPort("COM1");
port.DataReceived += new SerialDataReceivedEventHandler(MyDataReceivedHandler);
</code></pre>
<p>And the event handler:</p>
<pre><code>void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int count = port.BytesToRead;
byte[] ByteArray = new byte[count];
port.Read(ByteArray, 0, count);
}
</code></pre>
<p>But I am still sometimes missing data. I've tried different way of reading the data in the event handler but with no luck.</p>
<p>As the .NET 4.5 brings new possibilities to do some asynchronous tasks, like with the <a href="http://msdn.microsoft.com/en-us/library/hh137813.aspx" rel="nofollow noreferrer">ReadAsync</a> method that seems to be useable on a SerialPort stream, I'm curious to see what would be the recommended approach to handle those cases.</p> | 13,755,084 | 3 | 3 | null | 2012-12-06 23:45:44.867 UTC | 21 | 2022-08-21 00:45:13.457 UTC | 2022-08-21 00:45:13.457 UTC | null | 1,459,996 | null | 1,374,267 | null | 1 | 37 | c#|serial-port|.net-4.5 | 163,112 | <p>Could you try something like this for example I think what you are wanting to utilize is the <strong>port.ReadExisting()</strong> Method</p>
<pre><code> using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
</code></pre>
<p>Or is you want to do it based on what you were trying to do , you can try this</p>
<pre><code>public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
</code></pre> |
13,637,856 | .NET Caching how does Sliding Expiration work? | <p>If I use an ObjectCache and add an item like so:</p>
<pre><code>ObjectCache cache = MemoryCache.Default;
string o = "mydata";
cache.Add("mykey", o, DateTime.Now.AddDays(1));
</code></pre>
<p>I understand the object will expire in 1 day. But if the object is accessed 1/2 a day later using:</p>
<pre><code>object mystuff = cache["mykey"];
</code></pre>
<p>Does this reset the timer so it's now 1 day since the last access of the entry with the key "mykey", or it still 1/2 a day until expiry?</p>
<p>If the answer is no is there is a way to do this I would love to know.</p>
<p>Thanks.</p> | 13,637,942 | 2 | 0 | null | 2012-11-30 01:51:07.397 UTC | 8 | 2022-01-11 22:02:31.073 UTC | 2022-01-11 22:02:31.073 UTC | null | 107,945 | null | 107,945 | null | 1 | 60 | c#|.net|caching | 56,975 | <p>There are two types of cache policies you can use:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.absoluteexpiration.aspx" rel="noreferrer"><code>CacheItemPolicy.AbsoluteExpiration</code></a> will expire the entry after a set amount of time. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.slidingexpiration.aspx" rel="noreferrer"><code>CacheItemPolicy.SlidingExpiration</code></a> will expire the entry if it hasn't been accessed in a set amount of time. </p>
<p>The <code>ObjectCache Add()</code> overload you're using treats it as an absolute expiration, which means it'll expire after 1 day, regardless of how many times you access it. You'll need to use one of the other <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.add.aspx" rel="noreferrer">overloads</a>. Here's how you'd set a sliding expiration (it's a bit more complicated):</p>
<pre><code>CacheItem item = cache.GetCacheItem("item");
if (item == null) {
CacheItemPolicy policy = new CacheItemPolicy {
SlidingExpiration = TimeSpan.FromDays(1)
}
item = new CacheItem("item", someData);
cache.Set(item, policy);
}
</code></pre>
<p>You change the TimeSpan to the appropriate cache time that you want. </p> |
13,542,213 | Git, see a list of comments of my last N commits | <p>Is there a way to see a list of comments and time of my last N commits in Git?</p>
<p>After looking on SO, the only relevant thing I have found is
<a href="https://stackoverflow.com/questions/1314950/git-get-all-commits-and-blobs-they-created">Git - get all commits and blobs they created</a>, but it shows all commits from all users, and outputs a lot of other information.</p> | 13,542,327 | 7 | 0 | null | 2012-11-24 14:36:11.9 UTC | 29 | 2021-10-08 19:02:28.203 UTC | 2017-05-23 12:26:21.29 UTC | null | -1 | null | 1,090,562 | null | 1 | 176 | git|git-commit | 110,580 | <p>If you want to use the command line you can use the <code>--author=<your name></code></p>
<p>For example: to see your last 5 commits</p>
<pre><code>git log -n 5 --author=Salvador
</code></pre>
<p>If you want a simpler one line solution:</p>
<pre><code>git log --oneline -n 5 --author=Salvador
</code></pre>
<p><strong>Edited to add</strong></p>
<p>If you like the single line version, try creating an alias for <code>git log</code> like this (this is what I have for zsh)</p>
<pre><code>alias glog="git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
</code></pre>
<p>Now, I can just use:</p>
<pre><code>glog -n 5
</code></pre>
<p>And I get a nice output such as:</p>
<p><img src="https://i.stack.imgur.com/R9zyV.png" alt="Terminal output"></p>
<p>Which is colourised, shows the name of the author and also shows the graph and you can still pass in other flags (such as --author) which lets you filter it even more.</p> |
51,863,940 | What does DispatchWallTime do on iOS? | <p>I thought the difference between DispatchTime and DispatchWallTime had to do with whether the app was suspended or the device screen was locked or something: DispatchTime should pause, whereas DispatchWallTime should keep going because clocks in the real world keep going.</p>
<p>So I wrote a little test app:</p>
<pre><code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("backgrounding the app, starting timers for 60 seconds", Date())
DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
print("deadline 60 seconds ended", Date())
}
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60) {
print("wallDeadline 60 seconds ended", Date())
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("app coming to front", Date())
}
}
</code></pre>
<p>I ran the app on my device. I backgrounded the app, waited for a while, then brought the app to the foreground. Sometimes "waited for a while" included switching off the screen. I got results like this:</p>
<pre><code>backgrounding the app, starting timers for 60 seconds 2018-08-15 17:41:18 +0000
app coming to front 2018-08-15 17:41:58 +0000
wallDeadline 60 seconds ended 2018-08-15 17:42:24 +0000
deadline 60 seconds ended 2018-08-15 17:42:24 +0000
backgrounding the app, starting timers for 60 seconds 2018-08-15 17:42:49 +0000
app coming to front 2018-08-15 17:43:21 +0000
wallDeadline 60 seconds ended 2018-08-15 17:43:55 +0000
deadline 60 seconds ended 2018-08-15 17:43:55 +0000
</code></pre>
<p>The delay before the <code>deadline</code> timer fires is not as long as I expected: it's 6 seconds over the 60 second deadline, even though I "slept" the app for considerably longer than that. But even more surprising, both timers fire at the same instant.</p>
<p>So what does <code>wallDeadline</code> do on iOS that's <em>different</em> from what <code>deadline</code> does?</p> | 52,844,432 | 2 | 6 | null | 2018-08-15 17:53:28.04 UTC | 8 | 2019-04-09 18:53:38.157 UTC | null | null | null | null | 341,994 | null | 1 | 12 | ios|grand-central-dispatch | 2,056 | <p>This question has been here for quite a while without any answers, so I'd like to give it a try and point out subtle difference I noticed in practice.</p>
<blockquote>
<p>DispatchTime should pause, whereas DispatchWallTime should keep going
because clocks in the real world keep going</p>
</blockquote>
<p>You are correct here, at least they are supposed to act this way. However it tends to be really tricky to check, that DispatchTime works as expected. When iOS app is running under Xcode session, it has unlimited background time and isn't getting suspended. I also couldn't achieve that by running application without Xcode connected, so it's still a big question if DispatchTime is paused under whatever conditions. However the main thing to note is that <strong>DispatchTime doesn't depend on the system clock</strong>.</p>
<p><strong>DispatchWallTime</strong> works pretty much the same (it's not being suspended), apart from that it <strong>depends on the system clock</strong>. In order to see the difference, you can try out a little longer timer, say, 5 minutes. After that go to the system settings and set time 1 hour forward. If you now open the application you can notice, that <code>WallTimer</code> immediately expires whereas <code>DispatchTime</code> will keep waiting its time.</p> |
39,741,428 | ES7 Object.entries() in TypeScript not working | <p>I have an issue with transpiling ES7 code with TypeScript. This code:</p>
<pre><code>const sizeByColor = {
red: 100,
green: 500,
};
for ( const [ color, size ] of Object.entries(sizeByColor) ) {
console.log(color);
console.log(size);
}
</code></pre>
<p>gives the error:</p>
<p><code>TypeError: Object.entries is not a function</code></p>
<p><strong>TypeScript v2.0.3</strong></p>
<p>tsconfig.json:</p>
<pre><code>{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noEmitOnError": true,
"outDir": "dist",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"pretty": true,
"lib": [ "es2017" ],
},
"exclude": [
"node_modules"
],
"include": [
"./node_modules/@types/**/*.d.ts",
"./src/**/*.ts"
]
}
</code></pre>
<p>I want to iterate trough object with <code>Object.entries()</code>, so I assigned internal definitions <code>"lib": [ "es2017" ]</code>, but still, typescript wont allow me to transpile it.</p> | 39,815,452 | 5 | 4 | null | 2016-09-28 08:00:31.287 UTC | 4 | 2021-07-11 09:51:10.717 UTC | 2017-01-18 14:43:32.19 UTC | null | 1,079,075 | null | 2,465,883 | null | 1 | 25 | typescript | 53,300 | <p>Hm, it looks i forgot to inject <code>core-js</code> polyfill to <code>Object.entries</code>. import <code>'core-js/fn/object/entries';</code> With this polyfill transpilation works, but IDE is still complaining about it. When I include <code>@types/core-js</code> directly, IDE is ok, but Typescript will crash due to duplicate declarations in "lib/es2017".. It looks like IDE (WebStorm) cant handle "lib" settings inside <code>tsconfig.json</code></p>
<p><strong>EDIT:</strong>
Yey, i tried to modify WebStorm settings, and after set "Use TypeScript service (experimental)" to true, everything is ok !</p> |
3,938,676 | Python save matplotlib figure on an PIL Image object | <p>HI, is it possible that I created a image from matplotlib and I save it on an image object I created from PIL? Sounds very hard? Who can help me?</p> | 4,302,192 | 2 | 0 | null | 2010-10-15 00:45:33.723 UTC | 9 | 2022-03-15 16:40:19.973 UTC | null | null | null | null | 469,652 | null | 1 | 16 | python|image|matplotlib|python-imaging-library | 12,045 | <p>To render Matplotlib images in a webpage in the Django Framework:</p>
<ul>
<li><p>create the matplotlib plot</p>
</li>
<li><p>save it as a png file</p>
</li>
<li><p>store this image in a string buffer (using PIL)</p>
</li>
<li><p>pass this buffer to Django's <em><strong>HttpResponse</strong></em> (set <em>mime type</em> image/png)</p>
</li>
<li><p>which returns a <em>response object</em> (the rendered plot in this case).<br/><br/></p>
</li>
</ul>
<p>In other words, all of these steps should be placed in a Django <em>view</em> function, in <em><strong>views.py</strong></em>:</p>
<pre><code>from matplotlib import pyplot as PLT
import numpy as NP
import StringIO
import PIL
from django.http import HttpResponse
def display_image(request) :
# next 5 lines just create a matplotlib plot
t = NP.arange(-1., 1., 100)
s = NP.sin(NP.pi * x)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, 'b.')
buffer = StringIO.StringIO()
canvas = PLT.get_current_fig_manager().canvas
canvas.draw()
pil_image = PIL.Image.frombytes(
'RGB', canvas.get_width_height(), canvas.tostring_rgb())
pil_image.save(buffer, 'PNG')
PLT.close()
# Django's HttpResponse reads the buffer and extracts the image
return HttpResponse(buffer.getvalue(), mimetype='image/png')
</code></pre> |
9,423,510 | How to Check or Uncheck all Items in VB.NET CheckedListBox Control | <p>I need to select and unselect all items in a VB.NET <code>CheckedListBox</code> control, what is the best way to do this?</p>
<pre><code> Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With clbCheckedListBox
.Items.Add("Select/UnSelect All")
.Items.Add("Enero")
.Items.Add("Febrero")
.Items.Add("Marzo")
.Items.Add("Abril")
.Items.Add("Mayo")
.Items.Add("Junio")
.Items.Add("Julio")
.Items.Add("Agosto")
.Items.Add("Septiembre")
.Items.Add("Octubre")
.Items.Add("Noviembre")
.Items.Add("Diciembre")
.SelectedIndex = 0
End With
End Sub
Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
If e.NewValue = CheckState.Checked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
Next
ElseIf e.NewValue = CheckState.Unchecked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
Next
End If
End If
End Sub
</code></pre>
<p>After Hours the above code work fine for me !</p> | 19,778,263 | 8 | 2 | null | 2012-02-24 00:13:59.567 UTC | 5 | 2021-07-16 20:14:11.907 UTC | 2012-12-18 03:13:41.163 UTC | null | 194,721 | null | 194,721 | null | 1 | 7 | vb.net | 109,568 | <p>Ricardo, perhaps this might be what you are looking for:</p>
<pre><code>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim items$() = New String() {"Select/UnSelect All", "Enero",
"Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)
Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
Dim newCheckedState As CheckState = e.NewValue
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
Next
End If
End Sub
</code></pre> |
16,091,581 | How many prime numbers are there (available for RSA encryption)? | <p>Am I mistaken in thinking that the security of RSA encryption, in general, is limited by the amount of known prime numbers?</p>
<p>To crack (or create) a private key, one has to combine the right pair of prime numbers.</p>
<p>Is it impossible to publish a list of all the prime numbers in the range used by RSA? Or is that list sufficiently large to make this brute force attack unlikely? Wouldn't there be "commonly used" prime numbers?</p> | 16,091,676 | 2 | 3 | null | 2013-04-18 19:34:31.393 UTC | 12 | 2015-10-16 17:00:03.877 UTC | 2014-08-04 15:17:23.653 UTC | null | 275,567 | null | 1,653,320 | null | 1 | 50 | cryptography|rsa|primes|prime-factoring | 21,427 | <p>RSA doesn't pick from a list of known primes: it generates a new very large number, then applies an algorithm to find a nearby number that is almost certainly prime. See <a href="https://crypto.stackexchange.com/questions/71/how-can-i-generate-large-prime-numbers-for-rsa">this useful description of large prime generation</a>):</p>
<blockquote>
<p>The standard way to generate big prime numbers is to take a preselected random number of the desired length, apply a Fermat test (best with the base 2 as it can be optimized for speed) and then to apply a certain number of Miller-Rabin tests (depending on the length and the allowed error rate like 2−100) to get a number which is very probably a prime number.</p>
</blockquote>
<p>(You might ask why, in that case, we're not using this approach when we try and find larger and larger primes. The answer is that the largest known prime <a href="http://en.wikipedia.org/wiki/Largest_known_prime_number" rel="noreferrer">has over 17 million digits</a>- far beyond even the very large numbers typically used in cryptography).</p>
<p>As for whether collisions are possible- modern key sizes (depending on your desired security) range from 1024 to 4096, which means the prime numbers range from 512 to 2048 bits. That means that your prime numbers are on the order of 2^512: over 150 digits long.</p>
<p>We can very roughly estimate the density of primes using <code>1 / ln(n)</code> (see <a href="http://primes.utm.edu/howmany.shtml" rel="noreferrer">here</a>). That means that among these <code>10^150</code> numbers, there are approximately <code>10^150/ln(10^150)</code> primes, which works out to <code>2.8x10^147</code> primes to choose from- certainly more than you could fit into any list!!</p>
<p>So yes- the number of primes in that range is staggeringly enormous, and collisions are effectively impossible. (Even if you generated a trillion possible prime numbers, forming a septillion combinations, the chance of any two of them being the same prime number would be <code>10^-123</code>).</p> |
55,575,782 | Xcode Missing Support Files iOS 12.2 (16E227) | <p>My device is running iOS 12.2, but the latest Xcode version available (on the store, and directly from developer.apple, which just pushes me to the store) does not provide the support files for that iOS version, so I cannot build to devices.</p>
<p>Here's the error message from Xcode:</p>
<p><a href="https://i.stack.imgur.com/dmXBD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dmXBD.png" alt="enter image description here"></a></p>
<p>And my Xcode build running on macOS Mojava v.10.14:</p>
<p><a href="https://i.stack.imgur.com/Y40p9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Y40p9.png" alt="enter image description here"></a></p>
<p>Are there any reputable other places to download a more recent Xcode beta from (or just the support files, in Xcode > Contents > Developer > Platforms > iPhoneOS.platform > DeviceSupport), or am I missing something here? </p> | 55,576,391 | 7 | 6 | null | 2019-04-08 14:30:47.563 UTC | 12 | 2020-12-15 20:33:26.347 UTC | null | null | null | null | 917,802 | null | 1 | 73 | ios|xcode | 30,722 | <p>Download device support files from here -<a href="https://github.com/iGhibli/iOS-DeviceSupport/blob/master/DeviceSupport/12.2%20(16E226).zip" rel="noreferrer">https://github.com/iGhibli/iOS-DeviceSupport/blob/master/DeviceSupport/12.2%20(16E226).zip</a>,
if your Xcode version doesn't have them.
Extract the zip file and copy to
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport.
Rename 16E266 folder to 16E227.
Restart XCode.</p>
<p>As pointed out by @DavidH, this worked for me.</p> |
29,026,596 | retrofit gson converter for nested json with different objects | <p>I've JSON structure like follows - </p>
<pre><code>{
"status": true,
"message": "Registration Complete.",
"data": {
"user": {
"username": "user88",
"email": "[email protected]",
"created_on": "1426171225",
"last_login": null,
"active": "1",
"first_name": "User",
"last_name": "",
"company": null,
"phone": null,
"sign_up_mode": "GOOGLE_PLUS"
}
}
}
</code></pre>
<p>Above format is common . Only <code>data</code> key can hold different types of information like <code>user</code>, <code>product</code>, <code>invoice</code> etc. </p>
<p>I want to keep <code>status</code>, <code>message</code> and <code>data</code> keys same in every rest response. <code>data</code> will be treated according to <code>status</code> and <code>message</code> will be displayed to user. </p>
<p>So basically, above format is desired in all apis. <strong>Only information inside <code>data</code> key will be different each time.</strong></p>
<p>And I've setup a following class and set it up as gson converter - <strong>MyResponse.java</strong></p>
<pre><code>public class MyResponse<T> implements Serializable{
private boolean status ;
private String message ;
private T data;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
</code></pre>
<p><strong>Deserializer.java</strong></p>
<pre><code>class Deserializer<T> implements JsonDeserializer<T>{
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException{
JsonElement content = je.getAsJsonObject();
// Deserialize it. You use a new instance of Gson to avoid infinite recursion to this deserializer
return new Gson().fromJson(content, type);
}
}
</code></pre>
<p>And used it as follows - </p>
<pre><code>GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
gsonBuilder.registerTypeAdapter(MyResponse.class, new Deserializer<MyResponse>());
...... ..... ....
restBuilder.setConverter(new GsonConverter(gsonBuilder.create()));
</code></pre>
<p><strong>Service interface</strong> is as follows - </p>
<pre><code>@POST("/register")
public void test1(@Body MeUser meUser, Callback<MyResponse<MeUser>> apiResponseCallback);
@POST("/other")
public void test2(Callback<MyResponse<Product>> apiResponseCallback);
</code></pre>
<p><strong><em>Problem</em></strong></p>
<p>I can access <code>status</code> and <code>message</code> fields from inside callback. But information inside <code>data</code> key is not parsed and model like <code>MeUser</code> and <code>Product</code> always returns as empty.</p>
<p>If I change json structure to following above code works perfectly - </p>
<pre><code>{
"status": true,
"message": "Registration Complete.",
"data": {
"username": "user88",
"email": "[email protected]",
"created_on": "1426171225",
"last_login": null,
"active": "1",
"first_name": "User",
"last_name": "",
"company": null,
"phone": null,
"sign_up_mode": "GOOGLE_PLUS"
}
}
</code></pre>
<p>How can I have it worked with specifying separate key inside <code>data</code> object and parse it successfully ?</p> | 29,155,435 | 3 | 9 | null | 2015-03-13 07:04:06.963 UTC | 13 | 2016-04-21 15:28:05.757 UTC | null | null | null | null | 2,054,829 | null | 1 | 16 | java|android|json|gson|retrofit | 12,329 | <p>If I can suggest to change something in json is that you have to add at one new field that defines the type of data, so json should look like below:</p>
<pre><code>{
"status": true,
"message": "Registration Complete.",
"dataType" : "user",
"data": {
"username": "user88",
"email": "[email protected]",
"created_on": "1426171225",
"last_login": null,
"active": "1",
"first_name": "User",
"last_name": "",
"company": null,
"phone": null,
"sign_up_mode": "GOOGLE_PLUS"
}
}
</code></pre>
<p>The <code>MyResponse</code> class has to have new filed <code>DataType</code> so it should look like below:</p>
<pre><code>public class MyResponse<T> implements Serializable{
private boolean status ;
private String message ;
private DataType dataType ;
private T data;
public DataType getDataType() {
return dataType;
}
//... other getters and setters
}
</code></pre>
<p>The <code>DataType</code> is an enum which defines type of data. You have to pass Data.class as param in constructor. For all data types you have to create new classes. <code>DataType</code> enum should look like below:</p>
<pre><code>public enum DataType {
@SerializedName("user")
USER(MeUser.class),
@SerializedName("product")
Product(Product.class),
//other types in the same way, the important think is that
//the SerializedName value should be the same as dataType value from json
;
Type type;
DataType(Type type) {
this.type = type;
}
public Type getType(){
return type;
}
}
</code></pre>
<p>The desarializator for Json should looks like below:</p>
<pre><code>public class DeserializerJson implements JsonDeserializer<MyResponse> {
@Override
public MyResponse deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonObject content = je.getAsJsonObject();
MyResponse message = new Gson().fromJson(je, type);
JsonElement data = content.get("data");
message.setData(new Gson().fromJson(data, message.getDataType().getType()));
return message;
}
}
</code></pre>
<p>And when you create <code>RestAdapter</code>, in the line where you register Deserializator, you should use this :</p>
<pre><code> .registerTypeAdapter(MyResponse.class, new DeserializerJson())
</code></pre>
<p>Other classes (types of data) you define like standard POJO for Gson in separated classes.</p> |
17,564,556 | java.io.EOFException when try to read from a socket | <p>i don't know why java.io.EOFException appear. i want to write a file after i get binary stream from server.</p>
<p><strong>Here's my code</strong></p>
<pre><code>inputStream = new DataInputStream(new BufferedInputStream(connection.getInputStream()));
FileOutputStream fos = new FileOutputStream("D:/Apendo API resumable download.txt");
byte b = inputStream.readByte();
while(b != -1){
fos.write(b);
b = inputStream.readByte();
}
fos.close();
</code></pre>
<p><strong>Stack trace</strong></p>
<pre><code>java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at HttpRequestJSON.JSONRequest.sendRequest(JSONRequest.java:64)
at HttpRequestJSON.Main.main(Main.java:56)
</code></pre> | 17,564,635 | 4 | 3 | null | 2013-07-10 07:15:57.12 UTC | 1 | 2015-04-12 10:26:57.1 UTC | 2014-01-04 00:47:39.26 UTC | null | 207,421 | null | 1,722,143 | null | 1 | 6 | java|file|io|eofexception | 49,177 | <p>DataInputStream.readByte API does not say it return -1 on EOS, it says</p>
<p>Returns:the next byte of this input stream as a signed 8-bit byte. </p>
<p>Throws: EOFException - if this input stream has reached the end.</p>
<p>It assumes that when working withh DataInputStream.readByte we know how many bytes are left in the stream. Otherwise we can use EOFException as an indicator of EOS.</p>
<p>BTW If you use read() you will get -1 on EOS without EOFException</p> |
22,233,650 | jquery nested ajax calls formatting | <p>I have a requirement to make 6 ajax calls in succession based on data from the previous call. I am nesting each call in the success of the previous call. my question is what are some good ways to format the code so that it doesnt end up a million rows across my editor?</p>
<pre><code> $.ajax({
type: "POST",
url: "someScript/someScript.php",
data: form + "&func=build",
success: function (result) {
if (result == "ok")
{
$.ajax({
type: "POST",
url: "someScript/someScript.php",
data: form + "&func=someOtherFunc",
success: function (result) {
if (result == "ok")
{
$.ajax({
type: "POST",
url: "someScript/someScript.php",
data: form + "&func=someOtherFunc",
success: function (result) {
if (result == "ok")
{
.....and so on
}
})
}
})
})
}
})
</code></pre>
<p>ignore brackets, syntax isnt important for this question.</p> | 22,233,745 | 2 | 2 | null | 2014-03-06 19:05:39.077 UTC | 11 | 2016-08-02 18:18:56.187 UTC | null | null | null | null | 2,187,142 | null | 1 | 24 | jquery|ajax|formatting | 44,241 | <p>You can do something like this</p>
<pre><code>function ajaxCall1(){
$.ajax({
success: function(){
ajaxCall2();
}
});
}
function ajaxCall2(){
$.ajax({
success: function(){
ajaxCall3();
}
});
}
function ajaxCall3(){
$.ajax({
success: function(){
ajaxCall4();
}
});
}
</code></pre> |
21,410,675 | Getting the original variable name for an LLVM Value | <p>The operands for an <a href="http://llvm.org/docs/doxygen/html/classllvm_1_1User.html" rel="noreferrer"><code>llvm::User</code></a> (e.g. instruction) are <a href="http://llvm.org/docs/doxygen/html/classllvm_1_1Value.html" rel="noreferrer"><code>llvm::Value</code></a>s.</p>
<p>After the <em>mem2reg</em> pass, variables are in <a href="http://en.wikipedia.org/wiki/Static_single_assignment_form" rel="noreferrer">SSA form</a>, and their names as corresponding to the original source code are lost. <code>Value::getName()</code> is only set for some things; for most variables, which are intermediaries, its not set.</p>
<p>The <em>instnamer</em> pass can be run to give all the variables names like <em>tmp1</em> and <em>tmp2</em>, but this doesn't capture where they originally come from. Here's some LLVM IR beside the original C code:</p>
<p><img src="https://i.stack.imgur.com/No5IK.png" alt="enter image description here"></p>
<p>I am building a simple html page to visualise and debug some optimisations I am working on, and I want to show the SSA variables as <strong>name<sub>ver</sub></strong> notation, rather than just temporary instnamer names. Its just to aid my readability.</p>
<p>I am getting my LLVM IR from clang with a commandline such as:</p>
<pre><code> clang -g3 -O1 -emit-llvm -o test.bc -c test.c
</code></pre>
<p>There are calls to <code>llvm.dbg.declare</code> and <code>llvm.dbg.value</code> in the IR; how do you turn into the original sourcecode names and SSA version numbers?</p>
<p>So how can I determine the original variable (or named constant name) from an <code>llvm::Value</code>? Debuggers must be able to do this, so how can I?</p> | 21,411,476 | 4 | 4 | null | 2014-01-28 16:03:22.703 UTC | 15 | 2020-07-23 22:20:37.18 UTC | 2014-01-30 06:51:14.337 UTC | null | 15,721 | null | 15,721 | null | 1 | 22 | compiler-construction|clang|llvm|debug-symbols|llvm-ir | 9,339 | <p>This is part of the debug information that's attached to LLVM IR in the form of metadata. Documentation <a href="http://llvm.org/docs/SourceLevelDebugging.html">is here</a>. An old blog post with some background <a href="http://blog.llvm.org/2010/04/extensible-metadata-in-llvm-ir.html">is also available</a>.</p>
<hr>
<pre><code>$ cat > z.c
long fact(long arg, long farg, long bart)
{
long foo = farg + bart;
return foo * arg;
}
$ clang -emit-llvm -O3 -g -c z.c
$ llvm-dis z.bc -o -
</code></pre>
<p>Produces this:</p>
<pre><code>define i64 @fact(i64 %arg, i64 %farg, i64 %bart) #0 {
entry:
tail call void @llvm.dbg.value(metadata !{i64 %arg}, i64 0, metadata !10), !dbg !17
tail call void @llvm.dbg.value(metadata !{i64 %farg}, i64 0, metadata !11), !dbg !17
tail call void @llvm.dbg.value(metadata !{i64 %bart}, i64 0, metadata !12), !dbg !17
%add = add nsw i64 %bart, %farg, !dbg !18
tail call void @llvm.dbg.value(metadata !{i64 %add}, i64 0, metadata !13), !dbg !18
%mul = mul nsw i64 %add, %arg, !dbg !19
ret i64 %mul, !dbg !19
}
</code></pre>
<p>With <code>-O0</code> instead of <code>-O3</code>, you won't see <code>llvm.dbg.value</code>, but you will see <code>llvm.dbg.declare</code>.</p> |
19,761,487 | How to make a textBox accept only Numbers and just one decimal point in Windows 8 | <p>I am new to windows 8 phone. I am writing a calculator app that can only accept numbers in the textbox and just a single decimal point. how do I prevent users from inputting two or more decimal Points in the text box as the calculator cant handle that.</p>
<p>I have been using Keydown Event, is that the best or should I use Key up?</p>
<pre><code>private void textbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
}
</code></pre> | 19,844,219 | 14 | 3 | null | 2013-11-04 04:06:25.803 UTC | 1 | 2018-06-27 08:47:20.847 UTC | 2013-11-04 04:25:13.71 UTC | null | 933,198 | null | 2,822,104 | null | 1 | 4 | c#|windows-phone-8 | 58,846 | <p>Thanks all for the help. I finally did this and it worked very well in the Text changed event. That was after setting the inputscope to Numbers</p>
<pre><code>string dika = Textbox1.Text;
int countDot = 0;
for (int i = 0; i < dika.Length; i++)
{
if (dika[i] == '.')
{
countDot++;
if (countDot > 1)
{
dika = dika.Remove(i, 1);
i--;
countDot--;
}
}
}
Textbox1.Text = dika;
Textbox1.Select(dika.Text.Length, 0);
</code></pre> |
17,672,649 | R: Remove multiple empty columns of character variables | <p>I have a data frame where all the variables are of character type. Many of the columns are completely empty, i.e. only the variable headers are there, but no values. Is there any way to subset out the empty columns?</p> | 17,672,737 | 9 | 1 | null | 2013-07-16 09:21:26.46 UTC | 12 | 2019-12-30 10:51:19.763 UTC | 2018-10-16 08:05:33.497 UTC | null | 2,753,501 | null | 702,432 | null | 1 | 24 | r|is-empty|isnullorempty | 39,977 | <p>If your empty columns are <em>really</em> empty character columns, something like the following should work. It will need to be modified if your "empty" character columns include, say, spaces.</p>
<p>Sample data:</p>
<pre><code>mydf <- data.frame(
A = c("a", "b"),
B = c("y", ""),
C = c("", ""),
D = c("", ""),
E = c("", "z")
)
mydf
# A B C D E
# 1 a y
# 2 b z
</code></pre>
<p>Identifying and removing the "empty" columns.</p>
<pre><code>mydf[!sapply(mydf, function(x) all(x == ""))]
# A B E
# 1 a y
# 2 b z
</code></pre>
<hr>
<p>Alternatively, as recommended by @Roland:</p>
<pre><code>> mydf[, colSums(mydf != "") != 0]
A B E
1 a y
2 b z
</code></pre> |
17,507,206 | How to make a POST simple JSON using Django REST Framework? CSRF token missing or incorrect | <p>Would appreciate someone showing me how to make a simple POST request using JSON with Django REST framework. I do not see any examples of this in the tutorial anywhere?</p>
<p>Here is my Role model object that I'd like to POST. This will be a brand new Role that I'd like to add to the database but I'm getting a 500 error. </p>
<pre><code>{
"name": "Manager",
"description": "someone who manages"
}
</code></pre>
<p>Here is my curl request at a bash terminal prompt:</p>
<pre><code>curl -X POST -H "Content-Type: application/json" -d '[
{
"name": "Manager",
"description": "someone who manages"
}]'
http://localhost:8000/lakesShoreProperties/role
</code></pre>
<p>The URL </p>
<pre><code>http://localhost:8000/lakesShoreProperties/roles
</code></pre>
<p>DOES work with a GET request, and I can pull down all the roles in the database, but I can not seem to create any new Roles. I have no permissions set. I'm using a standard view in views.py</p>
<pre><code>class RoleDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Role.objects.all()
serializer_class = RoleSerializer
format = None
class RoleList(generics.ListCreateAPIView):
queryset = Role.objects.all()
serializer_class = RoleSerializer
format = None
</code></pre>
<p>And in my <code>urls.py</code> for this app, the relevant url - view mappings are correct:</p>
<pre><code>url(r'^roles/$', views.RoleList.as_view()),
url(r'^role/(?P<pk>[0-9]+)/$', views.RoleDetail.as_view()),
</code></pre>
<p>Error message is:</p>
<pre><code>{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
</code></pre>
<p>What is going on here and what is the fix for this? Is localhost a cross site request? I have added <code>@csrf_exempt</code> to <code>RoleDetail</code> and <code>RoleList</code> but it doesn't seem to change anything. Can this decorator even be added to a class, or does it have to be added to a method?
Adding the <code>@csrf_exempt</code> decorate, my error becomes:</p>
<pre><code>Request Method: POST
Request URL: http://127.0.0.1:8000/lakeshoreProperties/roles/
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'as_view'
</code></pre>
<p>Then I disabled CSRF throughtout the entire app, and I now get this message:</p>
<p>{"non_field_errors": ["Invalid data"]} when my JSON object I know is valid json. It's a non-field error, but I'm stuck right here.</p>
<p>Well, it turns out that my json was not valid?</p>
<pre><code>{
"name": "admin",
"description": "someone who administrates"
}
</code></pre>
<p>vs</p>
<pre><code>[
{
"name": "admin",
"description": "someone who administrates"
}
]
</code></pre>
<p>Having the enclosing brackets [], causes the POST request to fail. But using the jsonlint.com validator, both of my json objects validate.</p>
<p><strong>Update</strong>: The issue was with sending the POST with PostMan, not in the backend. See <a href="https://stackoverflow.com/a/17508420/203312">https://stackoverflow.com/a/17508420/203312</a></p> | 17,507,712 | 8 | 1 | null | 2013-07-06 21:12:35.637 UTC | 16 | 2017-07-01 05:36:18.407 UTC | 2017-05-23 12:34:08.33 UTC | null | -1 | null | 798,719 | null | 1 | 48 | django|json|post|django-rest-framework | 77,453 | <p>You probably need to send along the CSRF token with your request. Check out <a href="https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#csrf-ajax" rel="nofollow noreferrer">https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#csrf-ajax</a></p>
<p>Update: Because you've already tried exempting CSRF, maybe this could help (depending on which version of Django you're using): <a href="https://stackoverflow.com/a/14379073/977931">https://stackoverflow.com/a/14379073/977931</a></p> |
17,383,217 | Git: Clone from a branch other than master | <p>I am trying to pull from a repository in Github. But I don't want to clone the master branch. I want to clone some other branch. When I try <code>git clone <url></code>, I get the files from the master branch. What should I do?</p>
<p>Also, suppose the code is updated in the repository and I want to get the latest code, should I again use <code>git clone</code> ? Because the size of the project is huge. Also if I make changes to the project locally, and then I again use git clone, will the changes I made still be there? What if I don't want changes to be there?</p>
<p>I am not even sure if <code>git clone</code> is the right command. <code>git pull</code> or <code>git fetch</code>?</p>
<p>I am sorry, I am very new to git.</p> | 17,383,251 | 4 | 1 | null | 2013-06-29 18:06:35.75 UTC | 31 | 2021-05-09 10:06:58.723 UTC | 2021-05-09 10:06:58.723 UTC | null | 10,907,864 | null | 2,510,555 | null | 1 | 58 | git|github|github-for-windows | 88,967 | <p>Try this:</p>
<pre><code>git init
git fetch url-to-repo branchname:refs/remotes/origin/branchname
</code></pre>
<p><strong>EDIT</strong></p>
<p>A better solution:</p>
<pre><code>git clone -b mybranch --single-branch git://sub.domain.com/repo.git
</code></pre> |
17,538,686 | How to copy virtual devices downloaded by Genymotion to another machine? | <p>I have installed Genymotion for Android in one machine (windows PC) and downloaded a Nexus virtual device. How can I copy the virtual device to another development machine?</p>
<p>or do I have to download again for each dev machine?</p>
<p>Genymotion is storing the virtual devices in {users folder}\VirtualBox Vms</p>
<p>How can this virtual box can be moved to another machine and loaded into Genymotion?</p> | 17,547,965 | 10 | 0 | null | 2013-07-09 01:46:43.063 UTC | 36 | 2020-10-12 07:54:40.83 UTC | 2014-02-04 10:56:06.047 UTC | null | 2,006,635 | null | 1,555,633 | null | 1 | 63 | android|virtual-machine|virtualbox|genymotion | 99,236 | <p>The files in the VirtualBox folder are likely just the actual machine configurations, not the downloaded image files.</p>
<p>On my system (Windows 8 x64) the downloaded images are located here:</p>
<p><code>\Users\{username}\AppData\Local\Genymobile\</code></p>
<p>Inside this folder is another folder called <code>LaunchPad</code>. If you copy this folder to the same location on your other machine it should work.</p>
<p>I would advise you install and run Genymobile on the other machine, then exit it and copy the folder mentioned above. Re-launching it <em>should</em> then pickup the image files.</p>
<p>You will have to re-create the actual devices, but you won't have to download the images again.</p>
<blockquote>
<p><strong>I have also noticed that you only need to download 4 images - any tablet with/without google apps and any phone with/without google
apps. All the different phones/tablets use the same physical images
once they are downloaded.</strong></p>
</blockquote>
<p><strong>UPDATE (for Genymotion v1.1.0):</strong><br>
The folder for has changed in v1.1.0 - it is now called <code>Genymotion</code> instead of <code>LaunchPad</code>, but it is still in the path indicated above. In order to retain already downloaded images (from v1.0), rename the <code>LaunchPad</code> folder to <code>Genymotion</code> (or copy it's contents if it already exists).</p>
<p><strong>Update for Genymotion v2.0+</strong>:<br>
The folder is now called <code>Genymotion</code> (instead of <code>Launchpad</code>) but it's contents remain the same, just copy it to your other installations.</p>
<p>Additionally, images with Google Apps are no longer available - so you only need to download 2 images <strong>per version</strong> (phone/tablet). To get Google Apps in Genymotion there is a solution posted on <a href="http://forum.xda-developers.com/showthread.php?t=2528952" rel="noreferrer">XDA</a>.</p>
<p><strong>Update for Genymotion v2.8+</strong>:
The downloaded images are located at:</p>
<pre><code>\Users\{username}\AppData\Local\Genymobile\Genymotion\ova
</code></pre> |
17,441,871 | Is passing 'this' in a method call accepted practice in java | <p>Is it good/bad/acceptable practice to pass the current object in a method call. As in:</p>
<pre><code>public class Bar{
public Bar(){}
public void foo(Baz baz){
// modify some values of baz
}
}
public class Baz{
//constructor omitted
public void method(){
Bar bar = new Bar();
bar.foo(this);
}
}
</code></pre>
<p>Specifically, is the line <code>bar.foo(this)</code> acceptable?</p> | 17,441,899 | 10 | 10 | null | 2013-07-03 07:14:40.017 UTC | 13 | 2018-12-17 07:55:49.02 UTC | 2017-02-05 13:16:16.433 UTC | null | 1,033,581 | null | 2,515,106 | null | 1 | 96 | java | 19,349 | <p>There's no reason not to use it, <code>this</code> is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.</p>
<p>So use it.</p>
<p>As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common <code>java.lang</code> classes, the <code>String</code> one, and of course I found instances of this use, for example</p>
<pre><code>1084 // Argument is a String
1085 if (cs.equals(this))
1086 return true;
</code></pre>
<p>Look for <code>(this</code> in big "accepted" projects, you won't fail to find it.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.