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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8,674,831 | How do you increment an assigned variable in smarty without displaying it | <p>So I have an assigned variable in smarty:</p>
<pre><code>{assign var=number value=0}
</code></pre>
<p>Now I can increment it using</p>
<pre><code>{$number++}
</code></pre>
<p>or</p>
<pre><code>{++$number}
</code></pre>
<p>Which is exactly what I need, only problem is, it displays the value of $number on the page.
Is there a way I can increment the value but not display it?</p>
<p>This is not used inside of a loop otherwise I would use something like iteration or index.</p> | 8,674,976 | 4 | 0 | null | 2011-12-29 23:48:42.703 UTC | 5 | 2021-12-07 17:11:31.21 UTC | 2011-12-30 01:08:06.24 UTC | null | 1,047,662 | null | 572,014 | null | 1 | 44 | php|smarty | 78,149 | <p>You could do this:</p>
<pre><code>{assign var=val value=1}
{assign var=val value=$val+1}
{$val} // displays 2
</code></pre>
<p>The above will be compiled to:</p>
<pre><code>$this->assign('val', 1);
$this->assign('val', $this->_tpl_vars['val']+1);
echo $this->_tpl_vars['val'];
</code></pre>
<p>or</p>
<pre><code>{assign var=var value=1}
{capture assign=var}{$var+1}{/capture}
{$var} // displays 2
</code></pre>
<p>Which in turn will be compiled as:</p>
<pre><code>$this->assign('var', 1);
ob_start();
echo $this->_tpl_vars['var']+1;
$this->_smarty_vars['capture']['default'] = ob_get_contents();
$this->assign('var', ob_get_contents());
ob_end_clean();
echo $this->_tpl_vars['var'];
</code></pre>
<p>another approach would be to write a small plugin:</p>
<pre><code>// plugins/function.inc.php
function smarty_function_inc($params, Smarty &$smarty)
{
$params['step'] = empty($params['step']) ? 1 : intval($params['step']);
if (empty($params['var'])) {
trigger_error("inc: missing 'var' parameter");
return;
}
if (!in_array($params['var'], array_keys($smarty->_tpl_vars))) {
trigger_error("inc: trying to increment unassigned variable " . $params['var']);
return;
}
if (isset($smarty->_tpl_vars[$params['var']])) {
$smarty->assign($params['var'],
$smarty->_tpl_vars[$params['var']] + $params['step']);
}
}
</code></pre>
<p>The function would then be called like this, notice that <code>step</code> is optional and if not given the variable will be incremented by one:</p>
<pre><code>{assign var=var value=0}
{inc var=var step=2}
{$var} // displays 2
</code></pre>
<p><strong>Reference</strong><br />
<a href="http://www.smarty.net/docs/en/language.function.assign.tpl" rel="nofollow noreferrer">Smarty {assign}</a><br />
<a href="http://www.smarty.net/docs/en/language.function.capture.tpl" rel="nofollow noreferrer">Smarty {capture}</a><br />
<a href="http://www.smarty.net/docsv2/en/plugins.functions.tpl" rel="nofollow noreferrer">Extending Smarty With Plugins</a></p> |
8,896,178 | Eclipse - how to remove light bulb on warnings | <p>Super quick question here that has been bugging me for a very long time -
Is there any way to remove the light bulb that appears on the left side of the line when there is a warning in Eclipse (Specifically using Java IDE, if it matters).</p>
<p>It is very annoying the way it hides breakpoints, and honestly - I can see the little squiggly yellow line just fine.</p>
<p>Thanks.</p> | 8,896,409 | 5 | 0 | null | 2012-01-17 14:19:52.43 UTC | 8 | 2019-10-29 21:03:16.29 UTC | 2019-10-29 21:03:16.29 UTC | null | 736,508 | null | 736,508 | null | 1 | 51 | eclipse | 15,301 | <p>Go to <code>Windows > Preferences > General > Editors > Text Editors > Annotations</code>.
Select <code>Warnings</code> option in the <code>Annotation Types</code> list box, un-select <code>Vertical Ruler</code></p> |
26,763,344 | Convert Pandas Column to DateTime | <p>I have one field in a pandas DataFrame that was imported as string format.
It should be a datetime variable.
How do I convert it to a datetime column and then filter based on date.</p>
<p>Example:</p>
<ul>
<li>DataFrame Name: <strong>raw_data</strong> </li>
<li>Column Name: <strong>Mycol</strong> </li>
<li>Value
Format in Column: <strong>'05SEP2014:00:00:00.000'</strong></li>
</ul> | 26,763,793 | 7 | 0 | null | 2014-11-05 17:24:34.143 UTC | 124 | 2022-08-23 08:12:20.733 UTC | 2014-11-05 17:25:51.54 UTC | null | 2,867,928 | null | 3,971,910 | null | 1 | 422 | python|datetime|pandas | 901,546 | <p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> function, specifying a <a href="http://strftime.org/" rel="noreferrer">format</a> to match your data.</p>
<pre><code>raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
</code></pre> |
862,668 | .NET CLR that does not require an operating system? | <p>In the world of Java, BEA (now Oracle) has created LiquidVM which doesn't require an OS. Likewise, there are a variety of open source projects including <a href="http://www.jbox.dk/sanos/" rel="nofollow noreferrer">SANOS</a>, <a href="http://www.jnode.org/" rel="nofollow noreferrer">JNODE OS</a>, <a href="http://research.sun.com/projects/dashboard.php?id=185" rel="nofollow noreferrer">Project Guest VM</a>, <a href="http://en.wikipedia.org/wiki/JavaOS" rel="nofollow noreferrer">JavaOS</a>, etc.</p>
<p>Is there an equivalent being created for .NET?</p> | 862,734 | 3 | 0 | null | 2009-05-14 10:46:16.973 UTC | 9 | 2009-06-03 01:11:47.85 UTC | null | null | null | null | 85,095 | null | 1 | 4 | java|.net|linux|mono|kernel | 829 | <p>Some googling found out:</p>
<ul>
<li><a href="http://research.microsoft.com/en-us/projects/singularity/" rel="noreferrer">Singularity</a> (a Microsoft research project)</li>
<li><a href="http://en.wikipedia.org/wiki/Midori_(operating_system)" rel="noreferrer">Midori</a> (another Microsoft research project, which aims to replace or integrate with a future version of Windows, especially on mobile devices)</li>
<li><a href="http://www.sharpos.org/doku.php" rel="noreferrer">SharpOS</a> (an open-source GPL OS in C#)</li>
<li><a href="http://www.gocosmos.org/index.en.aspx" rel="noreferrer">Cosmos</a> (an open-source BSD OS in C#)</li>
</ul>
<p>As to how mature those systems are, you'll have to check by yourself ;).</p> |
1,223,311 | Is it possible to read from a url into a System.IO.Stream object? | <p>I am attempting to read from a url into a System.IO.Stream object. I tried to use </p>
<pre><code>Dim stream as Stream = New FileStream(msgURL, FileMode.Open)
</code></pre>
<p>but I get an error that URI formats are not supported with FileStream objects. Is there some method I can use that inherits from System.IO.Stream that is able to read from a URL?</p> | 1,223,333 | 3 | 0 | null | 2009-08-03 16:34:31.793 UTC | 2 | 2018-07-30 04:56:00.863 UTC | 2015-04-05 10:10:25.583 UTC | null | 447,214 | null | 119,387 | null | 1 | 22 | .net|vb.net|io|iostream | 41,853 | <p>VB.Net:</p>
<pre><code>Dim req As WebRequest = HttpWebRequest.Create("url here")
Using stream As Stream = req.GetResponse().GetResponseStream()
End Using
</code></pre>
<p>C#:</p>
<pre><code>var req = System.Net.WebRequest.Create("url here");
using (Stream stream = req.GetResponse().GetResponseStream())
{
}
</code></pre> |
302,977 | Tomcat VS Jetty | <p>I'm wondering about the downsides of each servers in respect to a production environment. Did anyone have big problems with one of the features? Performance, etc. I also quickly took a look at the new Glassfish, does it match up the simple servlet containers (it seems to have a good management interface at least)?</p> | 302,990 | 3 | 3 | null | 2008-11-19 19:03:47.75 UTC | 42 | 2017-08-01 11:54:03.577 UTC | 2017-08-01 11:54:03.577 UTC | null | 350,713 | null | 39,057 | null | 1 | 172 | java|tomcat|servlets|webserver|jetty | 103,506 | <p>I love Jetty for its low maintenance cost. It's just unpack and it's ready to roll. Tomcat is a bit high maintenance, requires more configuration and it's heavier. Besides, Jetty's continuations are very cool.</p>
<p>EDIT: In 2013, there are reports that Tomcat has gotten easier. See comments. I haven't verified that.</p> |
21,938,008 | Bootstrap's tooltip moves table cells to right a bit on hover | <p>I am using Bootstrap 3.1.1 for my project. Each cell in my table contains data like <code>000</code> or <code>111</code>. On hover, I want to display this data as a tooltip. So far, this works. However, when I hover over a <code><td></code>, all adjacent cells shift to the right.</p>
<p><a href="http://jsfiddle.net/uEqF2/" rel="noreferrer">Here's my JSFiddle</a></p>
<pre><code><table class="table">
<thead>
<tr>
<th class="matrisHeader">
&nbsp;
</th>
<th data-original-title="111"
data-toggle="tooltip" data-placement="bottom" title="">
PÇ1
</th>
<th data-original-title="222"
data-toggle="tooltip" data-placement="bottom" title="">
PÇ2
</th>
<th data-original-title="333" data-toggle="tooltip"
data-placement="bottom" title="">
PÇ3
</th>
<th data-original-title="444"
data-toggle="tooltip" data-placement="bottom"title="">
PÇ4
</th>
</tr>
</thead>
<tbody>
<tr>
<th data-original-title="555" data-toggle="tooltip" data-placement="bottom"
title="">
ÖÇ1
</th>
<td data-original-title="666"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="777"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="888"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="999"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
</tr>
<tr>
<th data-original-title="000" data-toggle="tooltip"
data-placement="bottom" title="">
ÖÇ2
</th>
<td data-original-title="aaa"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="bbb"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="ccc"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="ddd"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
</tr>
<tr>
<th data-original-title="eee" data-toggle="tooltip" data-placement="bottom"
title="">
ÖÇ3
</th>
<td data-original-title="fff"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="ggg"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="hhh"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
<td data-original-title="iii"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
</tr>
</tbody>
</table>
</code></pre> | 21,938,112 | 3 | 0 | null | 2014-02-21 15:08:49.013 UTC | 7 | 2021-10-26 21:41:18.967 UTC | 2014-02-24 09:25:56.243 UTC | null | 1,494,102 | null | 1,494,102 | null | 1 | 72 | javascript|jquery|html|css|twitter-bootstrap | 50,847 | <p>You have to add the <code>data-container="body"</code> as per documentation.</p>
<pre><code><td data-original-title="999" data-container="body"
data-toggle="tooltip" data-placement="bottom" title="">
&nbsp;
</td>
</code></pre>
<p><a href="http://jsfiddle.net/uEqF2/2/">http://jsfiddle.net/uEqF2/2/</a></p> |
41,753,358 | Creating custom exceptions in C++ | <p>I am learning C++ and I am experiencing when I try and create my own exception and throw them on Linux. </p>
<p>I've created a small test project to test my implementation and below is my exception class header file.</p>
<pre><code>class TestClass : public std::runtime_error
{
public:
TestClass(char const* const message) throw();
virtual char const* what() const throw();
};
</code></pre>
<p>The source file for the exception class is</p>
<pre><code>using namespace std;
TestClass::TestClass(char const* const message) throw()
: std::runtime_error(message)
{
}
char const * TestClass::what() const throw()
{
return exception::what();
}
</code></pre>
<p>In my main app, I am calling a function which throws my exception and catches it in a try/catch as follows:</p>
<pre><code>void runAFunctionAndthrow();
/*
*
*/
int main(int argc, char** argv) {
try
{
cout << "About to call function" << endl;
runAFunctionAndthrow();
}
catch (TestClass ex)
{
cout << "Exception Caught: " << ex.what() << endl;
}
return 0;
}
void runAFunctionAndthrow()
{
cout << "going to run now. oh dear I need to throw an exception" << endl;
stringstream logstream;
logstream << "This is my exception error. :(";
throw TestClass(logstream.str().c_str());
}
</code></pre>
<p>When I run I'm expecting to get the following output:</p>
<blockquote>
<p>About to call function </p>
<p>Going to run now. oh dear I need to throw an exception</p>
<p>Exception Caught: This is my exception error. :(</p>
</blockquote>
<p>Instead what I am getting is</p>
<blockquote>
<p>About to call function</p>
<p>going to run now. oh dear I need to throw an exception</p>
<p>Exception Caught: std::exception</p>
</blockquote>
<p>Notice the last line it says std::exception instead of my actual exception message "This is my exception error". </p>
<p>Why is this, it works OK on Windows but on Linux it does this. </p>
<p>From what I've seen on various posts what I've done is correct so what am I missing. </p> | 41,753,430 | 3 | 1 | null | 2017-01-19 23:06:45.197 UTC | 10 | 2017-07-16 03:56:29.843 UTC | 2017-07-16 03:56:29.843 UTC | null | 4,505,446 | null | 499,448 | null | 1 | 43 | c++|exception | 70,729 | <p>Your <code>what()</code> returns:</p>
<pre><code> return exception::what();
</code></pre>
<p>The return value from <code>std::exception::what()</code> is <a href="http://en.cppreference.com/w/cpp/error/exception/what" rel="noreferrer">specified as follows</a>:</p>
<blockquote>
<p>Pointer to a null-terminated string with explanatory information.</p>
</blockquote>
<p>That's it. Nothing more, nothing else. The text you're showing certainly qualifies as an "explanatory information". And this is the only requirement for the return value of <code>what()</code> (except for one other one which is not germane here).</p>
<p>In other words, C++ does not guarantee the exact contents of what you get with <code>what()</code>. <code>what()</code> you see is <code>what()</code> you get, as the saying goes.</p>
<p>If you want your exception to describe itself, in some way, it's up to you to implement that, as part of your <code>what()</code>.</p> |
41,683,444 | Check to see if a value is within a range? | <p>I have a dataset in a <code>data.table</code> format that looks as such:</p>
<pre><code>ID time.s time.e
1 1 2
2 1 4
3 2 3
4 2 4
</code></pre>
<p>I want to check to see if the value 1 is within <code>time.s</code> and <code>time.e</code> so that the end result would look like </p>
<pre><code>[1] TRUE TRUE FALSE FALSE
</code></pre>
<p>How would I go about this? I have tried to use </p>
<pre><code> a[1 %in% seq(time.s, time.e)]
</code></pre>
<p>But all I get is all TRUE values. Any recommendations?</p> | 41,683,627 | 7 | 2 | null | 2017-01-16 19:10:46.343 UTC | 3 | 2022-08-10 08:16:41.61 UTC | 2017-09-26 06:17:02.673 UTC | null | 2,204,410 | null | 3,591,401 | null | 1 | 14 | r | 51,825 | <p>Assuming that the values of <code>ID</code> are unique:</p>
<pre><code>DT[, list(OK = 1 %in% seq(time.s, time.e)), by = ID]
</code></pre>
<p>giving;</p>
<pre><code> ID OK
1: 1 TRUE
2: 2 TRUE
3: 3 FALSE
4: 4 FALSE
</code></pre> |
54,758,872 | Spring Boot Security - Postman gives 401 Unauthorized | <p>I am developing rest APIs in Spring Boot. I am able to do CRUD operations and postman gives correct responses, but when I add Spring Security username and password Postman gives 401 Unauthorized.</p>
<p>I have provided a spring boot security username and password as below.</p>
<p>application.proptries</p>
<pre><code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/pal?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.security.user.name=root
spring.security.user.password=root
</code></pre>
<p>I have done basic auth with username as root and password as root.
Preview request gives headers updated successfully message :</p>
<p><a href="https://i.stack.imgur.com/4fiqS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4fiqS.png" alt="enter image description here"></a></p>
<p><strong>EDIT</strong>
<a href="https://i.stack.imgur.com/bZYR6.png" rel="noreferrer">I have deleted the cookies in postman but still facing the same issue</a></p>
<pre><code>SecurityConfing.java
My Security Configuration are as below.
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.jdbcAuthentication().dataSource(dataSource())
.usersByUsernameQuery(
"select email,password from user where email=? and statusenable=true")
.authoritiesByUsernameQuery(
"select email,role from user where email=? and statusenable=true");
System.out.println(authenticationMgr.jdbcAuthentication().dataSource(dataSource())
.usersByUsernameQuery(
"select email,password from user where email=? and statusenable=true")
.authoritiesByUsernameQuery(
"select email,role from user where email=? and statusenable=true"));
}
@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/pal");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("");
return driverManagerDataSource;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.authorizeRequests().antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN","ROLE_USER").anyRequest().permitAll()
.and()
.authorizeRequests().antMatchers("/user/**").hasAnyRole("ROLE_USER").anyRequest().permitAll();
}
</code></pre> | 54,761,015 | 2 | 2 | null | 2019-02-19 04:29:59.017 UTC | 3 | 2021-01-14 10:21:52.347 UTC | 2019-07-03 14:53:23.3 UTC | null | 10,961,238 | null | 10,961,238 | null | 1 | 15 | java|spring|spring-boot|spring-security|postman | 41,684 | <pre><code>@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST,"/newuser").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.POST,"/newuser/*").permitAll()
.antMatchers(HttpMethod.GET,"/master/*").permitAll()
.antMatchers(HttpMethod.GET,"/exploreCourse").permitAll()
.anyRequest().authenticated()
}
}
</code></pre>
<p>You need to configure Spring Security, by default all routes all secured for authrorization.</p>
<p>Please have a look JWT Token implementation at this <a href="https://github.com/nishant-varshney/Spring-Boot-RestAPI/tree/master/LP_RESTAPI/src/main/java/com/nv/Configuration" rel="noreferrer">Link</a>.</p> |
42,920,602 | Calling a lambda with a numpy array | <p>While familiarizing myself with <code>numpy</code>, I noticed an interesting behaviour in <code>numpy</code> arrays:</p>
<pre><code>import numpy as np
arr = np.array([1, 2, 3])
scale = lambda x: x * 3
scale(arr) # Gives array([3, 6, 9])
</code></pre>
<p>Contrast this with normal Python lists:</p>
<pre><code>arr = [1, 2, 3]
scale = lambda x: x * 3
scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]
</code></pre>
<p>I'm curious as to how this is possible. Does a <code>numpy</code> array override the multiplication operator or something?</p> | 42,921,093 | 3 | 2 | null | 2017-03-21 07:19:12.833 UTC | 3 | 2020-07-29 15:27:07.27 UTC | 2017-03-21 07:53:36.367 UTC | null | 1,111,252 | null | 1,111,252 | null | 1 | 11 | python|arrays|numpy | 62,265 | <p><code>numpy.ndarray</code> <a href="https://stackoverflow.com/questions/6892616/python-multiplication-override">overloads</a> the <code>*</code> operator by defining its own <code>__mul__</code> method. Likewise for <code>+</code>, <code>-</code>, etc. This allows for vector arithmetic.</p> |
35,976,870 | How to set redirect_uri parameter on OpenIdConnectOptions for ASP.NET Core | <p>I'm trying to connect an ASP.NET application to Salesforce using OpenId, Currently this is my connecting code so far. I think I got everything except the redirect_uri parameter, which has to match the value on the other end exactly.</p>
<pre class="lang-cs prettyprint-override"><code>
app.UseCookieAuthentication(x =>
{
x.AutomaticAuthenticate = true;
x.CookieName = "MyApp";
x.CookieSecure = CookieSecureOption.Always;
x.AuthenticationScheme = "Cookies";
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseOpenIdConnectAuthentication(x =>
{
x.AutomaticAuthenticate = true;
x.Authority = "https://login.salesforce.com";
x.ClientId = "CLIENT_ID_HERE";
x.ResponseType = "code";
x.AuthenticationScheme = "oidc";
x.CallbackPath = new PathString("/services/oauth2/success");
//x.RedirectUri = "https://login.salesforce.com/services/oauth2/success";
x.Scope.Add("openid");
x.Scope.Add("profile");
x.Scope.Add("email");
});
</code></pre>
<p>But RedirectUri isn't a valid parameter to pass. What is the right way to set it?</p> | 35,977,924 | 2 | 1 | null | 2016-03-13 22:48:03.82 UTC | 9 | 2020-10-20 11:23:47.57 UTC | 2020-10-20 11:23:47.57 UTC | null | 1,945,651 | null | 637,811 | null | 1 | 21 | asp.net-core|openid-connect | 23,490 | <p><code>redirect_uri</code> is automatically computed for you using the scheme, host, port and path extracted from the current request and the <code>CallbackPath</code> you specify.</p>
<p><code>x.RedirectUri = "https://login.salesforce.com/services/oauth2/success"</code> looks highly suspicious (unless you work for Salesforce): don't forget it's the callback URL the user agent will be redirected to when the authentication flow completes, not the authorization endpoint of your identity provider.</p>
<p>So in your case, the user will be redirected to <code>http(s)://yourdomain.com/services/oauth2/success</code>. Is it the address you registered in your Salesforce options?</p> |
5,941,832 | PHP Using RegEx to get substring of a string | <p>I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need. </p>
<p>I am parsing a web page and need to grab a numeric value from the string, the string is like this</p>
<pre><code>producturl.php?id=736375493?=tm
</code></pre>
<p>I need to be able to obtain this part of the string:</p>
<p>736375493</p>
<p>Thanks Aaron</p> | 5,941,925 | 4 | 0 | null | 2011-05-09 19:57:43.183 UTC | 7 | 2019-05-27 02:33:08.093 UTC | null | null | null | null | 503,569 | null | 1 | 80 | php|regex|parsing|substring | 129,607 | <pre><code>$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
</code></pre>
<p>This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.</p>
<p><a href="http://php.net/manual/en/function.preg-match.php" rel="noreferrer">php.net/preg-match</a></p> |
5,856,451 | CSS a href styling | <p>i have a href with <code>class="button"</code></p>
<p>I am trying to style this like that:</p>
<pre><code>.button a:link {text-decoration: none}
.button a:visited {text-decoration: none}
.button a:active {text-decoration: none}
.button a:hover {text-decoration: none; background-color:yellow;color:blue}
</code></pre>
<p>why it is not working?
how to set stye for a href with that class (<code>class="button"</code>)</p> | 5,856,480 | 5 | 5 | null | 2011-05-02 11:15:41.017 UTC | 3 | 2016-02-19 10:28:11.92 UTC | null | null | null | null | 733,323 | null | 1 | 6 | css | 107,198 | <p><code>.button a</code> is a <em>descendant selector</em>. It matches all <code><a></code> tags that are <em>descendants of</em> <code>.button</code>.</p>
<p>You need to write <code>a.button:link</code> to match tags that are both <code><a></code> and <code>.button</code>.</p> |
2,073,543 | Use WinMerge as TortoiseHG Merge tool | <p>I am trying to set up WinMerge as the Merge tool into TortoiseHG;
Here is my Mercurial.ini:</p>
<pre><code>; User specific Mercurial config file.
; See the hgrc man page for details.
[ui]
username = Bargio <>
merge = winmergeu
[extdiff]
cmd.winmerge = C:\Program Files (x86)\WinMerge\WinMergeU.exe
opts.winmerge = /e /x /ub /wl
[merge-tools]
winmergeu.executable = C:\Program Files (x86)\WinMerge\WinMergeU.exe
winmergeu.priority= 1
winmergeu.fixeol=True
winmergeu.checkchanged=True
winmergeu.args= /e /ub /dl other /dr local $other $local $output
winmergeu.gui=False
[tortoisehg]
vdiff = winmerge
</code></pre>
<p>Visual diff works perfectly but when I try to merge two files, I get the following error:</p>
<pre><code>tool winmergeu can't handle binary
</code></pre>
<p>How can I fix it?</p> | 2,076,255 | 2 | 0 | null | 2010-01-15 17:30:34.833 UTC | 8 | 2018-09-13 16:51:44.047 UTC | 2018-09-13 16:51:44.047 UTC | null | 779,956 | null | 243,873 | null | 1 | 31 | mercurial|merge|tortoisehg|winmerge | 10,788 | <p>You can add</p>
<pre><code>winmergeu.binary=True
</code></pre>
<p>as found <a href="https://www.mercurial-scm.org/wiki/MergeToolConfiguration" rel="nofollow noreferrer">here</a> if winmerge can merge binary files. If it can't you'll want to configure another merge tool that can and use matters to send the binary files to that tool.</p> |
2,140,964 | Source of Android's lock screen | <p>I am looking for the source code of the android lock screen. It can be for any version of Android (1.5, 1.6, 2.0, etc).</p>
<p>I tried looking in the repository at: <a href="https://android.googlesource.com/" rel="nofollow noreferrer">https://android.googlesource.com/</a>, but it doesn't look like it's under <code>platform/frameworks/base</code>. Maybe it's closed source?</p> | 2,141,321 | 2 | 0 | null | 2010-01-26 16:50:14.013 UTC | 20 | 2017-07-24 10:13:34.503 UTC | 2017-07-24 10:13:34.503 UTC | null | 1,000,551 | null | 237,115 | null | 1 | 34 | android|android-source | 65,403 | <p>Do an actual full checkout of the source according to <a href="http://source.android.com/source/downloading.html" rel="noreferrer">Google's directions</a>.</p>
<p>As of Android 4.2, the keyguard source is at <code>frameworks/base/policy/src/com/android/internal/policy/impl/keyguard</code>. There's a <a href="https://github.com/android/platform_frameworks_base/tree/jb-mr1.1-release/policy/src/com/android/internal/policy/impl/keyguard" rel="noreferrer">mirror on GitHub</a> you can look at online (I pegged this link to the JB MR 1.1 release in case the location changes again in a future release).</p>
<p>When this question was originally answered, Android 2.3 and lower had their lockscreen source at <code>frameworks/policies/base/phone/com/android/internal/policy/impl</code>.
You can also view <a href="https://github.com/android/platform_frameworks_policies_base/blob/master/phone/com/android/internal/policy/impl/" rel="noreferrer">these sources online in their GitHub mirror</a>; that source is still kicking in the current repo, but hasn't been updated in several years.</p> |
1,434,451 | What does "connection reset by peer" mean? | <p>What is the meaning of the "connection reset by peer" error on a TCP connection? Is it a fatal error or just a notification or related to the network failure?</p> | 1,434,506 | 2 | 0 | null | 2009-09-16 17:38:58.233 UTC | 195 | 2019-11-03 10:46:18.783 UTC | 2017-04-28 09:58:30.533 UTC | null | 2,850,474 | null | 138,579 | null | 1 | 827 | sockets|tcp | 1,163,807 | <p>It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like <a href="http://everything2.com/title/Connection+reset+by+peer" rel="noreferrer">this description</a>:</p>
<blockquote>
<p>"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. </p>
</blockquote> |
29,648,907 | Using geom_rect for time series shading in R | <p>I am trying to shade a certain section of a time series plot (a bit like recession shading - similarly to the graph at the bottom of <a href="https://research.stlouisfed.org/tips/200511/recession_bars.pdf" rel="noreferrer">this article on recession shading in excel</a>). I have put a little, possibly clumsy, sample together to illustrate.
I first create a time series, plot it with ggplot2 and then want to use geom_rect to provide the shading. But I must get something wrong in the arguments.</p>
<pre><code>a<-rnorm(300)
a_ts<-ts(a, start=c(1910, 1), frequency=12)
a_time<-time(a_ts)
a_series<-ts.union(big=a_ts, month=a_time)
a_series_df<-as.data.frame(a_series)
ggplot(a_series)+
geom_line(mapping=aes_string(x="month", y="big"))+
geom_rect(
fill="red",alpha=0.5,
mapping=aes_string(x="month", y="big"),
xmin=as.numeric(as.Date(c("1924-01-01"))),
xmax=as.numeric(as.Date(c("1928-12-31"))),
ymin=0,
ymax=2
)
</code></pre>
<p>Note that I have also tried which also did not work.</p>
<pre><code>geom_rect(
fill="red",alpha=0.5,
mapping=aes_string(x="month", y="big"),
aes(
xmin=as.numeric(as.Date(c("1924-01-01"))),
xmax=as.numeric(as.Date(c("1928-12-31"))),
ymin=0,
ymax=2)
)
</code></pre>
<p><img src="https://i.stack.imgur.com/Wkq3O.png" alt="enter image description here"> </p> | 29,649,575 | 4 | 0 | null | 2015-04-15 11:23:11.48 UTC | 9 | 2019-08-14 16:24:32.123 UTC | 2019-02-14 06:51:39.187 UTC | null | 680,068 | null | 857,185 | null | 1 | 28 | r|date|ggplot2|time-series | 34,546 | <p>Code works fine, conversion to decimal date is needed for <em>xmin</em> and <em>xmax</em>, see below, requires <em>lubridate</em> package. </p>
<pre><code>library("lubridate")
library("ggplot2")
ggplot(a_series_df)+
geom_line(mapping = aes_string(x = "month", y = "big")) +
geom_rect(
fill = "red", alpha = 0.5,
mapping = aes_string(x = "month", y = "big"),
xmin = decimal_date(as.Date(c("1924-01-01"))),
xmax = decimal_date(as.Date(c("1928-12-31"))),
ymin = 0,
ymax = 2
)
</code></pre>
<p>Cleaner version, shading plotted first so the line colour doesn't change.</p>
<pre><code>ggplot() +
geom_rect(data = data.frame(xmin = decimal_date(as.Date(c("1924-01-01"))),
xmax = decimal_date(as.Date(c("1928-12-31"))),
ymin = -Inf,
ymax = Inf),
aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
fill = "grey", alpha = 0.5) +
geom_line(data = a_series_df,aes(month, big), colour = "blue") +
theme_classic()
</code></pre>
<p><img src="https://i.stack.imgur.com/ObwAn.jpg" alt="enter image description here"></p> |
5,938,694 | DateTime.Parse American Date Format C# | <p>Probably a simple question - </p>
<p>I'm reading in data from a number of files. </p>
<p>My problem is, that when I'm reading in the date from an american file, I parse it like so:</p>
<pre><code>DateSold = DateTime.Parse(t.Date)
</code></pre>
<p>This parses the string t.Date into a date format, however it formats the american date to a european date, e.g.</p>
<p>If the date is in the file as 03/01/2011, it is read as the 3rd of January, 2011, when it should be the 1st of March 2011. </p>
<p>Is there a way of doing this so that it formats to the european date? </p> | 5,938,717 | 5 | 0 | null | 2011-05-09 14:59:01.847 UTC | 4 | 2012-09-14 07:36:57.427 UTC | null | null | null | null | 376,083 | null | 1 | 26 | c#|asp.net|datetime | 65,538 | <pre><code>var dt = DateTime.ParseExact(t.Date, "MM/dd/yyyy", CultureInfo.InvariantCulture);
</code></pre>
<p>The DateTime itself has no formatting, it is only when you convert it to or from a string that the format is relevant.</p>
<p>To view your date with American format, you pass the format to the ToString method</p>
<pre><code>string americanFormat = dt.ToString("MM/dd/yyyy");
</code></pre> |
5,963,228 | Regex for names with special characters (Unicode) | <p>Okay, I have read about regex all day now, and still don't understand it properly. What i'm trying to do is validate a name, but the functions i can find for this on the internet only use <code>[a-zA-Z]</code>, leaving characters out that i need to accept to.</p>
<p>I basically need a regex that checks that the name is at least two words, and that it does not contain numbers or special characters like <code>!"#¤%&/()=...</code>, however the words can contain characters like æ, é, Â and so on...</p>
<p>An example of an accepted name would be: "John Elkjærd" or "André Svenson"<br />An non-accepted name would be: "<strong>Hans</strong>", "H<b>4</b>nn<b>3</b> Andersen" or "Martin Henriksen<b>!</b>"</p>
<p>If it matters i use the javascript <code>.match()</code> function client side and want to use php's <code>preg_replace()</code> only "in negative" server side. (removing non-matching characters).</p>
<p>Any help would be much appreciated.</p>
<p><strong>Update:</strong><br />
Okay, thanks to <a href="https://stackoverflow.com/questions/5963228/regex-for-names-with-special-characters/5963425#5963425">Alix Axel's answer</a> i have the important part down, the server side one.</p>
<p>But as the page from <a href="https://stackoverflow.com/questions/5963228/regex-for-names-with-special-characters/5963334#5963334">LightWing's answer</a> suggests, i'm unable to find anything about unicode support for javascript, so i ended up with half a solution for the client side, just checking for at least two words and minimum 5 characters like this:</p>
<pre><code>if(name.match(/\S+/g).length >= minWords && name.length >= 5) {
//valid
}
</code></pre>
<p>An alternative would be to specify all the unicode characters as suggested in <a href="https://stackoverflow.com/questions/5963228/regex-for-names-with-special-characters/5963417#5963417">shifty's answer</a>, which i might end up doing something like, along with the solution above, but it is a bit unpractical though.</p> | 5,963,425 | 7 | 0 | null | 2011-05-11 11:08:08.76 UTC | 11 | 2017-05-16 16:28:56.377 UTC | 2017-05-23 10:31:16.803 UTC | null | -1 | null | 676,713 | null | 1 | 13 | php|javascript|regex|character-properties | 22,250 | <p>Try the following regular expression:</p>
<pre><code>^(?:[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s?)+$
</code></pre>
<p>In PHP this translates to:</p>
<pre><code>if (preg_match('~^(?:[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s?)+$~u', $name) > 0)
{
// valid
}
</code></pre>
<p>You should read it like this:</p>
<pre><code>^ # start of subject
(?: # match this:
[ # match a:
\p{L} # Unicode letter, or
\p{Mn} # Unicode accents, or
\p{Pd} # Unicode hyphens, or
\' # single quote, or
\x{2019} # single quote (alternative)
]+ # one or more times
\s # any kind of space
[ #match a:
\p{L} # Unicode letter, or
\p{Mn} # Unicode accents, or
\p{Pd} # Unicode hyphens, or
\' # single quote, or
\x{2019} # single quote (alternative)
]+ # one or more times
\s? # any kind of space (0 or more times)
)+ # one or more times
$ # end of subject
</code></pre>
<p>I honestly don't know how to port this to Javascript, I'm not even sure Javascript supports Unicode properties but in PHP PCRE this <a href="http://www.ideone.com/eNQPq">seems to work flawlessly @ IDEOne.com</a>:</p>
<pre><code>$names = array
(
'Alix',
'André Svenson',
'H4nn3 Andersen',
'Hans',
'John Elkjærd',
'Kristoffer la Cour',
'Marco d\'Almeida',
'Martin Henriksen!',
);
foreach ($names as $name)
{
echo sprintf('%s is %s' . "\n", $name, (preg_match('~^(?:[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s?)+$~u', $name) > 0) ? 'valid' : 'invalid');
}
</code></pre>
<p>I'm sorry I can't help you regarding the Javascript part but probably someone here will.</p>
<hr>
<p><strong>Validates</strong>:</p>
<ul>
<li>John Elkjærd</li>
<li>André Svenson</li>
<li>Marco d'Almeida</li>
<li>Kristoffer la Cour</li>
</ul>
<p><strong>Invalidates</strong>:</p>
<ul>
<li>Hans</li>
<li>H4nn3 Andersen</li>
<li>Martin Henriksen!</li>
</ul>
<hr>
<p>To replace invalid characters, though I'm not sure why you need this, you just need to change it slightly:</p>
<pre><code>$name = preg_replace('~[^\p{L}\p{Mn}\p{Pd}\'\x{2019}\s]~u', '$1', $name);
</code></pre>
<p>Examples:</p>
<ul>
<li>H4nn3 Andersen <strong>-></strong> Hnn Andersen</li>
<li>Martin Henriksen! <strong>-></strong> Martin Henriksen</li>
</ul>
<p>Note that you always need to use the <em>u</em> modifier.</p> |
17,685,502 | In R, getting the following error: "attempt to replicate an object of type 'closure'" | <p>I am trying to write an R function that takes a data set and outputs the plot() function with the data set read in its environment. This means you don't have to use attach() anymore, which is good practice. Here's my example:</p>
<pre><code>mydata <- data.frame(a = rnorm(100), b = rnorm(100,0,.2))
plot(mydata$a, mydata$b) # works just fine
scatter_plot <- function(ds) { # function I'm trying to create
ifelse(exists(deparse(quote(ds))),
function(x,y) plot(ds$x, ds$y),
sprintf("The dataset %s does not exist.", ds))
}
scatter_plot(mydata)(a, b) # not working
</code></pre>
<p>Here's the error I'm getting:</p>
<blockquote>
<p>Error in rep(yes, length.out = length(ans)) :
attempt to replicate an object of type 'closure'</p>
</blockquote>
<p>I tried several other versions, but they all give me the same error. What am I doing wrong?</p>
<p>EDIT: I realize the code is not too practical. My goal is to understand functional programming better. I wrote a similar macro in SAS, and I was just trying to write its counterpart in R, but I'm failing. I just picked this as an example. I think it's a pretty simple example and yet it's not working.</p> | 17,687,610 | 1 | 1 | null | 2013-07-16 19:37:41.463 UTC | 1 | 2021-03-06 09:00:30.777 UTC | 2021-03-06 09:00:30.777 UTC | null | 6,123,824 | null | 1,997,537 | null | 1 | 19 | r|functional-programming|closures | 50,636 | <p>There are a few small issues. <code>ifelse</code> is a vectorized function, but you just need a simple <code>if</code>. In fact, you don't really need an <code>else</code> -- you could just throw an error immediately if the data set does not exist. Note that your error message is not using the name of the object, so it will create its own error.</p>
<p>You are passing <code>a</code> and <code>b</code> instead of <code>"a"</code> and <code>"b"</code>. Instead of the <code>ds$x</code> syntax, you should use the <code>ds[[x]]</code> syntax when you are programming (<code>fortunes::fortune(312)</code>). If that's the way you want to call the function, then you'll have to deparse those arguments as well. Finally, I think you want <code>deparse(substitute())</code> instead of <code>deparse(quote())</code></p>
<pre><code>scatter_plot <- function(ds) {
ds.name <- deparse(substitute(ds))
if (!exists(ds.name))
stop(sprintf("The dataset %s does not exist.", ds.name))
function(x, y) {
x <- deparse(substitute(x))
y <- deparse(substitute(y))
plot(ds[[x]], ds[[y]])
}
}
scatter_plot(mydata)(a, b)
</code></pre> |
19,305,994 | How to Set Banner-Like Background Image With CSS | <p>I have been looking at a lot of the source code for sites and can't seem to figure this out. I want to have an image that's in the background, behind everything. I don't, however, want the entire background to be that image; I only want it towards the top kinda like a banner of sorts. Some examples can be found at <a href="http://www.animefreak.tv/" rel="noreferrer">http://www.animefreak.tv/</a>, and <a href="http://us.battle.net/wow/en/" rel="noreferrer">http://us.battle.net/wow/en/</a>. Right now I have a textured background with: </p>
<pre><code>body
{
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iNiIgaGVpZ2h0PSI2Ij4KPHJlY3Qgd2lkdGg9IjYiIGhlaWdodD0iNiIgZmlsbD0iI2VlZWVlZSI+PC9yZWN0Pgo8ZyBpZD0iYyI+CjxyZWN0IHdpZHRoPSIzIiBoZWlnaHQ9IjMiIGZpbGw9IiNlNmU2ZTYiPjwvcmVjdD4KPHJlY3QgeT0iMSIgd2lkdGg9IjMiIGhlaWdodD0iMiIgZmlsbD0iI2Q4ZDhkOCI+PC9yZWN0Pgo8L2c+Cjx1c2UgeGxpbms6aHJlZj0iI2MiIHg9IjMiIHk9IjMiPjwvdXNlPgo8L3N2Zz4=");
font-size: .80em;
font-family: "Helvetica Neue", "Lucida Grande", "Segoe UI", Arial, Helvetica, Verdana, sans-serif;
margin: 0px;
padding: 0px;
color: #696969;
}
</code></pre>
<p>Any image I try to put in my CSS simply appears above the main page div of my site, when I want it to appear behind like in the given examples. I put a </p>
<pre><code> <div class = "topb">
</div>
</code></pre>
<p>at the top of my MasterPage and then used </p>
<pre><code>.topb
{
height: 243px;margin: 0px;padding: 0px;overflow: hidden;
background: url(/images/test2.jpg) no-repeat top center;
background-image:url(/images/test2.jpg);
}
</code></pre>
<p>in my CSS as a test, but I am obviously new to CSS and HTML development. Any Suggestions?</p> | 19,306,261 | 1 | 0 | null | 2013-10-10 20:51:56.067 UTC | 1 | 2016-12-24 17:15:22.39 UTC | null | null | null | null | 2,751,120 | null | 1 | 5 | html|asp.net|css | 53,559 | <p>There are several ways to accomplish this.</p>
<p>CSS3 allows you to have multiple background images. You can do this:</p>
<pre><code>body {
background-color: #000;
background-image: url(texture.png), url(banner.png);
background-position: center center, center top;
background-repeat: repeat, no-repeat;
}
</code></pre>
<p>Or you can add a wrapper <code>div</code> right after the <code><body></code> that holds all of the content and add your banner background image to that.</p>
<p>HTML:</p>
<pre><code><body>
<div id="Wrapper">
<!-- The rest of your site's content -->
</div>
</body>
</code></pre>
<p>CSS:</p>
<pre><code>body {
background: #000 url(texture.png) repeat center center;
}
#Wrapper {
background: url(banner.png) no-repeat center top;
}
</code></pre>
<p>If you want to add some spacing at the top so your content doesn't cover the banner, simply add some padding like so:</p>
<pre><code>#Wrapper { padding-top: 240px; }
</code></pre> |
41,621,071 | Restore subset of variables in Tensorflow | <p>I am training a Generative Adversarial Network (GAN) in tensorflow, where basically we have two different networks each one with its own optimizer.</p>
<pre><code>self.G, self.layer = self.generator(self.inputCT,batch_size_tf)
self.D, self.D_logits = self.discriminator(self.GT_1hot)
...
self.g_optim = tf.train.MomentumOptimizer(self.learning_rate_tensor, 0.9).minimize(self.g_loss, global_step=self.global_step)
self.d_optim = tf.train.AdamOptimizer(self.learning_rate, beta1=0.5) \
.minimize(self.d_loss, var_list=self.d_vars)
</code></pre>
<p>The problem is that I train one of the networks (g) first, and then, I want to train g and d together. However, when I call the load function:</p>
<pre><code>self.sess.run(tf.initialize_all_variables())
self.sess.graph.finalize()
self.load(self.checkpoint_dir)
def load(self, checkpoint_dir):
print(" [*] Reading checkpoints...")
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
self.saver.restore(self.sess, ckpt.model_checkpoint_path)
return True
else:
return False
</code></pre>
<p>I have an error like this (with a lot more traceback):</p>
<pre><code>Tensor name "beta2_power" not found in checkpoint files checkpoint/MR2CT.model-96000
</code></pre>
<p>I can restore the g network and keep training with that function, but when I want to star d from scratch, and g from the the stored model I have that error.</p> | 41,642,426 | 4 | 0 | null | 2017-01-12 19:11:01.147 UTC | 13 | 2018-05-07 14:47:05.17 UTC | 2017-01-12 23:42:49.4 UTC | null | 472,495 | null | 2,847,699 | null | 1 | 16 | python|tensorflow | 22,797 | <p>To restore a subset of variables, you must create a new <a href="https://www.tensorflow.org/api_docs/python/state_ops/saving_and_restoring_variables#Saver.__init__" rel="noreferrer"><code>tf.train.Saver</code></a> and pass it a specific list of variables to restore in the optional <code>var_list</code> argument.</p>
<p>By default, a <code>tf.train.Saver</code> will create ops that (i) save every variable in your graph when you call <a href="https://www.tensorflow.org/api_docs/python/state_ops/saving_and_restoring_variables#Saver.save" rel="noreferrer"><code>saver.save()</code></a> and (ii) lookup (by name) every variable in the given checkpoint when you call <a href="https://www.tensorflow.org/api_docs/python/state_ops/saving_and_restoring_variables#Saver.restore" rel="noreferrer"><code>saver.restore()</code></a>. While this works for most common scenarios, you have to provide more information to work with specific subsets of the variables:</p>
<ol>
<li><p>If you only want to restore a subset of the variables, you can get a list of these variables by calling <a href="https://www.tensorflow.org/api_docs/python/framework/graph_collections#get_collection" rel="noreferrer"><code>tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=G_NETWORK_PREFIX)</code></a>, assuming that you put the "g" network in a common <a href="https://www.tensorflow.org/api_docs/python/framework/utility_functions#name_scope" rel="noreferrer"><code>with tf.name_scope(G_NETWORK_PREFIX):</code></a> or <a href="https://www.tensorflow.org/api_docs/python/state_ops/sharing_variables#variable_scope" rel="noreferrer"><code>tf.variable_scope(G_NETWORK_PREFIX):</code></a> block. You can then pass this list to the <code>tf.train.Saver</code> constructor.</p></li>
<li><p>If you want to restore a subset of the variable and/or they variables in the checkpoint have <strong>different names</strong>, you can pass a dictionary as the <code>var_list</code> argument. By default, each variable in a checkpoint is associated with a <em>key</em>, which is the value of its <code>tf.Variable.name</code> property. If the name is different in the target graph (e.g. because you added a scope prefix), you can specify a dictionary that maps string keys (in the checkpoint file) to <code>tf.Variable</code> objects (in the target graph).</p></li>
</ol> |
69,182,132 | A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor | <p>I'm unable to use <code>questions[questionNumber]</code> as a Text Constructor in Flutter.</p>
<p><strong>Errors:</strong></p>
<p>Evaluation of this constant expression throws an exception.dart(const_eval_throws_exception)</p>
<p>A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor.
Try using a subtype, or removing the keyword 'const'.dartconst_constructor_param_type_mismatch</p>
<p>Arguments of a constant creation must be constant expressions.
Try making the argument a valid constant, or use 'new' to call the constructor.dartconst_with_non_constant_argument</p>
<pre><code>class _QuizPageState extends State<QuizPage> {
List<Widget> scoreKeeper = [];
List<String> questions = [
'You can lead a cow down stairs but not up stairs.',
'Approximately one quarter of human bones are in the feet.',
'A slug\'s blood is green.'
];
int questionNumber = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Expanded(
flex: 5,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text(
questions[questionNumber],
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
),
),
),
),
),
],
);
}
}
</code></pre> | 69,182,239 | 1 | 0 | null | 2021-09-14 17:26:07.467 UTC | 1 | 2021-09-14 17:34:58.687 UTC | null | null | null | null | 10,559,515 | null | 1 | 38 | flutter|dart | 21,963 | <p>Well, the error is due to using the keyword <code>const</code> for the <code>Expanded</code> widget. Just remove it and you will be all good.</p>
<p>So this:</p>
<pre><code> @override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
flex: 5,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text(
questions[questionNumber],
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
),
),
),
),
),
],
);
}
}
</code></pre> |
31,096,130 | How to JSON stringify a javascript Date and preserve timezone | <p>I have a date object that's created by the user, with the timezone filled in by the browser, like so:</p>
<pre><code>var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)
</code></pre>
<p>When I stringify it, though, the timezone goes bye-bye</p>
<pre><code>JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"
</code></pre>
<p>The best way I can get a ISO8601 string while preserving the browser's timezone is by using moment.js and using <code>moment.format()</code>, but of course that won't work if I'm serializing a whole command via something that uses <code>JSON.stringify</code> internally (in this case, AngularJS)</p>
<pre><code>var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);
</code></pre>
<p>For completeness, my domain <em>does</em> need both the local time and the offset.</p> | 31,104,671 | 7 | 0 | null | 2015-06-28 04:23:13.11 UTC | 28 | 2022-06-28 19:11:21.927 UTC | null | null | null | null | 185,422 | null | 1 | 90 | javascript|json|date|datetime|momentjs | 83,981 | <p>Assuming you have some kind of object that contains a <code>Date</code>:</p>
<pre><code>var o = { d : new Date() };
</code></pre>
<p>You can override the <code>toJSON</code> function of the <code>Date</code> prototype. Here I use moment.js to create a <code>moment</code> object from the date, then use moment's <code>format</code> function without parameters, which emits the ISO8601 extended format including the offset.</p>
<pre><code>Date.prototype.toJSON = function(){ return moment(this).format(); }
</code></pre>
<p>Now when you serialize the object, it will use the date format you asked for:</p>
<pre><code>var json = JSON.stringify(o); // '{"d":"2015-06-28T13:51:13-07:00"}'
</code></pre>
<p>Of course, that will affect <em>all</em> <code>Date</code> objects. If you want to change the behavior of only the specific date object, you can override just that particular object's <code>toJSON</code> function, like this:</p>
<pre><code>o.d.toJSON = function(){ return moment(this).format(); }
</code></pre> |
37,055,382 | How can I enable IntelliSense for JavaScript inside HTML? | <p>I want to use VS Code to try out the examples of a JavaScript book, but there's no IntelliSense, or at least I don't know how to activate it.</p>
<p>In Visual Studio this feature works out of the box :</p>
<p><a href="https://i.stack.imgur.com/kpKTs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kpKTs.jpg" alt="enter image description here" /></a></p>
<p>But in VS Code, all I got is a message saying "No suggestions."</p>
<p><a href="https://i.stack.imgur.com/u3pPX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3pPX.jpg" alt="enter image description here" /></a></p>
<p>What do I need to do to enable IntelliSense in VS Code?</p> | 37,082,868 | 5 | 0 | null | 2016-05-05 16:15:09.78 UTC | 5 | 2022-03-21 12:41:58.82 UTC | 2022-03-21 12:41:58.82 UTC | null | 9,213,345 | null | 2,736,344 | null | 1 | 28 | visual-studio-code|intellisense|javascript-intellisense | 31,064 | <h2>Currently Unsupported</h2>
<p><a href="https://github.com/Microsoft/vscode/issues/4369" rel="nofollow noreferrer">JS intellisense doesnt work in HTML script tag - VSCode GitHub Issues #4369</a></p>
<p><a href="https://stackoverflow.com/questions/37039910/smart-javascript-suggestions-inside-html-files-no-loger-working-after-visual-stu">Smart Javascript suggestions inside HTML files no loger working after Visual Studio Code update - StackOverflow</a></p> |
24,189,068 | Is there a command for formatting HTML in the Atom editor? | <p>I would like to format my HTML with a command, as I do in Visual Studio, using <kbd>Ctrl</kbd>+<kbd>K</kbd>+<kbd>D</kbd>. Is this possible in <a href="https://atom.io/" rel="noreferrer">Atom</a>? If not, are there other options?</p> | 25,026,804 | 6 | 0 | null | 2014-06-12 16:08:16.2 UTC | 30 | 2020-08-27 03:11:02.973 UTC | 2020-05-29 09:17:42.287 UTC | null | 6,904,888 | null | 376,456 | null | 1 | 248 | html|atom-editor|code-formatting | 186,413 | <p>Atom does not have a built-in command for formatting html. However, you can install the <a href="https://atom.io/packages/atom-beautify" rel="noreferrer">atom-beautify</a> package to get this behavior.</p>
<ol>
<li>Press <kbd>CTRL</kbd> + <kbd>SHFT</kbd> + <kbd>P</kbd> to bring up the command palette (<kbd>CMD</kbd> + <kbd>SHFT</kbd> + <kbd>P</kbd> on a Mac).</li>
<li>Type <em>Install Packages</em> to bring up the package manager.</li>
<li>Type <em>beautify</em> into the search box.</li>
<li>Choose <a href="https://atom.io/packages/atom-beautify" rel="noreferrer">atom-beautify</a> or one of the other packages and click <em>Install</em>.</li>
<li>Now you can use the default keybinding for atom-beautify <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>B</kbd> to beautify your HTML (<kbd>CTRL</kbd> + <kbd>OPTION</kbd> + <kbd>B</kbd> on a Mac).</li>
</ol> |
33,143,743 | read data from MultipartFile which has csv uploaded from browser | <p>May be I am doing it worng by using MultipartFile upload feature.</p>
<p>I have to read data from csv file which will be chosen by the client through the browser. I used MultipartFile to upload file. The file is coming to the controller but now I am unable to read csv data from it. Please guide the best way to do it or help me read csv data from MultipartFile.
The jsp has </p>
<pre><code> <form method="POST" action="uploadFile" enctype="multipart/form-data">
File to upload: <input type="file" name="file"> <input
type="submit" value="Upload"> Press here to upload the
file!
</form>
</code></pre>
<p>The controller has</p>
<pre><code>@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
</code></pre>
<p>Thanks.</p> | 33,168,456 | 3 | 1 | null | 2015-10-15 08:40:12.003 UTC | 7 | 2020-12-18 01:55:13.513 UTC | null | null | null | null | 3,323,380 | null | 1 | 20 | spring|spring-mvc|csv | 52,707 | <p>I figured out a workaround. I converted the file to bytes and then converted the bytes to String. From String I applied string.split() to get what I wanted out of the file.</p>
<pre><code> @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
String completeData = new String(bytes);
String[] rows = completeData.split("#");
String[] columns = rows[0].split(",");
</code></pre> |
10,784,208 | draw rounded edge arc in android with embossed effect | <p>I am trying to develop a custom component i.e. arc slider, I am done with the arc and the thumb but not able to figure out how can I draw the rounded edge arc and also the embossed effect in it. at the moment the slider looks something like this</p>
<p><img src="https://i.stack.imgur.com/Vetl1.png" alt="enter image description here"></p>
<p>the code for drawing the arc is </p>
<pre><code>private void drawSlider(Canvas canvas) {
float sweepDegrees = (value * arcWidthInAngle)
/ (maximumValue - minimumValue);
// the grey empty part of the circle
drawArc(canvas, startAngle, arcWidthInAngle, mTrackColor);
// the colored "filled" part of the circle
drawArc(canvas, startAngle, sweepDegrees, mFillColor);
// the thumb to drag.
int radius = ((diameter/2) - (mArcThickness/2));
Point thumbPoint = calculatePointOnArc(centerX, centerY, radius, startAngle + sweepDegrees);
thumbPoint.x = thumbPoint.x - (mThumbDiameter/2);
thumbPoint.y = thumbPoint.y - (mThumbDiameter/2);
Bitmap thumbBitmap = BitmapFactory.decodeResource(
mContext.getResources(), R.drawable.circle25);
thumbBitmap = getResizedBitmap(thumbBitmap, mThumbDiameter, mThumbDiameter);
canvas.drawBitmap(thumbBitmap, thumbPoint.x, thumbPoint.y,
null);
}
private void drawArc(Canvas canvas, float startAngle, float sweepDegrees,
Paint paint) {
if (sweepDegrees <= 0 || sweepDegrees > arcWidthInAngle) {
return;
}
path.reset();
path.arcTo(outerCircle, startAngle, sweepDegrees);
path.arcTo(innerCircle, startAngle + sweepDegrees, -sweepDegrees);
// innerCircle.
path.close();
canvas.drawPath(path, paint);
}
</code></pre>
<p>I am aiming for the arc something like this</p>
<p><img src="https://i.stack.imgur.com/1Q95R.jpg" alt="enter image description here"></p> | 10,797,042 | 4 | 1 | null | 2012-05-28 11:50:23.463 UTC | 19 | 2017-04-30 16:54:22.857 UTC | 2012-05-29 08:51:32.577 UTC | null | 206,809 | null | 739,076 | null | 1 | 29 | android|android-canvas | 11,666 | <p>I managed to build the arc some what like below</p>
<p><img src="https://i.stack.imgur.com/CdKfw.png" alt="enter image description here"></p>
<p>What I did is I calculated the arc starting and ending point and there I draw the circle with diameter equal to arc thickness.</p>
<p>The code for this is </p>
<pre><code>private void drawSlider(Canvas canvas) {
float sweepDegrees = (value * arcWidthInAngle)
/ (maximumValue - minimumValue);
// the grey empty part of the arc
drawArc(canvas, startAngle, arcWidthInAngle, mTrackColor);
// the colored "filled" part of the arc
drawArc(canvas, startAngle, sweepDegrees, mFillColor);
// the thumb to drag.
int radius = ((diameter/2) - (mArcThickness/2));
Point thumbPoint = calculatePointOnArc(centerX, centerY, radius, startAngle + sweepDegrees);
thumbPoint.x = thumbPoint.x - (mThumbDiameter/2);
thumbPoint.y = thumbPoint.y - (mThumbDiameter/2);
Bitmap thumbBitmap = BitmapFactory.decodeResource(
mContext.getResources(), R.drawable.circle25);
thumbBitmap = getResizedBitmap(thumbBitmap, mThumbDiameter, mThumbDiameter);
canvas.drawBitmap(thumbBitmap, thumbPoint.x, thumbPoint.y,
null);
//drawArc(canvas, startAngle, startAngle + sweepDegrees, white);
}
private void drawArc(Canvas canvas, float startAngle, float sweepDegrees,
Paint paint) {
if (sweepDegrees <= 0 || sweepDegrees > arcWidthInAngle) {
return;
}
path.reset();
int radius = ((diameter/2) - (mArcThickness/2));
Point startPoint = calculatePointOnArc(centerX, centerY, radius, startAngle);
Point endPoint = calculatePointOnArc(centerX, centerY, radius, startAngle + sweepDegrees);
path.arcTo(outerCircle, startAngle, sweepDegrees);
path.arcTo(innerCircle, startAngle + sweepDegrees, -sweepDegrees);
// drawing the circle at both the end point of the arc to git it rounded look.
path.addCircle(startPoint.x, startPoint.y, mArcThickness/2, Path.Direction.CW);
path.addCircle(endPoint.x, endPoint.y, mArcThickness/2, Path.Direction.CW);
path.close();
canvas.drawPath(path, paint);
}
// this is to calculate the end points of the arc
private Point calculatePointOnArc(int circleCeX, int circleCeY, int circleRadius, float endAngle)
{
Point point = new Point();
double endAngleRadian = endAngle * (Math.PI / 180);
int pointX = (int) Math.round((circleCeX + circleRadius * Math.cos(endAngleRadian)));
int pointY = (int) Math.round((circleCeY + circleRadius * Math.sin(endAngleRadian)));
point.x = pointX;
point.y = pointY;
return point;
}
// for the emboss effect set maskfilter of the paint to EmbossMaskFilter
private Paint mTrackColor = new Paint();
MaskFilter mEmboss = new EmbossMaskFilter(new float[] { 0.0f, -1.0f, 0.5f},
0.8f, 15, 1.0f);
mTrackColor.setMaskFilter(mEmboss);
</code></pre> |
10,736,238 | In a finally block, can I tell if an exception has been thrown | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/184704/is-it-possible-to-detect-if-an-exception-occurred-before-i-entered-a-finally-blo">Is it possible to detect if an exception occurred before I entered a finally block?</a> </p>
</blockquote>
<p>I have a workflow method that does things, and throws an exception if an error occurred. I want to add reporting metrics to my workflow. In the finally block below, is there any way to tell if one of the methods in the try/catch block threw an exception ? </p>
<p>I could add my own catch/throw code, but would prefer a cleaner solution as this is a pattern I'm reusing across my project.</p>
<pre><code>@Override
public void workflowExecutor() throws Exception {
try {
reportStartWorkflow();
doThis();
doThat();
workHarder();
} finally {
/**
* Am I here because my workflow finished normally, or because a workflow method
* threw an exception?
*/
reportEndWorkflow();
}
}
</code></pre> | 10,736,274 | 3 | 1 | null | 2012-05-24 11:03:35.263 UTC | 2 | 2012-05-24 11:14:39.493 UTC | 2017-05-23 12:18:15.267 UTC | null | -1 | null | 156,477 | null | 1 | 50 | java|exception|try-catch-finally | 24,235 | <p>There is no automatic way provided by Java. You could use a boolean flag:</p>
<pre><code>boolean success = false;
try {
reportStartWorkflow();
doThis();
doThat();
workHarder();
success = true;
} finally {
if (!success) System.out.println("No success");
}
</code></pre> |
7,426,451 | what are uri, contentValues | <p>Can anyone explain me about each term that I have used in working with calendar events?</p>
<ol>
<li><p><code>Uri event_uri = Uri.parse("content://com.android.calendar/" + "events");</code><br>
What is uri here, what actually is content, as we can initialize int value to 0? Is it<br>
possible to initialize a uri with a default value?</p></li>
<li><p><code>Uri reminder_uri = Uri.parse("content://com.android.calendar/" + "reminders");</code><br>
What signifies these uri? What are the differences between <code>event_uri</code> and <code>reminder_uri</code>?</p></li>
<li><p><code>ContentValues values = new ContentValues();<br>
values.put("calendar_id", 1);<br>
values.put("title", str);<br>
values.put("description", m_strDescription);</code><br>
What does the first one do? <code>values.put("calendar_id", 1);</code></p></li>
<li><p><code>ContentResolver cr = getContentResolver();</code><br>
What is the use of the content resolver? Sometimes we write:</p>
<p><code>Uri u = cr.insert(event_uri, values)</code><br>
What is this uri? How does it differ from the first two uris e.g <code>event_uri</code> and <code>reminder_uri</code></p>
<p>Again <code>values.put("event_id", Long.parseLong(event.getLastPathSegment()));
cr.insert(remindar_uri, values);</code> </p>
<p>What does it do?</p></li>
</ol> | 7,492,847 | 2 | 0 | null | 2011-09-15 05:58:05.15 UTC | 17 | 2015-11-02 07:45:54.753 UTC | 2015-11-02 07:45:54.753 UTC | null | 2,660,176 | null | 806,106 | null | 1 | 30 | android|uri|android-contentresolver | 40,034 | <p>Regarding questions 1 and 2, A <code>Uri</code> is an address that points to something of significance. In the case of <code>ContentProvider</code>s, the <code>Uri</code> is usually used to determine which table to use. So <code>event_uri</code> points to the events table and the <code>reminder_uri</code> points to the reminders table. There is really no "default value" for uris.</p>
<p>Regarding question 3, the <code>ContentValues</code> is essentially a set of key-value pairs, where the key represents the column for the table and the value is the value to be inserted in that column. So in the case of <code>values.put("calendar_id", 1);</code>, the column is "calendar_id" and the value being inserted for that column is 1.</p>
<p>Regarding question 4, the <code>ContentResolver</code> is what android uses to resolve <code>Uri</code>s to <code>ContentProvider</code>s. Anyone can create a <code>ContentProvider</code> and Android has <code>ContentProvider</code>s for the Calendar, Contacts, etc.. The <code>insert()</code> method on a <code>ContentResolver</code> returns the <code>Uri</code> of the inserted row. So in questions 1 and 2, those <code>Uri</code>s pointed to the table but <code>Uri</code>s are hierarchical so they can resolve to a specific row. For example:</p>
<p><code>content://com.android.calendar/events</code> points to the events table, but</p>
<p><code>content://com.android.calendar/events/1</code> points to the row in the events table with id 1.</p>
<p>Keep in mind, that this is the usual behavior, but the providing <code>ContentProvider</code> can customize the uris to be resolved differently.</p>
<p>I would strongly recommend reading the <a href="http://developer.android.com/guide/topics/providers/content-providers.html">ContentProvider docs</a>, especially the section on <a href="http://developer.android.com/guide/topics/providers/content-provider-basics.html#ContentURIs">Content URIs</a>.</p>
<hr>
<p>From the previously recommended documentation:</p>
<blockquote>
<p>In the previous lines of code, the full URI for the "words" table is:</p>
<p><code>content://user_dictionary/words</code></p>
<p>where the <code>user_dictionary</code> string is
the provider's authority, and <code>words</code> string is the table's path. The
string <code>content://</code> (the <strong>scheme</strong>) is always present, and identifies this
as a content URI.</p>
</blockquote> |
23,238,041 | Move and resize legends-box in matplotlib | <p>I'm creating plots using Matplotlib that I save as SVG, export to .pdf + .pdf_tex using Inkscape, and include the .pdf_tex-file in a LaTeX document. </p>
<p>This means that I can input LaTeX-commands in titles, legends etc., giving an image like this
<img src="https://i.stack.imgur.com/NSoiJ.png" alt="plot"></p>
<p>which renders like this when I use it in my LaTeX document. Notice that the font for the numbers on the axes change, and the LaTeX-code in the legend is compiled:</p>
<p><img src="https://i.stack.imgur.com/0j88w.png" alt="plot rendered using LaTeX"></p>
<p>Code for the plot (how to export to SVG not shown here, but can be shown on request):</p>
<pre><code>import numpy as np
x = np.linspace(0,1,100)
y = x**2
import matplotlib.pyplot as plt
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
plt.legend(loc = 'best')
plt.show()
</code></pre>
<p>The problem is, as you can see, that the alignment and size of the box around the legend is wrong. This is because the size of the text of the label changes when the image is passed through Inkscape + pdflatex (because <code>\footnotesize</code> etc. disappears, and the font size changes). </p>
<p>I have figured out that I can choose the placement of the label by either</p>
<pre><code>plt.label(loc = 'upper right')
</code></pre>
<p>or if I want more control I can use</p>
<pre><code>plt.label(bbox_to_anchor = [0.5, 0.2])
</code></pre>
<p>but I haven't found any way of making the box around the label smaller. Is this possible?</p>
<p>An alternative to making the box smaller is to remove the outline of the box using something like</p>
<pre><code>legend = plt.legend()
legend.get_frame().set_edgecolor('1.0')
</code></pre>
<p>and then moving the label to where I want it. In that case I would like to be able to set the placement of the label by first letting python/matplotlib place it using</p>
<pre><code>plt.label(loc = 'upper right')
</code></pre>
<p>and then for example moving it a bit to the right. Is this possible? I have tried using <code>get_bbox_to_anchor()</code> and <code>set_bbox_to_anchor()</code>, but can't seem to get it to work.</p> | 23,254,538 | 3 | 1 | null | 2014-04-23 07:46:08.813 UTC | 5 | 2022-08-25 08:15:08.103 UTC | null | null | null | null | 1,850,917 | null | 1 | 24 | python|matplotlib|legend | 72,982 | <p>You can move a legend after automatically placing it by drawing it, and then getting the bbox position. Here's an example:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# Plot data
x = np.linspace(0,1,100)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(221) #small subplot to show how the legend has moved.
# Create legend
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
leg = plt.legend( loc = 'upper right')
plt.draw() # Draw the figure so you can find the positon of the legend.
# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)
# Change to location of the legend.
xOffset = 1.5
bb.x0 += xOffset
bb.x1 += xOffset
leg.set_bbox_to_anchor(bb, transform = ax.transAxes)
# Update the plot
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/UKgXC.png" alt="legend moved after first drawing"></p> |
35,486,826 | Transform and filter a Java Map with streams | <p>I have a Java Map that I'd like to transform and filter. As a trivial example, suppose I want to convert all values to Integers then remove the odd entries.</p>
<pre><code>Map<String, String> input = new HashMap<>();
input.put("a", "1234");
input.put("b", "2345");
input.put("c", "3456");
input.put("d", "4567");
Map<String, Integer> output = input.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> Integer.parseInt(e.getValue())
))
.entrySet().stream()
.filter(e -> e.getValue() % 2 == 0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(output.toString());
</code></pre>
<p>This is correct and yields: <code>{a=1234, c=3456}</code></p>
<p>However, I can't help but wonder if there's a way to avoid calling <code>.entrySet().stream()</code> twice.</p>
<p>Is there a way I can perform both transform and filter operations and call <code>.collect()</code> only once at the end?</p> | 35,487,026 | 6 | 2 | null | 2016-02-18 16:19:51.627 UTC | 13 | 2019-01-29 06:09:25.383 UTC | 2016-02-18 21:20:08.883 UTC | null | 1,743,880 | null | 2,267,316 | null | 1 | 55 | java|java-8|java-stream|collectors | 68,363 | <p>Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value.</p>
<pre><code>Map<String, Integer> output =
input.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), Integer.valueOf(e.getValue())))
.filter(e -> e.getValue() % 2 == 0)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
</code></pre>
<p>Note that I used <code>Integer.valueOf</code> instead of <code>parseInt</code> since we actually want a boxed <code>int</code>.</p>
<hr>
<p>If you have the luxury to use the <a href="https://github.com/amaembo/streamex">StreamEx</a> library, you can do it quite simply:</p>
<pre><code>Map<String, Integer> output =
EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();
</code></pre> |
35,451,629 | redux-form is Destroying my state once the component is unmounted, what gives? | <p>I am not passing in any special config settings nor am I setting/or calling Destroy... but my state is being cleaned... anyway to prevent this? I need the state to stick around as I need that data thruout my application.</p>
<pre><code>prev state: I see it in there... via redux-logger
action: redux-form/Destroy
next state: it's gone.
</code></pre> | 40,849,164 | 2 | 2 | null | 2016-02-17 08:41:02.097 UTC | 8 | 2018-02-12 16:22:46.587 UTC | 2017-04-24 04:56:35.073 UTC | null | 1,082,449 | null | 1,054,992 | null | 1 | 39 | javascript|redux|redux-form | 21,399 | <p>The form's state subtree <em>is</em> destroyed when the form is unmounted, by design. This is the default and expected behaviour. </p>
<p><strong>From <a href="https://github.com/erikras/redux-form/pull/2113" rel="noreferrer">v6.2.1</a> onwards</strong> there is a form config property <code>destroyOnUnmount</code>, which explicitly enables/disables the state-clearing behaviour on a specific form (<a href="http://redux-form.com/6.0.0-alpha.4/docs/api/ReduxForm.md/#-destroyonunmount-boolean-optional-" rel="noreferrer">docs here</a>)</p>
<pre><code>import { reduxForm } from 'redux-form';
reduxForm({
form: 'example',
destroyOnUnmount: false
})(...)
</code></pre>
<p>This is useful when you have a form whose state you wish to preserve if the user abandons it halfway though, navigates away, and then returns later.</p> |
3,701,264 | Passing a hash to a function ( *args ) and its meaning | <p>When using an idiom such as:</p>
<pre><code>def func(*args)
# some code
end
</code></pre>
<p>What is the meaning of <code>*args</code>? Googling this specific question was pretty hard, and I couldn't find anything.</p>
<p>It seems all the arguments actually appear in <code>args[0]</code> so I find myself writing defensive code such as:</p>
<pre><code>my_var = args[0].delete(:var_name) if args[0]
</code></pre>
<p>But I'm sure there's a better way I'm missing out on.</p> | 3,701,314 | 1 | 0 | null | 2010-09-13 14:17:14.877 UTC | 25 | 2018-07-29 17:29:12.9 UTC | 2018-07-29 17:29:12.9 UTC | null | 2,252,927 | null | 252,348 | null | 1 | 72 | ruby | 47,453 | <p>The <code>*</code> is the <em>splat</em> (or asterisk) operator. In the context of a method, it specifies a variable length argument list. In your case, all arguments passed to <code>func</code> will be putting into an array called <code>args</code>. You could also specify specific arguments before a variable-length argument like so:</p>
<pre><code>def func2(arg1, arg2, *other_args)
# ...
end
</code></pre>
<p>Let's say we call this method:</p>
<pre><code>func2(1, 2, 3, 4, 5)
</code></pre>
<p>If you inspect <code>arg1</code>, <code>arg2</code> and <code>other_args</code> within <code>func2</code> now, you will get the following results:</p>
<pre><code>def func2(arg1, arg2, *other_args)
p arg1.inspect # => 1
p arg2.inspect # => 2
p other_args.inspect # => [3, 4, 5]
end
</code></pre>
<p>In your case, you seem to be passing a hash as an argument to your <code>func</code>, in which case, <code>args[0]</code> will contain the hash, as you are observing.</p>
<p>Resources:</p>
<ul>
<li><a href="http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Variable_Length_Argument_List.2C_Asterisk_Operator" rel="noreferrer">Variable Length Argument List, Asterisk Operator</a></li>
<li><a href="https://stackoverflow.com/questions/918449/what-is-the-operator-doing-to-this-string-in-ruby/918475#918475">What is the * operator doing</a></li>
</ul>
<hr>
<p><strong>Update based on OP's comments</strong></p>
<p>If you want to pass a Hash as an argument, you should not use the splat operator. Ruby lets you omit brackets, <em>including those that specify a Hash</em> (with a caveat, keep reading), in your method calls. Therefore:</p>
<pre><code>my_func arg1, arg2, :html_arg => value, :html_arg2 => value2
</code></pre>
<p>is equivalent to</p>
<pre><code>my_func(arg1, arg2, {:html_arg => value, :html_arg2 => value2})
</code></pre>
<p>When Ruby sees the <code>=></code> operator in your argument list, it knows to take the argument as a Hash, even without the explicit <code>{...}</code> notation (note that this only applies if the hash argument is the last one!).</p>
<p>If you want to collect this hash, you don't have to do anything special (though you probably will want to specify an empty hash as the default value in your method definition):</p>
<pre><code>def my_func(arg1, arg2, html_args = {})
# ...
end
</code></pre> |
8,611,700 | How exactly does !function(){}() work? | <p>I've seen:</p>
<pre><code>!function(){ //code }();
</code></pre>
<p>Used in several places to immediately execute an anonymous function. Normally, it's used in lieu of:</p>
<pre><code>(function(){ //code }())
</code></pre>
<p>Anyone know how the <code>!</code> actually makes the function execute?</p> | 8,611,734 | 2 | 1 | null | 2011-12-23 02:36:09.897 UTC | 10 | 2011-12-27 14:52:22.947 UTC | null | null | null | null | 84,380 | null | 1 | 18 | javascript | 1,664 | <p><em><strong>What the ! does</em></strong></p>
<p>When you use <code>!</code>, the function becomes the single operand of the <em>unary (logical) NOT</em> operator. </p>
<p>This forces the function to be evaluated as an expression, which allows it to be invoked immediately inline.</p>
<hr>
<p><em><strong>Other alternatives</em></strong></p>
<p>You can do this with just about any operator. Here are some examples...</p>
<pre><code>'invoke',function(){ /*code*/ }();
1+function(){ /*code*/ }();
void function(){ /*code*/ }();
~function(){ /*code*/ }();
+function(){ /*code*/ }();
</code></pre>
<p>Nice thing about some of these is that the meaning of the operator is not overloaded.</p>
<hr>
<p><em><strong>The problem with <code>()</code></em></strong></p>
<p>When you use <code>()</code> around the function, you can hit some bugs that will crop up if you have more than one in a row without a semicolon separating them.</p>
<pre><code>(function() {
alert('first');
}())
(function() {
alert('second');
}())
// TypeError: undefined is not a function
</code></pre>
<p>This will result in a <code>TypeError</code>, because the pair of outer <code>()</code> around the second function will be interpreted as intending to <em>call</em> a function. The first one doesn't return a function of course, so you're trying to call on <code>undefined</code>.</p>
<hr>
<p><em><strong>How using a different operator copes with (or avoids) the problem</em></strong></p>
<p>Even an operator like <code>+</code>, which is overloaded to some degree won't cause an error.</p>
<p>If you do this...</p>
<pre><code>+function() {
alert('first');
}()
+function() {
alert('second');
}()
</code></pre>
<p>The first <code>+</code> is interpreted as a <em>unary + operator</em>, and it converts the result returned from the first function, which in this case is <code>undefined</code> so it gets converted to <code>NaN</code>.</p>
<p>The second <code>+</code> will be interpreted as the <em>addition operator</em>, and so will try to add <code>NaN</code> to the return result of the second function, which again here is <code>undefined</code>.</p>
<p>The result of course is <code>NaN</code>, but it is harmless. There's no illegal code to throw an error.</p>
<hr>
<p><em><strong>Demonstration of how the operators interact with the functions</em></strong></p>
<p>To prove this, just give each function a return value, then paste it into the console...</p>
<pre><code>+function() {
alert('first');
return "10";
}()
+function() {
alert('second');
return 20;
}()
// 30
</code></pre>
<p>You'll get the two <code>alert</code>s, and then the console will show <code>30</code> because the first <code>+</code> operator converts the String <code>"10"</code> to the Number <code>10</code>, and the second <code>+</code> added the two results together.</p> |
977,090 | Fading in a background image | <p>I have a web page that uses a large image for its background. I was hoping to use jQuery to load the image once it is downloaded (basically the way that bing.com loads its background image). Is this possible with jQuery? If so, is there a plugin that you would recommend? </p> | 977,161 | 4 | 1 | null | 2009-06-10 17:36:17.63 UTC | 8 | 2012-06-30 10:23:09.42 UTC | 2012-06-30 10:23:09.42 UTC | null | 502,381 | null | 118,513 | null | 1 | 20 | jquery|background-image | 90,111 | <p>This <a href="http://jqueryfordesigners.com/image-loading/" rel="noreferrer">article</a> may be useful. Copying from there:</p>
<p><strong>HTML</strong></p>
<pre><code><div id="loader" class="loading"></div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>DIV#loader {
border: 1px solid #ccc;
width: 500px;
height: 500px;
}
/**
* While we're having the loading class set.
* Removig it, will remove the loading message
*/
DIV#loader.loading {
background: url(images/spinner.gif) no-repeat center center;
}
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code>// when the DOM is ready
$(function () {
var img = new Image();
// wrap our new image in jQuery, then:
$(img)
// once the image has loaded, execute this code
.load(function () {
// set the image hidden by default
$(this).hide();
// with the holding div #loader, apply:
$('#loader')
// remove the loading class (so no background spinner),
.removeClass('loading')
// then insert our image
.append(this);
// fade our image in to create a nice effect
$(this).fadeIn();
})
// if there was an error loading the image, react accordingly
.error(function () {
// notify the user that the image could not be loaded
})
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});
</code></pre> |
939,677 | Signing assemblies - basics | <p>What does it mean to sign an assembly? And why is it done?</p>
<p>What is the simplest way to sign it? What is the .snk file for?</p> | 940,767 | 4 | 0 | null | 2009-06-02 13:50:51.703 UTC | 11 | 2013-01-04 03:13:49.597 UTC | 2013-01-04 03:10:09.887 UTC | null | 63,550 | null | 66,975 | null | 1 | 27 | c#|.net|assemblies | 10,124 | <p>The other two answers are fine, but one additional point. It is easy to get confused between "certificate" signing and "strong name" signing. </p>
<p>The purpose of strong name signing is as Stefan Steinegger says: to allow your customer to establish that the code they THINK they're loading really is precisely the code that they ARE loading. That is ALL strong names are for. Specifically, strong names do not <em>establish</em> any kind of trust relationship between your customer and you. If the customer decides that they trust code that comes from you, it is up to THEM to figure out exactly what the correct strong name is for your code. The "key management" problem is not in any way solved; the customer has the burden of figuring out how to know what key to trust.</p>
<p>Certificate signing, that is, signing with a certificate you get from Verisign or some other certifying authority, has a much more complex purpose. The purpose of certificate signing is to establish an authenticated chain of trust and identity from the certifying authority down to the organization which signed the code. Your customer might not trust you, your customer might not have even <em>heard</em> of you, but your customer can say "if Verisign vouches for the identity of the author of this code, then I will trust them". The key management problem is reduced for the customer because the certifying authority has taken on that burden for them.</p> |
399,648 | Preventing same Event handler assignment multiple times | <p>If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the same handler to the same event.</p>
<pre><code>object.Event += MyFunction
</code></pre>
<p>Adding this in a spot that will be called more than once will execute the handler 'n' times (of course).</p>
<p>I have resorted to removing any previous handler before trying to add via </p>
<pre><code>object.Event -= MyFunction;
object.Event += MyFunction;
</code></pre>
<p>This works but seems off somehow. Any suggestions on proper handling ;) of this scenario.</p> | 399,772 | 4 | 2 | null | 2008-12-30 06:31:21.163 UTC | 9 | 2011-06-08 07:33:21.37 UTC | 2011-06-08 07:33:21.37 UTC | null | 16,076 | overpalm | null | null | 1 | 47 | c#|events | 20,459 | <p>Baget is right about using an explicitly implemented event (although there's a mixture there of explicit interface implementation and the full event syntax). You can probably get away with this:</p>
<pre><code>private EventHandler foo;
public event EventHandler Foo
{
add
{
// First try to remove the handler, then re-add it
foo -= value;
foo += value;
}
remove
{
foo -= value;
}
}
</code></pre>
<p>That may have some odd edge cases if you ever add or remove multicast delegates, but that's unlikely. It also needs careful documentation as it's not the way that events normally work.</p> |
45,585,000 | Azure CLI vs Powershell? | <p>Not precisely able to understand the merit of Azure CLI on Windows environment.</p>
<p>Is it targetted for the audience who want to manage Azure IAAS from Linux environment?</p>
<p>I thought <a href="https://github.com/PowerShell/PowerShell" rel="noreferrer">Powershell core</a> is going to be the way for non-Windows admins.
Is PowerShell Core not going to be ported to well on all platforms, to serve the cross-platform audience?</p>
<blockquote>
<p>In a nutshell, is it worth learning Azure CLI?</p>
</blockquote> | 45,585,899 | 12 | 1 | null | 2017-08-09 08:06:36.61 UTC | 7 | 2022-08-10 22:57:40.24 UTC | 2021-08-19 09:38:26.55 UTC | null | 4,167,200 | null | 1,431,250 | null | 1 | 80 | azure|powershell|azure-powershell|azure-cli|azure-cli2 | 55,762 | <p>Azure CLI is a PowerShell-like-tool available for all platforms. You can use the same commands no matter what platform you use: Windows, Linux or Mac.</p>
<p>Now, there are two version Azure CLI. The Azure CLI 1.0 was written with Node.js to achieve cross-platform capabilities, and the new Azure CLI 2.0 is written in Python to offer better cross-platform capabilities. Both are Open Source and available on Github. <strong>However, for now, only certain PowerShell cmdlets support use on Linux.</strong> </p>
<blockquote>
<p>Is it targetted for the audience who want to manage Azure IAAS from Linux
environment?</p>
</blockquote>
<p>I think the answer is yes. For a Linux or Mac developer, I think they more likely to use Azure CLI.</p> |
22,295,768 | How to use OSM map in an android application.? Is there any tutorial to learn about using OSM in android.? | <p>I am searching for a tutorial/manual or steps to include Open street map into my android application. All I found is either a big project with lot more functionality on it, otherwise so many questions ended without proper conclusion about "HOW"..!</p>
<p>Is there any proper blog/site or document that can a fresher can refer?</p> | 22,297,373 | 5 | 1 | null | 2014-03-10 08:58:36.433 UTC | 13 | 2020-12-27 13:14:57.867 UTC | 2020-12-27 13:14:57.867 UTC | null | 1,783,163 | null | 3,291,467 | null | 1 | 17 | android|google-maps-api-3|openstreetmap|osmdroid | 34,784 | <p>I don't know of any tutorials but here's the code I wrote for a minimal example using Osmdroid.</p>
<pre><code>// This is all you need to display an OSM map using osmdroid
package osmdemo.demo;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.app.Activity;
import android.os.Bundle;
public class OsmdroidDemoMap extends Activity {
private MapView mMapView;
private MapController mMapController;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.osm_main);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
mMapView.setBuiltInZoomControls(true);
mMapController = (MapController) mMapView.getController();
mMapController.setZoom(13);
GeoPoint gPt = new GeoPoint(51500000, -150000);
mMapController.setCenter(gPt);
}
}
/* HAVE THIS AS YOUR osm_main.xml
---------------------------------------------------------- XML START
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<org.osmdroid.views.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
</LinearLayout>
---------------------------------------------------------- XML END
Include slf4j-android-1.5.8.jar and osmdroid-android-4.1.jar in the build path
(Google search for where to get them from)
*/
</code></pre>
<p>Note that you must now use the latest version (4.1) to avoid getting blocked from downloading tiles from OSM.</p>
<p>Also note that they are moving their repositries to Github and the process isn't complete yet. This page <a href="http://code.google.com/p/osmdroid/wiki/Downloads">downloads</a> holds the links for the jars</p> |
48,145,432 | javascript includes() case insensitive | <p>I have an array of strings that I need to loop and check against with another passed in string.</p>
<pre><code>var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");
for (i = 0; i < filterstrings.lines.length; i++) {
if (passedinstring.includes(filterstrings[i])) {
alert("string detected");
}
}
</code></pre>
<p>How do I ensure that case sensitivity is ignored here (preferably by using regex) when filtering, if the <code>var passedinstring</code> were to have strings like <code>FirsTsTriNg</code> or <code>fiRSTStrING</code>?</p> | 48,145,521 | 11 | 2 | null | 2018-01-08 06:43:02.203 UTC | 13 | 2022-06-22 15:47:17.44 UTC | 2021-05-18 23:43:14.863 UTC | null | 1,730,638 | null | 5,921,881 | null | 1 | 144 | javascript|regex | 184,042 | <p>You can create a <strong>RegExp</strong> from <code>filterstrings</code> first</p>
<pre><code>var filterstrings = ['firststring','secondstring','thridstring'];
var regex = new RegExp( filterstrings.join( "|" ), "i");
</code></pre>
<p>then <code>test</code> if the <code>passedinstring</code> is there</p>
<pre><code>var isAvailable = regex.test( passedinstring );
</code></pre> |
29,756,194 | Access denied for user 'homestead'@'localhost' (using password: YES) | <p>I'm on a Mac OS Yosemite using Laravel 5.0.</p>
<p>While in my <strong>local</strong> environment, I run <code>php artisan migrate</code> I keep getting :</p>
<blockquote>
<p>Access denied for user 'homestead'@'localhost' (using password: YES)</p>
</blockquote>
<p><strong>Configuration</strong></p>
<p>Here is my <strong>.env</strong></p>
<pre><code>APP_ENV=local
APP_DEBUG=true
APP_KEY=*****
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code></pre>
<p><strong>app\config\database.php</strong></p>
<pre><code> 'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'unix_socket' => '/tmp/mysql.sock',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
]
</code></pre>
<p>How do I avoid this kind of error ?</p>
<p><strong>I've tried :</strong></p>
<hr />
<h1>1</h1>
<p>in <strong>app/database.php</strong></p>
<p>Replace <code>localhost</code> with <code>127.0.0.1</code></p>
<p><code>'host'=> env('DB_HOST', 'localhost')</code> --><code>'host' => env('DB_HOST', '127.0.0.1')</code></p>
<p>Also, in <strong>.env</strong></p>
<p><code>DB_HOST=localhost</code> --> <code>DB_HOST=127.0.0.1</code></p>
<hr />
<h1>2</h1>
<p>Try specify environment</p>
<p><code>php artisan migrate --env=local</code></p>
<hr />
<h1>3</h1>
<p>Check to see if the MySQL is running by run</p>
<p><code>mysqladmin -u homestead -p status Enter password: secret</code></p>
<p>I got</p>
<p><code>Uptime: 21281 Threads: 3 Questions: 274 Slow queries: 0 Opens: 327 Flush tables: 1 Open tables: 80 Queries per second avg: 0.012</code></p>
<p>Which mean it's running.</p>
<hr />
<h1>4</h1>
<p>Check MySQL UNIX Socket (<em>This step work for me</em>)</p> | 29,772,274 | 32 | 2 | null | 2015-04-20 18:59:20.15 UTC | 49 | 2022-04-15 16:21:38.51 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,480,164 | null | 1 | 177 | php|laravel|laravel-5|database-migration|homestead | 315,956 | <h1>Check MySQL UNIX Socket</h1>
<p>Find <strong>unix_socket</strong> location using MySQL</p>
<p><code>mysql -u homestead -p</code></p>
<pre><code>mysql> show variables like '%sock%';
+-----------------------------------------+-----------------------------+
| Variable_name | Value |
+-----------------------------------------+-----------------------------+
| performance_schema_max_socket_classes | 10 |
| performance_schema_max_socket_instances | 322 |
| socket | /var/run/mysqld/mysqld.sock |
+-----------------------------------------+-----------------------------+
3 rows in set (0.00 sec)
</code></pre>
<p>Then I go to <strong>config/database.php</strong></p>
<p>I update this line : <code>'unix_socket' => '/tmp/mysql.sock',</code></p>
<p>to : <code>'unix_socket' => '/var/run/mysqld/mysqld.sock',</code></p>
<p>That's it. It works for my as my 4th try.I hope these steps help someone. :D</p> |
4,235,078 | How to avoid infinite recursion with super()? | <p>I have code like this:</p>
<pre><code>class A(object):
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
self.b = 2
super(self.__class__, self).__init__()
class C(B):
def __init__(self):
self.c = 3
super(self.__class__, self).__init__()
</code></pre>
<p>Instantiating B works as expected but instantiating C recursed infinitely and causes a stack overflow. How can I solve this?</p> | 4,235,084 | 1 | 0 | null | 2010-11-20 21:22:34.043 UTC | 8 | 2010-11-21 10:32:30.32 UTC | null | null | null | null | 477,933 | null | 1 | 28 | python|oop|multiple-inheritance|super | 6,175 | <p>When instantiating C calls <code>B.__init__</code>, <code>self.__class__</code> will still be C, so the super() call brings it back to B.</p>
<p>When calling super(), use the class names directly. So in B, call <code>super(B, self)</code>, rather than <code>super(self.__class__, self)</code> (and for good measure, use <code>super(C, self)</code> in C). From Python 3, you can just use super() with no arguments to achieve the same thing</p> |
4,254,694 | Is it possible to access the TempData key/value from HttpContext? | <p>I'm trying to crate a custom action filter attribute. And some where, I need facilities, such us TempData[key] and TryUpdateModel... My custom attribute class deriving from the <strong>ActionFilterAttribute</strong>, I can access both below methods.</p>
<pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
</code></pre>
<p>Unfortunately, from both filtercontext local variables, I don't know how to access the TempData. I've tried to follow several leads, but without success. After all, maybe there's TempData in the filterContext variables. In that case, how do I access the TemData available?</p>
<p>Thanks for helping</p> | 4,254,731 | 1 | 0 | null | 2010-11-23 09:48:46.153 UTC | 3 | 2018-07-25 14:50:13.507 UTC | 2018-07-25 14:50:13.507 UTC | null | 1,180,926 | null | 202,382 | null | 1 | 31 | asp.net-mvc|attributes|tempdata | 8,769 | <pre><code>var foo = filterContext.Controller.TempData["foo"];
</code></pre> |
25,049,751 | Constructing an Abstract Syntax Tree with a list of Tokens | <p>I want to construct an AST from a list of tokens. I'm making a scripting language and I've already done the lexical analysis part, but I have no idea how to create an AST. So the question is, how do I take something like this:</p>
<pre><code>WORD, int
WORD, x
SYMBOL, =
NUMBER, 5
SYMBOL, ;
</code></pre>
<p>and convert it into an Abstract Syntax Tree? Preferably, I'd like to do so <strong>without</strong> a library like ANTLR or whatever, I'd rather try and do it from scratch myself. However, if it's a really complex task, I don't mind using a library :) Thanks</p> | 25,106,688 | 1 | 3 | null | 2014-07-31 02:08:41.01 UTC | 40 | 2018-05-06 11:40:17.793 UTC | null | null | null | null | 3,839,220 | null | 1 | 48 | java|interpreter|abstract-syntax-tree | 33,858 | <p>The fundamental trick is to recognize that parsing, however accomplished, happens in incremental steps, including the reading of the tokens one by one.</p>
<p>At each incremental step, there is an opportunity to build part of the AST by combining AST fragments built by other incremental steps. This is a recursive idea, and it bottoms out in building AST leaf nodes for tokens as they are scanned. This basic idea occurs in pretty much all AST-building parsers.</p>
<p>If one builds a recursive descent parser, one in effect builds a cooperating system of recursive procedures, each one of which recognizes a nonterminal in whatever grammar is being implemented. For pure parsing, each procedure simply returns a boolean for "nonterminal (not) recognized".</p>
<p>To build an AST with a recursive descent parser, one designs these procedures to return two values: the boolean "recognized", and, if recognized, an AST constructed (somehow) for the nonterminal. (A common hack is return a pointer, which is void for "not recognized", or points to the constructed AST if "recognized"). The way the resulting AST for a single procedure is built, is by combining the ASTs from the sub-procedures that it invokes. This is pretty trivial to do for leaf procedures, which read an input token and can immediately build a tree. </p>
<p>The downside to all this is one must manually code the recursive descent, and augment it with the tree building steps. In the grand scheme of things, this is actually pretty easy to code for small grammars.</p>
<p>For OP's example, assume we have this grammar:</p>
<pre><code>GOAL = ASSIGNMENT
ASSIGNMENT = LHS '=' RHS ';'
LHS = IDENTIFIER
RHS = IDENTIFIER | NUMBER
</code></pre>
<p>OK, our recursive descent parser:</p>
<pre><code>boolean parse_Goal()
{ if parse_Assignement()
then return true
else return false
}
boolean parse_Assignment()
{ if not Parse_LHS()
then return false
if not Parse_equalsign()
then throw SyntaxError // because there are no viable alternatives from here
if not Parse_RHS()
then throw SyntaxError
if not Parse_semicolon()
the throw SyntaxError
return true
}
boolean parse_LHS()
{ if parse_IDENTIFIER()
then return true
else return false
}
boolean parse_RHS()
{ if parse_IDENTIFIER()
then return true
if parse_NUMBER()
then return true
else return false
}
boolean parse_equalsign()
{ if TestInputAndAdvance("=") // this can check for token instead
then return true
else return false
}
boolean parse_semicolon()
{ if TestInputAndAdvance(";")
then return true
else return false
}
boolean parse_IDENTIFIER()
{ if TestInputForIdentifier()
then return true
else return false
}
boolean parse_NUMBER()
{ if TestInputForNumber()
then return true
else return false
}
</code></pre>
<p>Now, let's revise it build a abstract syntax tree:</p>
<pre><code>AST* parse_Goal() // note: we choose to return a null pointer for "false"
{ node = parse_Assignment()
if node != NULL
then return node
else return NULL
}
AST* parse_Assignment()
{ LHSnode = Parse_LHS()
if LHSnode == NULL
then return NULL
EqualNode = Parse_equalsign()
if EqualNode == NULL
then throw SyntaxError // because there are no viable alternatives from here
RHSnode = Parse_RHS()
if RHSnode == NULL
then throw SyntaxError
SemicolonNode = Parse_semicolon()
if SemicolonNode == NULL
the throw SyntaxError
return makeASTNode(ASSIGNMENT,LHSNode,RHSNode)
}
AST* parse_LHS()
{ IdentifierNode = parse_IDENTIFIER()
if node != NULL
then return IdentifierNode
else return NULL
}
AST* parse_RHS()
{ RHSnode = parse_IDENTIFIER()
if RHSnode != null
then return RHSnode
RHSnode = parse_NUMBER()
if RHSnode != null
then return RHSnode
else return NULL
}
AST* parse_equalsign()
{ if TestInputAndAdvance("=") // this can check for token instead
then return makeASTNode("=")
else return NULL
}
AST* parse_semicolon()
{ if TestInputAndAdvance(";")
then return makeASTNode(";")
else return NULL
}
AST* parse_IDENTIFIER()
{ text = TestInputForIdentifier()
if text != NULL
then return makeASTNode("IDENTIFIER",text)
else return NULL
}
AST* parse_NUMBER()
{ text = TestInputForNumber()
if text != NULL
then return makeASTNode("NUMBER",text)
else return NULL
}
</code></pre>
<p>I've obviously glossed over some details, but I assume the reader will have no trouble filling them in.</p>
<p>Parser generator tools like JavaCC and ANTLR basically generate recursive descent parsers, and have facilities for constructing trees that work very much like this.</p>
<p>Parser generator tools that build bottom-up parsers (YACC, Bison, GLR, ...) also build AST nodes in the same style. However, there is no set of recursive functions; instead, a stack of tokens seen and reduced-to nonterminals is managed by these tools. The AST nodes are constructed on a parallel stack; when a reduction occurs, the AST nodes on the part of the stack covered by the reduction are combined to produce a nonterminal AST node to replace them. This happens with "zero-size" stack segments for grammar rules which are empty too causing AST nodes (typically for 'empty list' or 'missing option') to seemingly appear from nowhere.</p>
<p>With bitty languages, writing recursive-descent parsers that build trees is pretty practical.</p>
<p>A problem with real languages (whether old and hoary like COBOL or hot and shiny like Scala) is that the number of grammar rules is pretty large, complicated by the sophistication of the language and the insistence on whatever language committee is in charge of it to perpetually add new goodies offered by other languages ("language envy", see the evolutionary race between Java, C# and C++). Now writing a recursive descent parser gets way out of hand and one tends to use parser generators. But even with a parser generator, writing all the custom code to build AST nodes is also a big battle (and we haven't discussed what it takes to design a good "abstract" syntax vs. the first thing that comes to mind). Maintaining grammar rules and AST building goo gets progressively harder with scale and ongoing evolution. (If your language is successful, within a year you'll want to change it). So even writing the AST building rules gets awkward.</p>
<p>Ideally, one would just like to write a grammar, and get a parser and tree. You <a href="https://stackoverflow.com/questions/1888854/what-is-the-difference-between-an-abstract-syntax-tree-and-a-concrete-syntax-tre/1916687#1916687">can do this with some recent parser generators: Our DMS Software Reengineering Toolkit accepts full context free grammars, and automatically constructs an AST</a>, no work on the grammar engineer's part; its been doing this since 1995. The ANTLR guys finally figured this out in 2014, and ANTLR4 now offers an option like this.</p>
<p>Last point: having a parser (even with an AST) is hardly a solution to the actual problem you set out to solve, whatever it was. Its just a foundation piece, and much to the shock for most parser-newbies, it is the <em>smallest</em> part to a tool that manipulates code. Google my essay on Life After Parsing (or check my bio) for more detail. </p> |
20,211,890 | SVG - Change fill color on button click | <p>I've done a simple test svg-image. </p>
<p>I would like to make toggle buttons so when I click on btn-test1, the path1 will be fill="#000" and the others "#FFF". I'm going to make a map with around 40 different paths, but I'm trying this first (don't know if it's possible) ? </p>
<p><strong>Here's the HTML so far:</strong></p>
<pre><code><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
<path id="path1" fill="#FFFFFF" stroke="#231F20" stroke-miterlimit="10" d="M291.451,51.919v202.54c0,0,164.521,119.846,140.146,0
C407.227,134.613,291.451,51.919,291.451,51.919z"/>
<path id="path2" fill="#FFFFFF" stroke="#231F20" stroke-miterlimit="10" d="M169.595,150.844c0,0-76.24,69.615-40.606,128.309
c35.634,58.695,155.798-51.867,151.654-85.993C276.498,159.034,177.054,89.42,169.595,150.844z"/>
<path id="path3" fill="#FFFFFF" stroke="#231F20" stroke-miterlimit="10" d="M40.332,90.466c0,0-39.911,76.119-2.691,87.83
c37.22,11.71,78.923-46.844,56.054-78.462C70.826,68.216,40.332,90.466,40.332,90.466z"/>
</svg>
</div>
<button class="btn" id="btn-test1">Test 1</button>
<button class="btn" id="btn-test2">Test 2</button>
<button class="btn" id="btn-test3">Test 3</button>
</code></pre>
<p><strong>EDIT: This javascript solved it</strong></p>
<pre><code><script>
$('.btn').click(function() {
$('#path1, #path2, #path3').css({ fill: "#ffffff" });
var currentId = $(this).attr('id');
$('#path' + currentId +'').css({ fill: "#000" });
});
</script>
</code></pre> | 20,212,046 | 3 | 1 | null | 2013-11-26 08:29:31.487 UTC | 7 | 2017-02-11 10:49:39.11 UTC | 2013-11-26 08:47:31.687 UTC | null | 1,472,067 | null | 1,472,067 | null | 1 | 18 | jquery|svg | 74,240 | <p>You are looking for the <code>fill</code> property.</p>
<p>See this fiddle: <strong><a href="http://jsfiddle.net/P6t2B/">http://jsfiddle.net/P6t2B/</a></strong></p>
<p>For example:</p>
<pre><code>$('#btn-test1').on("click", function() {
$('#path1').css({ fill: "#ff0000" });
});
</code></pre> |
7,585,210 | WebView, add local .CSS file to an HTML page? | <p>In android I'm using WebView to display a part of a webpage which I fetched from the internet using HttpClient from Apache. To only have the part I want from the html, I use Jsoup.</p>
<pre><code>String htmlString = EntityUtils.toString(entity4); // full html as a string
Document htmlDoc = Jsoup.parse(htmlString); // .. as a Jsoup Document
Elements tables = htmlDoc.getElementsByTag("table"); //important part
</code></pre>
<p>Now I can just load <code>tables.toString()</code> in the WebView and it displays. Now I want to link a CSS file which I store inside my assets folder with this page. I know I can have something like</p>
<pre><code><LINK href="styles/file.css" type="text/css" rel="stylesheet">
</code></pre>
<p>In my html, but how do I link it so that it uses the one I've stored locally?</p>
<p>---EDIT---<br />
I've now changed to this:</p>
<pre><code>StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\"file:///android_asset/htmlstyles_default.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(tables.toString());
sb.append("</body></HTML>");
return sb.toString();
</code></pre>
<p>Somehow I do not get the styles applied to the page. Is it the location path I used that is wrong?</p> | 7,736,654 | 3 | 3 | null | 2011-09-28 14:56:31.313 UTC | 29 | 2020-07-30 05:40:09.747 UTC | 2020-07-30 05:40:09.747 UTC | null | 214,143 | null | 717,572 | null | 1 | 39 | android|html|css|resources|httpclient | 50,548 | <p>Seva Alekseyev is right, you should store CSS files in <code>assets</code> folder, but referring by <code>file:///android_asset/filename.css</code> URL doesn't working for me.</p>
<p>There is another solution: put CSS in <code>assets</code> folder, do your manipulation with HTML, but <strong>refer to CSS by relative path</strong>, and load HTML to WebView by <a href="http://developer.android.com/reference/android/webkit/WebView.html#loadDataWithBaseURL%28java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String%29" rel="noreferrer"><code>loadDataWithBaseURL()</code></a> method:</p>
<pre><code>webView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "utf-8", null);
</code></pre>
<p>E.g. you have <code>styles.css</code> file, put it to <code>assets</code> folder, create HTML and load it:</p>
<pre><code>StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\"styles.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(tables.toString());
sb.append("</body></HTML>");
webView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);
</code></pre>
<p>P.S. I've come to this solution thanks to <a href="https://stackoverflow.com/questions/4114496/load-html-file-to-webview-with-custom-css/4114753#4114753">Peter Knego's answer</a>.</p> |
7,598,422 | Is it better to use the mapred or the mapreduce package to create a Hadoop Job? | <p>To create MapReduce jobs you can either use the old <code>org.apache.hadoop.mapred</code> package or the newer <code>org.apache.hadoop.mapreduce</code> package for Mappers and Reducers, Jobs ... The first one had been marked as deprecated but this got reverted meanwhile. Now I wonder whether it is better to use the old mapred package or the new mapreduce package to create a job and why. Or is it just dependent on whether you need stuff like the MultipleTextOutputFormat which is only available in the old mapred package?</p> | 7,600,339 | 3 | 2 | null | 2011-09-29 13:57:54.757 UTC | 18 | 2015-03-22 15:27:10.09 UTC | 2015-03-22 15:27:10.09 UTC | null | 3,275,167 | null | 808,388 | null | 1 | 46 | hadoop|mapreduce | 16,176 | <p>Functionality wise there is not much difference between the old (<code>o.a.h.mapred</code>) and the new (<code>o.a.h.mapreduce</code>) API. The only significant difference is that records are pushed to the mapper/reducer in the old API. While the new API supports both pull/push mechanism. You can get more information about the pull mechanism <a href="https://stackoverflow.com/questions/7537797/how-to-pull-data-in-the-map-reduce-functions">here</a>.</p>
<p>Also, the old API has been <a href="https://issues.apache.org/jira/browse/MAPREDUCE-1735" rel="noreferrer">un-deprecated</a> since 0.21. You can find more information about the new API <a href="http://www.cloudera.com/blog/2010/08/what%E2%80%99s-new-in-apache-hadoop-0-21/" rel="noreferrer">here</a>.</p>
<p>As you mentioned some of the classes (like MultipleTextOutputFormat) have not been migrated to the new API, due to this and the above mentioned reason it's better to stick to the old API (although a translation is usually quite simple).</p> |
7,655,393 | Clear Contents of a Column | <p>How would I clear the contents of a column from cell A3 to cell __ where __ represents the last entry in the column (assuming there are no empty spaces between entries).</p>
<p>Thanks for the help.</p> | 7,655,488 | 4 | 0 | null | 2011-10-05 00:08:01.06 UTC | 0 | 2021-03-13 07:58:26.48 UTC | 2018-04-02 18:31:47.213 UTC | null | 8,112,776 | null | 977,343 | null | 1 | 5 | vba|excel | 71,171 | <pre><code>range("A3", Range("A" & Columns("A").SpecialCells(xlCellTypeLastCell).Row)).Delete
</code></pre>
<p>That will delete A3 through the last cell in column A, regardless of any blanks in the column.</p>
<pre><code>range("A3", range("A3").End(xlDown)).Delete
</code></pre>
<p>That will delete from A3 down to the first blank cell after A3 in column A.</p>
<p><strong>EDIT:</strong> Fixed the first code snippet so it only deletes cells in column A.</p> |
7,199,911 | how to File.listFiles in alphabetical order? | <p>I've got code as below:</p>
<pre><code>class ListPageXMLFiles implements FileFilter {
@Override
public boolean accept(File pathname) {
DebugLog.i("ListPageXMLFiles", "pathname is " + pathname);
String regex = ".*page_\\d{2}\\.xml";
if(pathname.getAbsolutePath().matches(regex)) {
return true;
}
return false;
}
}
public void loadPageTrees(String xml_dir_path) {
ListPageXMLFiles filter_xml_files = new ListPageXMLFiles();
File XMLDirectory = new File(xml_dir_path);
for(File _xml_file : XMLDirectory.listFiles(filter_xml_files)) {
loadPageTree(_xml_file);
}
}
</code></pre>
<p>The <code>FileFilter</code> is working nicely, but <code>listFiles()</code> seems to be listing the files in reverse alphabetical order. Is there some quick way of telling <code>listFile()</code> to list the files in alphabetical order?</p> | 7,199,929 | 4 | 1 | null | 2011-08-26 04:04:31.753 UTC | 13 | 2019-03-14 13:30:20.603 UTC | 2011-08-26 04:22:40.913 UTC | null | 272,824 | null | 194,309 | null | 1 | 105 | java|java-io | 133,414 | <p>The <code>listFiles</code> method, with or without a filter does not guarantee any order.</p>
<p>It does, however, return an array, which you can sort with <code>Arrays.sort()</code>.</p>
<pre><code>File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
</code></pre>
<p>This works because <code>File</code> is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.</p>
<p>If you prefer using Streams:</p>
<p>A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:</p>
<pre><code>Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
</code></pre>
<p>Replace the <code>System.out::println</code> with whatever you want to do with the file names. If you want only filenames that end with <code>"xml"</code> just do:</p>
<pre><code>Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
</code></pre>
<p>Again, replace the printing with whichever processing operation you would like.</p> |
7,814,794 | How to structure a Node, Express, Connect-Auth and Backbone application on the server-side? | <p>I'm a client-side guy that just stepped into the world of server-side javascript. I've got this idea about how I think I want to build my first Nodejs application. I want a server-side that pretty much only serves an empty shell and lots of JSON. I want to put the rest of the logic in a Backbone.js-equipped front-end.</p>
<p>So I quick whipped up a small application (code in the bottom) and I've got a few questions.</p>
<ol>
<li><p>Are session variables safe? Can I use session variables to store an user identifier that I later read to fetch sensitive date. Is it possible to modify sessions variables so that, in my case, one user could get hold of another user's data?</p></li>
<li><p>Does it make sense to serve JSON in the way I'm doing it on my '/profile' route. In my application there will be a lot of routes just like that one. Routes that fetch something from the database and serves them as JSON to the client.</p></li>
<li><p>Looking at my code, do you have any tips or tricks? Things I should do differently. Modules I probably should have a look at?</p></li>
<li><p>Does my idea of an almost JSON-only backend makes sense?</p></li>
</ol>
<p>My application below. </p>
<pre><code>var facebook = {
'appId' : "my app id",
'appSecret' : "my app secret",
'scope' : "email",
'callback' : "http://localhost:2000/"
}
var express = require('express');
var MongoStore = require('connect-mongo');
var auth = require('connect-auth')
var UserProvider = require('./providers/user').UserProvider;
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(auth([auth.Facebook(facebook)]));
app.use(express.session({secret: 'my secret',store: new MongoStore({db: 'app'})}));
app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Providers
var UserProvider = new UserProvider('localhost', 27017);
// Routes
app.get('/', function( request, response ) {
if( !request.session.userId ) {
request.authenticate(['facebook'], function(error, authenticated) {
if( authenticated ) {
request.session.userId = request.getAuthDetails().user.id;
}
});
}
response.render( 'index.jade' );
});
app.get('/profile', function( request, response ) {
response.contentType('application/json');
if( request.session.userId ){
UserProvider.findById( request.session.userId, function( error, user ){
var userJSON = JSON.stringify( user );
response.send( userJSON );
});
} else {
response.writeHead(303, { 'Location': "/" });
}
});
app.get('/logout', function( request, response, params ) {
request.session.destroy();
request.logout();
response.writeHead(303, { 'Location': "/" });
response.end('');
});
app.listen(2000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
</code></pre> | 7,821,013 | 1 | 2 | null | 2011-10-18 23:02:25.41 UTC | 15 | 2011-10-19 12:05:32.463 UTC | 2011-10-19 10:11:11.44 UTC | null | 672,132 | null | 672,132 | null | 1 | 10 | javascript|node.js|backbone.js|express | 6,956 | <p>I think you have the right idea, although I'll throw out a couple of thoughts:</p>
<ul>
<li><strong>Defining Routes</strong> - If you are defining a lot of routes, especially with JSON, you may want to define them dynamically via an MVC type framework. You can find a good example of that <a href="https://github.com/visionmedia/express/tree/master/examples/mvc" rel="noreferrer">in the express samples here</a>. It would save you a lot of handwritten routes and you could pass node objects back to the client as JSON without doing much else on the server side.</li>
<li><strong>Backbone on the Server</strong> - If you want to go a little crazier (and I have not ever used this technique), <a href="http://developmentseed.org/" rel="noreferrer">Development Seed</a> have built a framework called <a href="https://github.com/developmentseed/bones" rel="noreferrer">bones</a> that <a href="https://github.com/developmentseed/bones" rel="noreferrer">uses backbone on the server side</a>.</li>
<li><strong>Login Example</strong> - There is <a href="http://dailyjs.com/2010/12/06/node-tutorial-5/" rel="noreferrer">a good tutorial over at DailyJS</a> regarding user session management.</li>
<li><strong>Accessibility</strong> - As long as you don't have accessibility concerns, providing data via a REST API makes sense. If you have to worry about 508 compliance or other javascript limitations you might run into problems.</li>
</ul>
<p>As for security, setting your session timeout to a lower value and choosing an appropriate secret key would probably go a long way toward making sure someone can't generate session cookies (by default the actual data isn't stored on the client). I'm not sure what algorithm node.js uses to generate session cookies. Here are some details on the <a href="http://senchalabs.github.com/connect/middleware-session.html" rel="noreferrer">express session middleware</a>.</p> |
1,415,256 | Alignment requirements for atomic x86 instructions vs. MS's InterlockedCompareExchange documentation? | <p>Microsoft offers the <a href="http://msdn.microsoft.com/en-us/library/ms683560%28VS.85%29.aspx" rel="nofollow noreferrer"><code>InterlockedCompareExchange</code></a> function for performing atomic compare-and-swap operations. There is also an <a href="https://msdn.microsoft.com/en-us/library/ttk2z1ws.aspx" rel="nofollow noreferrer"><code>_InterlockedCompareExchange</code></a> <em>intrinsic</em>.</p>
<p>On x86 these are implemented using the <code>lock cmpxchg</code> instruction.</p>
<p>However, reading through the documentation on these three approaches, they don't seem to agree on the alignment requirements.</p>
<p>Intel's <a href="http://download.intel.com/design/intarch/manuals/24319101.pdf" rel="nofollow noreferrer">reference manual</a> says nothing about alignment (other than that <em>if</em> alignment checking is enabled and an unaligned memory reference is made, an exception is generated)</p>
<p>I also looked up the <code>lock</code> prefix, which specifically states that</p>
<blockquote>
<p>The integrity of the LOCK prefix is <strong>not</strong> affected by the alignment of the memory field.</p>
</blockquote>
<p><em>(emphasis mine)</em></p>
<p>So Intel seems to say that alignment is irrelevant. The operation will be atomic no matter what.</p>
<p>The <code>_InterlockedCompareExchange</code> intrinsic documentation also says nothing about alignment, however the <code>InterlockedCompareExchange</code> <em>function</em> states that</p>
<blockquote>
<p>The parameters for this function must be aligned on a 32-bit boundary; otherwise, the function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems.</p>
</blockquote>
<p>So what gives?
Are the alignment requirements for <code>InterlockedCompareExchange</code> just to make sure the function will work even on pre-486 CPU's where the <code>cmpxchg</code> instruction isn't available?
That seems likely based on the above information, but I'd like to be sure before I rely on it. :)</p>
<p>Or is alignment required by the ISA to guarantee atomicity, and I'm just looking the wrong places in Intel's reference manuals?</p> | 5,178,914 | 4 | 2 | null | 2009-09-12 14:24:08.14 UTC | 14 | 2019-11-27 07:40:09.043 UTC | 2019-11-27 07:40:09.043 UTC | null | 224,132 | null | 33,213 | null | 1 | 37 | winapi|x86|atomic|memory-alignment|interlocked | 6,417 | <p>The <a href="http://download.intel.com/design/intarch/manuals/24319101.pdf">PDF you are quoting from</a> is from 1999 and CLEARLY outdated.</p>
<p>The <a href="http://www.intel.com/products/processor/manuals/">up-to-date Intel documentation</a>, specifically <a href="http://www.intel.com/Assets/PDF/manual/253668.pdf">Volume-3A</a> tells a different story.</p>
<p>For example, on a Core-i7 processor, you STILL have to make sure your data doesn't not span over cache-lines, or else the operation is NOT guaranteed to be atomic.</p>
<p>On Volume 3A, System Programming, For x86/x64 Intel clearly states:</p>
<blockquote>
<h1>8.1.1 Guaranteed Atomic Operations</h1>
<p>The Intel486 processor (and newer processors since) guarantees that the following
basic memory operations will always be carried out atomically:</p>
<ul>
<li>Reading or writing a byte</li>
<li>Reading or writing a word aligned on a 16-bit boundary</li>
<li>Reading or writing a doubleword aligned on a 32-bit boundary</li>
</ul>
<p>The Pentium processor (and newer processors since) guarantees that the following
additional memory operations will always be carried out atomically:</p>
<ul>
<li>Reading or writing a quadword aligned on a 64-bit boundary</li>
<li>16-bit accesses to uncached memory locations that fit within a 32-bit data bus</li>
</ul>
<p>The P6 family processors (and newer processors since) guarantee that the following
additional memory operation will always be carried out atomically:</p>
<ul>
<li>Unaligned 16-, 32-, and 64-bit accesses to cached memory that fit within a cache
line</li>
</ul>
<p>Accesses to cacheable memory that are split across cache lines and page boundaries
are not guaranteed to be atomic by the Intel Core 2 Duo, Intel® Atom™, Intel Core
Duo, Pentium M, Pentium 4, Intel Xeon, P6 family, Pentium, and Intel486 processors.
The Intel Core 2 Duo, Intel Atom, Intel Core Duo, Pentium M, Pentium 4, Intel Xeon,
and P6 family processors provide bus control signals that permit external memory
subsystems to make split accesses atomic; however, nonaligned data accesses will
seriously impact the performance of the processor and should be avoided</p>
</blockquote> |
1,699,582 | JavaScript: How to select "Cancel" by default in confirm box? | <p>I am displaying a JavaScript confirm box when the user clicks on the "Delete Data" button. I am displaying it as shown in this image: </p>
<p><img src="https://i.stack.imgur.com/7KQn2.jpg" alt="alt text"></p>
<p>In the image, the "OK" button is selected by default. I want to select the "Cancel" button by default, so that if the user accidentally presses the <kbd>enter</kbd> key, the records will be safe and will not be deleted.</p>
<p>Is there any way in JavaScript to select the "Cancel" button by default?</p> | 1,699,600 | 4 | 4 | null | 2009-11-09 07:33:37.82 UTC | 6 | 2021-02-17 20:35:22.03 UTC | 2014-09-20 07:39:44.757 UTC | null | 1,402,846 | null | 45,261 | null | 1 | 37 | javascript|jquery|confirm | 35,967 | <p>If you can use jQuery plugin then here is a nice one</p>
<p><a href="http://trentrichardson.com/Impromptu/" rel="nofollow noreferrer">jQuery Impromptu</a></p>
<p>To change the default focused button:</p>
<pre><code>$.prompt('Example 4',{ buttons: { Ok: true, Cancel: false }, focus: 1 });
</code></pre> |
1,379,565 | How to fetch the first and last record of a grouped record in a MySQL query with aggregate functions? | <p>I am trying to fetch the first and the last record of a 'grouped' record.<br>
More precisely, I am doing a query like this</p>
<pre><code>SELECT MIN(low_price), MAX(high_price), open, close
FROM symbols
WHERE date BETWEEN(.. ..)
GROUP BY YEARWEEK(date)
</code></pre>
<p>but I'd like to get the first and the last record of the group. It could by done by doing tons of requests but I have a quite large table.</p>
<p>Is there a (low processing time if possible) way to do this with MySQL?</p> | 1,552,389 | 4 | 1 | null | 2009-09-04 14:20:14.54 UTC | 24 | 2019-02-07 23:35:34.86 UTC | 2016-08-09 16:22:00.943 UTC | null | 182,371 | null | 93,480 | null | 1 | 39 | mysql|aggregate-functions | 90,809 | <p>You want to use <code>GROUP_CONCAT</code> and <code>SUBSTRING_INDEX</code>:</p>
<pre><code>SUBSTRING_INDEX( GROUP_CONCAT(CAST(open AS CHAR) ORDER BY datetime), ',', 1 ) AS open
SUBSTRING_INDEX( GROUP_CONCAT(CAST(close AS CHAR) ORDER BY datetime DESC), ',', 1 ) AS close
</code></pre>
<p>This avoids expensive sub queries and I find it generally more efficient for this particular problem.</p>
<p>Check out the manual pages for both functions to understand their arguments, or visit this article which includes an example of how to do <a href="http://www.zonalivre.org/2009/10/12/simulating-firstlast-aggregate-functions-in-mysql/" rel="noreferrer">timeframe conversion in MySQL</a> for more explanations.</p> |
49,720,178 | Xcode not supported for iOS 11.3 by Xcode 9.2 needed 9.3 | <p>Apparently, with the latest IOS update, my version of Xcode could not build due to the following error.</p>
<blockquote>
<p>Could not locate device support files. This iPhone 7 Plus (Model 1661, 1784, 1785, 1786) is running iOS 11.3 (15E216), which may not be supported by this version of Xcode.</p>
</blockquote>
<p>Tried to install Xcode 9.3 via this link <a href="https://developer.apple.com/download/more/" rel="noreferrer">https://developer.apple.com/download/more/</a>. But as it turns out, my Mac OS version sees the update as an incompatible version. Running on <strong>Sierra 10.12.6</strong></p> | 49,790,425 | 8 | 6 | null | 2018-04-08 16:36:59.78 UTC | 15 | 2020-02-14 09:17:18.7 UTC | 2018-04-08 16:40:58.793 UTC | null | 4,812,515 | null | 4,812,515 | null | 1 | 48 | ios|xcode|xcode9.3 | 63,469 | <p>Another option is to download the 11.3 device support at:</p>
<p><a href="https://github.com/filsv/iPhoneOSDeviceSupport/issues/7" rel="noreferrer">iOS 11.3 (15E217)</a></p>
<p>And don't forget to remove "(15E217)" from folder name, so it became "11.3". Restart Xcode afterwards.</p>
<p><a href="https://i.stack.imgur.com/aDCUU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aDCUU.png" alt="enter image description here"></a></p>
<p><strong>Where to paste it</strong> according to comment of EdwardM</p>
<p>For those that don't know where to paste the contents of the zipped file. Find your Applications icon in the dock, right-click, "Open Applications". The folder will open in Finder. Right-click Xcode > Show Package Contents. Then go to Developer > Platforms > iPhoneOS.platform > DeviceSupport</p> |
10,491,631 | Need to select ALL columns while using COUNT/Group By | <p>Ok so I have a table in which ONE of the columns have a FEW REPEATING records.</p>
<p>My task is to select the REPEATING records with all attributes.</p>
<p>CustID FN LN DOB City State</p>
<p>the DOB has some repeating values which I need to select from the whole table and list all columns of all records that are same within the DOB field..</p>
<p>My try...</p>
<pre><code>Select DOB, COUNT(DOB) As 'SameDOB' from Table1
group by DOB
HAVING (COUNT(DOB) > 1)
</code></pre>
<p>This only returns two columns and one row 1st column is the DOB column that occurs more than once and the 2nd column gives count on how many.</p>
<p>I need to figure out a way to list all attributes not just these two...</p>
<p>Please guide me in the right direction.</p> | 10,491,917 | 4 | 2 | null | 2012-05-08 02:10:35.197 UTC | 3 | 2016-03-02 08:51:58.477 UTC | null | null | null | null | 1,373,003 | null | 1 | 8 | sql|sql-server|database|group-by | 40,430 | <p>I think a more general solution is to use windows functions:</p>
<pre><code>select *
from (select *, count(*) over (partition by dob) as NumDOB
from table
) t
where numDOB > 1
</code></pre>
<p>The reason this is more general is because it is easy to change to duplicates across two or more columns.</p> |
10,487,104 | Difference between List and Array | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7869212/primitive-array-vs-arraylist">Primitive Array vs ArrayList</a> </p>
</blockquote>
<p>What is the difference between List and Array in java? or the difference between Array and Vector!</p> | 10,487,175 | 1 | 2 | null | 2012-05-07 18:25:40.4 UTC | 12 | 2019-06-10 19:30:59.227 UTC | 2017-05-23 11:54:07.15 UTC | null | -1 | null | 1,380,430 | null | 1 | 37 | java | 95,658 | <p>In general (and in Java) an array is a data structure generally consisting of sequential memory storing a collection of objects.</p>
<p><code>List</code> is an <a href="http://en.wikipedia.org/wiki/Interface_%28Java%29" rel="noreferrer">interface</a> in Java, which means that it may have multiple implementations. One of these implementations is <code>ArrayList</code>, which is a class that implements the behavior of the <code>List</code> interface using arrays as the data structure.</p>
<p>There are a number of other classes that implement the <code>List</code> interface. One easy way to take a look at them is by viewing the Javadoc for <code>List</code>: <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html" rel="noreferrer">http://docs.oracle.com/javase/6/docs/api/java/util/List.html</a></p>
<p>On that page, you'll see "all known implementing classes," which are all of the kinds of lists in Java.</p> |
49,215,791 | VS Code C# - System.NotSupportedException: No data is available for encoding 1252 | <p>I am trying to use ExcelDataReader to read an .xls file on Ubuntu. I am using VS Code with C#. Here is the code:</p>
<pre><code>var stream = File.Open(filePath, mode: FileMode.Open, access: FileAccess.Read);
var reader = ExcelReaderFactory.CreateReader(stream);
</code></pre>
<p>I also tried this:</p>
<pre><code>var reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(stream);
</code></pre>
<p>When I run, I am getting the following exception:</p>
<blockquote>
<p>Unhandled Exception: System.NotSupportedException: No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
at System.Text.Encoding.GetEncoding(Int32 codepage)</p>
</blockquote>
<p>I already installed the <code>libmono-i18n-west4.0-cil</code> (tried also with <code>libmono-i18n4.0-all</code>) as I found out some people recommending this, but the problem persists. Also installed the package <code>System.Text.Encoding.CodePages</code> without success.</p>
<p>Can anyone help to solve this?</p> | 49,701,230 | 1 | 4 | null | 2018-03-11 01:36:25.727 UTC | 9 | 2022-05-16 06:00:44.527 UTC | null | null | null | null | 1,930,814 | null | 1 | 69 | c#|visual-studio-code|xls|exceldatareader | 37,322 | <p>I faced the same problem with .net Core application. I added the <code>System.Text.Encoding.CodePages</code> nuget package and registered the encoding provider before <code>ExcelReaderFactory.CreateReader(stream)</code> which resolved the issue.</p>
<pre><code>System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
//open file and returns as Stream
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
}
}
</code></pre> |
7,221,981 | How to allocate and deallocate heap memory for 2D array? | <p>I'm used to PHP, but I'm starting to learn C. I'm trying to create a program that reads a file line by line and stores each line to an array.</p>
<p>So far I have a program that reads the file line by line, and even prints each line as it goes, but now I just need to add each line to an array.</p>
<p>My buddy last night was telling me a bit about it. He said I'd have to use a multidimensional array in C, so basically <code>array[x][y]</code>. The <code>[y]</code> part itself is easy, because I know the maximum amount of bytes that each line will be. However, I don't know how many <em>lines</em> the file will be.</p>
<p>I figure I can make it loop through the file and just increment an integer each time and use that, but I feel that there might be a more simple way of doing it.</p>
<p>Any ideas or even a hint in the right direction? I appreciate any help.</p> | 7,222,039 | 6 | 2 | null | 2011-08-28 15:51:16.28 UTC | 4 | 2020-05-13 06:20:32.507 UTC | 2020-05-13 06:20:32.507 UTC | null | 3,396,951 | null | 266,542 | null | 1 | 15 | c|arrays|file|loops|multidimensional-array | 48,031 | <p>To dynamically allocate a 2D array:</p>
<pre><code>char **p;
int i, dim1, dim2;
/* Allocate the first dimension, which is actually a pointer to pointer to char */
p = malloc (sizeof (char *) * dim1);
/* Then allocate each of the pointers allocated in previous step arrays of pointer to chars
* within each of these arrays are chars
*/
for (i = 0; i < dim1; i++)
{
*(p + i) = malloc (sizeof (char) * dim2);
/* or p[i] = malloc (sizeof (char) * dim2); */
}
/* Do work */
/* Deallocate the allocated array. Start deallocation from the lowest level.
* that is in the reverse order of which we did the allocation
*/
for (i = 0; i < dim1; i++)
{
free (p[i]);
}
free (p);
</code></pre>
<p>Modify the above method. When you need another line to be added do <code>*(p + i) = malloc (sizeof (char) * dim2);</code> and update <code>i</code>. In this case you need to predict the max numbers of lines in the file which is indicated by the <code>dim1</code> variable, for which we allocate the <code>p</code> array first time. This will only allocate the <code>(sizeof (int *) * dim1)</code> bytes, thus much better option than <code>char p[dim1][dim2]</code> (in c99).</p>
<p>There is another way i think. Allocate arrays in blocks and chain them when there is an overflow.</p>
<pre><code>struct _lines {
char **line;
int n;
struct _lines *next;
} *file;
file = malloc (sizeof (struct _lines));
file->line = malloc (sizeof (char *) * LINE_MAX);
file->n = 0;
head = file;
</code></pre>
<p>After this the first block is ready to use. When you need to insert a line just do:</p>
<pre><code>/* get line into buffer */
file.line[n] = malloc (sizeof (char) * (strlen (buffer) + 1));
n++;
</code></pre>
<p>When <code>n</code> is <code>LINE_MAX</code> allocate another block and link it to this one.</p>
<pre><code>struct _lines *temp;
temp = malloc (sizeof (struct _lines));
temp->line = malloc (sizeof (char *) * LINE_MAX);
temp->n = 0;
file->next = temp;
file = file->next;
</code></pre>
<p>Something like this.</p>
<p>When one block's <code>n</code> becomes <code>0</code>, deallocate it, and update the current block pointer <code>file</code> to the previous one. You can either traverse from beginning single linked list and traverse from the start or use double links.</p> |
7,305,612 | junit arrays not equal test | <p>I'm trying to write a test case where my scenario is that two <strong>byte arrays</strong> should be <strong>not equal</strong>.</p>
<p>Can I do this with junit?</p>
<p>Or do I have to use something external like Hamcrest? <a href="https://stackoverflow.com/questions/1096650/why-doesnt-junit-provide-assertnotequals-methods/1464411#1464411">I couldn't change the code in this answer to do the job</a> </p>
<p>Please give a sample.</p> | 7,305,637 | 6 | 0 | null | 2011-09-05 08:34:14.497 UTC | 2 | 2022-09-23 21:15:02.82 UTC | 2018-08-17 12:27:49.957 UTC | null | 1,610,034 | null | 928,499 | null | 1 | 45 | java|arrays|junit | 40,382 | <p>I prefer doing this the Hamcrest way, which is more expressive:</p>
<pre><code>Assert.assertThat(array1, IsNot.not(IsEqual.equalTo(array2)));
</code></pre>
<p>Or the short version with static imports:</p>
<pre><code>assertThat(array1, not(equalTo(array2)));
</code></pre>
<p>(The <code>IsEqual</code> matcher is smart enough to understand arrays, fortunately.)</p>
<p>Note that a limited version of Hamcrest is part of the JUnit 4.x distribution, so you don't need to add an external library.</p> |
7,054,188 | Is it possible to negate a scope in Rails? | <p>I have the following scope for my class called <code>Collection</code>:</p>
<pre><code>scope :with_missing_coins, joins(:coins).where("coins.is_missing = ?", true)
</code></pre>
<p>I can run <code>Collection.with_missing_coins.count</code> and get a result back -- it works great!
Currently, if I want to get collections without missing coins, I add another scope:</p>
<pre><code>scope :without_missing_coins, joins(:coins).where("coins.is_missing = ?", false)
</code></pre>
<p>I find myself writing a lot of these "opposite" scopes. Is it possible to get the opposite of a scope without sacrificing readability or resorting to a lambda/method (that takes <code>true</code> or <code>false</code> as a parameter)?</p>
<p>Something like this:</p>
<pre><code>Collection.!with_missing_coins
</code></pre> | 7,054,274 | 7 | 0 | null | 2011-08-14 00:30:57.627 UTC | 4 | 2022-06-07 09:03:28.623 UTC | 2022-02-12 10:14:54.693 UTC | null | 1,511,504 | null | 118,175 | null | 1 | 44 | ruby-on-rails|ruby|named-scope | 27,554 | <p>I wouldn't use a single scope for this, but two:</p>
<pre><code>scope :with_missing_coins, joins(:coins).where("coins.is_missing = ?", true)
scope :without_missing_coins, joins(:coins).where("coins.is_missing = ?", false)
</code></pre>
<p>That way, when these scopes are used then it's explicit what's happening. With what numbers1311407 suggests, it is not immediately clear what the <code>false</code> argument to <code>with_missing_coins</code> is doing. </p>
<p>We should try to write code as clear as possible and if that means being less of a zealot about DRY once in while then so be it.</p> |
7,271,082 | How to reload a module's function in Python? | <p>Following up on <a href="https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">this question regarding reloading a module</a>, how do I reload a specific function from a changed module?</p>
<p>pseudo-code:</p>
<pre><code>from foo import bar
if foo.py has changed:
reload bar
</code></pre> | 7,274,356 | 8 | 0 | null | 2011-09-01 13:34:03.777 UTC | 12 | 2020-10-18 23:36:03.727 UTC | 2017-05-23 10:30:49.48 UTC | null | -1 | null | 348,545 | null | 1 | 60 | python|methods|import|reload | 61,615 | <p>What you want is possible, but requires reloading two things... first <code>reload(foo)</code>, but then you also have to <code>reload(baz)</code> (assuming <code>baz</code> is the name of the module containing the <code>from foo import bar</code> statement).</p>
<p>As to why... When <code>foo</code> is first loaded, a <code>foo</code> object is created, containing a <code>bar</code> object. When you import <code>bar</code> into the <code>baz</code> module, it stores a reference to <code>bar</code>. When <code>reload(foo)</code> is called, the <code>foo</code> object is blanked, and the module re-executed. This means all <code>foo</code> references are still valid, but a new <code>bar</code> object has been created... so all references that have been imported somewhere are still references to the <em>old</em> <code>bar</code> object. By reloading <code>baz</code>, you cause it to reimport the new <code>bar</code>.</p>
<hr>
<p>Alternately, you can just do <code>import foo</code> in your module, and always call <code>foo.bar()</code>. That way whenever you <code>reload(foo)</code>, you'll get the newest <code>bar</code> reference.</p>
<p>NOTE: As of Python 3, the reload function needs to be imported first, via <code>from importlib import reload</code></p> |
7,334,035 | get ec2 pricing programmatically? | <p>Is there a way to get AWS pricing programmatically (cost per hour of each instance type, cost per GB/month of storage on S3, and etc)?</p>
<p>Also, are there cost monitoring tools? For example, is there a tool that can report your EC2 instance usage on an hourly basis (versus a monthly basis, which is what Amazon does)?</p>
<p>Thanks in advance.</p> | 7,334,197 | 12 | 0 | null | 2011-09-07 12:40:43.147 UTC | 33 | 2022-07-13 13:43:57.33 UTC | null | null | null | null | 891,441 | null | 1 | 50 | amazon-ec2|amazon-web-services | 32,930 | <p><strong>UPDATE:</strong></p>
<p>There is now AWS pricing API:
<a href="https://aws.amazon.com/blogs/aws/new-aws-price-list-api/" rel="noreferrer">https://aws.amazon.com/blogs/aws/new-aws-price-list-api/</a></p>
<p><strong>Orginal answer:</strong></p>
<p>The price lists are available in form of JSONP files (you need to strip off function call) which are used by the AWS pricing pages. Each table (and each tab for table) has separate JSON file. It is not an API maybe, but definitely computer digestible. Here is a list that supports EC2 pricing page (as of 17 December 2014):</p>
<ul>
<li>On-demand Linux: <a href="http://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js</a></li>
<li>On-demand RedHat: <a href="http://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js</a></li>
<li>On-demand SUSE: <a href="http://a0.awsstatic.com/pricing/1/ec2/sles-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/sles-od.min.js</a></li>
<li>On-demand Windows: <a href="http://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js</a></li>
<li>On-demand SQL Standard: <a href="http://a0.awsstatic.com/pricing/1/ec2/mswinSQL-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/mswinSQL-od.min.js</a></li>
<li>On-demand SQL Web: <a href="http://a0.awsstatic.com/pricing/1/ec2/mswinSQLWeb-od.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/mswinSQLWeb-od.min.js</a></li>
<li>Reserved Linux: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/linux-unix-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/linux-unix-shared.min.js</a></li>
<li>Reserved RedHat: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/red-hat-enterprise-linux-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/red-hat-enterprise-linux-shared.min.js</a></li>
<li>Reserved SUSE: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/suse-linux-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/suse-linux-shared.min.js</a></li>
<li>Reserved Windows: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-shared.min.js</a></li>
<li>Reserved SQL Standard: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-with-sql-server-standard-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-with-sql-server-standard-shared.min.js</a></li>
<li>Reserved SQL Web: <a href="http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-with-sql-server-web-shared.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/ri-v2/windows-with-sql-server-web-shared.min.js</a></li>
<li>Reserved Spot instances: <a href="http://spot-price.s3.amazonaws.com/spot.js" rel="noreferrer">http://spot-price.s3.amazonaws.com/spot.js</a></li>
<li>Data transfer: <a href="http://a0.awsstatic.com/pricing/1/ec2/pricing-data-transfer-with-regions.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/pricing-data-transfer-with-regions.min.js</a></li>
<li>EBS optimized: <a href="http://a0.awsstatic.com/pricing/1/ec2/pricing-ebs-optimized-instances.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/pricing-ebs-optimized-instances.min.js</a></li>
<li>EBS: <a href="http://a0.awsstatic.com/pricing/1/ebs/pricing-ebs.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ebs/pricing-ebs.min.js</a></li>
<li>Elastic IP: <a href="http://a0.awsstatic.com/pricing/1/ec2/pricing-elastic-ips.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/pricing-elastic-ips.min.js</a></li>
<li>CloudWatch: <a href="http://a0.awsstatic.com/pricing/1/cloudwatch/pricing-cloudwatch.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/cloudwatch/pricing-cloudwatch.min.js</a></li>
<li>ELB: <a href="http://a0.awsstatic.com/pricing/1/ec2/pricing-elb.min.js" rel="noreferrer">http://a0.awsstatic.com/pricing/1/ec2/pricing-elb.min.js</a></li>
<li>EMR: <a href="https://a0.awsstatic.com/pricing/1/emr/pricing-emr.min.js" rel="noreferrer">https://a0.awsstatic.com/pricing/1/emr/pricing-emr.min.js</a></li>
</ul>
<p><strong>WARNING:</strong> The endpoints change from time to time and often old URL is still there with old values. It is best to check what is the current status rather than relying on links provided in this thread. </p>
<p>So, here is a short command to get current set or URLs from any AWS pricing page. Example based on EC2. Run it on Linux or Cygwin. Actually this command was used to create the list above.</p>
<pre><code>curl http://aws.amazon.com/ec2/pricing/ 2>/dev/null | grep 'model:' | sed -e "s/.*'\(.*\)'.*/http:\\1/"
</code></pre>
<p>For those who don't like command line, you can also check in a web browser network console (you get there with F12), filter with JS objects:</p>
<p><img src="https://i.stack.imgur.com/Ns6aq.png" alt="enter image description here"> </p> |
7,376,966 | Heroku problem : The page you were looking for doesn't exist | <p>I have followed book until chapter 5 finished and it's working OK in my linux workstation
when I push to Heroku, all data pushed correctly but when I try to open Heroku (http://vivid-sky-685.heroku.com)</p>
<p>I get a 404 message.</p>
<blockquote>
<p>The page you were looking for doesn't exist.
You may have mistyped the address or the page may have moved.</p>
</blockquote>
<p>Below is my <code>Gemfile</code> for application</p>
<pre><code>source 'http://rubygems.org'
gem 'rails', '3.0.5'
gem 'sqlite3'
group :development do
gem 'rspec-rails', '2.5.0'
end
group :test do
gem 'rspec', '2.5.0'
gem 'webrat', '0.7.1'
gem 'spork', '0.9.0.rc4'
end
gem 'rake','~> 0.8.7'
</code></pre>
<p>Any ideas what could be going wrong?</p>
<p>@odin here is my heroku logs , thanks </p>
<pre><code>2011-09-11T10:41:57+00:00 heroku[router]: GET vivid-sky-685.heroku.com/y dyno=web.1 queue=0 wait=0ms service=5ms status=404 bytes=728
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 app[web.1]: Started GET "/y" for 93.186.31.80 at 2011-09-11 03:41:57 -0700
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 app[web.1]: ActionController::RoutingError (No route matches "/y"):
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 app[web.1]:
2011-09-11T10:41:57+00:00 heroku[nginx]: 93.186.31.80 - - [11/Sep/2011:03:41:57 -0700] "GET /y HTTP/1.1" 404 728 "-" "Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en) AppleWebKit/534.8+ (KHTML, like Gecko) Version/6.0.0.546 Mobile Safari/534.8+" vivid-sky-685.heroku.com
2011-09-11T11:45:28+00:00 heroku[web.1]: Idl
2011-09-11T11:45:29+00:00 heroku[web.1]: State changed from up to down
2011-09-11T11:45:29+00:00 heroku[web.1]: State changed from down to created
2011-09-11T11:45:29+00:00 heroku[web.1]: State changed from created to starting
2011-09-11T11:45:30+00:00 heroku[web.1]: Stopping process with SIGTERM
2011-09-11T11:45:30+00:00 app[web.1]: >> Stopping ...
2011-09-11T11:45:30+00:00 heroku[web.1]: Process exited
2011-09-11T11:45:30+00:00 heroku[web.1]: Starting process with command `thin -p 16738 -e production -R /home/heroku_rack/heroku.ru start`
2011-09-11T11:45:33+00:00 app[web.1]: >> Thin web server (v1.2.6 codename Crazy Delicious)
2011-09-11T11:45:33+00:00 app[web.1]: >> Maximum connections set to 1024
2011-09-11T11:45:33+00:00 app[web.1]: >> Listening on 0.0.0.0:16738, CTRL+C to stop
2011-09-11T11:45:33+00:00 heroku[web.1]: State changed from starting to up
2011-09-11T12:53:00+00:00 heroku[web.1]: Idling
2011-09-11T12:53:01+00:00 heroku[web.1]: State changed from up to down
2011-09-11T12:53:02+00:00 heroku[web.1]: Stopping process with SIGTERM
2011-09-11T12:53:02+00:00 app[web.1]: >> Stopping ...
2011-09-11T12:53:02+00:00 heroku[web.1]: Process exited
2011-09-11T13:18:21+00:00 heroku[rake.1]: State changed from created to starting
2011-09-11T13:18:23+00:00 app[rake.1]: Awaiting client
2011-09-11T13:18:23+00:00 app[rake.1]: Starting process with command `bundle exec rake db:migrate`
2011-09-11T13:18:26+00:00 heroku[rake.1]: Process exited
2011-09-11T13:18:26+00:00 heroku[rake.1]: State changed from up to complete
2011-09-11T13:20:02+00:00 heroku[web.1]: Unidling
2011-09-11T13:20:02+00:00 heroku[web.1]: State changed from down to created
2011-09-11T13:20:02+00:00 heroku[web.1]: State changed from created to starting
2011-09-11T13:20:04+00:00 heroku[web.1]: Starting process with command `thin -p 48393 -e production -R /home/heroku_rack/heroku.ru start`
2011-09-11T13:20:06+00:00 app[web.1]: >> Thin web server (v1.2.6 codename Crazy Delicious)
2011-09-11T13:20:06+00:00 app[web.1]: >> Maximum connections set to 1024
2011-09-11T13:20:06+00:00 app[web.1]: >> Listening on 0.0.0.0:48393, CTRL+C to stop
2011-09-11T13:20:07+00:00 heroku[web.1]: State changed from starting to up
2011-09-11T13:20:07+00:00 app[web.1]:
2011-09-11T13:20:07+00:00 app[web.1]:
2011-09-11T13:20:07+00:00 app[web.1]: Started GET "/" for 118.137.144.220 at 2011-09-11 06:20:07 -0700
2011-09-11T13:20:08+00:00 app[web.1]:
2011-09-11T13:20:08+00:00 app[web.1]: ActionController::RoutingError (uninitialized constant PagesController):
2011-09-11T13:20:08+00:00 app[web.1]:
2011-09-11T13:20:08+00:00 app[web.1]:
2011-09-11T13:20:08+00:00 app[web.1]:
2011-09-11T13:20:08+00:00 heroku[router]: GET vivid-sky-685.heroku.com/ dyno=web.1 queue=0 wait=0ms service=403ms status=404 bytes=728
2011-09-11T13:20:08+00:00 heroku[nginx]: 118.137.144.220 - - [11/Sep/2011:06:20:08 -0700] "GET / HTTP/1.1" 404 728 "-" "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0" vivid-sky-685.heroku.com
</code></pre> | 7,546,073 | 13 | 3 | null | 2011-09-11 07:46:18.58 UTC | 10 | 2019-12-02 17:22:32.693 UTC | 2013-06-06 13:49:30.49 UTC | user1228 | null | null | 938,947 | null | 1 | 29 | ruby-on-rails | 57,869 | <p>I got the same problem; however, after changing 1 line code of production.rb located in <code>config/environments/production.rb</code> from</p>
<pre><code>config.assets.compile = false
</code></pre>
<p>to</p>
<pre><code>config.assets.compile = true
</code></pre>
<p>commit the new change. Then my sample app works fine on heroku</p> |
14,338,156 | Formatting Excel cells (currency) | <p>I developed an Add-In for Excel so you can insert some numbers from a MySQL database into specific cells. Now I tried to format these cells to currency and I have two problems with that.
1. When using a formula on formatted cells, the sum for example is displayed like that:
"353,2574€". What do I have to do to display it in an appropriate way?
2. Some cells are empty but have to be formatted in currency as well. When using the same format I used for the sum formula and type something in, there's only the number displayed. No "€", nothing. What is that?
I specified a Excel.Range and used this to format the range</p>
<pre><code>sum.NumberFormat = "#.## €";
</code></pre>
<p>But I also tried</p>
<pre><code>sum.NumberFormat = "0,00 €";
sum.NumberFormat = "#.##0,00 €";
</code></pre>
<p>Any idea someone?</p> | 14,338,842 | 1 | 0 | null | 2013-01-15 12:51:06.823 UTC | 2 | 2017-02-22 02:39:55.837 UTC | 2013-01-15 13:23:03.797 UTC | null | 238,902 | null | 1,980,278 | null | 1 | 19 | c#|excel|format|currency | 60,174 | <p>This one works for me. I have excel test app that formats the currency into 2 decimal places with comma as thousand separator. Below is the Console Application that writes data on Excel File.</p>
<p>Make sure you have referenced Microsoft.Office.Interop.Excel dll</p>
<pre><code>using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var bankAccounts = new List<Account> {
new Account { ID = 345678, Balance = 541.27},
new Account {ID = 1230221,Balance = -1237.44},
new Account {ID = 346777,Balance = 3532574},
new Account {ID = 235788,Balance = 1500.033333}
};
DisplayInExcel(bankAccounts);
}
static void DisplayInExcel(IEnumerable<Account> accounts)
{
var excelApp = new Excel.Application { Visible = true };
excelApp.Workbooks.Add();
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
workSheet.Cells[1, "A"] = "ID Number";
workSheet.Cells[1, "B"] = "Current Balance";
var row = 1;
foreach (var acct in accounts)
{
row++;
workSheet.Cells[row, "A"] = acct.ID;
workSheet.Cells[row, "B"] = acct.Balance;
}
workSheet.Range["B2", "B" + row].NumberFormat = "#,###.00 €";
workSheet.Columns[1].AutoFit();
workSheet.Columns[2].AutoFit();
}
}
public class Account
{
public int ID { get; set; }
public double Balance { get; set; }
}
}
</code></pre>
<p>The Output </p>
<p><img src="https://i.stack.imgur.com/XNk9v.png" alt="enter image description here"></p> |
14,097,388 | Can an algorithm detect sarcasm | <p>I was asked to write an algorithm to detect sarcasm but I came across a flaw (or what seems like one) in the logic.</p>
<p>For example if a person says</p>
<blockquote>
<p>A: I love Justin Beiber. Do you like him to?</p>
<p>B: Yeah. Sure. <i>I absolutely love him.</i></p>
</blockquote>
<p>Now this may be considered sarcasm or not and the only way to know seems to be to know if B is serious or not.</p>
<p>(I wasn't supposed to be in depth. We were given a bunch of phrases and just were told that if these were in the sentence then it was sarcastic but I got interested?)</p>
<p>Is there any way to work around this? Or are computers absolutely stuck when it comes to sarcasm?</p>
<p>(I suppose it depends on the tone of the speaker but my input is text)</p> | 14,099,786 | 4 | 18 | null | 2012-12-31 04:21:12.483 UTC | 19 | 2012-12-31 09:37:35.437 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,059,273 | null | 1 | 37 | algorithm|nlp | 10,054 | <p>Looks like there are studies that attempted just that, but they have yet to come up with a well working algorithm.</p>
<p>From <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.207.5253&rep=rep1&type=pdf" rel="noreferrer">González-Ibáñez, R. et al. "Identifying sarcasm in Twitter: a closer look"</a> </p>
<blockquote>
<p>Sarcasm and irony are well-studied phenomena in linguistics,
psychology and cognitive science[...]. But in the text mining
literature, automatic detection of sarcasm is considered a difficult
problem [...] and
has been addressed in only a few studies. [...] The work most closely related to ours is that of Davidov et al.
(2010), whose objective was to identify sarcastic and non-sarcastic
utterances in Twitter and in Amazon product reviews. In this paper, we
consider the somewhat harder problem of distinguishing sarcastic tweets from non- sarcastic tweets</p>
</blockquote>
<p>They conclude:</p>
<blockquote>
<p>Perhaps unsurprisingly, neither the human judges nor the machine
learning techniques perform very well. [...] Our results suggest that lexical features alone are not sufficient for identifying sarcasm and that pragmatic and contextual features merit further study</p>
</blockquote>
<p>Here is another recent, relevant paper:<br>
<a href="http://dblab.mgt.ncu.edu.tw/%E6%95%99%E6%9D%90/2012_SNM/90.pdf" rel="noreferrer">Reyes, A. "From humor recognition to irony detection: The figurative language of social media"</a> </p> |
13,900,515 | How can I access a classmethod from inside a class in Python | <p>I would like to create a class in Python that manages above all static members. These members should be initiliazed during definition of the class already. Due to the fact that there will be the requirement to reinitialize the static members later on I would put this code into a classmethod.</p>
<p>My question: How can I call this classmethod from inside the class?</p>
<pre><code>class Test():
# static member
x = None
# HERE I WOULD LOVE TO CALL SOMEHOW static_init!
# initialize static member in classmethod, so that it can be
#reinitialized later on again
@classmethod
def static_init(cls):
cls.x = 10
</code></pre>
<p>Any help is appreciated!</p>
<p>Thanks in advance,
Volker</p> | 13,900,861 | 7 | 2 | null | 2012-12-16 10:47:01.777 UTC | 6 | 2021-11-14 18:28:22.23 UTC | null | null | null | null | 1,907,681 | null | 1 | 41 | python|class-members | 43,500 | <p>At the time that <code>x=10</code> is executed in your example, not only does the class not exist, but the classmethod doesn't exist either.</p>
<p>Execution in Python goes top to bottom. If <code>x=10</code> is above the classmethod, there is no way you can access the classmethod at that point, because it hasn't been defined yet.</p>
<p>Even if you could run the classmethod, it wouldn't matter, because the class doesn't exist yet, so the classmethod couldn't refer to it. The class is not created until after the entire class block runs, so while you're inside the class block, there's no class.</p>
<p>If you want to factor out some class initialization so you can re-run it later in the way you describe, use a class decorator. The class decorator runs after the class is created, so it can call the classmethod just fine.</p>
<pre><code>>>> def deco(cls):
... cls.initStuff()
... return cls
>>> @deco
... class Foo(object):
... x = 10
...
... @classmethod
... def initStuff(cls):
... cls.x = 88
>>> Foo.x
88
>>> Foo.x = 10
>>> Foo.x
10
>>> Foo.initStuff() # reinitialize
>>> Foo.x
88
</code></pre> |
14,119,277 | Subtract two dates in SQL and get days of the result | <pre><code>Select I.Fee
From Item I
WHERE GETDATE() - I.DateCreated < 365 days
</code></pre>
<p>How can I subtract two days? Result should be days. Ex: 365 days. 500 days.. etc...</p> | 14,119,294 | 7 | 0 | null | 2013-01-02 09:03:11.85 UTC | 4 | 2021-02-01 05:39:41.777 UTC | 2013-01-02 09:19:27.833 UTC | null | 13,302 | null | 1,218,067 | null | 1 | 44 | sql|sql-server|tsql | 189,188 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/ms189794.aspx">DATEDIFF</a></p>
<pre><code>Select I.Fee
From Item I
WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365
</code></pre> |
14,007,545 | Python Regex instantly replace groups | <p>Is there any way to directly replace all groups using regex syntax?</p>
<p>The normal way:</p>
<pre><code>re.match(r"(?:aaa)(_bbb)", string1).group(1)
</code></pre>
<p>But I want to achieve something like this:</p>
<pre><code>re.match(r"(\d.*?)\s(\d.*?)", "(CALL_GROUP_1) (CALL_GROUP_2)")
</code></pre>
<p>I want to build the new string instantaneously from the groups the Regex just captured.</p> | 14,007,559 | 2 | 0 | null | 2012-12-22 23:45:57.31 UTC | 17 | 2019-09-11 08:51:47.837 UTC | 2018-05-04 01:16:10.173 UTC | null | 3,071,419 | user1467267 | null | null | 1 | 157 | python|regex|regex-group | 119,944 | <p>Have a look at <a href="http://docs.python.org/2/library/re.html#re.sub" rel="noreferrer"><code>re.sub</code></a>:</p>
<pre><code>result = re.sub(r"(\d.*?)\s(\d.*?)", r"\1 \2", string1)
</code></pre>
<p>This is Python's regex substitution (replace) function. The replacement string can be filled with so-called backreferences (backslash, group number) which are replaced with what was matched by the groups. Groups are counted the same as by the <code>group(...)</code> function, i.e. starting from <code>1</code>, from left to right, by opening parentheses. </p> |
30,045,417 | Android Gradle Could not reserve enough space for object heap | <p>I've installed Android Studio 1.1.0. I haven't done anything yet like start new Android application or import anything. Somehow it is trying to build something and it throws sync error.</p>
<blockquote>
<p>Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at <a href="http://gradle.org/docs/2.2.1/userguide/gradle_daemon.html" rel="noreferrer">http://gradle.org/docs/2.2.1/userguide/gradle_daemon.html</a></p>
<p>Please read the following process output to find out more:</p>
<hr>
<p>Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.</p>
</blockquote>
<p>I've already checked at <code>gradle.org/.../gradle_daemon.html</code> but couldn't find anything that helps me to solve the problem.</p>
<p>It isn't a memory problem because I've 8GB of physical memory and no other program running. </p> | 31,760,855 | 8 | 7 | null | 2015-05-05 06:10:25.033 UTC | 28 | 2021-10-08 22:10:01.74 UTC | 2021-10-08 22:10:01.74 UTC | null | 5,459,839 | null | 1,031,959 | null | 1 | 101 | android|gradle|jvm|heap-memory | 145,422 | <p>For Android Studio 1.3 : (Method 1)</p>
<p>Step 1 : Open <strong>gradle.properties</strong> file in your Android Studio project.</p>
<p>Step 2 : Add this line at the end of the file</p>
<pre><code>org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m
</code></pre>
<p>Above methods seems to work but if in case it won't then do this (Method 2)</p>
<p>Step 1 : Start Android studio and close any open project (<strong>File > Close Project</strong>).</p>
<p>Step 2 : On Welcome window, Go to <strong>Configure > Settings</strong>.</p>
<p>Step 3 : Go to <strong>Build, Execution, Deployment > Compiler</strong></p>
<p>Step 4 : <strong>Change Build process heap size (Mbytes) to 1024</strong> and <strong>Additional build process to VM Options to -Xmx512m</strong>.</p>
<p>Step 5 : Close or <strong>Restart Android Studio</strong>.</p>
<p><a href="https://i.stack.imgur.com/tO1OH.png"><img src="https://i.stack.imgur.com/tO1OH.png" alt="SOLVED - Andriod Studio 1.3 Gradle Could not reserve enough space for object heap Issue"></a></p> |
30,211,605 | Javascript HTML collection showing as 0 length | <pre><code> var eval_table = document.getElementsByClassName("evaluation_table");
console.log(eval_table);
</code></pre>
<p>This displays as:</p>
<pre><code>[item: function, namedItem: function]0:
table.widefat.fixed.evaluation_table
length: 1
__proto__: HTMLCollection
</code></pre>
<p>However, when I try to get a length of <code>eval_table</code>, <code>eval_table.length</code>, it returns a value of <code>0</code>. I've used this approach before, had no issues with this approach before. Is there anything wrong with what I'm trying to achieve above? </p> | 30,212,541 | 3 | 7 | null | 2015-05-13 10:04:41.58 UTC | 8 | 2019-06-09 03:31:49.683 UTC | 2015-05-13 10:16:13.083 UTC | null | 4,141,176 | null | 4,141,176 | null | 1 | 31 | javascript | 42,956 | <p>This is because your JS is running before the elements are rendered to the DOM. I bet the script you have running is loaded before the <code><body></code> of your html. You have two options:</p>
<ol>
<li>Add the self-executing <code><script></code> as the last thing in your <code><body></code> tag or; </li>
<li>Wrap your function so that it waits for the DOM to be loaded before executing. You can do this with either:
<ul>
<li>jQuery's <code>$(document).ready</code> or </li>
<li>if you're not running jQuery: <code>document.addEventListener("DOMContentLoaded", function(e) {// do stuff })</code> </li>
</ul></li>
</ol>
<p>Code sample below:</p>
<pre><code><html>
<head></head>
<script>
document.addEventListener("DOMContentLoaded", function(e) {
var eval_table = document.getElementsByClassName('evaluation_table');
console.log(eval_table, eval_table.length);
});
</script>
<body>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
</body>
</html>
</code></pre> |
44,956,653 | Selecting block of code in Visual Studio Code | <p>Is there a keyboard shortcut or an extension that would allow me to select a block of code?</p>
<p>I'd like to select everything between curly braces, between HTML tags, etc.</p> | 64,222,679 | 8 | 2 | null | 2017-07-06 18:42:46.763 UTC | 5 | 2022-07-01 12:03:33.823 UTC | 2020-12-30 05:35:39.353 UTC | null | 63,550 | null | 336,431 | null | 1 | 46 | visual-studio-code | 36,878 | <p>On Mac <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>→</kbd> to expand the selection. Press multiple times to expand to the block.</p> |
1,176,427 | Shared libraries and .h files | <p>I have some doubt about how do programs use shared library.</p>
<p>When I build a shared library ( with -shared -fPIC switches) I make some functions available from an external program.
Usually I do a dlopen() to load the library and then dlsym() to link the said functions to some function pointers.
This approach does not involve including any .h file.
Is there a way to avoid doing dlopen() & dlsym() and just including the .h of the shared library?</p>
<p>I <em>guess</em> this may be how c++ programs uses code stored in system shared library. ie just including stdlib.h etc.</p> | 1,186,836 | 5 | 0 | null | 2009-07-24 08:36:51.397 UTC | 21 | 2021-12-30 01:53:08.633 UTC | null | null | null | null | 144,333 | null | 1 | 14 | c++|c|shared-libraries|fpic | 24,799 | <p>Nick, I think all the other answers are actually answering your question, which is how you link libraries, but the way you phrase your question suggests you have a misunderstanding of the difference between headers files and libraries. They are not the same. You need <em>both</em>, and they are not doing the same thing.</p>
<p>Building an executable has two main phases, compilation (which turns your source into an intermediate form, containing executable binary instructions, but is not a runnable program), and linking (which combines these intermediate files into a single running executable or library).</p>
<p>When you do <code>gcc -c program.c</code>, you are compiling, and you generate <code>program.o</code>. This step is where <em>headers</em> matter. You need to <code>#include <stdlib.h></code> in <code>program.c</code> to (for example) use <code>malloc</code> and <code>free</code>. (Similarly you need <code>#include <dlfcn.h></code> for <code>dlopen</code> and <code>dlsym</code>.) If you don't do that the compiler will complain that it doesn't know what those names are, and halt with an error. But if you do <code>#include</code> the header the compiler does <em>not</em> insert the code for the function you call into <code>program.o</code>. It merely inserts a <em>reference</em> to them. The reason is to avoid duplication of code: The code is only going to need to be accessed once by every part of your program, so if you needed further files (<code>module1.c</code>, <code>module2.c</code> and so on), even if they <em>all</em> used <code>malloc</code> you would merely end up with many references to a single copy of <code>malloc</code>. That single copy is present in the standard <em>library</em> in either it's shared or static form (<code>libc.so</code> or <code>libc.a</code>) but these are not referenced in your source, and the compiler is not aware of them.</p>
<p>The linker <em>is</em>. In the linking phase you do <code>gcc -o program program.o</code>. The linker will then search all libraries you pass it on the command line and find the <em>single</em> definition of all functions you've called which are not defined in your own code. That is what the <code>-l</code> does (as the others have explained): tell the linker the list of libraries you need to use. Their names often have little to do with the headers you used in the previous step. For example to get use of <code>dlsym</code> you need <code>libdl.so</code> or <code>libdl.a</code>, so your command-line would be <code>gcc -o program program.o -ldl</code>. To use <code>malloc</code> or most of the functions in the <code>std*.h</code> headers you need <code>libc</code>, but because that library is used by <em>every</em> C program it is <em>automatically</em> linked (as if you had done <code>-lc</code>).</p>
<p>Sorry if I'm going into a lot of detail but if you don't know the difference you will want to. It's very hard to make sense of how C compilation works if you don't.</p>
<p>One last thing: <code>dlopen</code> and <code>dlsym</code> are not the normal method of linking. They are used for special cases where you want to dynamically determine what behavior you want based on information that is, for whatever reason, only available at runtime. If you know what functions you want to call at compile time (true in 99% of the cases) you do not need to use the <code>dl*</code> functions.</p> |
1,096,591 | How to hide cmd window while running a batch file? | <p>How to hide cmd window while running a batch file?</p>
<p>I use the following code to run batch file</p>
<pre><code>process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
</code></pre> | 1,096,626 | 5 | 0 | null | 2009-07-08 07:22:28.933 UTC | 7 | 2020-11-08 22:00:49.407 UTC | 2010-03-08 02:28:16.277 UTC | null | 164,901 | null | 14,118 | null | 1 | 22 | c#|process|batch-file | 45,742 | <p>If proc.StartInfo.UseShellExecute is <strong>false</strong>, then you are launching the process and can use:</p>
<pre><code>proc.StartInfo.CreateNoWindow = true;
</code></pre>
<p>If proc.StartInfo.UseShellExecute is <strong>true</strong>, then the OS is launching the process and you have to provide a "hint" to the process via:</p>
<pre><code>proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
</code></pre>
<p>However the called application may ignore this latter request.</p>
<p>If using UseShellExecute = <strong>false</strong>, you might want to consider redirecting standard output/error, to capture any logging produced:</p>
<pre><code>proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
</code></pre>
<p>And have a function like</p>
<pre><code>private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
</code></pre>
<p>There's a good page covering <code>CreateNoWindow</code> this on <a href="http://blogs.msdn.com/jmstall/archive/2006/09/28/CreateNoWindow.aspx" rel="noreferrer">an MSDN blog</a>.</p>
<p>There is also a bug in Windows which may throw a dialog and defeat <code>CreateNoWindow</code> if you are passing a username/password. For details</p>
<p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476</a>
<a href="http://support.microsoft.com/?kbid=818858" rel="noreferrer">http://support.microsoft.com/?kbid=818858</a></p> |
257,433 | PostgreSQL UNIX domain sockets vs TCP sockets | <p>I wonder if the UNIX domain socket connections with postgresql are faster then tcp connections from localhost in high concurrency rate and if it does, by how much?</p> | 257,479 | 5 | 1 | null | 2008-11-02 21:50:29.797 UTC | 27 | 2012-08-24 09:13:14.447 UTC | 2008-11-02 22:16:08.92 UTC | null | 20,955 | null | 20,955 | null | 1 | 53 | performance|postgresql|tcp|sockets | 23,744 | <p>UNIX domain sockets should offer better performance than TCP sockets over loopback interface (less copying of data, fewer context switches), but I don't know whether the performance increase can be demonstrated with PostgreSQL.</p>
<p>I found a small comparison on the FreeBSD mailinglist: <a href="http://lists.freebsd.org/pipermail/freebsd-performance/2005-February/001143.html" rel="noreferrer">http://lists.freebsd.org/pipermail/freebsd-performance/2005-February/001143.html</a>.</p> |
1,107,437 | Learn Joomla in a Weekend | <p>Long story short, I need to get up to speed with Joomla <em>fast</em>. I only have this weekend to do that which translates to about 12 hours of time. Right now I only know that Joomla is an open source CMS written in PHP. What would be the best way to familiarize myself with Joomla in this short amount of time? Official documentation? Videos? Books?</p>
<p>My background: I think I have a fairly decent knowledge of PHP and I'm currently learning CodeIgniter while building a simple webapp with it.</p> | 1,131,288 | 6 | 3 | null | 2009-07-10 02:45:43.18 UTC | 12 | 2011-12-27 19:29:40.203 UTC | null | null | null | null | 66,449 | null | 1 | 15 | joomla | 4,786 | <p>I was in a similar situation. I purchased "Joomla! A User's Guide: Building a Successful Joomla! Powered Website" by Barrie M. North. This was big help.</p>
<p>Next, I'd start out with some really good Joomla templates that were created by others. I like to learn from example, so here are the good examples I'd recommend.</p>
<ol>
<li><p>Beez: is a free XHTML/CSS template that comes with Joomla. By default, Joomla uses TABLES for many of its modules and components. Thankfully, <a href="http://docs.joomla.org/How_to_override_the_output_from_the_Joomla!_core" rel="noreferrer">Joomla Overrides</a> let you, well, override those ugly outputs with cleaner markup. Beez will show you how to do that and is even good enough to serve as your base.</p></li>
<li><p>Compass Designs: is the home of Barrie North, the book I recommended. He has several free templates and tutorials.</p></li>
<li><p>YOOtheme: Will cost you something, but you will get both good example templates and some handy AJAX tools to use as Joomla Extensions.</p></li>
</ol> |
313,839 | What is the best way to write event log entries? | <p>I recently had a problem during the deployment of a windows service. Four computers did not cause any problems, but on the fifth any attempt to start the service failed due to an exception. The exception stack trace is written to the event log, so I though it should be easy to identify the cause:</p>
<pre><code>protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Starting service", EventLogEntryType.Information);
try
{
//...
base.OnStart(args);
}
catch (Exception ex)
{
EventLog.WriteEntry("Service can not start. Stack trace:" + ex.StackTrace, EventLogEntryType.Error);
Stop();
return;
}
EventLog.WriteEntry("Service started", EventLogEntryType.Information);
}
</code></pre>
<p>But alas, no information was ever written to the log. I finally traced it to the first log entry being written. It threw an exception because the application event log was full with recent entries, and configured to only overwrite entries older than 7 days.</p>
<p>What are the best practices on writing to the event log, considering that I can not change the configuration of the application event log? </p>
<p>Should I always put <code>EventLog.WriteEntry</code> in a try block, if yes, how should I handle the exception (writing it to the event log is probably a bad idea), should I check on the event log status in my <code>OnStart</code> method, or do you have any better suggestion?</p> | 313,865 | 6 | 0 | null | 2008-11-24 10:33:23.27 UTC | 10 | 2009-06-04 12:17:09.173 UTC | 2009-03-11 15:34:46.047 UTC | Treb | 22,114 | Treb | 22,114 | null | 1 | 16 | .net|event-log | 19,893 | <p>I think logging exceptions is one of the rare cases where you are better off swallowing the exception. In most cases you don't want your app to fail on this.</p>
<p>But why are you writing your logging code yourself anyway? Use a framework like NLog or Log4Net! These also swallow exceptions like I just said but you can redirect the logging output to a different location (file, messagebox etc.) with just a configuration change. This makes solving problems like this much easier.</p> |
1,273,687 | Why or why not should I use 'UL' to specify unsigned long? | <pre><code>ulong foo = 0;
ulong bar = 0UL;//this seems redundant and unnecessary. but I see it a lot.
</code></pre>
<p>I also see this in referencing the first element of arrays a good amount</p>
<pre><code>blah = arr[0UL];//this seems silly since I don't expect the compiler to magically
//turn '0' into a signed value
</code></pre>
<p>Can someone provide some insight to why I need 'UL' throughout to specify specifically that this is an unsigned long?</p> | 1,273,749 | 6 | 0 | null | 2009-08-13 18:15:38.823 UTC | 4 | 2015-06-08 15:11:42.5 UTC | null | null | null | null | 136,396 | null | 1 | 16 | c++ | 42,903 | <pre><code>void f(unsigned int x)
{
//
}
void f(int x)
{
//
}
...
f(3); // f(int x)
f(3u); // f(unsigned int x)
</code></pre>
<p>It is just another tool in C++; if you don't need it don't use it!</p> |
44,034 | How can I get the definition (body) of a trigger in SQL Server? | <p>Unable to find a SQL diff tool that meets my needs, I am writing my own. Between the INFORMATION_SCHEMA and sys tables, I have a mostly-complete working version. But one thing I can't find in the metadata is the <em>definition</em> of a trigger, you know, the actual SQL code. Am I overlooking something?</p>
<p>Thanks.</p>
<hr>
<p>Thanks, Pete, I didn't know about that!</p>
<p>Scott, I'm working with very basic hosting packages that don't allow remote connections to the DB. I don't know from the specs on RedGate (which I can't afford anyway) whether they provide a workaround for that, and although there are also API's out there (such as the one from Apex), I didn't see the point in investing in a solution that was still going to require more programming on my part. :)</p>
<p>My solution is to drop an ASPX page on the site that acts as a kind of "schema service", returning the collected metadata as XML. I set up a little AJAX app that compares any number of catalog instances to a master and shows the diffs. It's not perfect, but a major step forward for me.</p>
<p>Thanks again!</p> | 44,045 | 6 | 2 | null | 2008-09-04 15:46:07.743 UTC | 8 | 2019-12-10 11:15:44.07 UTC | 2013-01-24 12:22:04.033 UTC | null | 50,776 | null | 4,525 | null | 1 | 29 | sql-server|triggers|metadata | 51,463 | <p>sp_helptext works to get the sql that makes up a trigger.</p>
<p>The text column in the syscomments view also contains the sql used for object creation.</p> |
37,772,798 | Unable to self-update Composer | <p>I am trying to update Composer without any luck!</p>
<p>What I have tried:</p>
<pre><code>$ composer self-update
</code></pre>
<blockquote>
<p>[InvalidArgumentException]
Command "self-update" is not defined.</p>
</blockquote>
<pre><code>$ sudo -H composer self-update
</code></pre>
<blockquote>
<p>[InvalidArgumentException]
Command "self-update" is not defined.</p>
</blockquote>
<pre><code>$ sudo apt-get install composer
</code></pre>
<blockquote>
<p>Reading package lists... Done Building dependency tree Reading
state information... Done composer is already the newest version. The
following packages were automatically installed and are no longer
required: libntdb1 linux-headers-4.2.0-30
linux-headers-4.2.0-30-generic linux-image-4.2.0-30-generic
linux-image-extra-4.2.0-30-generic python-ntdb Use 'apt-get
autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove
and 10 not upgraded.</p>
</blockquote>
<p>I am trying to self-update Composer because I am facing the following each time I try:</p>
<pre><code>$ composer update
</code></pre>
<blockquote>
<p>Loading composer repositories with package information Updating
dependencies (including require-dev)
[RuntimeException]
Could not load package rmrevin/yii2-fontawesome in
<a href="http://packagist.org" rel="noreferrer">http://packagist.org</a>: [UnexpectedValueException] Could not parse
version constraint v4.1 .<em>: Invalid version string "v4.1.</em>"
[UnexpectedValueException]
Could not parse version constraint v4.1.<em>: Invalid version string
"v4.1.</em>"</p>
</blockquote>
<p>How can I fix this issue?</p>
<p>My PHP version is:</p>
<pre><code>php --version
</code></pre>
<blockquote>
<p>PHP 5.6.11-1ubuntu3.4 (cli) Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies</p>
</blockquote>
<p>My composer version is:</p>
<pre><code>composer --version
</code></pre>
<blockquote>
<p>Composer version @package_branch_alias_version@ (@package_version@)
@release_date@</p>
</blockquote> | 37,788,750 | 10 | 3 | null | 2016-06-12 09:42:28.297 UTC | 14 | 2022-05-19 13:45:39.843 UTC | 2021-04-21 15:21:09.713 UTC | null | 63,550 | null | 1,431,096 | null | 1 | 88 | php|composer-php | 152,133 | <p>Since I posted my answer, I have learnt a new easier way to install Composer programmatically: <em><a href="https://getcomposer.org/doc/faqs/how-to-install-composer-programmatically.md" rel="noreferrer">How do I install Composer programmatically?</a></em></p>
<h2>Old Answer:</h2>
<hr />
<p>As per @JimL comment, I was able to self update Composer by:</p>
<ul>
<li>Uninstalling Composer from the package manager (apt).</li>
<li>I installed it according to the <a href="https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx" rel="noreferrer">official documentation</a></li>
</ul>
<p>Now it works as expected.</p> |
37,700,536 | Visual studio code terminal, how to run a command with administrator rights? | <p>The new version 1.2.0 include a terminal, but when I try to install any pack with node I get the npm ERR! code EPERM that I usually solve right clicking and running it as administrator. So how I do that in the vscode terminal? There is something like sudo for linux?</p>
<p><a href="https://cloud.githubusercontent.com/assets/4368630/15891190/5e101d12-2d6b-11e6-9ef3-77d05bedce01.PNG" rel="noreferrer"><img src="https://cloud.githubusercontent.com/assets/4368630/15891190/5e101d12-2d6b-11e6-9ef3-77d05bedce01.PNG" alt="vscode terminal"></a></p> | 39,948,482 | 7 | 3 | null | 2016-06-08 10:55:28.183 UTC | 42 | 2022-08-31 18:06:21.9 UTC | 2019-04-12 22:39:27.813 UTC | null | 349,659 | null | 1,475,004 | null | 1 | 151 | windows|npm|visual-studio-code | 212,634 | <h3>Option 1 - Easier & Persistent</h3>
<p>Running Visual Studio Code as Administrator should do the trick.</p>
<p>If you're on Windows you can:</p>
<ol>
<li>Right click the shortcut or app/exe</li>
<li>Go to properties</li>
<li>Compatibility tab</li>
<li>Check "Run this program as an administrator"</li>
</ol>
<strong>There is a caveat to it though</strong>
<p>Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.</p>
<strong>Related Changes in Codebase</strong>
<ul>
<li><a href="https://visualstudio.uservoice.com/forums/293070-visual-studio-code/suggestions/8915236-visual-code-w-terminal-integrated-and-super-admin" rel="noreferrer">https://visualstudio.uservoice.com/forums/293070-visual-studio-code/suggestions/8915236-visual-code-w-terminal-integrated-and-super-admin</a></li>
<li><a href="https://github.com/Microsoft/vscode/issues/7407" rel="noreferrer">https://github.com/Microsoft/vscode/issues/7407</a></li>
</ul>
<h3>Option 2 - More like Sudo</h3>
<p>If for some weird reason this is not running your commands as an Administrator you can try the <code>runas</code> command. <a href="https://technet.microsoft.com/en-us/library/cc771525(v=ws.11).aspx" rel="noreferrer">Microsoft: runas command</a></p>
Examples
<ul>
<li><code>runas /user:Administrator myCommand</code></li>
<li><code>runas "/user:First Last" "my command"</code></li>
</ul>
Notes
<ul>
<li>Just don't forget to put double quotes around anything that has a space in it.</li>
<li>Also it's quite possible that you have never set the password on the Administrator account, as it will ask you for the password when trying to run the command. You can always use an account without the username of Administrator if it has administrator access rights/permissions.</li>
</ul> |
20,930,401 | Smooth transitioning between tree, cluster, radial tree, and radial cluster layouts | <p>For a project, I need to interactively change hierarchical data layout of a visualization - without any change of the underlying data whatsoever. The layouts capable of switching between themselves should be tree, cluster, radial tree, and radial cluster. And transitioning should be preferably an animation.</p>
<p>I thought that would be relatively easy task with <code>D3</code>. I started, but I got lost in translations and rotations, data bindings, and similar, so I am asking you for help. Also, probably I am doing something not in the spirit of D3, which is bad since I am seeking a clean solution.</p>
<p>I put together a <a href="http://jsfiddle.net/VividD/YV2XX/">jsfidle</a>, but it is just a starting point, with added radio buttons, convenient small data set, and initial cluster layout - just to help anybody who wants to take a look at this. Thanks in advance!</p>
<p><strong>UPDATE:</strong></p>
<p>I wanted to focus on links only, so I temporary disabled other elements. Building on @AmeliaBR method, following animations are obtained:</p>
<p><img src="https://i.stack.imgur.com/7KU0F.gif" alt="enter image description here"></p>
<p>Here is <a href="http://jsfiddle.net/VividD/2Gcrd/">updated jsfiddle</a>.</p>
<p><strong>UPDATE 2:</strong></p>
<p>Now with circles: (excuse my choice of colors)</p>
<p><em>{doom-duba-doom}</em></p>
<p><img src="https://i.stack.imgur.com/tN9Lu.gif" alt="enter image description here"></p>
<p>Here is <a href="http://jsfiddle.net/VividD/3TkJj/">one more updated jsfiddle</a>.</p> | 20,972,522 | 2 | 4 | null | 2014-01-05 05:20:42.173 UTC | 22 | 2014-01-07 13:11:35.917 UTC | 2014-01-06 19:36:44.623 UTC | null | 3,052,751 | null | 3,052,751 | null | 1 | 22 | d3.js|hierarchy|hierarchical-data|dendrogram | 9,346 | <p>I don't have enough reputation to make a comment...so, I am just giving this tiny contribution as a pseudo-answer. After looking at this <a href="https://stackoverflow.com/questions/20970688/d3-js-drag-and-drop-zoomable-panning-collapsible-tree-with-auto-sizing-need">post</a>, and based on @VividD's perfect comment on how simple the transitions turned out to be, I simply added the Tree Vertical option to the transformations in this <a href="http://jsfiddle.net/Nivaldo/7FdD8/2/" rel="nofollow noreferrer">fiddle</a>.</p>
<p>The addition is simply this:</p>
<pre><code>var diagonalVertical = d3.svg.diagonal()
.projection(function (d) {
return [d.x, d.y];
});
</code></pre>
<p>Anyways, I have bookmarked this highly instructional interaction.</p> |
44,070,437 | How to get a File() or Blob() from an URL in javascript? | <p>I try to upload an image to the Firebase storage from an URL (with <code>ref().put(file)</code>)(www.example.com/img.jpg). </p>
<p>To do so i need a File or Blob, but whenever I try <code>new File(url)</code> it says "not enough arguments“…</p>
<p>EDIT:
And I actually want to upload a whole directory of files, that’s why i can’t upload them via Console</p> | 44,070,566 | 5 | 2 | null | 2017-05-19 12:41:52.127 UTC | 14 | 2022-07-15 19:06:51.003 UTC | null | null | null | null | 3,343,292 | null | 1 | 44 | javascript|file|url|blob|firebase-storage | 95,064 | <p>Try using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="nofollow noreferrer">fetch API</a>. You can use it like so:</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>fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here's where you get access to the blob
// And you can use it for whatever you want
// Like calling ref().put(blob)
// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.src = objectURL;
document.getElementById('myImg').appendChild(myImage)
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myImg"></div></code></pre>
</div>
</div>
</p>
<p>As of July 2022, the fetch API has about <a href="https://caniuse.com/#search=fetch" rel="nofollow noreferrer">97% browser support</a> worldwide, with basically just IE missing it. You can get that to near 100% using a <a href="https://github.com/github/fetch" rel="nofollow noreferrer">polyfill</a>, which I recommend if you're still targeting IE.</p> |
17,880,171 | SQL Server table to json | <p>I am looking to pull some columns (Col1 and 2) of a table and put in JSON format and also write some hardcoded JSON in each node, like this. </p>
<blockquote>
<p>{ "col1":"xxxx", "col2":"xxxx", "hardcodedString":"xxxx",
"hardcodedString":"xxxx", "hardcodedString":"xxxx",
"hardcodedString":"xxxx", "hardcodedString":"xxxx"},</p>
</blockquote>
<p>I found the following git script, it creates a SP that should generate JSON but when i executed as required i get 'Commands Completed Succesfully'</p>
<p>Any ideas where the output is going or indeed if a better way to acheive my JSON?</p>
<pre><code>create procedure [dbo].[GetJSON] (
@schema_name varchar(50),
@table_name varchar(50),
@registries_per_request smallint = null
)
as
begin
if ( ( select count(*) from information_schema.tables where table_schema = @schema_name and table_name = @table_name ) > 0 )
begin
declare @json varchar(max),
@line varchar(max),
@columns varchar(max),
@sql nvarchar(max),
@columnNavigator varchar(50),
@counter tinyint,
@size varchar(10)
if (@registries_per_request is null)
begin
set @size = ''
end
else
begin
set @size = 'top ' + convert(varchar, @registries_per_request)
end
set @columns = '{'
declare schemaCursor cursor for
select column_name
from information_schema.columns
where table_schema = @schema_name
and table_name = @table_name
open schemaCursor
fetch next from schemaCursor into @columnNavigator
select @counter = count(*)
from information_schema.columns
where table_schema = @schema_name
and table_name = @table_name
while @@fetch_status = 0
begin
set @columns = @columns + '''''' + @columnNavigator + ''''':'''''' + convert(varchar, ' + @columnNavigator + ') + '''''''
set @counter = @counter - 1
if ( 0 != @counter )
begin
set @columns = @columns + ','
end
fetch next from schemaCursor into @columnNavigator
end
set @columns = @columns + '}'
close schemaCursor
deallocate schemaCursor
set @json = '['
set @sql = 'select ' + @size + '''' + @columns + ''' as json into tmpJsonTable from [' + @schema_name + '].[' + @table_name + ']'
exec sp_sqlexec @sql
select @counter = count(*) from tmpJsonTable
declare tmpCur cursor for
select * from tmpJsonTable
open tmpCur
fetch next from tmpCur into @line
while @@fetch_status = 0
begin
set @counter = @counter - 1
set @json = @json + @line
if ( 0 != @counter )
begin
set @json = @json + ','
end
fetch next from tmpCur into @line
end
set @json = @json + ']'
close tmpCur
deallocate tmpCur
drop table tmpJsonTable
select @json as json
end
end
</code></pre> | 17,882,333 | 3 | 2 | null | 2013-07-26 11:29:08.807 UTC | 7 | 2019-05-02 05:31:04.383 UTC | 2013-07-26 13:02:10.66 UTC | null | 510,981 | null | 510,981 | null | 1 | 15 | sql|json|sql-server-2008 | 42,832 | <p>I wouldn't really advise it, there are much better ways of doing this in the application layer, but the following avoids loops, and is a lot less verbose than your current method:</p>
<pre><code>CREATE PROCEDURE dbo.GetJSON @ObjectName VARCHAR(255), @registries_per_request smallint = null
AS
BEGIN
IF OBJECT_ID(@ObjectName) IS NULL
BEGIN
SELECT Json = '';
RETURN
END;
DECLARE @Top NVARCHAR(20) = CASE WHEN @registries_per_request IS NOT NULL
THEN 'TOP (' + CAST(@registries_per_request AS NVARCHAR) + ') '
ELSE ''
END;
DECLARE @SQL NVARCHAR(MAX) = N'SELECT ' + @Top + '* INTO ##T ' +
'FROM ' + @ObjectName;
EXECUTE SP_EXECUTESQL @SQL;
DECLARE @X NVARCHAR(MAX) = '[' + (SELECT * FROM ##T FOR XML PATH('')) + ']';
SELECT @X = REPLACE(@X, '<' + Name + '>',
CASE WHEN ROW_NUMBER() OVER(ORDER BY Column_ID) = 1 THEN '{'
ELSE '' END + Name + ':'),
@X = REPLACE(@X, '</' + Name + '>', ','),
@X = REPLACE(@X, ',{', '}, {'),
@X = REPLACE(@X, ',]', '}]')
FROM sys.columns
WHERE [Object_ID] = OBJECT_ID(@ObjectName)
ORDER BY Column_ID;
DROP TABLE ##T;
SELECT Json = @X;
END
</code></pre>
<p>N.B. I've changed your two part object name (@schema and @table) to just accept the full object name.</p>
<p><strong><a href="http://www.sqlfiddle.com/#!3/9d14c/1" rel="noreferrer">Example on SQL Fiddle</a></strong></p>
<p>The idea is to basically use the XML extension within SQL-Server to turn the table into XML, then just replace the start tags with <code>{ColumnName:</code> and the end tags with <code>,</code>. It then requires two more replaces to stop add the closing bracket to the last column of each row, and the remove the final <code>,</code> from the JSON string.</p> |
18,168,286 | How can I style external links like Wikipedia? | <p>I would like to distinguish between external and internal links using just CSS. </p>
<p>I would like to add a small icon to the right side of these links, without it covering up other text.</p>
<p>The icon I would like to use is the <a href="http://commons.wikimedia.org/wiki/File:Icon_External_Link.png" rel="noreferrer">icon used on Wikipedia</a>.</p>
<p>For example, this is an external link:</p>
<pre><code><a href="http://stackoverflow.com">StackOverflow</a>
</code></pre>
<p>This is an internal link:</p>
<pre><code><a href="/index.html">home page</a>
</code></pre>
<hr>
<p><img src="https://i.stack.imgur.com/0tk39.jpg" alt="sample of desired result"></p>
<hr>
<p>How can I do this using just CSS?</p> | 18,168,287 | 3 | 0 | null | 2013-08-11 02:52:14.63 UTC | 12 | 2021-08-16 17:17:18.073 UTC | 2013-08-11 03:11:29.187 UTC | null | 1,074,592 | null | 1,074,592 | null | 1 | 32 | css|progressive-enhancement | 21,848 | <h2><a href="http://codepen.io/brigand/pen/vsdIi">demo</a></h2>
<h2>Basics</h2>
<p>Using <code>:after</code> we can inject content after each matched selector.</p>
<p>The first selector matches any <code>href</code> attribute starting with <code>//</code>. This is for links that keep the same protocol (http or https) as the current page.</p>
<pre><code>a[href^="//"]:after,
</code></pre>
<p>These are the traditionally more common urls, like <a href="http://google.com">http://google.com</a> and <a href="https://encrypted.google.com">https://encrypted.google.com</a></p>
<pre><code>a[href^="http://"]:after,
a[href^="https://"]:after {
</code></pre>
<p>We can then pass a url to the content attribute to display the image after the link. The margin can be customized to fit the </p>
<pre><code> content: url(http://upload.wikimedia.org/wikipedia/commons/6/64/Icon_External_Link.png);
margin: 0 0 0 5px;
}
</code></pre>
<h2>Allow certain domains as local</h2>
<p>Let's say we're on <code>example.org</code> and we want to mark links to <code>blog.example.org</code> as on the same domain for this purpose. This is a fairly safe way to do it, however we could have a url like <a href="http://example.org/page//blog.example.org/">http://example.org/page//blog.example.org/</a></p>
<p><em>note: make sure this comes after the above in your styles</em></p>
<pre><code>a[href*="//blog.example.org/"]:after {
content: '';
margin: 0;
}
</code></pre>
<p>For more strict matching, we can take our initial settings and override them.</p>
<pre><code>a[href^="//blog.example.org/"]:after,
a[href^="http://blog.example.org/"]:after,
a[href^="https://blog.example.org/"]:after {
content: '';
margin: 0;
}
</code></pre> |
33,431,591 | Pass checkbox value to angular's ng-click | <p>Is there a way to pass to angular directive ng-click the value of the associated input?</p>
<p>In other words, what should replace <em><code>this.value</code></em> in the following:</p>
<pre><code><input type="checkbox" id="cb1" ng-click="checkAll(this.value)" />
</code></pre>
<p><strong>PS.</strong> I don't want a workaround to alternate values, I just wonder if is possible to <em>pass a value of an input as argument to an angular function</em>.</p> | 33,431,731 | 5 | 3 | null | 2015-10-30 08:28:44.923 UTC | 6 | 2021-02-11 13:17:49.03 UTC | 2017-07-19 17:22:23.757 UTC | null | 961,631 | null | 961,631 | null | 1 | 26 | javascript|angularjs|checkbox|angularjs-ng-click | 60,666 | <p>You can do the following things:</p>
<ul>
<li>Use <a href="https://docs.angularjs.org/api/ng/directive/ngModel" rel="noreferrer"><strong>ng-model</strong></a> if you want to bind a html component to angular scope </li>
<li>Change <code>ng-click</code> to <code>ng-change</code></li>
<li>If you have to bind some value upon checking and un-checking the checkbox use <code>ng-true-value="someValue"</code> and <code>ng-false-value="someValue"</code></li>
</ul>
<blockquote>
<p>The order of execution of <code>ng-click</code> and <code>ng-model</code> is ambiguous since
they do not define clear priorities. Instead you should use ng-change
or a <code>$watch</code> on the <code>$scope</code> to ensure that you obtain the correct values
of the model variable.</p>
</blockquote>
<p>Courtesy of <a href="https://stackoverflow.com/a/20290803/1575570">musically_ut</a></p>
<p><strong><a href="http://jsfiddle.net/q3La9teg/" rel="noreferrer">Working Demo</a></strong></p>
<pre><code><input type="checkbox" id="cb1" ng-model="check" ng-change="checkAll(check)" ng-true-value="YES" ng-false-value="NO"/> Citizen
</code></pre> |
2,150,161 | WebClient generates (401) Unauthorized error | <p>I have the following code running in a windows service:</p>
<pre><code>WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential("me", "12345", "evilcorp.com");
webClient.DownloadFile(downloadUrl, filePath);
</code></pre>
<p>Each time, I get the following exception</p>
<pre><code>{"The remote server returned an error: (401) Unauthorized."}
</code></pre>
<p>With the following inner exception:</p>
<pre><code>{"The function requested is not supported"}
</code></pre>
<p>I know for sure the credentials are valid, in fact, if I go to downloadUrl in my web browser and put in my credentials as evilcorp.com\me with password 12345, it downloads fine.</p>
<p>What is weird though is that if I specify my credentials as [email protected] with 12345, it appears to fail.</p>
<p>Is there a way to format credentials?</p> | 2,150,244 | 5 | 1 | null | 2010-01-27 20:53:28.997 UTC | 4 | 2020-01-22 13:08:23.463 UTC | null | null | null | null | 127,257 | null | 1 | 37 | c#|webclient|download | 63,879 | <p>Apparently the OS you are running on matters, as the default encryption has changed between OSes.
This blog has more details: <a href="http://ferozedaud.blogspot.com/2009/10/ntlm-auth-fails-with.html" rel="nofollow noreferrer">http://ferozedaud.blogspot.com/2009/10/ntlm-auth-fails-with.html</a></p>
<p>This has apparently also been discussed on stackoverflow here: <a href="https://stackoverflow.com/questions/1443617/407-authentication-required-no-challenge-sent/1482442#1482442">407 Authentication required - no challenge sent</a></p>
<p>I would suggest read the blog first as the distilled knowledge is there.</p> |
2,131,305 | how to jump back to the previous edit place | <p>Is it possible to go back to the previous edit place in vim? I know using marks, one can move back and forth between different places within a file, but I don't know whether or not vim could automatically remember the previous edit place for you.</p> | 2,131,318 | 5 | 0 | null | 2010-01-25 09:35:22.273 UTC | 20 | 2018-02-01 22:05:14.24 UTC | 2012-08-23 08:54:36.32 UTC | null | 225,037 | null | 157,300 | null | 1 | 60 | vim | 18,664 | <p>The last change is held in the mark named <code>.</code> so you can jump to the mark with <kbd>`</kbd><kbd>.</kbd> (backtick, dot) or <kbd>'</kbd><kbd>.</kbd> (apostrophe, dot). See:</p>
<pre><code>:help mark-motions
:help '.
</code></pre> |
2,148,115 | How can I remove CSS element style inline (without JavaScript)? | <p>I have a style assigned for a specific HTML element in my stylesheet file, like this</p>
<pre><code>
label {
width: 200px;
color: red;
}
</code></pre>
<p>In one special case, I would like to use a label element in the HTML document, but ignore the style specified for the label element (just for one instance in the document). Is there any way to achieve this in a generic way <strong>without overriding the element style attributes with inline styles</strong>?</p>
<pre><code>
<label for="status">Open</label>
</code></pre>
<p>To reiterate, to the HTML code displaying the label the element style (width 200 px, color red) is applied. I would like the default style attributes to be used (without knowing what they are) and without having to know what is specifically specified in the element style setting.</p> | 2,148,164 | 6 | 0 | null | 2010-01-27 15:28:37.53 UTC | 1 | 2016-06-01 12:56:51.49 UTC | 2010-01-27 15:35:13.18 UTC | null | 76,777 | null | 76,777 | null | 1 | 14 | html|css|inheritance|overriding | 48,455 | <p>From the <a href="https://developer.mozilla.org/en/Common_CSS_Questions" rel="noreferrer">Mozilla developer center</a>:</p>
<blockquote>
<p>Because CSS does not provide a "default" keyword, the only way to restore the default value of a property is to explicitly re-declare that property.</p>
<p>Thus, particular care should be taken when writing style rules using selectors (e.g., selectors by tag name, such as p) that you may want to override with more specific rules (such as those using id or class selectors), because the original default value cannot be automatically restored.</p>
<p>Because of the cascading nature of CSS, it is good practice to define style rules as specifically as possible to prevent styling elements that were not intended to be styled.</p>
</blockquote> |
1,573,170 | How can I count the number of elements that match my CSS selector? | <p>I am trying to use SeleniumRC to test my GWT App and am trying to match elements using CSS selectors.</p>
<p>I want to count the number of enabled buttons in the following HTML.</p>
<p>A button is enabled if it is under a <code><td></code> with <code>class="x-panel-btn-td "</code> and disabled if it is under a <code><td></code> with <code>class="x-panel-btn-td x-hide-offsets"</code>.</p>
<p>So basically, I want to retrieve the number of buttons under all <code><td></code>s with the class <code>x-panel-btn-td</code>.</p>
<pre><code><table cellspacing="0">
<tbody>
<tr>
<td id="ext-gen3504" class="x-panel-btn-td ">
<em unselectable="on">
<button id="ext-gen3506" class="x-btn-text" type="button">OK</button>
</em>
</td>
<td id="ext-gen3512" class="x-panel-btn-td x-hide-offsets">
<em unselectable="on">
<button id="ext-gen3506" class="x-btn-text" type="button">Yes</button>
</em>
</td>
<td id="ext-gen3520" class="x-panel-btn-td">
<em unselectable="on">
<button id="ext-gen3506" class="x-btn-text" type="button">No</button>
</em>
</td>
<td id="ext-gen3528" class="x-panel-btn-td x-hide-offsets">
<em unselectable="on">
<button id="ext-gen3506" class="x-btn-text" type="button">Cancel</button>
</em>
</td>
</tr>
</tbody>
</table>
</code></pre> | 1,573,301 | 6 | 1 | null | 2009-10-15 15:37:00.46 UTC | 2 | 2014-01-11 04:37:30.597 UTC | 2011-10-19 12:36:16.39 UTC | null | 496,830 | null | 190,695 | null | 1 | 27 | selenium|css-selectors|selenium-rc | 53,066 | <p>As far as I am aware you can't do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:</p>
<pre><code>verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2
</code></pre>
<p>In Selenium RC (Java) this would look more like</p>
<pre><code>assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);
</code></pre> |
1,475,701 | How to know if MySQLnd is the active driver? | <p>Maybe it's an obvious question, but I want to be sure.</p>
<p>How can i know if it MySQLnd is the active driver?</p>
<p>I'm runing PHP 5.3 and MySQL 5.1.37.
In phpinfo() mysqlnd is listed but only with this I can't be sure if I'm using MySQLnd or the old driver...</p>
<p>Extract of phpinfo() output</p>
<pre><code>mysql
MySQL Support enabled
Active Persistent Links 0
Active Links 0
Client API version mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
mysqli
MysqlI Support enabled
Client API library version mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
Active Persistent Links 0
Inactive Persistent Links 0
Active Links 26
mysqlnd
mysqlnd enabled
Version mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
PDO
PDO support enabled
PDO drivers mysql
pdo_mysql
PDO Driver for MySQL enabled
Client API version mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
</code></pre>
<p>I'm using PDO, and PDO driver says mysql...</p> | 1,475,996 | 6 | 1 | null | 2009-09-25 06:20:55.233 UTC | 22 | 2021-07-08 19:30:04.003 UTC | 2012-12-23 21:39:34.853 UTC | null | 168,868 | null | 92,462 | null | 1 | 59 | php|mysql|mysqlnd | 45,645 | <blockquote>
<p><strong>Warning!</strong> This method is unreliable and does not work since PHP 8.1</p>
</blockquote>
<p>If you are accessing via <code>mysqli</code>, this should do the trick:</p>
<pre><code><?php
$mysqlnd = function_exists('mysqli_fetch_all');
if ($mysqlnd) {
echo 'mysqlnd enabled!';
}
</code></pre>
<p>To detect if its the active <code>PDO</code> driver, create your MySQL PDO object then:</p>
<pre><code>if (strpos($pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), 'mysqlnd') !== false) {
echo 'PDO MySQLnd enabled!';
}
</code></pre> |
1,886,185 | Eclipse and Windows newlines | <p>I had to move my Eclipse workspace from Linux to Windows when my desktop crashed. A week later I copy it back to Linux, code happily, commit to CVS. And alas, windows newlines have polluted many files, so CVS diff dumps the entire file, even when I changed a line or two!</p>
<p>I could cook up a script, but I am wondering if it will mess up my Eclipse project files.</p> | 1,887,619 | 6 | 1 | null | 2009-12-11 06:27:40.79 UTC | 53 | 2019-08-09 01:47:56.177 UTC | 2017-08-16 13:18:28.843 UTC | null | 2,147,927 | null | 205,586 | null | 1 | 191 | eclipse|newline|delimiter | 144,212 | <p>As mentioned <a href="http://twigstechtips.blogspot.com/2008/12/eclipse-windowsunix-new-line-formatting.html" rel="noreferrer">here</a> and <a href="http://www.sics.se/node/2108" rel="noreferrer">here</a>:</p>
<blockquote>
<p>Set file encoding to <code>UTF-8</code> and line-endings for new files to Unix, so that text files are saved in a format that is not specific to the Windows OS and most easily shared across heterogeneous developer desktops:</p>
<ul>
<li>Navigate to the Workspace preferences (General:Workspace)</li>
<li>Change the Text File Encoding to <code>UTF-8</code></li>
<li>Change the New Text File Line Delimiter to Other and choose Unix from the pick-list</li>
</ul>
</blockquote>
<p><img src="https://i.stack.imgur.com/qwLz0.jpg" alt="alt text"></p>
<blockquote>
<ul>
<li>Note: to convert the line endings of an existing file, open the file in Eclipse and choose <code>File : Convert Line Delimiters to : Unix</code></li>
</ul>
</blockquote>
<p><strong>Tip</strong>: You can easily convert existing file by selecting then in the Package Explorer, and then going to the menu entry <code>File : Convert Line Delimiters to : Unix</code></p> |
1,550,831 | What is the profile of a SharePoint developer | <p>I have a development team specialized in ASP.NET. So the solutions we provide are web based, running on IIS and using MS SQL server. Everything within the intranet of the company. The team has this expertise, and they are excellent in C#, and .Net in general.</p>
<p>The company is deploying SharePoint MOSS 2007. This deployment is part of a project that I am not involved in, and for which I have very little information. However I know that they have established the "thinkers" layer (those who will say what to do), the integrations layer (the who will configure, deploy and manage the production), and that they need to establish the so called development layer (those who will do things the other two can't).</p>
<p>I am asked to evaluate the possibility to increase my team's expertise by adding SharePoint development. This is the easy part, I just have to find the required training and send my people.</p>
<p>However these days the word development could mean a lot of things and sometimes I discover that configuration is used in place of development.
I don't have any objections to evolve the team by developing new expertise, but I want to be sure to keep things stimulating for my developers.
Secondly I don't want to say that we have SharePoint development expertise, and actually what we do is just modifying css or xml files. Also, I don't think that using wizards to produce a solution is the best path to push a C# developer to follow.</p>
<p>The questions I am asking myself first is : what is the background of a SharePoint developer? how could .Net developers feel if asked to become SharePoint developers?</p>
<p>Any thoughts will be greatly appreciated.</p> | 1,550,939 | 7 | 0 | null | 2009-10-11 14:35:49.46 UTC | 9 | 2009-10-22 16:08:03.04 UTC | null | null | null | null | 169,015 | null | 1 | 6 | sharepoint | 2,242 | <p>I started in Sharepoint development over a year ago when I inherited a WSS 3.0 solution at my company. </p>
<p>Personally I think it was a great step for me getting to know Sharepoint development a little, there are a lot of problems (e.g. security, load – balance, ghosting) that was good to see how was solved by the WSS team and helps me solve problems in other solutions I‘m working on. But I don‘t work on WSS solutions full time, so others have to anwer how it is working with WSS every day.</p>
<p>WSS and Sharepoint are an extension on the ASP.NET platform, so any experience in ASP.NET and .NET in general should be a good foundation for a developer that is starting creating Sharepoint solutions. I read the <a href="https://rads.stackoverflow.com/amzn/click/com/0735623201" rel="noreferrer" rel="nofollow noreferrer">Inside Microsoft Windows Sharepoint Services 3.0</a> book in order to get the basic concepts and wss solution architecuture before I started working on WSS projects.</p>
<p>I quickly found out that you have to have a Virtual Machine environment for Sharepoint development, this is because it‘s a pain working on a client and attaching to a remote process on the server to get in debug mode. Therefore I recommend creating a MOSS virtual machine that has Visual Studio installed that has access to your source control system. Develop solutions on that machine and when finished then check into source control.</p>
<p>I also recommend looking at development tools, such as <a href="http://www.codeplex.com/stsdev" rel="noreferrer">stsdev</a> and <a href="http://www.codeplex.com/wspbuilder" rel="noreferrer">wspbuilder</a> to help you building your solution, these will ease you development process quite a bit. There are also quite a lot of tools available on the web, e.g. <a href="http://www.codeplex.com/" rel="noreferrer">codeplex</a> to help you out.</p>
<p>Sometimes it can be a pain developing these solutions, changes can require recycling the IIS pool or a brute-force IISReset, error messages can sometimes by a little cryptic and so on. But you quickly catch on and know where to look. Sharepoint also helps you out a lot, I‘ve had millions of questions from clients that can be solved with standard out-of the box web parts, so that I don‘t have to code anhything to keep my clients happy :)</p>
<p>Sharepoint also expects solutions to be coded in certain way, e.g. 12 hive filestructure so it helps you standardizing your solutions.</p>
<p>There is a serious lack of documentation, so that you have to rely on Reflector and such tools a lot, just to know what is happening within the framework, hopefully this gets better with 2010.</p>
<p>The initial learning curve is high, and a lot of new concepts an technologies to learn ,e.g. Workflows within sharepoint, featuers, ghosting and code access security
There is a lot of Xml configuration that sharepoint uses that developers have to learn, this includes the site definition, list templates and more. There are sometimes days when I‘m stuck in Xml edit mode and can‘t figure out why things don‘t work as they should do</p>
<p>These are just few of my thought, I‘ve been working mainly in WSS development and it would be great if someone could comment regarding web part configuration in Sharepoint, e.g. configuring the search. Which is something I haven‘t been doing a lot of.</p> |
1,811,967 | How to write automated unit tests for java annotation processor? | <p>I'm experimenting with java annotation processors. I'm able to write integration tests using the "JavaCompiler" (in fact I'm using "hickory" at the moment). I can run the compile process and analyse the output. The Problem: a single test runs for about half a second even without any code in my annotation processor. This is way too long to using it in TDD style.</p>
<p>Mocking away the dependencies seems very hard for me (I would have to mock out the entire "javax.lang.model.element" package). Have someone succeed to write unit tests for an annotation processor (Java 6)? If not ... what would be your approach?</p> | 1,813,801 | 7 | 0 | null | 2009-11-28 08:19:13.377 UTC | 12 | 2021-04-24 03:22:43.81 UTC | 2011-10-18 16:01:17.383 UTC | null | 648,313 | null | 204,845 | null | 1 | 32 | java|unit-testing|annotations|annotation-processing | 9,935 | <p>You're right mocking the annotation processing API (with a mock library like easymock) is painful. I tried this approach and it broke down pretty rapidly. You have to setup to many method call expectations. The tests become unmaintainable.</p>
<p>A <strong>state-based test approach</strong> worked for me reasonably well. I had to implement the parts of the <a href="https://bitbucket.org/blob79/quickcheck/src/c8e12cc026fd6295966bf9ff5d20919961ff4149/quickcheck-src-generator/src/test/java/net/java/quickcheck/srcgenerator/Model.java?at=default" rel="noreferrer">javax.lang.model.* API I needed for my tests</a>. (That were only < 350 lines of code.)</p>
<p>This is the part of a test to initiate the javax.lang.model objects. After the setup the model should be in the same state as the Java compiler implementation.</p>
<pre><code>DeclaredType typeArgument = declaredType(classElement("returnTypeName"));
DeclaredType validReturnType = declaredType(interfaceElement(GENERATOR_TYPE_NAME), typeArgument);
TypeParameterElement typeParameter = typeParameterElement();
ExecutableElement methodExecutableElement = Model.methodExecutableElement(name, validReturnType, typeParameter);
</code></pre>
<p>The static factory methods are defined in the class <code>Model</code> implementing the javax.lang.model.* classes. For example <code>declaredType</code>. (All unsupported operations will throw exceptions.)</p>
<pre><code>public static DeclaredType declaredType(final Element element, final TypeMirror... argumentTypes) {
return new DeclaredType(){
@Override public Element asElement() {
return element;
}
@Override public List<? extends TypeMirror> getTypeArguments() {
return Arrays.asList(argumentTypes);
}
@Override public String toString() {
return format("DeclareTypeModel[element=%s, argumentTypes=%s]",
element, Arrays.toString(argumentTypes));
}
@Override public <R, P> R accept(TypeVisitor<R, P> v, P p) {
return v.visitDeclared(this, p);
}
@Override public boolean equals(Object obj) { throw new UnsupportedOperationException(); }
@Override public int hashCode() { throw new UnsupportedOperationException(); }
@Override public TypeKind getKind() { throw new UnsupportedOperationException(); }
@Override public TypeMirror getEnclosingType() { throw new UnsupportedOperationException(); }
};
}
</code></pre>
<p>The rest of the test verifies the behavior of the class under test.</p>
<pre><code>Method actual = new Method(environment(), methodExecutableElement);
Method expected = new Method(..);
assertEquals(expected, actual);
</code></pre>
<p>You can have a look at the <a href="https://bitbucket.org/blob79/quickcheck/src/c8e12cc026fd6295966bf9ff5d20919961ff4149/quickcheck-src-generator/src/test/java/net/java/quickcheck/srcgenerator?at=default" rel="noreferrer">source code of the Quickcheck @Samples and @Iterables source code generator tests</a>. (The code is not optimal, yet. The Method class has to many parameters and the Parameter class is not tested in its own test but as part of the Method test. It should illustrate the approach nevertheless.)</p>
<p>Viel Glück!</p> |
1,980,953 | Is there a Java equivalent to C#'s 'yield' keyword? | <p>I know there is no direct equivalent in Java itself, but perhaps a third party?</p>
<p>It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield.</p> | 17,167,174 | 7 | 1 | null | 2009-12-30 16:08:35.43 UTC | 29 | 2022-06-07 17:49:34.983 UTC | 2009-12-30 18:28:07.76 UTC | null | 11,236 | null | 11,236 | null | 1 | 116 | java|yield|yield-return | 38,183 | <p>The two options I know of is <a href="https://code.google.com/p/infomancers-collections/" rel="noreferrer">Aviad Ben Dov's infomancers-collections library from 2007</a> and <a href="http://svn.jimblackler.net/jimblackler/trunk/IdeaProjects/YieldAdapter/" rel="noreferrer">Jim Blackler's YieldAdapter library from 2008</a> (which is also mentioned in the other answer).</p>
<p>Both will allow you to write code with <code>yield return</code>-like construct in Java, so both will satisfy your request. The notable differences between the two are:</p>
<h3>Mechanics</h3>
<p>Aviad's library is using bytecode manipulation while Jim's uses multithreading. Depending on your needs, each may have its own advantages and disadvantages. It's likely Aviad's solution is faster, while Jim's is more portable (for example, I don't think Aviad's library will work on Android).</p>
<h3>Interface</h3>
<p>Aviad's library has a cleaner interface - here's an example:</p>
<pre><code>Iterable<Integer> it = new Yielder<Integer>() {
@Override protected void yieldNextCore() {
for (int i = 0; i < 10; i++) {
yieldReturn(i);
if (i == 5) yieldBreak();
}
}
};
</code></pre>
<p>While Jim's is way more complicated, requiring you to <code>adept</code> a generic <code>Collector</code> which has a <code>collect(ResultHandler)</code> method... ugh. However, you could use something like <a href="https://github.com/domlachowicz/java-generators" rel="noreferrer">this wrapper around Jim's code by Zoom Information</a> which greatly simplifies that:</p>
<pre><code>Iterable<Integer> it = new Generator<Integer>() {
@Override protected void run() {
for (int i = 0; i < 10; i++) {
yield(i);
if (i == 5) return;
}
}
};
</code></pre>
<h3>License</h3>
<p>Aviad's solution is BSD.</p>
<p>Jim's solution is public domain, and so is its wrapper mentioned above.</p> |
1,690,197 | What does Google Closure Library offer over jQuery? | <p>Considering</p>
<ul>
<li>business background</li>
<li>community support</li>
<li>available extensions</li>
<li>default set of features</li>
<li>simplicity of use</li>
<li>and reliability</li>
</ul>
<p>why do you prefer one over the another?</p> | 1,690,494 | 8 | 4 | null | 2009-11-06 20:31:28.827 UTC | 86 | 2012-09-26 08:21:50.523 UTC | 2009-11-08 12:23:07.913 UTC | null | 54,091 | null | 69,424 | null | 1 | 191 | jquery|google-closure|google-closure-library | 56,790 | <p>I'll try to add my piece of information.</p>
<h3>More than another JS lib</h3>
<p>As I understand it, Google Closure is not only another JS library, but it is also a set of tools that will allow you to optimize your JS code. Working with jQuery gives you good tools and a lightweight library, but it does not minify your own code. The <a href="http://code.google.com/closure/compiler/" rel="noreferrer">Closure compiler</a> will. The <a href="http://code.google.com/closure/compiler/docs/inspector.html" rel="noreferrer">closure inspector</a> may also be useful, as sometimes minified code has a different behavior than the original one, and is a pain to debug. It integrates with <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a> and support unit tests, which are both developers' best friends nowadays.</p>
<h3>Documentation</h3>
<p>I guess that as any new library VS a well established one, it will lack the availability of tons of extensions and tutorial that jQuery has. However, being pushed by Google should ensure that support and reliability will be both pretty good. The current <a href="http://closure-library.googlecode.com/svn/docs/index.html" rel="noreferrer">documentation</a> and <a href="http://code.google.com/closure/library/docs/tutorial.html" rel="noreferrer">tutorial</a> both seem really good, too.</p>
<h3>Features</h3>
<p>The features of Closure look decent, though, and its modular architecture is promising, too. I guess Google has been using it internally for a long time, which means that you could expect all basic features (and more) to be implemented, and probably in a very optimized and scalable way. They are trying to present it as the STL of JavaScript, so they should have polished it.</p>
<p>After looking at the features more closely, it seems that this may be a step forward for web-applications development compared to existing libraries as jQuery. It guess it benefits internal developments at Google, but things like detecting the online state (see <a href="http://closure-library.googlecode.com/svn/docs/class_goog_events_OnlineHandler.html" rel="noreferrer">goog.events.OnlineHandler</a>), easy integration of AJAX requests and JS actions in the browser history (see <a href="http://closure-library.googlecode.com/svn/docs/class_goog_History.html" rel="noreferrer">goog.History</a>), or the legions of great widgets they provide (see <a href="http://closure-library.googlecode.com/svn/docs/namespace_goog_ui.html" rel="noreferrer">goog.ui package</a>) may help all of us building even more awesome webapps ;) !</p>
<p>It comes with <a href="http://code.google.com/closure/templates/" rel="noreferrer">templates features</a> that integrates with Java (who said <a href="http://code.google.com/webtoolkit/" rel="noreferrer">GWT</a> ?), so this may also be another plus for Closure.</p>
<h3>Ease of use</h3>
<p>Finally, it looks pretty simple to use. The syntax may be a bit more verbose than the short $ jQuery function, but with IDEs and auto-completion, it's not a real problem. Moreover, I'd say we can expect a good integration in IDEs like Eclipse, coming from Google.</p>
<p>EDIT: as requested, let me say a few words about the GWT reference. Google Web Toolkit is a Java library that allows to create AJAX-enabled web interfaces and that generates (and optimizes) the required JavaScript code. As Google Closure allows to create Templates that can be used both client- and server-side (using JavaScript and Java), my guess is that it will soon be possible to use them jointly (if it's not already the case).</p> |
2,012,610 | Generating an action URL in JavaScript for ASP.NET MVC | <p>I'm trying to redirect to another page by calling an action in controller with a specific parameter. I'm trying to use this line:</p>
<pre><code>window.open('<%= Url.Action("Report", "Survey",
new { id = ' + selectedRow + ' } ) %>');
</code></pre>
<p>But I couldn't make it work; it gives the following error: </p>
<blockquote>
<p><code>CS1012: Too many characters in character literal.</code></p>
</blockquote>
<p>Can't I generate the action URL this was on the client side? Or do I have to make an Ajax call by supplying the parameter and get back the needed URL? This doesn't seem right, but I want to if it's the only way. </p>
<p>Is there an easier solution?</p> | 2,013,403 | 9 | 1 | null | 2010-01-06 11:39:34.267 UTC | 5 | 2015-07-29 10:13:29.983 UTC | 2013-03-12 15:59:26.077 UTC | null | 61,654 | null | 244,660 | null | 1 | 19 | asp.net|javascript|asp.net-mvc | 49,912 | <p>Remember that everything between <% and %> is interpreted as C# code, so what you're actually doing is trying to evaluate the following line of C#:</p>
<pre><code>Url.Action("Report", "Survey", new { id = ' + selectedRow + ' } )
</code></pre>
<p>C# thinks the single-quotes are surrounding a character literal, hence the error message you're getting (character literals can only contain a single character in C#)</p>
<p>Perhaps you could generate the URL once in your page script - somewhere in your page HEAD, do this:</p>
<pre><code>var actionUrl =
'<%= Url.Action("Report", "Survey", new { id = "PLACEHOLDER" } ) %>';
</code></pre>
<p>That'll give you a Javascript string containing the URL you need, but with PLACEHOLDER instead of the number. Then set up your click handlers as:</p>
<pre class="lang-js prettyprint-override"><code>window.open(actionUrl.replace('PLACEHOLDER', selectedRow));
</code></pre>
<p>i.e. when the handler runs, you find the PLACEHOLDER value in your pre-calculated URL, and replace it with the selected row.</p> |
1,728,303 | How can I split and trim a string into parts all on one line? | <p>I want to split this line:</p>
<pre><code>string line = "First Name ; string ; firstName";
</code></pre>
<p>into an array of their trimmed versions:</p>
<pre><code>"First Name"
"string"
"firstName"
</code></pre>
<p><strong>How can I do this all on one line?</strong> The following gives me an error "cannot convert type void":</p>
<pre><code>List<string> parts = line.Split(';').ToList().ForEach(p => p.Trim());
</code></pre> | 1,728,318 | 9 | 1 | null | 2009-11-13 10:06:53.67 UTC | 27 | 2021-11-22 22:05:29.193 UTC | 2012-02-08 12:34:44.89 UTC | null | 41,956 | null | 4,639 | null | 1 | 161 | c#|.net|split|trim | 114,783 | <p>Try</p>
<pre><code>List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
</code></pre>
<p>FYI, the Foreach method takes an Action (takes T and returns void) for parameter, and your lambda return a string as string.Trim return a string</p>
<p>Foreach extension method is meant to modify the state of objects within the collection. As string are immutable, this would have no effect</p>
<p>Hope it helps ;o)</p>
<p>Cédric</p> |
1,777,126 | In java to remove an element in an array can you set it to null? | <p>I am trying to make a remove method that works on an array implementation of a list.
Can I set the the duplicate element to null to remove it? Assuming that the list is in order.</p>
<pre><code>ArrayList a = new ArrayList[];
public void removeduplicates(){
for(a[i].equals(a[i+1]){
a[i+1] = null;
}
a[i+1] = a[i];
}
</code></pre> | 1,777,134 | 9 | 8 | null | 2009-11-21 23:22:44.153 UTC | null | 2011-06-14 20:23:25.303 UTC | 2011-06-14 20:23:25.303 UTC | null | 102,937 | null | 148,636 | null | 1 | -1 | java|null|list|arrays | 38,517 | <p>No you can't remove an element from an array, as in making it shorter. Java arrays are fixed-size. You need to use an <a href="http://doc.javanb.com/javasdk-docs-6-0-en/api/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList</code></a> for that.</p>
<p>If you set an element to null, the array will still have the same size, but with a null reference at that point.</p>
<pre><code> // Let's say a = [0,1,2,3,4] (Integer[])
a[2] = null;
// Now a = [0,1,null,3,4]
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.