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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,034,084 | Creating a Jar of test binaries - Gradle | <p>I'm using the latest version of Gradle (milestone 9), and I'm trying to figure out how to create a Jar of all test binaries. </p>
<p>From what I've found on the internet, the following should work:</p>
<pre><code>task packageTests(type: Jar) {
from sourceSets.test.classes
}
</code></pre>
<p>However I am getting a - </p>
<blockquote>
<p>Cannot get the value of write-only property 'classes' on source set
test.</p>
</blockquote>
<p>What is the correct way of coding what I'm trying to achieve?</p>
<p>Is the property 'classes' somehow deprecated now ?</p> | 10,036,708 | 3 | 0 | null | 2012-04-05 18:38:36.01 UTC | 4 | 2021-09-04 09:00:04.62 UTC | null | null | null | null | 76,487 | null | 1 | 53 | gradle | 17,053 | <p>Changing <code>sourceSets.test.classes</code> to <code>sourceSets.test.output</code> fixes the problem.</p> |
50,779,617 | Pandas pd.Series.isin performance with set versus array | <p>In Python generally, membership of a hashable collection is best tested via <code>set</code>. We know this because the use of hashing gives us O(1) lookup complexity versus O(n) for <code>list</code> or <code>np.ndarray</code>.</p>
<p>In Pandas, I often have to check for membership in very large collections. I presumed that the same would apply, i.e. checking each item of a series for membership in a <code>set</code> is more efficient than using <code>list</code> or <code>np.ndarray</code>. However, this doesn't seem to be the case:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(0)
x_set = {i for i in range(100000)}
x_arr = np.array(list(x_set))
x_list = list(x_set)
arr = np.random.randint(0, 20000, 10000)
ser = pd.Series(arr)
lst = arr.tolist()
%timeit ser.isin(x_set) # 8.9 ms
%timeit ser.isin(x_arr) # 2.17 ms
%timeit ser.isin(x_list) # 7.79 ms
%timeit np.in1d(arr, x_arr) # 5.02 ms
%timeit [i in x_set for i in lst] # 1.1 ms
%timeit [i in x_set for i in ser.values] # 4.61 ms
</code></pre>
<p>Versions used for testing:</p>
<pre><code>np.__version__ # '1.14.3'
pd.__version__ # '0.23.0'
sys.version # '3.6.5'
</code></pre>
<p>The source code for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="noreferrer"><code>pd.Series.isin</code></a>, I believe, utilises <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="noreferrer"><code>numpy.in1d</code></a>, which presumably means a large overhead for <code>set</code> to <code>np.ndarray</code> conversion.</p>
<p>Negating the cost of constructing the inputs, the implications for Pandas:</p>
<ul>
<li>If you know your elements of <code>x_list</code> or <code>x_arr</code> are unique, don't bother converting to <code>x_set</code>. This will be costly (both conversion and membership tests) for use with Pandas.</li>
<li>Using list comprehensions are the only way to benefit from O(1) set lookup.</li>
</ul>
<p>My questions are:</p>
<ol>
<li>Is my analysis above correct? This seems like an obvious, yet undocumented, result of how <code>pd.Series.isin</code> has been implemented.</li>
<li>Is there a workaround, without using a list comprehension or <code>pd.Series.apply</code>, which <em>does</em> utilise O(1) set lookup? Or is this an unavoidable design choice and/or corollary of having NumPy as the backbone of Pandas?</li>
</ol>
<p><strong>Update</strong>: On an older setup (Pandas / NumPy versions) I see <code>x_set</code> outperform <code>x_arr</code> with <code>pd.Series.isin</code>. So an additional question: has anything fundamentally changed from old to new to cause performance with <code>set</code> to worsen?</p>
<pre><code>%timeit ser.isin(x_set) # 10.5 ms
%timeit ser.isin(x_arr) # 15.2 ms
%timeit ser.isin(x_list) # 9.61 ms
%timeit np.in1d(arr, x_arr) # 4.15 ms
%timeit [i in x_set for i in lst] # 1.15 ms
%timeit [i in x_set for i in ser.values] # 2.8 ms
pd.__version__ # '0.19.2'
np.__version__ # '1.11.3'
sys.version # '3.6.0'
</code></pre> | 50,881,584 | 1 | 10 | null | 2018-06-10 00:25:45.563 UTC | 24 | 2019-11-06 18:18:05.503 UTC | 2018-06-16 12:08:51.673 UTC | null | 9,209,546 | null | 9,209,546 | null | 1 | 36 | python|performance|pandas|numpy|series | 6,204 | <p>This might not be obvious, but <code>pd.Series.isin</code> uses <code>O(1)</code>-look up per element.</p>
<p>After an analysis, which proves the above statement, we will use its insights to create a Cython-prototype which can easily beat the fastest out-of-the-box-solution.</p>
<hr>
<p>Let's assume that the "set" has <code>n</code> elements and the "series" has <code>m</code> elements. The running time is then:</p>
<pre><code> T(n,m)=T_preprocess(n)+m*T_lookup(n)
</code></pre>
<p>For the pure-python version, that means:</p>
<ul>
<li><code>T_preprocess(n)=0</code> - no preprocessing needed</li>
<li><code>T_lookup(n)=O(1)</code> - well known behavior of python's set</li>
<li>results in <code>T(n,m)=O(m)</code></li>
</ul>
<p>What happens for <code>pd.Series.isin(x_arr)</code>? Obviously, if we skip the preprocessing and search in linear time we will get <code>O(n*m)</code>, which is not acceptable. </p>
<p>It is easy to see with help of a debugger or a profiler (I used valgrind-callgrind+kcachegrind), what is going on: the working horse is the function <code>__pyx_pw_6pandas_5_libs_9hashtable_23ismember_int64</code>. Its definition can be found <a href="https://github.com/pandas-dev/pandas/blob/ec5956ed350d33ac2cee07bf9a24ea5315529443/pandas/_libs/hashtable_func_helper.pxi.in#L216" rel="noreferrer">here</a>:</p>
<ul>
<li>In a preprocessing step, a hash-map (pandas uses <a href="https://github.com/attractivechaos/klib" rel="noreferrer">khash from klib</a>) is created out of <code>n</code> elements from <code>x_arr</code>, i.e. in running time <code>O(n)</code>.</li>
<li><code>m</code> look-ups happen in <code>O(1)</code> each or <code>O(m)</code> in total in the constructed hash-map.</li>
<li>results in <code>T(n,m)=O(m)+O(n)</code></li>
</ul>
<p>We must remember - the elements of numpy-array are raw-C-integers and not the Python-objects in the original set - so we cannot use the set as it is. </p>
<p>An alternative to converting the set of Python-objects to a set of C-ints, would be to convert the single C-ints to Python-object and thus be able to use the original set. That is what happens in <code>[i in x_set for i in ser.values]</code>-variant:</p>
<ul>
<li>No preprocessing.</li>
<li>m look-ups happen in <code>O(1)</code> time each or <code>O(m)</code> in total, but the look-up is slower due to necessary creation of a Python-object.</li>
<li>results in <code>T(n,m)=O(m)</code></li>
</ul>
<p>Clearly, you could speed-up this version a little bit by using Cython.</p>
<p>But enough theory, let's take a look at the running times for different <code>n</code>s with fixed <code>m</code>s:</p>
<p><a href="https://i.stack.imgur.com/pWAf9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pWAf9.png" alt="enter image description here"></a></p>
<p>We can see: the linear time of preprocessing dominates the numpy-version for big <code>n</code>s. The version with conversion from numpy to pure-python (<code>numpy->python</code>) has the same constant behavior as the pure-python version but is slower, because of the necessary conversion - this all in accordance with our analysis.</p>
<p>That cannot be seen well in the diagram: if <code>n < m</code> the numpy version becomes faster - in this case the faster look-up of <code>khash</code>-lib plays the most important role and not the preprocessing-part.</p>
<p>My take-aways from this analysis:</p>
<ul>
<li><p><code>n < m</code>: <code>pd.Series.isin</code> should be taken because <code>O(n)</code>-preprocessing isn't that costly.</p></li>
<li><p><code>n > m</code>: (probably cythonized version of) <code>[i in x_set for i in ser.values]</code> should be taken and thus <code>O(n)</code> avoided.</p></li>
<li><p>clearly there is a gray zone where <code>n</code> and <code>m</code> are approximately equal and it is hard to tell which solution is best without testing. </p></li>
<li><p>If you have it under your control: The best thing would be to build the <code>set</code> directly as a C-integer-set (<code>khash</code> (<a href="https://github.com/pandas-dev/pandas/blob/ec5956ed350d33ac2cee07bf9a24ea5315529443/pandas/_libs/hashtable.pxd" rel="noreferrer">already wrapped in pandas</a>) or maybe even some c++-implementations), thus eliminating the need for preprocessing. I don't know, whether there is something in pandas you could reuse, but it is probably not a big deal to write the function in Cython.</p></li>
</ul>
<hr>
<p>The problem is that the last suggestion doesn't work out of the box, as neither pandas nor numpy have a notion of a set (at least to my limited knowledge) in their interfaces. But having raw-C-set-interfaces would be best of both worlds:</p>
<ul>
<li>no preprocessing needed because values are already passed as a set</li>
<li>no conversion needed because the passed set consists of raw-C-values</li>
</ul>
<p>I've coded a quick and dirty <a href="https://github.com/realead/cykhash" rel="noreferrer">Cython-wrapper for khash</a> (inspired by the wrapper in pandas), which can be installed via <code>pip install https://github.com/realead/cykhash/zipball/master</code> and then used with Cython for a faster <code>isin</code> version:</p>
<pre><code>%%cython
import numpy as np
cimport numpy as np
from cykhash.khashsets cimport Int64Set
def isin_khash(np.ndarray[np.int64_t, ndim=1] a, Int64Set b):
cdef np.ndarray[np.uint8_t,ndim=1, cast=True] res=np.empty(a.shape[0],dtype=np.bool)
cdef int i
for i in range(a.size):
res[i]=b.contains(a[i])
return res
</code></pre>
<p>As a further possibility the c++'s <code>unordered_map</code> can be wrapped (see listing C), which has the disadvantage of needing c++-libraries and (as we will see) is slightly slower.</p>
<p>Comparing the approaches (see listing D for creating of timings):</p>
<p><a href="https://i.stack.imgur.com/RwSB4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RwSB4.png" alt="enter image description here"></a></p>
<p>khash is about factor 20 faster than the <code>numpy->python</code>, about factor 6 faster than the pure python (but pure-python is not what we want anyway) and even about factor 3 faster than the cpp's-version.</p>
<hr>
<p>Listings</p>
<p>1) profiling with valgrind:</p>
<pre><code>#isin.py
import numpy as np
import pandas as pd
np.random.seed(0)
x_set = {i for i in range(2*10**6)}
x_arr = np.array(list(x_set))
arr = np.random.randint(0, 20000, 10000)
ser = pd.Series(arr)
for _ in range(10):
ser.isin(x_arr)
</code></pre>
<p>and now:</p>
<pre><code>>>> valgrind --tool=callgrind python isin.py
>>> kcachegrind
</code></pre>
<p>leads to the following call graph:</p>
<p><a href="https://i.stack.imgur.com/5Wwgz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5Wwgz.png" alt="enter image description here"></a></p>
<p>B: ipython code for producing the running times:</p>
<pre><code>import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
np.random.seed(0)
x_set = {i for i in range(10**2)}
x_arr = np.array(list(x_set))
x_list = list(x_set)
arr = np.random.randint(0, 20000, 10000)
ser = pd.Series(arr)
lst = arr.tolist()
n=10**3
result=[]
while n<3*10**6:
x_set = {i for i in range(n)}
x_arr = np.array(list(x_set))
x_list = list(x_set)
t1=%timeit -o ser.isin(x_arr)
t2=%timeit -o [i in x_set for i in lst]
t3=%timeit -o [i in x_set for i in ser.values]
result.append([n, t1.average, t2.average, t3.average])
n*=2
#plotting result:
for_plot=np.array(result)
plt.plot(for_plot[:,0], for_plot[:,1], label='numpy')
plt.plot(for_plot[:,0], for_plot[:,2], label='python')
plt.plot(for_plot[:,0], for_plot[:,3], label='numpy->python')
plt.xlabel('n')
plt.ylabel('running time')
plt.legend()
plt.show()
</code></pre>
<p>C: cpp-wrapper:</p>
<pre><code>%%cython --cplus -c=-std=c++11 -a
from libcpp.unordered_set cimport unordered_set
cdef class HashSet:
cdef unordered_set[long long int] s
cpdef add(self, long long int z):
self.s.insert(z)
cpdef bint contains(self, long long int z):
return self.s.count(z)>0
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def isin_cpp(np.ndarray[np.int64_t, ndim=1] a, HashSet b):
cdef np.ndarray[np.uint8_t,ndim=1, cast=True] res=np.empty(a.shape[0],dtype=np.bool)
cdef int i
for i in range(a.size):
res[i]=b.contains(a[i])
return res
</code></pre>
<p>D: plotting results with different set-wrappers:</p>
<pre><code>import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
from cykhash import Int64Set
np.random.seed(0)
x_set = {i for i in range(10**2)}
x_arr = np.array(list(x_set))
x_list = list(x_set)
arr = np.random.randint(0, 20000, 10000)
ser = pd.Series(arr)
lst = arr.tolist()
n=10**3
result=[]
while n<3*10**6:
x_set = {i for i in range(n)}
x_arr = np.array(list(x_set))
cpp_set=HashSet()
khash_set=Int64Set()
for i in x_set:
cpp_set.add(i)
khash_set.add(i)
assert((ser.isin(x_arr).values==isin_cpp(ser.values, cpp_set)).all())
assert((ser.isin(x_arr).values==isin_khash(ser.values, khash_set)).all())
t1=%timeit -o isin_khash(ser.values, khash_set)
t2=%timeit -o isin_cpp(ser.values, cpp_set)
t3=%timeit -o [i in x_set for i in lst]
t4=%timeit -o [i in x_set for i in ser.values]
result.append([n, t1.average, t2.average, t3.average, t4.average])
n*=2
#ploting result:
for_plot=np.array(result)
plt.plot(for_plot[:,0], for_plot[:,1], label='khash')
plt.plot(for_plot[:,0], for_plot[:,2], label='cpp')
plt.plot(for_plot[:,0], for_plot[:,3], label='pure python')
plt.plot(for_plot[:,0], for_plot[:,4], label='numpy->python')
plt.xlabel('n')
plt.ylabel('running time')
ymin, ymax = plt.ylim()
plt.ylim(0,ymax)
plt.legend()
plt.show()
</code></pre> |
28,075,699 | Coloring Cells in Pandas | <p>I am able to import data from an excel file using Pandas by using:</p>
<pre><code>xl = read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
</code></pre>
<p>Now that I have all the data in xl as DataFrame. I would like to colour some cells in that data based on conditions defined in another function and export the same (with colour coding) to an Excel file. </p>
<p>Can someone tell me how should I go about this?</p>
<p>Thank you.</p> | 41,272,883 | 4 | 6 | null | 2015-01-21 19:53:41.117 UTC | 13 | 2020-08-13 13:36:52.48 UTC | null | null | null | null | 4,417,394 | null | 1 | 22 | python|pandas|ipython | 91,086 | <p>Pandas has a relatively new <code>Styler</code> feature where you can apply conditional formatting type manipulations to dataframes.
<a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/style.html</a></p>
<p>You can use some of their built-in functions like <code>background_gradient</code> or <code>bar</code> to replicate excel-like features like conditional formatting and data bars. You can also format cells to display percentages, floats, ints, etc. without changing the original dataframe.</p>
<p>Here's an example of the type of chart you can make using <code>Styler</code> (this is a nonsense chart but just meant to demonstrate features):</p>
<p><a href="https://i.stack.imgur.com/qLb0Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qLb0Q.png" alt="enter image description here"></a></p>
<p>To harness the full functionality of <code>Styler</code> you should get comfortable with the <code>Styler.apply()</code> and <code>Styler.applymap()</code> APIs. These allow you to create custom functions and apply them to the table's columns, rows or elements. For example, if I wanted to color a +ive cell green and a -ive cell red, I'd create a function </p>
<pre><code>def _color_red_or_green(val):
color = 'red' if val < 0 else 'green'
return 'color: %s' % color
</code></pre>
<p>and call it on my <code>Styler</code> object, i.e., <code>df.style.applymap(_color_red_or_green)</code>.</p>
<p>With respect to exporting back to Excel, as far as I'm aware this is not supported in <code>Styler</code> yet so I'd probably go the xlsxwriter route if you NEED Excel for some reason. However, in my experience this is a great pure Python alternative, for example along with matplotlib charts and in emails/reports.</p> |
28,153,203 | "undefined" function declared in another file? | <p>I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:</p>
<pre><code>undefined: NewEmployee
</code></pre>
<p>Here is the source code:</p>
<p><code>main.go</code>:</p>
<pre><code>package main
func main() {
emp := NewEmployee()
}
</code></pre>
<p><code>employee.go</code>:</p>
<pre><code>package main
type Employee struct {
name string
age int
}
func NewEmployee() *Employee {
p := &Employee{}
return p
}
func PrintEmployee (p *Employee) {
return "Hello world!"
}
</code></pre> | 28,153,553 | 14 | 11 | null | 2015-01-26 15:27:12.027 UTC | 43 | 2022-08-20 23:09:38.357 UTC | 2021-02-23 09:12:30.167 UTC | null | 13,860 | null | 2,438,413 | null | 1 | 212 | go|undefined|func | 160,380 | <p>Please read <a href="http://golang.org/doc/code.html" rel="noreferrer">"How to Write Go Code"</a>.</p>
<p>Use <code>go build</code> or <code>go install</code> within the package directory, or supply an import path for the package. Do not use file arguments for <code>build</code> or <code>install</code>.</p>
<p>While you can use file arguments for <code>go run</code>, you should build a package instead, usually with <code>go run .</code>, though you should almost always use <code>go install</code>, or <code>go build</code>.</p> |
10,182,798 | Why are ports below 1024 privileged? | <p>I've heard it's meant to be a security feature, but it often seems like a security problem. If I want to write a server that uses a privileged port, not only do I have to worry about how secure my code is, I have to especially worry about whether I'm using <code>setuid</code> right and dropping privileges.</p> | 10,182,831 | 2 | 4 | null | 2012-04-16 22:49:45.313 UTC | 16 | 2020-08-19 00:32:08.467 UTC | 2020-08-19 00:32:08.467 UTC | null | 8,242,447 | null | 306 | null | 1 | 71 | unix|ip|port | 46,495 | <p>True. But it also means that anyone talking to you knows that you must have to root privileges to run that server. When you log in to a server on port 22 (say), you know you're talking to a process that was run by root (security problems aside), so you trust it with your password for that system, or other information you might not trust to anyone with a user account on that system.</p>
<p>Reference: <a href="http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html">http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html</a>.</p>
<p>Edit to elaborate on the reasoning: a lot of the most important network services - telnet (yes, it's still used - surprisingly often), SSH, many HTTP services, FTP etc. etc. - involve sending important data like passwords over the wire. In a secure setup some sort of encryption, whether inherent in the protocol (SSH) or wrapped around it (stunnel, IPSec), protects the data from being snooped on the wire, but all these protections end at the server. </p>
<p>In order to protect your data properly, you need to be sure that you're talking to the 'real' server. Today secure certificates are the most important way of doing this on the web (and elsewhere): you assume that only the 'real' server has access to the certificate, so if you verify that the server you're talking to has that certificate you'll trust it.</p>
<p>Privileged ports work in a very similar way: only root has access to privileged ports, so if you're talking to a privileged port you know you're talking to root. This isn't very useful on the modern web: what matters is the <em>identity</em> of the server, not its IP. In other types of networks, this isn't the case: in an academic network, for example, servers are often physically controlled by trusted staff in secure rooms, but students and staff have quite free access as users. In this situation it's often safe to assume you can always trust root, so you can log in and send private data to a privileged port safely. If ordinary users could listen on all ports, you'd need a whole extra layer to verify that a particular program was trusted with certain data.</p> |
11,752,977 | AngularJS ng-model $scope in ng-repeat is undefined | <p>I apologize in advance if i'm not wording this properly. I have a textbox with <code>ng-model</code> inside an <code>ng-repeat</code> and when I try to get the textbox value it's always <code>undefined</code>. I just want it to display whatever I type in the corresponding textbox. </p>
<p>It seems to be an issue with the <code>$scope</code>, so how would I make the <code>$scope.postText</code> global or at the controller root level so it can be accessible?</p>
<p>Here's the JSFiddle to help clear things up: <a href="http://jsfiddle.net/stevenng/9mx9B/14/">http://jsfiddle.net/stevenng/9mx9B/14/</a></p> | 11,753,160 | 4 | 0 | null | 2012-08-01 05:24:31.463 UTC | 14 | 2014-10-07 04:26:00.003 UTC | null | null | null | null | 386,283 | null | 1 | 19 | angularjs | 33,093 | <p>In your click expression you can reference the <code>postText</code> and access it in your <code>savePost</code> function. If this wasn't in an ng-repeat you could access the single <code>$scope.postText</code> successfully but <a href="http://docs.angularjs.org/api/ng.directive%3angRepeat">ng-repeat</a> creates a new scope for each item.</p>
<p><a href="http://jsfiddle.net/VnQqH/">Here</a> is an updated fiddle.</p>
<pre><code><div ng-repeat="post in posts">
<strong>{{post}}</strong>
<input type="text" ng-model="postText">
<a href="#" ng-click="savePost(postText)">save post</a>
</div>
$scope.savePost = function(post){
alert('post stuff in textbox: ' + post);
}
</code></pre> |
11,517,150 | How to change background color of cell in table using java script | <p>I need to change background color of single cell in table using java script. </p>
<p>During document i need style of all cell should be same ( so used style sheet to add this. ) , but on button click i need to change color of first cell.</p>
<p>following is the sample code</p>
<pre><code><html lang="en">
<head>
<script type="text/javascript" >
function btnClick()
{
var x = document.getElementById("mytable").cells;
x[0].innerHTML = "i want to change my cell color";
x[0].bgColor = "Yellow";
}
</script>
</head>
<style>
div
{
text-align: left;
text-indent: 0px;
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
}
td.td
{
border-width : 1px;
background-color: #99cc00;
text-align:center;
}
</style>
<body>
<div>
<table id = "mytable" width="100%" border="1" cellpadding="2" cellspacing="2" style="background-color: #ffffff;">
<tr valign="top">
<td class = "td"><br /> </td>
<td class = "td"><br /> </td>
</tr>
<tr valign="top">
<td class = "td"><br /> </td>
<td class = "td"><br /> </td>
</tr>
</table>
</div>
<input type="button" value="Click" OnClick = "btnClick()">
</body>
</html>
</code></pre> | 11,517,189 | 3 | 0 | null | 2012-07-17 06:34:00.497 UTC | 5 | 2016-03-21 01:10:17.077 UTC | null | null | null | null | 126,373 | null | 1 | 27 | javascript|html | 195,468 | <p>Try this:</p>
<pre><code>function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
</code></pre>
<p>Set from JS, <code>backgroundColor</code> is the equivalent of <code>background-color</code> in your style-sheet.</p>
<p>Note also that the <code>.cells</code> collection belongs to a table <em>row</em>, not to the table itself. To get all the cells from all rows you can instead use <code>getElementsByTagName()</code>.</p>
<p>Demo: <a href="http://jsbin.com/ekituv/edit#preview" rel="noreferrer">http://jsbin.com/ekituv/edit#preview</a></p> |
11,545,541 | How to Mock a readonly property whose value depends on another property of the Mock | <p>(As indicated by the tags, I am using moq).</p>
<p>I have an interface like this:</p>
<pre><code>interface ISource
{
string Name { get; set; }
int Id { get; set; }
}
interface IExample
{
string Name { get; }
ISource Source { get; set; }
}
</code></pre>
<p>In my application, concrete instances of IExample accept a DTO (IDataTransferObject) as the Source. Some properties on the concrete implementation of IExample are simply delegated to the Source. Like this...</p>
<pre><code>class Example : IExample
{
IDataTransferObject Source { get; set; }
string Name { get { return _data.Name; } }
}
</code></pre>
<p>I would like to create a standalone mock of IExample (standalone meaning that I cannot use a captured variable because several instances of the IExample mock will be created in the course of a test) and setup the Mock such that IExample.Name returns the value of IExample.Source.Name. So, I would like to create a mock something like this:</p>
<pre><code>var example = new Mock<IExample>();
example.SetupProperty(ex => ex.Source);
example.SetupGet(ex => ex.Name).Returns(what can I put here to return ex.Source.Name);
</code></pre>
<p>Essentially, I want to configure the mock to return, as the value of one property, the value of a property of a subobject of the mock.</p>
<p>Thanks.</p> | 11,545,633 | 1 | 0 | null | 2012-07-18 16:00:42.47 UTC | 3 | 2013-10-21 09:42:05.383 UTC | null | null | null | null | 125,439 | null | 1 | 28 | c#|.net|moq | 19,526 | <p>You could probably use:</p>
<pre><code>example.SetupGet(ex => ex.Name).Returns(() => example.Object.Source.Name);
</code></pre>
<p>The value to be returned will then be determined when the property is accessed, and will be taken from <code>Name</code> property of the mock's <code>Source</code> property.</p> |
11,947,987 | Margin does not impact in "include" | <p>I have a view with articles. It uses "include", and I'm trying to make a little margin between them. However, "android:layout_marginTop" does not seem to have any impact on the layout.</p>
<p>What am I doing wrong?</p>
<pre><code><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include android:id="@+id/article1" layout="@layout/mainarticle" />
<include android:id="@+id/article2" android:layout_marginTop="10dip" layout="@layout/article" />
<include android:id="@+id/article3" android:layout_marginTop="10dip" layout="@layout/article" />
<include android:id="@+id/article4" android:layout_marginTop="10dip" layout="@layout/article" />
<include android:id="@+id/article5" android:layout_marginTop="10dip" layout="@layout/article" />
</LinearLayout>
</code></pre> | 13,623,383 | 6 | 0 | null | 2012-08-14 07:52:56.83 UTC | 8 | 2020-12-14 13:29:33.667 UTC | 2016-10-12 06:18:21.063 UTC | null | 1,402,846 | null | 1,003,363 | null | 1 | 51 | android|android-layout | 18,334 | <p>You should add the <code>android:layout_width</code> and <code>android:layout_height</code> attributes in the <code>include</code> tag. Otherwise, the margins are not taken into consideration.</p>
<blockquote>
<p>However, if you want to override layout attributes using the <code><include></code> tag, you must override both <code>android:layout_height</code> and <code>android:layout_width</code> in order for other layout attributes to take effect.</p>
</blockquote>
<p><a href="https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include">https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include</a></p> |
11,699,215 | How to upgrade node.js on Windows? | <p>I already have Node.js v0.8.0 running on Windows. Can I just run the latest installer to upgrade it to v0.8.4? I am afraid it will break existing third party modules on my machine.</p> | 11,700,175 | 9 | 1 | null | 2012-07-28 07:36:34.327 UTC | 14 | 2020-11-04 18:28:25.97 UTC | null | null | null | null | 312,483 | null | 1 | 68 | node.js | 90,834 | <p>Yes, you just install the latest version. Generally you shouldn't have any compatibility problems if you are already using the same major version (e.g. Version 0.8.x). If you are concerned about changes, you can always check the changelog for each version (link to changelog is on node.js download page at nodejs.org). That should tell you of any big changes (i.e API changes, etc). </p> |
11,583,562 | How to kill a process running on particular port in Linux? | <p>I tried to close the tomcat using <code>./shutdown.sh</code> from tomcat <code>/bin</code> directory. But found that the server was not closed properly. And thus I was unable to restart<br>My tomcat is running on port <code>8080</code>.</p>
<p>I want to kill the tomcat process running on <code>8080</code>. I first want to have the list of processes running on a specific port (8080) in order to select which process to kill.</p> | 11,583,564 | 34 | 1 | null | 2012-07-20 16:39:17.32 UTC | 502 | 2022-08-25 16:00:28.88 UTC | 2017-08-10 10:55:15.173 UTC | null | 3,885,376 | null | 1,356,127 | null | 1 | 1,218 | linux|unix|port|kill-process | 2,049,316 | <p>Use the command</p>
<pre><code> sudo netstat -plten |grep java
</code></pre>
<p>used <code>grep java</code> as <code>tomcat</code> uses <code>java</code> as their processes.</p>
<p>It will show the list of processes with port number and process id</p>
<pre><code>tcp6 0 0 :::8080 :::* LISTEN
1000 30070621 16085/java
</code></pre>
<p>the number before <code>/java</code> is a process id. Now use <code>kill</code> command to kill the process</p>
<pre><code>kill -9 16085
</code></pre>
<p><code>-9</code> implies the process will be killed forcefully.</p> |
19,835,174 | How to check if 3 sides form a triangle in C++ | <p>I am trying to check if 3 sides form a triangle in C++, but the answer for all possible numbers I tried it says wrong...</p>
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
if (pow(a,2) == pow(b,2) * pow(c,2) || pow(b,2) == pow(a,2) * pow(c,2) || pow(c,2) == pow(a,2) * pow(b,2))
cout << "The sides form a triangle" << endl;
else
cout << "The sides do not form a triangle." << endl;
return 0;
}
</code></pre> | 19,835,249 | 6 | 6 | null | 2013-11-07 11:50:34.347 UTC | 1 | 2019-04-20 19:02:50 UTC | 2015-02-19 05:41:29.433 UTC | null | 1,118,321 | null | 2,943,407 | null | 1 | 6 | c++|geometry | 49,190 | <p>Let's say that a, b, c is the sides of the triangle. Therefore, it must be satisfy this criteria :</p>
<ol>
<li>a + b > c</li>
<li>a + c > b</li>
<li>b + c > a</li>
</ol>
<p>All the criteria must be true. If one of them are false, then a, b, c will not create the triangle.</p>
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
// check whether a, b, c can form a triangle
if (a+b > c && a+c > b && b+c > a)
cout << "The sides form a triangle" << endl;
else
cout << "The sides do not form a triangle." << endl;
return 0;
}
</code></pre> |
3,907,408 | Flatten a tree (list of lists) with one statement? | <p>Thanks to nHibernate, some of the data structures I work with are lists within lists within lists. So for example I have a data object called "category" which has a .Children property that resolves to a list of categories ... each one of which can have children ... and so on and so on.</p>
<p>I need to find a way of starting at a top-level category in this structure and getting a list or array or something similar of all the children in the entire structure - so all the children of all the children etc etc, flattened into a single list.</p>
<p>I'm sure it can be done with recursion, but I find recursive code a pain to work through, and I'm convinced there must be a more straightforward way in .Net 4 using Linq or somesuch - any suggestions?</p> | 3,907,683 | 4 | 2 | null | 2010-10-11 15:01:32.737 UTC | 11 | 2018-01-19 09:20:36.707 UTC | 2013-02-25 12:07:41.457 UTC | null | 254,882 | null | 271,907 | null | 1 | 24 | .net|tree|flatten | 11,386 | <p>Assuming your Category class looks something like:</p>
<pre><code> public class Category
{
public string Name { get; set; }
public List<Category> Children { get; set; }
}
</code></pre>
<p>I don't think there's an "easy" non-recursive way to do it; if you're simply looking for a single method call to handle it, the "easy" way is to write the recursive version into a single method call. There's probably an iterative way to do this, but I'm guessing it's actually pretty complicated. It's like asking the "easy" way to find a tangent to a curve without using calculus.</p>
<p>Anyway, this would probably do it:</p>
<pre><code>public static List<Category> Flatten(Category root) {
var flattened = new List<Category> {root};
var children = root.Children;
if(children != null)
{
foreach (var child in children)
{
flattened.AddRange(Flatten(child));
}
}
return flattened;
}
</code></pre> |
3,417,074 | Why would an IN condition be slower than "=" in sql? | <p>Check the question <a href="https://stackoverflow.com/questions/3416076/this-select-query-takes-180-seconds-to-finish">This SELECT query takes 180 seconds to finish</a> (check the comments on the question itself).<br>
The IN get to be compared against only one value, but still the time difference is enormous.<br>
Why is it like that?</p> | 3,417,190 | 4 | 1 | null | 2010-08-05 16:45:30.19 UTC | 5 | 2015-09-08 11:56:58.57 UTC | 2017-05-23 11:45:32.283 UTC | null | -1 | null | 67,153 | null | 1 | 29 | sql|mysql|performance|comparison | 7,866 | <p>Summary: This is a <a href="http://bugs.mysql.com/bug.php?id=32665" rel="noreferrer">known problem</a> in MySQL and was fixed in MySQL 5.6.x. The problem is due to a missing optimization when a subquery using IN is incorrectly indentified as dependent subquery instead of an independent subquery.</p>
<hr>
<p>When you run EXPLAIN on the original query it returns this:</p>
<pre>
1 'PRIMARY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'
2 'DEPENDENT SUBQUERY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'
3 'DEPENDENT SUBQUERY' 'question_law' 'ALL' '' '' '' '' 10040 'Using where'
</pre>
<p>When you change <code>IN</code> to <code>=</code> you get this:</p>
<pre>
1 'PRIMARY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'
2 'SUBQUERY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'
3 'SUBQUERY' 'question_law' 'ALL' '' '' '' '' 10040 'Using where'
</pre>
<p>Each dependent subquery is run once per row in the query it is contained in, whereas the subquery is run only once. MySQL can sometimes optimize dependent subqueries when there is a condition that can be converted to a join but here that is not the case.</p>
<p>Now this of course leaves the question of why MySQL believes that the IN version needs to be a dependent subquery. I have made a simplified version of the query to help investigate this. I created two tables 'foo' and 'bar' where the former contains only an id column, and the latter contains both an id and a foo id (though I didn't create a foreign key constraint). Then I populated both tables with 1000 rows:</p>
<pre><code>CREATE TABLE foo (id INT PRIMARY KEY NOT NULL);
CREATE TABLE bar (id INT PRIMARY KEY, foo_id INT NOT NULL);
-- populate tables with 1000 rows in each
SELECT id
FROM foo
WHERE id IN
(
SELECT MAX(foo_id)
FROM bar
);
</code></pre>
<p>This simplified query has the same problem as before - the inner select is treated as a dependent subquery and no optimization is performed, causing the inner query to be run once per row. The query takes almost one second to run. Changing the <code>IN</code> to <code>=</code> again allows the query to run almost instantly.</p>
<p>The code I used to populate the tables is below, in case anyone wishes to reproduce the results.</p>
<pre><code>CREATE TABLE filler (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT
) ENGINE=Memory;
DELIMITER $$
CREATE PROCEDURE prc_filler(cnt INT)
BEGIN
DECLARE _cnt INT;
SET _cnt = 1;
WHILE _cnt <= cnt DO
INSERT
INTO filler
SELECT _cnt;
SET _cnt = _cnt + 1;
END WHILE;
END
$$
DELIMITER ;
CALL prc_filler(1000);
INSERT foo SELECT id FROM filler;
INSERT bar SELECT id, id FROM filler;
</code></pre> |
3,911,626 | Find cycle of shortest length in a directed graph with positive weights | <p>I was asked this question in an interview, but I couldn't come up with any decent solution. So, I told them the naive approach of finding all the cycles then picking the cycle with the least length. </p>
<p>I'm curious to know what is an efficient solution to this problem. </p> | 3,912,537 | 5 | 0 | null | 2010-10-12 04:10:49.02 UTC | 23 | 2020-12-11 16:30:49.433 UTC | 2015-08-14 17:12:35.72 UTC | null | 3,924,118 | null | 374,499 | null | 1 | 22 | algorithm|graph|dijkstra | 45,995 | <p>You can easily modify <a href="http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm" rel="noreferrer">Floyd-Warshall algorithm</a>. (If you're not familiar with graph theory at all, I suggest checking it out, e.g. getting a copy of <a href="http://en.wikipedia.org/wiki/Introduction_to_Algorithms" rel="noreferrer">Introduction to Algorithms</a>). </p>
<p>Traditionally, you start <code>path[i][i] = 0</code> for each <code>i</code>. But you can instead start from <code>path[i][i] = INFINITY</code>. It won't affect algorithm itself, as those zeroes weren't used in computation anyway (since path <code>path[i][j]</code> will never change for <code>k == i</code> or <code>k == j</code>).</p>
<p>In the end, <code>path[i][i]</code> is the length the shortest cycle going through <code>i</code>. Consequently, you need to find <code>min(path[i][i])</code> for all <code>i</code>. And if you want cycle itself (not only its length), you can do it just like it's usually done with normal paths: by memorizing <code>k</code> during execution of algorithm.</p>
<p>In addition, you can also use <a href="http://en.wikipedia.org/wiki/Dijkstra's_algorithm" rel="noreferrer">Dijkstra's algorithm</a> to find a shortest cycle going through any given node. If you run this modified Dijkstra for each node, you'll get the same result as with Floyd-Warshall. And since each Dijkstra is <code>O(n^2)</code>, you'll get the same <code>O(n^3)</code> overall complexity.</p> |
3,644,417 | python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S" | <p>I would like a python datetime object to output (and use the result in django) like this:</p>
<pre><code>Thu the 2nd at 4:30
</code></pre>
<p>But I find no way in python to output <code>st</code>, <code>nd</code>, <code>rd</code>, or <code>th</code> like I can with PHP datetime format with the <code>S</code> string (What they call "English Ordinal Suffix") (<a href="http://uk.php.net/manual/en/function.date.php" rel="noreferrer">http://uk.php.net/manual/en/function.date.php</a>).</p>
<p><strong>Is there a built-in way to do this in django/python?</strong> <code>strftime</code> isn't good enough (<a href="http://docs.python.org/library/datetime.html#strftime-strptime-behavior" rel="noreferrer">http://docs.python.org/library/datetime.html#strftime-strptime-behavior</a>).</p>
<p>Django has a filter which does what I want, but I want a function, not a filter, to do what I want. Either a django or python function will be fine.</p> | 3,644,459 | 5 | 1 | null | 2010-09-04 23:42:04.323 UTC | 5 | 2020-08-11 06:03:26 UTC | 2012-06-21 03:46:44.61 UTC | null | 875,806 | null | 10,608 | null | 1 | 28 | php|python|django|datetime|format | 26,637 | <p>The <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/dateformat.py" rel="noreferrer">django.utils.dateformat</a> has a function <code>format</code> that takes two arguments, the first one being the date (a <code>datetime.date</code> [[or <code>datetime.datetime</code>]] instance, where <code>datetime</code> is the module in Python's standard library), the second one being the format string, and returns the resulting formatted string. The uppercase-<code>S</code> format item (if part of the format string, of course) is the one that expands to the proper one of 'st', 'nd', 'rd' or 'th', depending on the day-of-month of the date in question.</p> |
3,614,925 | Remove EXIF data from JPG using PHP | <p>Is there any way to remove the EXIF data from a JPG using PHP? I have heard of PEL, but I'm hoping there's a simpler way. I am uploading images that will be displayed online and would like the EXIF data removed.</p>
<p>Thanks!</p>
<p>EDIT: I don't/can't install ImageMagick.</p> | 3,615,080 | 8 | 0 | null | 2010-09-01 03:52:52.86 UTC | 9 | 2019-11-24 04:15:25.387 UTC | 2010-09-01 04:51:58.493 UTC | null | 273,270 | null | 273,270 | null | 1 | 26 | php|image-processing|imagemagick|exif | 56,234 | <p>Use <code>gd</code> to recreate the graphical part of the image in a new one, that you save <strong><em>with another name</em></strong>.</p>
<p>See <a href="http://php.net/manual/en/book.image.php" rel="noreferrer">PHP gd</a>
<hr>
<strong>edit 2017</strong></p>
<p>Use the new Imagick feature.</p>
<p>Open Image:</p>
<pre><code><?php
$incoming_file = '/Users/John/Desktop/file_loco.jpg';
$img = new Imagick(realpath($incoming_file));
</code></pre>
<p>Be sure to keep any ICC profile in the image</p>
<pre><code> $profiles = $img->getImageProfiles("icc", true);
</code></pre>
<p>then strip image, and put the profile back if any</p>
<pre><code> $img->stripImage();
if(!empty($profiles)) {
$img->profileImage("icc", $profiles['icc']);
}
</code></pre>
<p>Comes from <a href="http://php.net/manual/en/imagick.stripimage.php" rel="noreferrer">this PHP page</a>, see comment from Max Eremin down the page.</p> |
3,903,222 | Measure execution time in C# | <p>I want to measure the execution of a piece of code and I'm wondering what the best method to do this is?</p>
<p>Option 1:</p>
<pre><code>DateTime StartTime = DateTime.Now;
//Code
TimeSpan ts = DateTime.Now.Subtract(StartTime);
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
</code></pre>
<p>Option 2:
using System.Diagnostics;</p>
<pre><code> Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//Code
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
</code></pre>
<p>This isn't simply for benchmarking, its actually part of the application. The time the function takes to execute is relevant data. It doesn't however need to be atomic or hyper-accurate.</p>
<p>Which option is better for production code, or does anybody else use something different and perhaps better?</p> | 3,903,248 | 8 | 1 | null | 2010-10-11 02:42:05.323 UTC | 9 | 2013-10-12 00:30:53.8 UTC | 2010-10-11 02:55:23.51 UTC | null | 114,029 | null | 471,333 | null | 1 | 38 | c#|datetime|execution-time|measure | 25,885 | <p>The <code>Stopwatch</code> class is specifically designed to measure elapsed time and may (if available on your hardware) provide good granularity/accuracy using an underlying high-frequency hardware timer. So this seem the best choice.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx" rel="noreferrer">IsHighResolution property</a> can be used to determine whether high resolution timing is available. Per the documentation, this class offers a wrapper on the 'best available' Win32 APIs for accurate timing:</p>
<blockquote>
<p>Specifically, the <code>Frequency</code> field and
<code>GetTimestamp</code> method can be used in
place of the unmanaged Win32 APIs
<code>QueryPerformanceFrequency</code> and
<code>QueryPerformanceCounter</code>.</p>
</blockquote>
<p>There is detailed background on those Win32 APIs [here] and in linked MSDN docs <a href="http://msdn.microsoft.com/en-us/library/ms644900(v=VS.85).aspx" rel="noreferrer">2</a>.</p>
<blockquote>
<p><strong>High-Resolution Timer</strong></p>
<p>A counter is a general term used in
programming to refer to an
incrementing variable. Some systems
include a high-resolution performance
counter that provides high-resolution
elapsed times.</p>
<p>If a high-resolution performance
counter exists on the system, you can
use the <em>QueryPerformanceFrequency</em>
function to express the frequency, in
counts per second. The value of the
count is processor dependent. On some
processors, for example, the count
might be the cycle rate of the
processor clock.</p>
<p>The <em>QueryPerformanceCounter</em> function
retrieves the current value of the
high-resolution performance counter.
By calling this function at the
beginning and end of a section of
code, an application essentially uses
the counter as a high-resolution
timer. For example, suppose that
<em>QueryPerformanceFrequency</em> indicates
that the frequency of the
high-resolution performance counter is
50,000 counts per second. If the
application calls
<em>QueryPerformanceCounter</em> immediately
before and immediately after the
section of code to be timed, the
counter values might be 1500 counts
and 3500 counts, respectively. These
values would indicate that .04 seconds
(2000 counts) elapsed while the code
executed.</p>
</blockquote> |
3,539,594 | Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate) | <p>Is there a way to make files opened for editing in the terminal open in Textedit instead? </p>
<p>For example, where a command might open a file for editing (like <code>git commit</code>), instead of opening that file in vim or emacs, it would open in Textedit (or perhaps another text editing application of your choosing, such as Coda or Sublime). </p>
<p>And as a bonus question, is there any way to specifically configure git to automatically open the file created after running <code>git commit</code> in an editor from the applications directory?</p> | 3,539,630 | 8 | 3 | null | 2010-08-22 00:30:59 UTC | 37 | 2020-08-12 20:32:21.65 UTC | 2017-07-23 14:39:20.78 UTC | null | 321,731 | null | 153,097 | null | 1 | 129 | macos|terminal|text-editor | 142,297 | <p>Most programs will check the <code>$EDITOR</code> environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.</p>
<h3>How to do this:</h3>
<ul>
<li>Add the following to your <code>~/.bashrc</code> file:<br />
<code>export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"</code></li>
<li>or just type the following command into your Terminal:<br />
<code>echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc</code></li>
</ul>
<p>If you are using zsh, use <code>~/.zshrc</code> instead of <code>~/.bashrc</code>.</p> |
3,930,181 | How to deal with Singleton along with Serialization | <p>Consider I have a Singleton class defined as follows.</p>
<pre><code>public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MySingleton(){
}
static{
myInstance =new MySingleton();
}
public static MySingleton getInstance(){
return MySingleton.myInstance;
}
}
</code></pre>
<p>The above definition according to me satisfies the requirements of a Singleton.The only additional behaviour added is that the class implements serializable interface.</p>
<p>If another class X get the instance of the single and writes it to a file and at a later point deserializes it to obtain another instance we would have two instances which is against the Singleton principle.</p>
<p>How can I avoid this or am I wrong in above definition itself.</p> | 3,930,212 | 9 | 5 | null | 2010-10-14 04:53:03.31 UTC | 19 | 2019-02-07 10:09:10.413 UTC | null | null | null | null | 314,763 | null | 1 | 42 | java|singleton | 58,789 | <p>The best way to do this is to use the enum singleton pattern:</p>
<pre><code>public enum MySingleton {
INSTANCE;
}
</code></pre>
<p>This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.</p>
<p>More generally, you can provide a <code>readResolve()</code> method like so:</p>
<pre><code>protected Object readResolve() {
return myInstance;
}
</code></pre> |
3,783,186 | How do I edit CSS in Chrome like in Firebug for Firefox? | <p>I've been editing CSS using Firebug in Firefox, but recently noticed that Chrome is rendering my pages much quicker (with scrolling, interactive elements etc) and wanted to switch to it. </p>
<p>I found Chrome shows the computed CSS and what attributes are overruled in the stack and I can alter them one-by-one but what I liked about Firebug was that I could just edit the entire stylesheet in a real-time text editor. Is this same feature somewhere in the Chrome developer panel, or is there a Chrome extension that lets me alter the stylesheets this way?</p> | 3,789,741 | 10 | 1 | null | 2010-09-23 23:20:04.593 UTC | 6 | 2014-03-03 22:58:29.657 UTC | null | null | null | null | 375,968 | null | 1 | 18 | css|google-chrome | 43,830 | <p>Try <a href="https://chrome.google.com/extensions/detail/oiaejidbmkiecgbjeifoejpgmdaleoha" rel="noreferrer">StyleBot</a>. It can also save edited CSS.</p> |
3,801,275 | How to convert image to byte array | <p>Can anybody suggest how I can convert an image to a byte array and vice versa? </p>
<p>I'm developing a WPF application and using a stream reader.</p> | 3,801,289 | 12 | 1 | null | 2010-09-27 05:17:33.707 UTC | 38 | 2022-08-01 12:08:20.903 UTC | 2019-10-24 12:19:57.91 UTC | null | 1,506,454 | null | 358,240 | null | 1 | 177 | c#|wpf | 483,094 | <p>Sample code to change an image into a byte array</p>
<pre><code>public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
</code></pre>
<p><a href="http://www.codeproject.com/KB/recipes/ImageConverter.aspx" rel="noreferrer">C# Image to Byte Array and Byte Array to Image Converter Class</a></p> |
3,905,784 | What (not) to do in a constructor | <p>I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not.</p>
<p>Should I only use it for attribute initializations, calling parent constructors etc.?
Or might I even put more complex functions into them like reading and parsing configuration data, setting up external libraries a.s.o.</p>
<p>Or should I write special functions for this? Resp. <code>init()</code> / <code>cleanup()</code>?</p>
<p>What are the PRO's and CON's here?</p>
<p>I figured out yet that for example I can get rid of shared pointers when using <code>init()</code> and <code>cleanup()</code>. I can create the objects on the stack as class attributes and initialize it later while it is already constructed.</p>
<p>If I handle it in the constructor I need to instantiate it during runtime. Then I need a pointer.</p>
<p>I really don't know how to decide.</p>
<p>Maybe you can help me out?</p> | 3,905,916 | 13 | 9 | null | 2010-10-11 11:32:35.947 UTC | 20 | 2019-03-06 17:49:14.933 UTC | 2010-10-11 11:59:26.263 UTC | null | 28,817 | null | 468,102 | null | 1 | 46 | c++|oop|constructor|shared-ptr | 14,928 | <p>Complex logic and constructor do not always mix well, and there are strong proponents against doing heavy work in a constructor (with reasons).</p>
<p>The cardinal rule is that the constructor should yield a fully usable object.</p>
<pre><code>class Vector
{
public:
Vector(): mSize(10), mData(new int[mSize]) {}
private:
size_t mSize;
int mData[];
};
</code></pre>
<p>It does not mean a fully initialized object, you may defer some initialization (think lazy) as long as the user does not have to think about it.</p>
<pre><code>class Vector
{
public:
Vector(): mSize(0), mData(0) {}
// first call to access element should grab memory
private:
size_t mSize;
int mData[];
};
</code></pre>
<p>If there is heavy work to be done, you might choose to proceed with a builder method, that will do the heavy work prior to calling the constructor. For example, imagine retrieving settings from a database and building a setting object.</p>
<pre><code>// in the constructor
Setting::Setting()
{
// connect
// retrieve settings
// close connection (wait, you used RAII right ?)
// initialize object
}
// Builder method
Setting Setting::Build()
{
// connect
// retrieve settings
Setting setting;
// initialize object
return setting;
}
</code></pre>
<p>This builder method is useful if postponing the construction of the object yields a significant benefit. From example if the objects grab a lot of memory, postponing the memory acquisition after tasks that are likely to fail may not be a bad idea.</p>
<p>This builder method implies Private constructor and Public (or friend) Builder. Note that having a Private constructor imposes a number of restrictions on the usages that can be done of a class (cannot be stored in STL containers, for example) so you might need to merge in other patterns. Which is why this method should only be used in exceptional circumstances.</p>
<p>You might wish to consider how to test such entities too, if you depend on an external thing (file / DB), think about Dependency Injection, it really helps with Unit Testing.</p> |
3,960,257 | Cannot open backup device. Operating System error 5 | <p>Below is the query that I am using to backup (create a <code>.bak</code>) my database. </p>
<p>However, whenever I run it, I always get this error message:</p>
<blockquote>
<p>Msg 3201, Level 16, State 1, Line 1<br>
Cannot open backup device 'C:\Users\Me\Desktop\Backup\MyDB.Bak'. Operating system error 5(Access is denied.).</p>
<p>Msg 3013, Level 16, State 1, Line 1<br>
BACKUP DATABASE is terminating abnormally.</p>
</blockquote>
<p>This is my query:</p>
<pre><code>BACKUP DATABASE AcinsoftDB
TO DISK = 'C:\Users\Me\Desktop\Backup\MyDB.Bak'
WITH FORMAT,
MEDIANAME = 'C_SQLServerBackups',
NAME = 'Full Backup of MyDB';
</code></pre> | 7,870,758 | 23 | 5 | null | 2010-10-18 14:40:56.92 UTC | 33 | 2022-03-23 08:28:01.21 UTC | 2020-02-14 05:31:23.517 UTC | null | 107,625 | null | 387,906 | null | 1 | 170 | sql-server-2008|backup|access-denied|permission-denied | 298,394 | <p>Yeah I just scored this one. </p>
<p>Look in Windows Services. Start > Administration > Services</p>
<p>Find the Service in the list called: SQL Server (MSSQLSERVER) look for the "Log On As" column (need to add it if it doesn't exist in the list).</p>
<p>This is the account you need to give permissions to the directory, right click in explorer > properties > Shares (And Security)</p>
<p><strong>NOTE</strong>: Remember to give permissions to the actual directory AND to the share if you are going across the network.</p>
<p>Apply and wait for the permissions to propogate, try the backup again.</p>
<p><strong>NOTE 2</strong>: if you are backing up across the network and your SQL is running as "Local Service" then you are in trouble ... you can try assigning permissions or it may be easier to backup locally and xcopy across outside of SQL Server (an hour later).</p>
<p><strong>NOTE 3</strong>: If you're running as network service then SOMETIMES the remote machine will not recognize the network serivce on your SQL Server. If this is the case you need to add permissions for the actual computer itself eg. MyServer$. </p> |
7,936,119 | Setting maximum width for content in jQuery Mobile? | <p>I have a jQuery Mobile webpage which currently has a <code>width=device-width</code> but my form elements (textfields and the submit button) stretch to the width of the browser when viewed on a desktop computer.</p>
<p>Is there any way to set a maximum width so that these elements (or the whole content div) display properly on mobile devices but don't exceed a fixed maximum width when viewed on desktop computers?</p> | 8,699,150 | 4 | 0 | null | 2011-10-29 00:18:54.997 UTC | 15 | 2017-05-24 05:53:12.383 UTC | null | null | null | null | 343,486 | null | 1 | 18 | jquery|jquery-mobile|width | 20,595 | <pre><code> <style type='text/css'>
<!--
html { background-color: #333; }
@media only screen and (min-width: 600px){
.ui-page {
width: 600px !important;
margin: 0 auto !important;
position: relative !important;
border-right: 5px #666 outset !important;
border-left: 5px #666 outset !important;
}
}
-->
</style>
</code></pre>
<p>The <code>@media only screen and (min-width: 600px)</code> restricts the CSS rule to desktop devices with a minimum window width of 600px. For these the <code>width</code> of the page container created by jQuery Mobile is fixed to 600px, <code>margin: 0 auto</code> centers the page. The rest improves the result aesthetically.</p>
<p>However, ther is one drawback: this doesn't really play well with the sliding animation. I suggest to disable the animation (maybe also depending on the media type and screen size using <code>@media</code>), because it looks just weird on a big screen anyways.</p> |
7,887,072 | How can I wait till the Parallel.ForEach completes | <p>I'm using TPL in my current project and using Parallel.Foreach to spin many threads. The Task class contains Wait() to wait till the task gets completed. Like that, how I can wait for the Parallel.ForEach to complete and then go into executing next statements?</p> | 7,887,092 | 4 | 0 | null | 2011-10-25 09:11:27.52 UTC | 8 | 2022-05-14 16:40:42.197 UTC | 2015-07-24 02:33:36.687 UTC | null | 2,063,547 | null | 741,616 | null | 1 | 145 | c#|task-parallel-library | 119,986 | <p>You don't have to do anything special, <code>Parallel.Foreach()</code> will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.</p> |
4,784,825 | How to read PDF files using Java? | <p>I want to read some text data from a PDF file using Java. How can I do that?</p> | 4,784,894 | 3 | 0 | null | 2011-01-24 17:10:05.28 UTC | 21 | 2021-12-25 16:42:30 UTC | 2019-09-27 07:49:28.983 UTC | null | 1,788,806 | null | 441,628 | null | 1 | 80 | java|pdf | 230,756 | <p><a href="http://pdfbox.apache.org">PDFBox</a> is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found <a href="http://pdfbox.apache.org/1.8/cookbook/textextraction.html">here</a>.</p>
<p>It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are <strong>both</strong> inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!</p>
<p><a href="http://itextpdf.com">Itext</a> is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.</p> |
4,611,190 | Passing variables in jquery | <p>What is the best way to pass the var full to function b. I don't want to use global variables. Is return the only option. </p>
<pre><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<style>
.aaa, .bbb, .ccc { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
</style>
<body class="123">
<p id="ptest"></p>
<p class="aaa" id="aaaid"></p>
<p class="bbb" id="bbbid"></p>
<p class="ccc" id="cccid"></p>
<div></div>
</body>
<script type="text/javascript">
$("body").click(function(e){
var name = $(e.target)[0].nodeName;
var nameid = $(e.target)[0].id;
var classname = $(name+"#"+nameid).attr('class');
var full = name+"#"+nameid;
console.log(nameid);
function b(){
alert(full);
};
});
</script>
</code></pre> | 4,611,215 | 4 | 1 | null | 2011-01-06 02:16:42.22 UTC | null | 2011-01-06 02:34:43.253 UTC | 2011-01-06 02:20:21.687 UTC | null | 166,938 | null | 560,735 | null | 1 | 1 | jquery|variables | 61,695 | <p>You can pass a variable to a function by defining it as follows:</p>
<pre><code>function b(x) {
alert(x);
}
</code></pre>
<p>and then calling it by stating its name and passing a variable as the argument:</p>
<pre><code>b(full);
</code></pre>
<p>So in the context of your code:</p>
<pre><code>$("body").click(function(e){
var name = $(e.target)[0].nodeName;
var nameid = $(e.target)[0].id;
var classname = $(name+"#"+nameid).attr('class');
var full = name+"#"+nameid;
console.log(nameid);
function b(x){
alert(x);
};
b(full);
});
</code></pre> |
4,291,545 | How to properly put JSPs in the WEB-INF folder? | <p>My question is how to put all the JSP files in <code>WEB-INF/JSP/</code> in the proper manner?</p>
<p>Is there any configuration for this as the structure I'm aware of is:</p>
<pre><code>WEB-INF / JSP --> all jsp is reside in that folder
/ CLASSES -- all classes is reside that folder
/ LIB --> library file reside in that folder
</code></pre>
<p>How do I set this up properly according to the spec. Please help me with an answer for this. </p> | 4,291,588 | 4 | 0 | null | 2010-11-27 12:03:34.713 UTC | 9 | 2019-02-23 17:08:09.47 UTC | 2019-02-23 17:08:09.47 UTC | null | 9,129,885 | null | 549,698 | null | 1 | 10 | java|jsp|servlets|jakarta-ee|web-applications | 30,616 | <p>Its not a standard practice or valid as per the J2EE spec (I know using most of the java Web development frameworks like Struts, Spring MVC, Stripes you can do this). As per the spec, all our publicly accessibly pages should be out side of <code>WEB-INF</code>. But if you want the pages to be in <code>web-inf</code>, what you can do is to create a servlet along the lines of a controller servlet and forward the requests to jsp pages from your servlet and those pages can be in <code>WEB-INF</code>, and there is no special configuration that can be done to do this.</p> |
4,434,327 | Same-named attributes in attrs.xml for custom view | <p>I'm writing a few custom views which share some same-named attributes. In their respective <code><declare-styleable></code> section in <code>attrs.xml</code> I'd like to use the same names for attributes:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView1">
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
...
</declare-styleable>
<declare-styleable name="MyView2">
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
...
</declare-styleable>
</resources>
</code></pre>
<p>I'm getting an error saying that <code>myattr1</code> and <code>myattr2</code> are already defined. I found that I should omit the <code>format</code> attribute for <code>myattr1</code> and <code>myattr2</code> in <code>MyView2</code>, but if I do that, I obtain the following error in the console:</p>
<pre><code>[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute
</code></pre>
<p>Is there a way I could accomplish this, maybe some sort of namespacing (just guessing)?</p> | 4,464,966 | 5 | 0 | null | 2010-12-13 22:58:41.26 UTC | 24 | 2018-09-28 19:01:07.447 UTC | 2017-02-18 08:06:38.29 UTC | null | 3,681,880 | null | 247,095 | null | 1 | 215 | android|android-view|android-custom-view|android-custom-attributes | 45,427 | <p><strong>Solution:</strong> Simply extract common attributes from both views and add them directly as children of the <code><resources></code> node:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
<declare-styleable name="MyView1">
<attr name="myattr1" />
<attr name="myattr2" />
...
</declare-styleable>
<declare-styleable name="MyView2">
<attr name="myattr1" />
<attr name="myattr2" />
...
</declare-styleable>
</resources>
</code></pre> |
4,192,227 | How can I do 'if..else' inside a for-comprehension? | <p>I am asking a very basic question which confused me recently.
I want to write a Scala For expression to do something like the following:</p>
<pre><code>for (i <- expr1) {
if (i.method) {
for (j <- i) {
if (j.method) {
doSomething()
} else {
doSomethingElseA()
}
}
} else {
doSomethingElseB()
}
}
</code></pre>
<p>The problem is that, in the multiple generators For expression, I don't know where can I put each for expression body.</p>
<pre><code>for {i <- expr1
if(i.method) // where can I write the else logic ?
j <- i
if (j.method)
} doSomething()
</code></pre>
<p>How can I rewrite the code in Scala Style?</p> | 4,197,092 | 6 | 4 | null | 2010-11-16 08:22:04.14 UTC | 14 | 2012-11-13 07:48:17.287 UTC | 2012-11-13 07:48:17.287 UTC | null | 464,309 | null | 241,824 | null | 1 | 25 | scala|for-comprehension | 32,161 | <p>The first code you wrote is perfectly valid, so there's no need to rewrite it. Elsewhere you said you wanted to know how to do it Scala-style. There isn't really a "Scala-style", but I'll assume a more functional style and tack that.</p>
<pre><code>for (i <- expr1) {
if (i.method) {
for (j <- i) {
if (j.method) {
doSomething()
} else {
doSomethingElseA()
}
}
} else {
doSomethingElseB()
}
}
</code></pre>
<p>The first concern is that this returns no value. All it does is side effects, which are to be avoided as well. So the first change would be like this:</p>
<pre><code>val result = for (i <- expr1) yield {
if (i.method) {
for (j <- i) yield {
if (j.method) {
returnSomething()
// etc
</code></pre>
<p>Now, there's a big difference between</p>
<pre><code>for (i <- expr1; j <- i) yield ...
</code></pre>
<p>and</p>
<pre><code>for (i <- expr1) yield for (j <- i) yield ...
</code></pre>
<p>They return different things, and there are times you want the later, not the former. I'll assume you want the former, though. Now, before we proceed, let's fix the code. It is ugly, difficult to follow and uninformative. Let's refactor it by extracting methods.</p>
<pre><code>def resultOrB(j) = if (j.method) returnSomething else returnSomethingElseB
def nonCResults(i) = for (j <- i) yield resultOrB(j)
def resultOrC(i) = if (i.method) nonCResults(i) else returnSomethingC
val result = for (i <- expr1) yield resultOrC(i)
</code></pre>
<p>It is already much cleaner, but it isn't returning quite what we expect. Let's look at the difference:</p>
<pre><code>trait Element
object Unrecognized extends Element
case class Letter(c: Char) extends Element
case class Punct(c: Char) extends Element
val expr1 = "This is a silly example." split "\\b"
def wordOrPunct(j: Char) = if (j.isLetter) Letter(j.toLower) else Punct(j)
def validElements(i: String) = for (j <- i) yield wordOrPunct(j)
def classifyElements(i: String) = if (i.nonEmpty) validElements(i) else Unrecognized
val result = for (i <- expr1) yield classifyElements(i)
</code></pre>
<p>The type of <code>result</code> there is <code>Array[AnyRef]</code>, while using multiple generators would yield <code>Array[Element]</code>. The easy part of the fix is this:</p>
<pre><code>val result = for {
i <- expr1
element <- classifyElements(i)
} yield element
</code></pre>
<p>But that alone won't work, because classifyElements itself returns <code>AnyRef</code>, and we want it returning a collection. Now, <code>validElements</code> return a collection, so that is not a problem. We only need to fix the <code>else</code> part. Since <code>validElements</code> is returning an <code>IndexedSeq</code>, let's return that on the <code>else</code> part as well. The final result is:</p>
<pre><code>trait Element
object Unrecognized extends Element
case class Letter(c: Char) extends Element
case class Punct(c: Char) extends Element
val expr1 = "This is a silly example." split "\\b"
def wordOrPunct(j: Char) = if (j.isLetter) Letter(j.toLower) else Punct(j)
def validElements(i: String) = for (j <- i) yield wordOrPunct(j)
def classifyElements(i: String) = if (i.nonEmpty) validElements(i) else IndexedSeq(Unrecognized)
val result = for {
i <- expr1
element <- classifyElements(i)
} yield element
</code></pre>
<p>That does exactly the same combination of loops and conditions as you presented, but it is much more readable and easy to change.</p>
<p><strong>About Yield</strong></p>
<p>I think it is important to note one thing about the problem presented. Let's simplify it:</p>
<pre><code>for (i <- expr1) {
for (j <- i) {
doSomething
}
}
</code></pre>
<p>Now, that is implemented with <code>foreach</code> (see <a href="https://stackoverflow.com/questions/3754089/scala-for-comprehension/3754568#3754568">here</a>, or other similar questions and answer). That means the code above does exactly the same thing as this code:</p>
<pre><code>for {
i <- expr1
j <- i
} doSomething
</code></pre>
<p>Exactly the same thing. That is not true at all when one is using <code>yield</code>. The following expressions do not yield the same result:</p>
<pre><code>for (i <- expr1) yield for (j <- i) yield j
for (i <- expr1; j <- i) yield j
</code></pre>
<p>The first snippet will be implemented through two <code>map</code> calls, while the second snippet will use one <code>flatMap</code> and one <code>map</code>.</p>
<p>So, it is only in the context of <code>yield</code> that it even makes any sense to worry about nesting <code>for</code> loops or using multiple generators. And, in fact, <em>generators</em> stands for the fact that something is being <em>generated</em>, which is only true of true for-comprehensions (the ones <code>yield</code>ing something).</p> |
4,556,910 | How do I get regex support in Excel via a function, or custom function? | <p>It appears that regex (as in regular expressions) is not supported in Excel, except via VBA. Is this so, and if it is, are there any "open source" custom VBA functions that support regex? In this case I'm looking to extract complex pattern within a string, and any implementation of a custom VBA function that expose support of regex within the function itself would be of use. If you know of semi-related function such as the <a href="http://office.microsoft.com/en-us/excel-help/is-functions-HP005209147.aspx" rel="nofollow noreferrer">IS</a> function, feel free to comment, though I'm really looking for a full regular expression implementation that is exposed via functions.</p>
<p>Also, just a heads up that I'm using Office 2010 on Windows 7; added this info after an answer that appears to be a great suggestion turned out not to work on Office 2010.</p> | 4,557,079 | 6 | 2 | null | 2010-12-29 18:51:06.53 UTC | 18 | 2021-08-27 21:11:56.383 UTC | 2021-03-04 20:53:58.51 UTC | null | 2,753,501 | null | 471,255 | null | 1 | 26 | regex|excel|vba | 54,474 | <p>Nothing built into Excel. VBScript has built-in support and can be called from VBA. More info <a href="http://www.regular-expressions.info/vbscript.html" rel="noreferrer" title="VBScript RegExp Object">available here</a>. You can call the object using late binding in VBA. I've included a few functions that I put together recently. Please note that these are not well-tested and may have some bugs, but they are pretty straightforward.</p>
<p>This should at least get you started:</p>
<pre><code>'---------------------------------------------------------------------------------------vv
' Procedure : RegEx
' Author : Mike
' Date : 9/1/2010
' Purpose : Perform a regular expression search on a string and return the first match
' or the null string if no matches are found.
' Usage : If Len(RegEx("\d{1,2}[/-]\d{1,2}[/-]\d{2,4}", txt)) = 0 Then MsgBox "No date in " & txt
' : TheDate = RegEx("\d{1,2}[/-]\d{1,2}[/-]\d{2,4}", txt)
' : CUSIP = Regex("[A-Za-z0-9]{8}[0-9]",txt)
'---------------------------------------------------------------------------------------
'^^
Function RegEx(Pattern As String, TextToSearch As String) As String 'vv
Dim RE As Object, REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
.Global = False
.IgnoreCase = False
.Pattern = Pattern
End With
Set REMatches = RE.Execute(TextToSearch)
If REMatches.Count > 0 Then
RegEx = REMatches(0)
Else
RegEx = vbNullString
End If
End Function '^^
'---------------------------------------------------------------------------------------
' Procedure : RegExReplace
' Author : Mike
' Date : 11/4/2010
' Purpose : Attempts to replace text in the TextToSearch with text and back references
' from the ReplacePattern for any matches found using SearchPattern.
' Notes - If no matches are found, TextToSearch is returned unaltered. To get
' specific info from a string, use RegExExtract instead.
' Usage : ?RegExReplace("(.*)(\d{3})[\)\s.-](\d{3})[\s.-](\d{4})(.*)", "My phone # is 570.555.1234.", "$1($2)$3-$4$5")
' My phone # is (570)555-1234.
'---------------------------------------------------------------------------------------
'
Function RegExReplace(SearchPattern As String, TextToSearch As String, ReplacePattern As String, _
Optional GlobalReplace As Boolean = True, _
Optional IgnoreCase As Boolean = False, _
Optional MultiLine As Boolean = False) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = MultiLine
.Global = GlobalReplace
.IgnoreCase = IgnoreCase
.Pattern = SearchPattern
End With
RegExReplace = RE.Replace(TextToSearch, ReplacePattern)
End Function
'---------------------------------------------------------------------------------------
' Procedure : RegExExtract
' Author : Mike
' Date : 11/4/2010
' Purpose : Extracts specific information from a string. Returns empty string if not found.
' Usage : ?RegExExtract("(.*)(\d{3})[\)\s.-](\d{3})[\s.-](\d{4})(.*)", "My phone # is 570.555.1234.", "$2$3$4")
' 5705551234
' ?RegExExtract("(.*)(\d{3})[\)\s.-](\d{3})[\s.-](\d{4})(.*)", "My name is Mike.", "$2$3$4")
'
' ?RegExReplace("(.*)(\d{3})[\)\s.-](\d{3})[\s.-](\d{4})(.*)", "My name is Mike.", "$2$3$4")
' My name is Mike.
'---------------------------------------------------------------------------------------
'
Function RegExExtract(SearchPattern As String, TextToSearch As String, PatternToExtract As String, _
Optional GlobalReplace As Boolean = True, _
Optional IgnoreCase As Boolean = False, _
Optional MultiLine As Boolean = False) As String
Dim MatchFound As Boolean
MatchFound = Len(RegEx(SearchPattern, TextToSearch)) > 0
If MatchFound Then
RegExExtract = RegExReplace(SearchPattern, TextToSearch, PatternToExtract, _
GlobalReplace, IgnoreCase, MultiLine)
Else
RegExExtract = vbNullString
End If
End Function
</code></pre> |
4,140,727 | Why code-as-data? | <p>What is code-as-data? I've heard it's superior to "code-as-ascii-characters" but why? I personally find the code-as-data philosophy a bit confusing actually.</p>
<p>I've dabbled in Scheme, but I never really got the whole code-as-data thing and wondered what exactly does it mean?</p> | 4,140,815 | 6 | 2 | null | 2010-11-10 02:33:44.25 UTC | 14 | 2010-11-11 17:54:01.203 UTC | 2010-11-10 07:31:16.527 UTC | null | 133,520 | null | 470,535 | null | 1 | 46 | data-structures|coding-style|lisp|scheme|common-lisp | 11,076 | <p>It means that your program code you write is also data which can be manipulated by a program. Take a simple Scheme expression like</p>
<pre><code>(+ 3 (* 6 7))
</code></pre>
<p>You can regard it as a mathematical expression which when evaluated yields a value. But it is also a list containing three elements, namely <code>+</code>, <code>3</code> and <code>(* 6 7)</code>. By <em>quoting</em> the list,</p>
<pre><code> '(+ 3 (* 6 7))
</code></pre>
<p>You tell scheme to regard it as the latter, namely just a list containing three elements. Thus, you can manipulate this list with a program and <em>then</em> evaluate it. The power it gives you is tremendous, and when you "get" the idea, there are some very cool tricks to be played.</p> |
4,764,680 | How to get the location of the DLL currently executing? | <p>I have a config file that I need to load as part of the execution of a dll I am writing.</p>
<p>The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.</p>
<p>For example, I put the dll and xml file here:</p>
<blockquote>
<p>D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins</p>
</blockquote>
<p>But if I try to reference the xml file (in my dll) like this:</p>
<pre><code>XDocument doc = XDocument.Load(@".\AggregatorItems.xml")
</code></pre>
<p>then <strong>.\AggregatorItems.xml</strong> translates to:</p>
<blockquote>
<p>C:\windows\system32\inetsrv\AggregatorItems.xml</p>
</blockquote>
<p>So, I need to find a way (I hope) of knowing where the dll that is currently executing is located. Basically I am looking for this:</p>
<pre><code>XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
</code></pre> | 4,764,701 | 6 | 0 | null | 2011-01-21 22:52:56.217 UTC | 13 | 2022-07-29 09:15:04.463 UTC | null | null | null | null | 16,241 | null | 1 | 108 | c#|.net|dll|file-io | 124,499 | <p>You are looking for <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx" rel="noreferrer"><code>System.Reflection.Assembly.GetExecutingAssembly()</code></a></p>
<pre><code>string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
</code></pre>
<p><strong>Note:</strong></p>
<p>The <code>.Location</code> property returns the location of the currently running DLL file.</p>
<p>Under some conditions the DLL is shadow copied before execution, and the <code>.Location</code> property will return the path of the copy. If you want the path of the original DLL, use the <code>Assembly.GetExecutingAssembly().CodeBase</code> property instead.</p>
<p><code>.CodeBase</code> contains a prefix (<code>file:\</code>), which you may need to remove.</p> |
4,084,975 | jquery confirm password validation | <p>I am using jquery for form validation. Rest is well except the confirm password field. Even when the same password is typed, the <strong>Please enter the same password.</strong> is not removed.</p>
<p>My script is:</p>
<pre><code> <script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
password: {
required: true, minlength: 5
},
c_password: {
required: true, equalTo: "#password", minlength: 5
},
email: {
required: true, email: true
},
phone: {
required: true, number: true, minlength: 7
},
url: {
url: true
},
description: {
required: true
},
gender: {
required: true
}
},
messages: {
description: "Please enter a short description.",
gender: "Please select your gender."
}
});
});
-->
</script>
</code></pre>
<p>And inside the form tag:</p>
<pre><code><div class="form-row"><span class="label">Password</span><input type="password" name="password" class="required" id="password" /></div>
<div class="form-row"><span class="label">Confirm Password</span><input type="password" name="c_password" id="c_password" /></div>
</code></pre>
<p>Any suggestion?
Would be much thankful for the help.</p> | 4,085,615 | 7 | 0 | null | 2010-11-03 07:34:53.4 UTC | 12 | 2014-05-04 12:22:05.28 UTC | 2014-05-04 12:22:05.28 UTC | null | 437,917 | null | 437,917 | null | 1 | 27 | javascript|jquery|jquery-validate | 61,846 | <p>Your fields doesn't have the ID property.
In jQuery the "#password" selector means "the object that has an <code>id</code> property with value <code>'password'</code>"</p>
<p>Your code should look like this:</p>
<pre><code><input type="password" name="password" id="password" class="required"/>
</code></pre> |
4,366,730 | How do I check if a string contains a specific word? | <p>Consider:</p>
<pre><code>$a = 'How are you?';
if ($a contains 'are')
echo 'true';
</code></pre>
<p>Suppose I have the code above, what is the correct way to write the statement <code>if ($a contains 'are')</code>?</p> | 4,366,748 | 36 | 0 | 2018-05-04 06:13:24.457 UTC | 2010-12-06 13:14:05.093 UTC | 695 | 2022-08-26 14:55:14.15 UTC | 2018-05-01 10:30:52.12 UTC | user3205578 | 1,946,501 | null | 495,452 | null | 1 | 2,658 | php|string|substring|contains|string-matching | 6,262,989 | <p><strong>Now with PHP 8 you can do this using <a href="https://www.php.net/manual/en/function.str-contains" rel="noreferrer">str_contains</a>:</strong></p>
<pre><code>if (str_contains('How are you', 'are')) {
echo 'true';
}
</code></pre>
<p><a href="https://wiki.php.net/rfc/str_contains" rel="noreferrer">RFC</a></p>
<p><strong>Before PHP 8</strong></p>
<p>You can use the <a href="http://php.net/manual/en/function.strpos.php" rel="noreferrer"><code>strpos()</code></a> function which is used to find the occurrence of one string inside another one:</p>
<pre><code>$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
</code></pre>
<p>Note that the use of <code>!== false</code> is deliberate (neither <code>!= false</code> nor <code>=== true</code> will return the desired result); <code>strpos()</code> returns either the offset at which the needle string begins in the haystack string, or the boolean <code>false</code> if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like <code>!strpos($a, 'are')</code>.</p> |
14,371,817 | ambiguity between variables in C# | <p>I want to start by saying I did search first, and found a lot of similar issues on various other things, but not this problem exactly.</p>
<p>I have this code:</p>
<pre><code>namespace New_Game.GameClasses
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Error : Microsoft.Xna.Framework.GameComponent
{
bool gameOver = false;
List<Enemy> enemies = new List<Enemy>();
public bool gameOver {
get { return gameOver; }
set { gameOver = value; }
}
public override void Update(GameTime gameTime, Vector2 target)
{
// TODO: Add your update code here
Rectangle playerRect = new Rectangle((int)target.X, (int)target.Y, 64, 64);
foreach (Enemy e in enemies)
{
e.Target = target;
e.Update(gameTime);
Rectangle enemyRect = new Rectangle((int)e.Position.X + 7, (int)e.Position.Y + 7, 32 - 7, 32 - 7);
if (playerRect.Intersects(enemyRect))
{
gameOver = true;
}
}
}
}
}
</code></pre>
<p>My problem comes in an error saying this: Ambiguity between 'New_Game.GameClasses.Error.gameOver' and 'New_Game.GameClasses.Error.gameOver'</p>
<p>If I remove the get/set method, I run into a different error when I try and access gameOver from my Game1.cs. If I change it to the following I get the same error:</p>
<pre><code>public bool gameOver { get; set; }
</code></pre>
<p>My question, is how do I resolve the ambiguity errors?</p> | 14,371,840 | 4 | 0 | null | 2013-01-17 03:33:06.67 UTC | 3 | 2020-06-11 14:14:04.497 UTC | null | null | null | null | 1,985,823 | null | 1 | 13 | c# | 76,985 | <p>You need to rename your private gameOver variable. Change this:</p>
<pre><code>bool gameOver = false;
public bool GameOver {
get { return gameOver; }
set { gameOver = value; }
}
</code></pre>
<p>to</p>
<pre><code>bool _gameOver = false;
public bool GameOver {
get { return _gameOver; }
set { _gameOver = value; }
}
</code></pre>
<p>You can't use the same variable name in a single class. </p>
<p>Alternatively, assuming you're using a recent version of .Net, you could remove your private variable and just have:</p>
<pre><code>public bool GameOver { get; set; }
</code></pre>
<p>Good luck.</p> |
14,851,064 | Why does Magento keep only the first 1000 products in a category, after saving the category? | <p>Using Magento's back-office, after saving a category which was linked to many products, only the first 1000 products (or 2000, or x000, depending on host configuration) are kept.</p>
<p>All other category/product links are deleted from the <code>catalog_category_product</code> table in the database.<br>
This occurs even though no checkboxes have been unchecked in the products grid (Category Products tab).</p>
<p>No error message is displayed or logged.<br>
Tracing data posted from the browser to the server doesn't reveal any missing product IDs, but even if you check more products on the back-office grid, when finally saving the category, the server only keeps the first x000 and removes other IDs...</p> | 14,851,065 | 6 | 0 | null | 2013-02-13 10:11:41.34 UTC | 10 | 2021-03-02 06:53:03.76 UTC | null | null | null | null | 1,632,561 | null | 1 | 18 | php|magento|magento-1.7 | 11,274 | <p>Though some answers can be found on other websites, I thought it was worth sharing this on StackOverflow...</p>
<p>The source of the problem can be found in <code>Mage_Adminhtml_Catalog_CategoryController</code>, where the <code>saveAction()</code> method retrieves a big POSTed string (<code>category_products</code>, encoded like a query string), which is processed by PHP function <code>parse_str()</code>:</p>
<pre><code>if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
}
</code></pre>
<p>Alas! As from version 5.3.9 of PHP, there is a new configuration setting called <code>max_input_vars</code>, which limits the number of input variables that may be accepted.<br>
This limit is mainly applied to <code>$_GET</code>, <code>$_POST</code> and <code>$_COOKIE</code> superglobals, but is also used internally by the <code>parse_str()</code> function!<br>
(See <a href="http://www.php.net/manual/en/info.configuration.php#ini.max-input-var" rel="noreferrer">PHP manual</a>)</p>
<p>Depending on the <code>php.ini</code> configuration of your host, the number of products linked to a category is therefore limited by this setting...</p>
<p><strong>One solution</strong> is to increase the value of <code>max_input_vars</code>, in <code>php.ini</code> or in <code>.htaccess</code>:</p>
<pre><code><IfModule mod_php5.c>
php_value max_input_vars 10000
</IfModule>
</code></pre>
<p>This can even be done more safely by changing this setting only for admin pages (adapt the LocationMatch pattern to your own back-office URL style):</p>
<pre><code><LocationMatch "mymagentostore/(index\.php/)?admin/">
<IfModule mod_php5.c>
php_value max_input_vars 10000
</IfModule>
</LocationMatch>
</code></pre>
<p>(<a href="http://www.magentocommerce.com/boards/viewreply/405627/" rel="noreferrer">Source</a>)</p>
<p>This only solves the problem until one of your categories reaches the new max number of products... </p>
<p><strong>Another solution</strong> would be to fix Magento's code in order <em>not</em> to use the parse_str() function at this point.<br>
For instance, in <code>Mage_Adminhtml_Catalog_CategoryController</code>, <code>saveAction()</code> method, replace:</p>
<pre><code>parse_str($data['category_products'], $products);
</code></pre>
<p>with:</p>
<pre><code>$cat_products_split = explode('&', $data['category_products']);
foreach($cat_products_split as $row) {
$arr = array();
parse_str($row, $arr); //This will always work
list($k, $v) = each($arr);
if (!empty($k) && !empty($v)) {
$products[$k] = $v;
}
}
</code></pre>
<p>(<a href="https://gist.github.com/mshmsh5000/3440260" rel="noreferrer">Source</a>)</p>
<p>It's hard to decide which solution is the best, since the first one makes your server more vulnerable to attacks (as the <code>max_input_vars</code> is meant to mitigate the possibility of denial of service attacks which use hash collisions), and the second solution makes you modify a Magento core class, which can lead to further problems in future Magento upgrades...</p>
<p>Hope this is useful anyway, I struggled some time before I could find out why some categories kept loosing some products!</p> |
14,374,181 | Moving back an iteration in a for loop | <p>So I want to do something like this:</p>
<pre><code>for i in range(5):
print(i);
if(condition==true):
i=i-1;
</code></pre>
<p>However, for whatever reason, even though I'm decrementing i, the loop doesn't seem to notice. Is there any way to repeat an iteration?</p> | 14,374,229 | 8 | 2 | null | 2013-01-17 07:34:26.713 UTC | 7 | 2019-05-13 18:54:40.96 UTC | null | null | null | null | 788,067 | null | 1 | 32 | python|for-loop | 37,464 | <p><code>for</code> loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as <code>while</code>:</p>
<pre><code>i = 0
while i < 5:
print(i)
if condition:
i=i-1
i += 1
</code></pre>
<p>Or even better:</p>
<pre><code>i = 0
while i < 5:
print(i)
if condition:
do_something()
# don't increment here, so we stay on the same value for i
else:
# only increment in the case where we're not "moving backwards"
i += 1
</code></pre> |
14,538,899 | Null values of Strings and Integers in Java | <pre><code>public class Test {
public static void main(String[] args) {
String s = null;
String s1 = null;
Integer i = null;
Integer i1 = null;
System.out.println(s+i);
System.out.println(i+s);
System.out.println(s+s1);
try {
System.out.println(i+i1);
} catch (NullPointerException np) {
System.out.print("NullPointerException");
}
}
}
</code></pre>
<p>The question is simple - why do I receive a <code>NullPointerException</code> only at the last line?</p> | 14,538,989 | 6 | 2 | null | 2013-01-26 16:24:31.043 UTC | 3 | 2013-02-01 17:51:26.033 UTC | 2013-01-27 07:43:25.53 UTC | null | 367,273 | null | 1,306,025 | null | 1 | 49 | java|string|nullpointerexception|addition|autoboxing | 8,520 | <p>Your code makes use of two different <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18" rel="noreferrer">additive operators</a>. The first three lines use <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1" rel="noreferrer">string concatenation</a>, whereas the last one uses <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2" rel="noreferrer">numeric addition</a>.</p>
<p>String concatenation is <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.11" rel="noreferrer">well-defined to turn <code>null</code> into <code>"null"</code></a>:</p>
<blockquote>
<ul>
<li>If the reference is <code>null</code>, it is converted to the string <code>"null"</code> (four ASCII characters <code>n</code>, <code>u</code>, <code>l</code>, <code>l</code>).</li>
</ul>
</blockquote>
<p>Hence there is no NPE.</p>
<p>Adding two <code>Integer</code> objects together requires them to be <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.8" rel="noreferrer">unboxed</a>. This results in the <code>null</code> reference being dereferenced, which leads to the NPE:</p>
<blockquote>
<ul>
<li>If <code>r</code> is null, unboxing conversion throws a <code>NullPointerException</code></li>
</ul>
</blockquote> |
14,898,768 | How to access nested elements of json object using getJSONArray method | <p>I have a JSON response that looks like this: </p>
<pre><code>{
"result": {
"map": {
"entry": [
{
"key": { "@xsi.type": "xs:string", "$": "ContentA" },
"value": "fsdf"
},
{
"key": { "@xsi.type": "xs:string", "$": "ContentB" },
"value": "dfdf"
}
]
}
}
}
</code></pre>
<p>I want to access the value of the <code>"entry"</code> array object. I am trying to access:</p>
<pre><code>RESPONSE_JSON_OBJECT.getJSONArray("entry");
</code></pre>
<p>I am getting <code>JSONException</code>. Can someone please help me get the JSON array from the above JSON response?</p> | 14,899,024 | 7 | 3 | null | 2013-02-15 16:15:09.653 UTC | 25 | 2018-05-29 22:42:07.707 UTC | 2018-05-29 22:41:23.36 UTC | null | 5,007,059 | null | 2,017,131 | null | 1 | 65 | java|json|arrays | 171,870 | <p>You have to decompose the full object to reach the <code>entry</code> array. </p>
<p>Assuming <code>REPONSE_JSON_OBJECT</code> is already a parsed <code>JSONObject</code>. </p>
<pre><code>REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
</code></pre> |
14,798,640 | creating a random number using MYSQL | <p>I would like to know is there a way to select randomly generated number between 100 and 500 along with a select query. </p>
<p>Eg: <code>SELECT name, address, random_number FROM users</code></p>
<p>I dont have to store this number in db and only to use it to display purpose. </p>
<p>I tried it something like this, but it can't get to work..</p>
<pre><code>SELECT name, address, FLOOR(RAND() * 500) AS random_number FROM users
</code></pre>
<p>Hope someone help me out.
Thank you</p> | 14,798,686 | 6 | 1 | null | 2013-02-10 14:16:27.82 UTC | 30 | 2018-11-01 11:43:47.66 UTC | null | null | null | null | 1,942,155 | null | 1 | 103 | mysql|sql | 125,096 | <p>This should give what you want:</p>
<pre><code>FLOOR(RAND() * 401) + 100
</code></pre>
<p>Generically, <code>FLOOR(RAND() * (<max> - <min> + 1)) + <min></code> generates a number between <code><min</code>> and <code><max></code> inclusive.</p>
<p><strong>Update</strong></p>
<p>This full statement should work:</p>
<pre><code>SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number`
FROM users
</code></pre> |
14,787,580 | Object reference not set to an instance of an object.Why doesn't .NET show which object is `null`? | <p>Regarding this .NET unhandled exception message:</p>
<blockquote>
<p>Object reference not set to an instance of an object.</p>
</blockquote>
<p>Why doesn't .NET show which object is <code>null</code>?</p>
<p>I know that I can check for <code>null</code> and resolve the error. However, why doesn't .NET help pointing out which object has a null-reference and which expression triggered the <code>NullReferenceException</code>?</p> | 14,787,852 | 5 | 19 | null | 2013-02-09 11:22:17.973 UTC | 18 | 2018-02-07 05:48:29.203 UTC | 2013-05-21 19:16:18.453 UTC | user1968030 | null | user1968030 | null | null | 1 | 105 | c#|.net | 36,719 | <p>(For information about the new exception helper in Visual Studio 2017 see the end of this answer)</p>
<hr>
<p>Consider this code:</p>
<pre><code>String s = null;
Console.WriteLine(s.Length);
</code></pre>
<p>This will throw a <code>NullReferenceException</code> in the second line and you want to know why .NET doesn't tell you that it was <code>s</code> that was null when the exception was thrown.</p>
<p>To understand why you don't get that piece of information you should remember that it is not C# source that executes but rather IL:</p>
<pre>
IL_0001: ldnull
IL_0002: stloc.0 // s
IL_0003: ldloc.0 // s
IL_0004: callvirt System.String.get_Length
IL_0009: call System.Console.WriteLine
</pre>
<p>It is the <code>callvirt</code> opcode that throws the <code>NullReferenceException</code> and it does that when the first argument on the evaluation stack is a null reference (the one that was loaded using <code>ldloc.0</code>).</p>
<p>If .NET should be able to tell that it was <code>s</code> that was a null reference it should in some way track that the first argument on the evaluation stack originated form <code>s</code>. In this case it is easy for us to see that it is <code>s</code> that was null but what if the value was a return value from another function call and not stored in any variable? Anyway, this kind of information is not what you want to keep track of in a virtual machine like the .NET virtual machine.</p>
<hr>
<p>To avoid this problem I suggest that you perform argument null checking in all public method calls (unless of course you allow the null reference):</p>
<pre><code>public void Foo(String s) {
if (s == null)
throw new ArgumentNullException("s");
Console.WriteLine(s.Length);
}
</code></pre>
<p>If null is passed to the method you get an exception that precisely describes what the problem is (that <code>s</code> is null).</p>
<hr>
<p>Four years later Visual Studio 2017 now has a new exception helper that will try to tell what is null when a <code>NullReferenceException</code> is thrown. It is even able to give you the required information when it is the return value of a method that is null:</p>
<p><a href="https://i.stack.imgur.com/Mv5gE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mv5gE.png" alt="Visual Studio 2017 exception helper"></a></p>
<p>Note that this only works in a DEBUG build.</p> |
14,836,053 | How can I change the cache path for npm (or completely disable the cache) on Windows? | <p>I've installed Node.js on my Windows 7 x64 development machine, the manual way:</p>
<pre class="lang-none prettyprint-override"><code>mkdir C:\Devel\nodejs
cd C:\Devel\nodejs
set NODE_PATH=%CD%
setx /M PATH "%PATH%;%NODE_PATH%"
setx /M NODE_PATH "%NODE_PATH%\node_modules"
</code></pre>
<p>I've placed the main <a href="http://nodejs.org/dist/latest/x64/" rel="noreferrer">node x64 binary</a> along with <a href="http://nodejs.org/dist/npm/" rel="noreferrer">npm package manager</a> in <code>C:\Devel\nodejs</code>. Works like a charm and I can update the main binary without dealing with the installer.</p>
<p>The only problem I can't solve is moving the cache folder. When I install a local package:</p>
<pre class="lang-none prettyprint-override"><code>npm install express
</code></pre>
<p>... cache is placed under <code>%APP_DATA%\npm-cache</code> folder. I'd like to change it to:</p>
<p><code>C:\Devel\nodejs\npm-cache</code></p>
<p>How can I change the npm cache folder, or disable it completely?</p> | 14,841,880 | 6 | 1 | null | 2013-02-12 15:34:51.33 UTC | 36 | 2022-08-17 15:04:55.907 UTC | null | null | null | null | 220,180 | null | 1 | 140 | node.js|npm | 127,281 | <p>You can change npm cache folder using the <code>npm</code> command line. (see <a href="https://docs.npmjs.com/cli/v6/using-npm/config#cache" rel="noreferrer">https://docs.npmjs.com/cli/v6/using-npm/config#cache</a>)</p>
<p>So you might want to try this command :</p>
<pre><code>> npm config set cache C:\Devel\nodejs\npm-cache --global
</code></pre>
<p>Then, run <code>npm --global cache verify</code> after running this command.</p> |
24,587,443 | AWS - Disconnected : No supported authentication methods available (server sent :publickey) | <p>SSH to my AWS server just broke for both Putty and Filezilla. I'm making some effort for this post to be a comprehensive troubleshooting list, so if you share links to other stack overflow pages, I'll edit them into the question.</p>
<pre><code>Disconnected : No supported authentication methods available (server sent :publickey)
</code></pre>
<p><br>
The error is familiar from when I set up the connection almost a year ago. If you're setting up AWS SSH for the first time, these address the most common problems:</p>
<ul>
<li><b>Wrong username:</b> <a href="https://stackoverflow.com/questions/21535907/disconnected-no-supported-authentication-methods-available-server-sent-publi">Disconnected : No supported authentication methods available (server sent :publickey)</a></li>
<li><b>Incorrect .ppk file:</b> <a href="https://stackoverflow.com/questions/19096348/unable-to-connect-to-amazon-server-using-putty">Unable to connect to amazon server using putty</a></li>
</ul>
<p>However, the only thing I could think that would impact a previously working system is:</p>
<ul>
<li><b>Wrong IP:</b> Restarting an AWS instance (or creating an image) is not guaranteed to keep the same IP address. This would obviously have to be updated in putty. </li>
</ul>
<p>What other possibilities are there? </p>
<p><em>Solution to this one (per the accepted post below) is that for AWS EC2 all 3 of these need to have proper permissions (777 <strong>not</strong> ok for any of these). Here's one example that works:</em></p>
<pre><code>/home/ec2-user/ - 700
/home/ec2-user/.ssh/ - 600
/home/ec2-user/.ssh/authorized_keys - 600
</code></pre>
<p>/var/log/secure will tell you which one is throwing an error, consult this video tutorial to get access if you're completely locked out:
<a href="http://d2930476l2fsmh.cloudfront.net/LostKeypairRecoveryOfLinuxInstance.mp4" rel="noreferrer">http://d2930476l2fsmh.cloudfront.net/LostKeypairRecoveryOfLinuxInstance.mp4</a></p> | 36,808,935 | 25 | 0 | null | 2014-07-05 14:32:40.043 UTC | 11 | 2022-08-31 06:02:21.97 UTC | 2017-12-04 14:36:15.2 UTC | null | 3,749,301 | null | 3,749,301 | null | 1 | 62 | amazon-web-services|ssh|putty | 227,298 | <p>For me this error appeared immediatey after I changed the user's home directory by</p>
<pre><code>sudo usermod -d var/www/html username
</code></pre>
<p>It can also happen because of lack of proper permission to authorized_key file in <strong>~/.ssh</strong>. Make sure the permission of this file is <strong>0600</strong> and permission of <strong>~/.ssh</strong> is <strong>700</strong>.</p> |
3,204,060 | Django how to set main page | <p>i want to set a main page or an index page for my app.
i tried adding MAIN_PAGE in settings.py and then creating a main_page view returning a main_page object, but it doesn't work
Also, i tries to add in the urls.py a declaration like</p>
<pre><code>(r'^$', index),
</code></pre>
<p>where indexshould be the name of the index.html file on the root (but it obviously does not work)</p>
<p>What is the best way to set a main page in a Django website?</p>
<p>thanks!</p> | 3,204,106 | 4 | 0 | null | 2010-07-08 13:29:11.027 UTC | 2 | 2019-03-21 06:40:29.053 UTC | null | null | null | null | 342,279 | null | 1 | 22 | django|indexing|set|program-entry-point | 49,055 | <p>If you want to refer to a static page (not have it go through any dynamic processing), you can use the <code>direct_to_template</code> view function from <code>django.views.generic.simple</code>. In your URL conf:</p>
<pre><code>from django.views.generic.simple import direct_to_template
urlpatterns += patterns("",
(r"^$", direct_to_template, {"template": "index.html"})
)
</code></pre>
<p>(Assuming <code>index.html</code> is at the root of one of your template directories.)</p> |
56,835,040 | .Net Core 3.0 JsonSerializer populate existing object | <p>I'm preparing a migration from ASP.NET Core 2.2 to 3.0.</p>
<p>As I don't use more advanced JSON features (but maybe one as described below), and 3.0 now comes with a built-in namespace/classes for JSON, <code>System.Text.Json</code>, I decided to see if I could drop the previous default <code>Newtonsoft.Json</code>.<br />
<em>Do note, I'm aware that <code>System.Text.Json</code> will not completely replace <code>Newtonsoft.Json</code>.</em></p>
<p>I managed to do that everywhere, e.g.</p>
<pre><code>var obj = JsonSerializer.Parse<T>(jsonstring);
var jsonstring = JsonSerializer.ToString(obj);
</code></pre>
<p>but in one place, where I populate an existing object.</p>
<p>With <code>Newtonsoft.Json</code> one can do</p>
<pre><code>JsonConvert.PopulateObject(jsonstring, obj);
</code></pre>
<hr />
<p>The built-in <code>System.Text.Json</code> namespace has some additional classes, like <code>JsonDocumnet</code>, <code>JsonElement</code> and <code>Utf8JsonReader</code>, though I can't find any that take an existing object as a parameter.</p>
<p>Nor am I experienced enough to see how to make use of the existing one's.</p>
<p>There might be <a href="https://github.com/dotnet/corefx/issues/37627" rel="noreferrer">a possible upcoming feature in .Net Core</a> (thanks to <a href="https://stackoverflow.com/users/3445247/mustafa-gursel">Mustafa Gursel</a> for the link), but meanwhile (and what if it doesn't),...</p>
<p>...I now wonder, is it possible to achieve something similar as what one can do with <code>PopulateObject</code>?</p>
<p>I mean, is it possible with any of the other <code>System.Text.Json</code> classes to accomplish the same, and update/replace only the properties set?,... or some other clever workaround?</p>
<hr />
<p>Here is a sample input/output of what I am looking for, and it need to be generic as the object passed into the deserialization method is of type <code><T></code>). I have 2 Json string's to be parsed into an object, where the first have some default properties set, and the second some, e.g.</p>
<p><em>Note, a property value can be of any other type than a <code>string</code></em>.</p>
<p>Json string 1:</p>
<pre><code>{
"Title": "Startpage",
"Link": "/index",
}
</code></pre>
<p>Json string 2:</p>
<pre><code>{
"Head": "Latest news"
"Link": "/news"
}
</code></pre>
<p>Using the 2 Json strings above, I want an object resulting in:</p>
<pre><code>{
"Title": "Startpage",
"Head": "Latest news",
"Link": "/news"
}
</code></pre>
<p>As seen in above sample, if properties in the 2nd has values/is set, it replace values in the 1st (as with "Head" and "Link"), if not, existing value persist (as with "Title")</p> | 56,906,228 | 8 | 1 | null | 2019-07-01 11:40:06.73 UTC | 9 | 2022-03-31 14:47:27.597 UTC | 2020-08-13 10:56:08.223 UTC | null | 2,827,823 | null | 2,827,823 | null | 1 | 48 | c#|asp.net-core|razor-pages|asp.net-core-3.0|system.text.json | 25,365 | <p>So assuming that Core 3 doesn't support this out of the box, let's try to work around this thing. So, what's our problem?</p>
<p>We want a method that overwrites some properties of an existing object with the ones from a json string. So our method will have a signature of:</p>
<pre><code>void PopulateObject<T>(T target, string jsonSource) where T : class
</code></pre>
<p>We don't really want any custom parsing as it's cumbersome, so we'll try the obvious approach - deserialize <code>jsonSource</code> and copy the result properties into our object. We cannot, however, just go</p>
<pre><code>T updateObject = JsonSerializer.Parse<T>(jsonSource);
CopyUpdatedProperties(target, updateObject);
</code></pre>
<p>That's because for a type</p>
<pre><code>class Example
{
int Id { get; set; }
int Value { get; set; }
}
</code></pre>
<p>and a JSON</p>
<pre><code>{
"Id": 42
}
</code></pre>
<p>we will get <code>updateObject.Value == 0</code>. Now we don't know if <code>0</code> is the new updated value or if it just wasn't updated, so we need to know exactly which properties <code>jsonSource</code> contains.</p>
<p>Fortunately, the <code>System.Text.Json</code> API allows us to examine the structure of the parsed JSON.</p>
<pre><code>using var json = JsonDocument.Parse(jsonSource).RootElement;
</code></pre>
<p>We can now enumerate over all properties and copy them.</p>
<pre><code>foreach (var property in json.EnumerateObject())
{
OverwriteProperty(target, property);
}
</code></pre>
<p>We will copy the value using reflection:</p>
<pre><code>void OverwriteProperty<T>(T target, JsonProperty updatedProperty) where T : class
{
var propertyInfo = typeof(T).GetProperty(updatedProperty.Name);
if (propertyInfo == null)
{
return;
}
var propertyType = propertyInfo.PropertyType;
v̶a̶r̶ ̶p̶a̶r̶s̶e̶d̶V̶a̶l̶u̶e̶ ̶=̶ ̶J̶s̶o̶n̶S̶e̶r̶i̶a̶l̶i̶z̶e̶r̶.̶P̶a̶r̶s̶e̶(̶u̶p̶d̶a̶t̶e̶d̶P̶r̶o̶p̶e̶r̶t̶y̶.̶V̶a̶l̶u̶e̶,̶ ̶p̶r̶o̶p̶e̶r̶t̶y̶T̶y̶p̶e̶)̶;̶
var parsedValue = JsonSerializer.Deserialize(
updatedProperty.Value.GetRawText(),
propertyType);
propertyInfo.SetValue(target, parsedValue);
}
</code></pre>
<p>We can see here that what we're doing is a <em>shallow</em> update. If the object contains another complex object as its property, that one will be copied and overwritten as a whole, not updated. If you require <em>deep</em> updates, this method needs to be changed to extract the current value of the property and then call the <code>PopulateObject</code> recursively if the property's type is a reference type (that will also require accepting <code>Type</code> as a parameter in <code>PopulateObject</code>).</p>
<p>Joining it all together we get:</p>
<pre><code>void PopulateObject<T>(T target, string jsonSource) where T : class
{
using var json = JsonDocument.Parse(jsonSource).RootElement;
foreach (var property in json.EnumerateObject())
{
OverwriteProperty(target, property);
}
}
void OverwriteProperty<T>(T target, JsonProperty updatedProperty) where T : class
{
var propertyInfo = typeof(T).GetProperty(updatedProperty.Name);
if (propertyInfo == null)
{
return;
}
var propertyType = propertyInfo.PropertyType;
v̶a̶r̶ ̶p̶a̶r̶s̶e̶d̶V̶a̶l̶u̶e̶ ̶=̶ ̶J̶s̶o̶n̶S̶e̶r̶i̶a̶l̶i̶z̶e̶r̶.̶P̶a̶r̶s̶e̶(̶u̶p̶d̶a̶t̶e̶d̶P̶r̶o̶p̶e̶r̶t̶y̶.̶V̶a̶l̶u̶e̶,̶ ̶p̶r̶o̶p̶e̶r̶t̶y̶T̶y̶p̶e̶)̶;̶
var parsedValue = JsonSerializer.Deserialize(
updatedProperty.Value.GetRawText(),
propertyType);
propertyInfo.SetValue(target, parsedValue);
}
</code></pre>
<p>How robust is this? Well, it certainly won't do anything sensible for a JSON array, but I'm not sure how you'd expect a <code>PopulateObject</code> method to work on an array to begin with. I don't know how it compares in performance to the <code>Json.Net</code> version, you'd have to test that by yourself. It also silently ignores properties that are not in the target type, by design. I thought it was the most sensible approach, but you might think otherwise, in that case the property null-check has to be replaced with an exception throw.</p>
<p><strong>EDIT:</strong></p>
<p>I went ahead and implemented a deep copy:</p>
<pre><code>void PopulateObject<T>(T target, string jsonSource) where T : class =>
PopulateObject(target, jsonSource, typeof(T));
void OverwriteProperty<T>(T target, JsonProperty updatedProperty) where T : class =>
OverwriteProperty(target, updatedProperty, typeof(T));
void PopulateObject(object target, string jsonSource, Type type)
{
using var json = JsonDocument.Parse(jsonSource).RootElement;
foreach (var property in json.EnumerateObject())
{
OverwriteProperty(target, property, type);
}
}
void OverwriteProperty(object target, JsonProperty updatedProperty, Type type)
{
var propertyInfo = type.GetProperty(updatedProperty.Name);
if (propertyInfo == null)
{
return;
}
var propertyType = propertyInfo.PropertyType;
object parsedValue;
if (propertyType.IsValueType || propertyType == typeof(string))
{
̶p̶a̶r̶s̶e̶d̶V̶a̶l̶u̶e̶ ̶=̶ ̶J̶s̶o̶n̶S̶e̶r̶i̶a̶l̶i̶z̶e̶r̶.̶P̶a̶r̶s̶e̶(̶u̶p̶d̶a̶t̶e̶d̶P̶r̶o̶p̶e̶r̶t̶y̶.̶V̶a̶l̶u̶e̶,̶ ̶p̶r̶o̶p̶e̶r̶t̶y̶T̶y̶p̶e̶)̶;̶
parsedValue = JsonSerializer.Deserialize(
updatedProperty.Value.GetRawText(),
propertyType);
}
else
{
parsedValue = propertyInfo.GetValue(target);
P̶o̶p̶u̶l̶a̶t̶e̶O̶b̶j̶e̶c̶t̶(̶p̶a̶r̶s̶e̶d̶V̶a̶l̶u̶e̶,̶ ̶u̶p̶d̶a̶t̶e̶d̶P̶r̶o̶p̶e̶r̶t̶y̶.̶V̶a̶l̶u̶e̶,̶ ̶p̶r̶o̶p̶e̶r̶t̶y̶T̶y̶p̶e̶)̶;̶
PopulateObject(
parsedValue,
updatedProperty.Value.GetRawText(),
propertyType);
}
propertyInfo.SetValue(target, parsedValue);
}
</code></pre>
<p>To make this more robust you'd either have to have a separate <code>PopulateObjectDeep</code> method or pass <code>PopulateObjectOptions</code> or something similar with a deep/shallow flag.</p>
<p><strong>EDIT 2:</strong></p>
<p>The point of deep-copying is so that if we have an object</p>
<pre><code>{
"Id": 42,
"Child":
{
"Id": 43,
"Value": 32
},
"Value": 128
}
</code></pre>
<p>and populate it with</p>
<pre><code>{
"Child":
{
"Value": 64
}
}
</code></pre>
<p>we'd get</p>
<pre><code>{
"Id": 42,
"Child":
{
"Id": 43,
"Value": 64
},
"Value": 128
}
</code></pre>
<p>In case of a shallow copy we'd get <code>Id = 0</code> in the copied child.</p>
<p><strong>EDIT 3:</strong></p>
<p>As @ldam pointed out, this no longer works in stable .NET Core 3.0, because the API was changed. The <code>Parse</code> method is now <code>Deserialize</code> and you have to dig deeper to get to a <code>JsonElement</code>'s value. There is <a href="https://github.com/dotnet/corefx/issues/37564" rel="nofollow noreferrer">an active issue in the corefx repo</a> to allow direct deserialization of a <code>JsonElement</code>. Right now the closest solution is to use <code>GetRawText()</code>. I went ahead and edited the code above to work, leaving the old version struck-through.</p> |
40,711,160 | Woocommerce - Getting the order item price and quantity. | <p>Using Woocommerce 2.6.8 , I can't get the Order Item Data information as described in the <a href="https://docs.woocommerce.com/wc-apidocs/source-class-WC_Abstract_Order.html#1186-1218" rel="noreferrer">docs</a> and <a href="https://stackoverflow.com/a/39409201/2193349">here on SO</a>.</p>
<p>All I want is to get the Line Item price and Quantity, which should be as simple as:</p>
<pre><code>$order = new WC_Order( $order_id );
$order_items = $order->get_items();
foreach ($order_items as $items_key => $items_value) {
echo $items_value['name']; //this works
echo $items_value['qty']; //this doesn't work
echo $items_value[item_meta][_qty][0]; //also doesn't work
echo $items_value['line_total']; //this doesn't work
}
</code></pre>
<p>Looking closer at what gets returned returned</p>
<pre><code>Array
(
[1] => Array
(
[name] => Sample Product 1
[type] => line_item
[item_meta] =>
[item_meta_array] => Array
(
[1] => stdClass Object
(
[key] => _qty
[value] => 1
)
[2] => stdClass Object
(
[key] => _tax_class
[value] =>
)
[3] => stdClass Object
(
[key] => _product_id
[value] => 8
)
[4] => stdClass Object
(
[key] => _variation_id
[value] => 0
)
[5] => stdClass Object
(
[key] => _line_subtotal
[value] => 50
)
[6] => stdClass Object
(
[key] => _line_total
[value] => 50
)
[7] => stdClass Object
(
[key] => _line_subtotal_tax
[value] => 0
)
[8] => stdClass Object
(
[key] => _line_tax
[value] => 0
)
[9] => stdClass Object
(
[key] => _line_tax_data
[value] => a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}
)
)
)
)
</code></pre>
<p>This is all using documented Woocommerce methods, why is the information I need stored in this <code>item_meta_array</code>? </p>
<p>Does anyone know how I can get that information? </p>
<p>Preferably using documented methods as opposed to a crude hack of looping through the <code>item_meta_array</code> until I find the key I'm looking for.</p>
<p>I feel like I must be missing something obvious here.</p> | 40,715,347 | 3 | 0 | null | 2016-11-21 00:36:07.483 UTC | 16 | 2021-09-04 09:22:10.837 UTC | 2017-05-23 10:32:59.757 UTC | null | -1 | null | 2,193,349 | null | 1 | 27 | php|wordpress|woocommerce|items|orders | 113,484 | <blockquote>
<p><strong>Update <em>(For WooCommerce 3+)</em></strong> <br></p>
</blockquote>
<p>Now for the code you can use <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item_Product.html" rel="noreferrer"><code>WC_Order_Item_Product</code></a> (and <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html" rel="noreferrer"><code>WC_Product</code></a>) methods instead, like:</p>
<pre><code>## For WooCommerce 3+ ##
// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id );
// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item ) {
// Get an instance of corresponding the WC_Product object
$product = $item->get_product();
$active_price = $product->get_price(); // The product active raw price
$regular_price = $product->get_sale_price(); // The product raw sale price
$sale_price = $product->get_regular_price(); // The product raw regular price
$product_name = $item->get_name(); // Get the item name (product name)
$item_quantity = $item->get_quantity(); // Get the item quantity
$item_subtotal = $item->get_subtotal(); // Get the item line total non discounted
$item_subto_tax = $item->get_subtotal_tax(); // Get the item line total tax non discounted
$item_total = $item->get_total(); // Get the item line total discounted
$item_total_tax = $item->get_total_tax(); // Get the item line total tax discounted
$item_taxes = $item->get_taxes(); // Get the item taxes array
$item_tax_class = $item->get_tax_class(); // Get the item tax class
$item_tax_status= $item->get_tax_status(); // Get the item tax status
$item_downloads = $item->get_item_downloads(); // Get the item downloads
// Displaying this data (to check)
echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 );
}
</code></pre>
<p><strong>Update:</strong> Also all the following <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Abstract_Order.html" rel="noreferrer"><code>WC_Abstract_Order</code> methods</a> allow to get order items data with various interesting options like:</p>
<pre><code>// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id );
// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item) {
## Option: Including or excluding Taxes
$inc_tax = true;
## Option: Round at item level (or not)
$round = false; // Not rounded at item level ("true" for rounding at item level)
$item_cost_excl_disc = $order->get_item_subtotal( $item, $inc_tax, $round ); // Calculate item cost (not discounted) - useful for gateways.
$item_cost_incl_disc = $order->get_item_total( $item, $inc_tax, $round ); // Calculate item cost (discounted) - useful for gateways.
$item_tax_cost = $order->get_item_tax( $item, $inc_tax, $round ); // Get item tax cost - useful for gateways.
$item_Line_subtotal = $order->get_line_subtotal( $item, $inc_tax, $round ); // Get line subtotal - not discounted.
$item_Line_total = $order->get_line_total( $item, $inc_tax, $round ); // Get line total - discounted
$item_Line_tax = $order->get_line_tax( $item ); // Get line tax
$form_line_subtotal = $order->get_formatted_line_subtotal( $item, $tax_display = '' ) // Gets line subtotal - formatted for display.
}
</code></pre>
<p><em>Thanks to @Casper for his comment</em></p>
<hr />
<p>Also <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Data.html" rel="noreferrer"><code>WC_Data</code> methods</a> can be used to get order item data as an unprotected array or to get a specific nested or custom meta data value from a specific meta key:</p>
<pre><code>// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id );
// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item ) {
$order_item_data = $item->get_data(); // Get WooCommerce order item meta data in an unprotected array
print_r( $order_item_data ); // display raw data
$item_meta_data = $item->get_meta_data(); // Get order item nested and custom meta data in an unprotected array
print_r( $item_meta_data ); // display raw data
$item_value = $item->get_meta('meta_key'); // Get specific order item custom or nested meta data value from a meta_key
print_r( $item_value ); // display raw data (can be a string or an array)
}
</code></pre>
<p>This code is tested and works.</p>
<blockquote>
<p>Method <code>get_item_meta()</code> is deprecated and has been replaced by <a href="https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_item_meta.html" rel="noreferrer"><strong><code>wc_get_order_item_meta</code></strong></a> and it's not anymore a method <strong>but a function</strong> with some parameters:</p>
</blockquote>
<blockquote>
<pre><code>/** Parameters summary
</code></pre>
</blockquote>
<pre><code> * @param mixed $item_id
* @param mixed $key
* @param bool $single (default: true)
* @return mixed
*/
</code></pre>
<blockquote>
<pre><code>wc_get_order_item_meta( $item_id, $key, $single = true );
</code></pre>
</blockquote>
<hr />
<blockquote>
<p>Prior versions of woocommerce (from 2.4 to 2.6.x)</p>
</blockquote>
<p>You can use <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Abstract_Order.html#_get_item_meta" rel="noreferrer"><strong><code>get_item_meta()</code></strong></a> WC_Abstract_order method, to get the order metadata (the item quantity and the item price total).</p>
<p>So your code will be:</p>
<pre><code>// Getting the order object "$order"
$order = wc_get_order( $order_id );
// Getting the items in the order
$order_items = $order->get_items();
// Iterating through each item in the order
foreach ($order_items as $item_id => $item) {
// Get the product name
$product_name = $item['name'];
// Get the item quantity
$item_quantity = $order->get_item_meta($item_id, '_qty', true);
// Get the item line total
$item_total = $order->get_item_meta($item_id, '_line_total', true);
// Displaying this data (to check)
echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. $item_total;
}
</code></pre>
<p>This code is tested and fully functional.</p>
<p>Reference: <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Abstract_Order.html#_get_item_meta" rel="noreferrer">Class WC_Abstract_Order Methods</a></p> |
40,768,621 | python OpenCV jpeg compression in memory | <p>In OpenCV it is possible to save an image to disk with a certain jpeg compression. Is there also a way to do this in memory? Or should I write a function using <code>cv2.imsave()</code> that loads the file and removes it again from disk? If anyone knows a better way that is also fine.</p>
<p>The use case is real-time data augmentation. Using something else than OpenCV would cause possibly unnecessary overhead. </p>
<p>Example of desired function <code>im = cv2.imjpgcompress(90)</code> </p> | 40,768,705 | 1 | 0 | null | 2016-11-23 15:42:37.2 UTC | 9 | 2018-11-07 10:26:55.397 UTC | null | null | null | null | 470,433 | null | 1 | 27 | python|opencv|jpeg | 36,957 | <p>You can use <code>imencode</code>:</p>
<pre><code>encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
result, encimg = cv2.imencode('.jpg', img, encode_param)
</code></pre>
<p>(The default value for <a href="https://docs.opencv.org/master/d4/da8/group__imgcodecs.html#ga292d81be8d76901bff7988d18d2b42ac" rel="noreferrer"><code>IMWRITE_JPEG_QUALITY</code></a> is 95.)</p>
<p>You can decode it back with:</p>
<pre><code>decimg = cv2.imdecode(encimg, 1)
</code></pre>
<hr>
<p><sub> Snippet from <a href="https://github.com/kyatou/python-opencv_tutorial/blob/master/08_image_encode_decode.py" rel="noreferrer">here</a></sub></p> |
1,270,522 | how to create a linked server using ODBC correctly? | <p>can someone please let me know the steps on creating a linked server using ODBC connection? thanks....</p> | 1,270,541 | 1 | 0 | null | 2009-08-13 07:24:35.11 UTC | null | 2009-08-13 07:57:24.593 UTC | 2009-08-13 07:57:24.593 UTC | null | 23,118 | null | 127,986 | null | 1 | 1 | sql-server|odbc|linked-server | 43,522 | <p>Take a look at this page:</p>
<ul>
<li><a href="http://www.ideaexcursion.com/2009/02/25/howto-setup-sql-server-linked-server-to-mysql/" rel="nofollow noreferrer">http://www.ideaexcursion.com/2009/02/25/howto-setup-sql-server-linked-server-to-mysql/</a></li>
</ul>
<p>which has a walk through on creating a linked server to MySQL using an ODBC driver.</p> |
48,709,404 | Initialize empty Pandas series and conditionally add to it | <p>I have a pandas DataFrame named <code>X</code> as shown below. </p>
<pre><code>X = pd.DataFrame({
'month_1': [1, 0, 0, 0, 0],
'month_2': [0, 1, 0, 0, 0],
'age': [1, 2, 3, 4, 5]
})
months = X['month_1'] + X['month_2']
age = X['age']
</code></pre>
<p>I want to create an equation that adds up series from <code>X</code> based on whether that term from <code>keep</code> is True or False. The code below works. </p>
<pre><code>keep={'seasonality':True, 'age':True}
equation = months
if keep['age']:
equation = equation + age
print(equation)
0 2
1 3
2 3
3 4
4 5
dtype: int64
</code></pre>
<p>However, I can't get it to work if I initialize <code>equation</code> with an empty series and then add terms based on <code>keep</code>. When I try to do this I get NaN values. How can I do this?</p>
<pre><code>keep={'seasonality':True, 'age':True}
equation = pd.Series([])
if keep['seasonality']:
equation = equation + months
if keep['age']:
equation = equation + age
print(equation)
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
</code></pre> | 48,709,472 | 1 | 0 | null | 2018-02-09 15:45:47.62 UTC | 1 | 2018-09-24 08:57:28.07 UTC | null | null | null | null | 4,913,108 | null | 1 | 8 | python|pandas|dataframe | 46,952 | <p>If I understand correctly , you can using <code>add</code> + <code>fill_value=0</code></p>
<pre><code>equation = pd.Series([])
if keep['seasonality']:
equation = equation.add(months,fill_value=0)
if keep['age']:
equation = equation.add(age,fill_value=0)
equation
Out[91]:
0 2.0
1 3.0
2 3.0
3 4.0
4 5.0
dtype: float64
</code></pre> |
48,716,536 | How to show a dockerfile of image docker | <p>I download a image from docker repository and Im trying to display the Dockerfile of 'X' image to create my own Dockerfile with the same structure to experiment with him. Im using this command:</p>
<pre><code>docker inspect --format='{{.Config.Image}}' 'here paste the id of image'
</code></pre>
<p>That command return a 'sha256', some like this:</p>
<pre><code>sha256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</code></pre>
<p>but I need a command to display a json file with configuration of Dockerfile. Someone know how can I do this?
Sorry if the format or the question is not ok, Im a beginner!</p>
<p>Thanks everyone!</p> | 48,716,676 | 1 | 0 | null | 2018-02-10 02:04:37.97 UTC | 9 | 2020-09-30 08:56:57.693 UTC | 2019-10-31 11:48:08.29 UTC | null | 3,001,761 | null | 7,288,685 | null | 1 | 11 | docker|dockerfile|inspect | 18,281 | <p>The raw output, as described in "<a href="https://stackoverflow.com/a/48444917/6309">How to generate a Dockerfile from an image?</a>", would be:</p>
<pre><code>docker history --no-trunc <IMAGE_ID>
</code></pre>
<p>But a more complete output would be from <a href="https://github.com/CenturyLinkLabs/dockerfile-from-image" rel="nofollow noreferrer"><code>CenturyLinkLabs/dockerfile-from-image</code></a></p>
<pre><code>docker run -v /var/run/docker.sock:/var/run/docker.sock \
centurylink/dockerfile-from-image <IMAGE_TAG_OR_ID>
</code></pre>
<p>Note there <a href="https://github.com/CenturyLinkLabs/dockerfile-from-image#limitations" rel="nofollow noreferrer">were limitations</a>.</p>
<p><strong>In 2020</strong>, as <a href="https://stackoverflow.com/a/30793515/6309">illustrated here</a>:</p>
<pre><code>docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage \
-sV=1.36 <IMAGE_TAG_OR_ID>
</code></pre> |
33,834,742 | Remove and adding elements to array in GO lang | <p>I have 2 arrays declared as :
<code>var input []string</code> and <code>var output []string</code> . </p>
<p>The input array is filled with some IDs initially. Output array is NULL.</p>
<p>After every iteration I want to remove a random element from input array and add it to output array. </p>
<p>At the end all the elements in output array will be same as input array (but with different ordering(indexing)). </p>
<pre><code>for index := 0; index < len(input); index++ {
if !visited[index] {
//do something
}
}
output[#iteration index] = input[current index]
</code></pre>
<p>When I try to do this, I get <code>array out of bounds error</code>.</p> | 33,834,777 | 2 | 0 | null | 2015-11-20 19:37:14.483 UTC | 12 | 2018-01-18 14:17:38.617 UTC | 2017-02-09 08:35:45.747 UTC | null | 2,311,366 | null | 5,375,370 | null | 1 | 38 | arrays|go|append|slice | 102,217 | <p>For the <code>output</code> array you need to use <code>append</code> or allocate it with an initial capacity to match the size of <code>input</code>.</p>
<pre><code>// before the loop
output := make([]string, len(input))
</code></pre>
<p>would be my recommendation because <code>append</code> causes a bunch of needless reallocations and you already know what capacity you need since it's based on the <code>input</code>.</p>
<p>The other thing would be:</p>
<pre><code>output = append(output, input[index])
</code></pre>
<p>But like I said, from what I've observed append grows the initial capacity exponentially. This will be base 2 if you haven't specified anything which means you're going to be doing several unneeded reallocations before reaching the desired capacity.</p> |
29,924,170 | Elixir - Looping through and adding to map | <p>I'm rebuilding something in Elixir from some code I built in C#.</p>
<p>It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).</p>
<p>Essentially what it did was check some RSS feeds and see if there was any new content. This is the code:</p>
<pre><code>Map historic (URL as key, post title as value).
List<string> blogfeeds
while true
for each blog in blogfeeds
List<RssPost> posts = getposts(blog)
for each post in posts
if post.url is not in historic
dothing(post)
historic.add(post)
</code></pre>
<p>I am wondering how I can do Enumeration effectively in Elixir. Also, it seems that my very process of adding things to "historic" is anti-functional programming.</p>
<p>Obviously the first step was declaring my list of URLs, but beyond that the enumeration idea is messing with my head. Could someone help me out? Thanks.</p> | 29,924,465 | 3 | 0 | null | 2015-04-28 15:54:50.037 UTC | 14 | 2019-05-31 06:28:58.313 UTC | 2015-04-28 16:15:54.953 UTC | null | 4,739,548 | null | 4,394,748 | null | 1 | 42 | enumeration|elixir | 25,918 | <p>This is a nice challenge to have and solving it will definitely give you some insight into functional programming.</p>
<p>The solution for such problems in functional languages is usually <code>reduce</code> (often called <code>fold</code>). I will start with a short answer (and not a direct translation) but feel free to ask for a follow up.</p>
<p>The approach below will typically not work in functional programming languages:</p>
<pre><code>map = %{}
Enum.each [1, 2, 3], fn x ->
Map.put(map, x, x)
end
map
</code></pre>
<p>The map at the end will still be empty because we can't mutate data structures. Every time you call <code>Map.put(map, x, x)</code>, it will return a new map. So we need to explicitly retrieve the new map after each enumeration.</p>
<p>We can achieve this in Elixir using reduce:</p>
<pre><code>map = Enum.reduce [1, 2, 3], %{}, fn x, acc ->
Map.put(acc, x, x)
end
</code></pre>
<p>Reduce will emit the result of the previous function as accumulator for the next item. After running the code above, the variable <code>map</code> will be <code>%{1 => 1, 2 => 2, 3 => 3}</code>.</p>
<p>For those reasons, we rarely use <code>each</code> on enumeration. Instead, we use the functions in <a href="http://elixir-lang.org/docs/stable/elixir/Enum.html">the <code>Enum</code> module</a>, that support a wide range of operations, eventually falling back to <code>reduce</code> when there is no other option.</p>
<p>EDIT: to answer the questions and go through a more direct translation of the code, this what you can do to check and update the map as you go:</p>
<pre><code>Enum.reduce blogs, %{}, fn blog, history ->
posts = get_posts(blog)
Enum.reduce posts, history, fn post, history ->
if Map.has_key?(history, post.url) do
# Return the history unchanged
history
else
do_thing(post)
Map.put(history, post.url, true)
end
end
end
</code></pre>
<p>In fact, a set would be better here, so let's refactor this and use a set in the process:</p>
<pre><code>def traverse_blogs(blogs) do
Enum.reduce blogs, HashSet.new, &traverse_blog/2
end
def traverse_blog(blog, history) do
Enum.reduce get_posts(blog), history, &traverse_post/2
end
def traverse_post(post, history) do
if post.url in history do
# Return the history unchanged
history
else
do_thing(post)
HashSet.put(history, post.url)
end
end
</code></pre> |
34,556,991 | Pod install displaying error in cocoapods version 1.0.0.beta.1 | <p>My podfile was working but after updating to cocoapods version 1.0.0.beta.1</p>
<p>pod install displays following error</p>
<pre><code>MacBook-Pro:iOS-TuneIn home$ pod install
Fully deintegrating due to major version update
Deleted 1 'Copy Pods Resources' build phases.
Deleted 1 'Check Pods Manifest.lock' build phases.
Deleted 1 'Embed Pods Frameworks' build phases.
- libPods.a
- Pods.debug.xcconfig
- Pods.release.xcconfig
Deleted 1 'Copy Pods Resources' build phases.
Deleted 1 'Check Pods Manifest.lock' build phases.
- libPods.a
Deleted 1 'Copy Pods Resources' build phases.
Deleted 1 'Check Pods Manifest.lock' build phases.
- libPods.a
Deleted 1 'Copy Pods Resources' build phases.
Deleted 1 'Check Pods Manifest.lock' build phases.
- libPods.a
Deleted 1 'Copy Pods Resources' build phases.
Deleted 1 'Check Pods Manifest.lock' build phases.
- libPods.a
- libPods.a
Deleted 1 empty `Pods` groups from project.
Removing `Pods` directory.
Project has been deintegrated. No traces of CocoaPods left in project.
Note: The workspace referencing the Pods project still remains.
Updating local specs repositories
Analyzing dependencies
[!] The dependency `AFNetworking (= 2.6.3)` is not used in any concrete target.
The dependency `MBProgressHUD (~> 0.9.1)` is not used in any concrete target.
The dependency `PDKeychainBindingsController (~> 0.0.1)` is not used in any concrete target.
The dependency `FMDB/SQLCipher` is not used in any concrete target.
The dependency `ZXingObjC (~> 3.1.0)` is not used in any concrete target.
The dependency `SDWebImage (~> 3.7.2)` is not used in any concrete target.
The dependency `SignalR-ObjC (~> 2.0.0.beta3)` is not used in any concrete target.
The dependency `CJPAdController (from `https://github.com/nabeelarif100/CJPAdController.git`)` is not used in any concrete target.
The dependency `ECSlidingViewController (~> 2.0.3)` is not used in any concrete target.
The dependency `VGParallaxHeader` is not used in any concrete target.
The dependency `EMString` is not used in any concrete target.
The dependency `Google/SignIn` is not used in any concrete target.
The dependency `VIPhotoView (~> 0.1)` is not used in any concrete target.
The dependency `EncryptedCoreData (from `https://github.com/project-imas/encrypted-core-data.git`)` is not used in any concrete target.
MacBook-Pro:iOS-TuneIn home$
</code></pre>
<p>Podfile:</p>
<pre><code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
pod 'AFNetworking', '2.6.3'
pod 'MBProgressHUD', '~> 0.9.1'
pod 'PDKeychainBindingsController', '~> 0.0.1'
pod 'FMDB/SQLCipher'
pod 'ZXingObjC', '~> 3.1.0'
pod 'SDWebImage', '~>3.7.2'
pod 'SignalR-ObjC','~>2.0.0.beta3'
pod 'CJPAdController', :git => 'https://github.com/nabeelarif100/CJPAdController.git'
pod 'ECSlidingViewController', '~> 2.0.3'
pod 'VGParallaxHeader'
pod 'EMString'
pod 'Google/SignIn'
pod 'VIPhotoView', '~> 0.1'
pod 'EncryptedCoreData', :git => 'https://github.com/project-imas/encrypted-core-data.git'
</code></pre> | 34,558,516 | 12 | 0 | null | 2016-01-01 14:30:01.97 UTC | 29 | 2017-05-22 12:22:18.333 UTC | null | null | null | null | 800,848 | null | 1 | 177 | ios|cocoapods | 76,610 | <p>You have to specify a target for each pod.</p>
<p>e.g. if before you had your Podfile written like this:</p>
<pre><code>pod 'Alamofire', '~> 3.1.4'
pod 'SwiftyJSON', '~> 2.3.2'
</code></pre>
<p>just change it to</p>
<pre><code>target "TargetName" do
pod 'Alamofire', '~> 3.1.4'
pod 'SwiftyJSON', '~> 2.3.2'
end
</code></pre> |
28,922,126 | How to align flexbox columns left and right? | <p>With typical CSS I could float one of two columns left and another right with some gutter space in-between. How would I do that with flexbox?</p>
<p><a href="http://jsfiddle.net/1sp9jd32/" rel="noreferrer">http://jsfiddle.net/1sp9jd32/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
width: 500px;
border: solid 1px #000;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
#a {
width: 20%;
border: solid 1px #000;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div></code></pre>
</div>
</div>
</p> | 28,922,140 | 5 | 0 | null | 2015-03-08 01:30:34.94 UTC | 35 | 2021-05-25 10:50:10.47 UTC | 2019-08-30 14:58:08.837 UTC | null | 2,756,409 | null | 1,881,088 | null | 1 | 182 | html|css|flexbox | 244,839 | <p>You could add <code>justify-content: space-between</code> to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.</p>
<p><a href="http://jsfiddle.net/zeLh0foy/"><strong>Updated Example</strong></a></p>
<pre><code>#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#a {
width: 20%;
border: solid 1px #000;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div></code></pre>
</div>
</div>
</p>
<hr>
<p>You could also add <code>margin-left: auto</code> to the second element in order to align it to the right.</p>
<p><a href="http://jsfiddle.net/3t2uj4hz/"><strong>Updated Example</strong></a></p>
<pre><code>#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
width: 500px;
border: solid 1px #000;
display: flex;
}
#a {
width: 20%;
border: solid 1px #000;
margin-right: auto;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div></code></pre>
</div>
</div>
</p> |
29,519,805 | How to use ng-click on ng-option( or other way to assign value) | <p>How to use ng-options.</p>
<pre><code>$scope.fieldTable = [
{
filed:"text",
title:"Global"
},
{
field: "relatedentity",
title: "Entity"
},
{
field:"title",
title:"Title"
},
{
field: "content",
title: "Content"
}
]
</code></pre>
<p>I want to build a which use the title as displayed and when select something, popout a alert window which display the according field. The initial selection is </p>
<pre><code>{
filed:"text",
title:"Global"
}
</code></pre>
<p>Can anyone help?</p> | 29,520,264 | 2 | 0 | null | 2015-04-08 16:06:50.693 UTC | 1 | 2017-02-09 14:55:44.55 UTC | 2017-02-09 14:55:44.55 UTC | null | 3,687,463 | null | 1,647,559 | null | 1 | 15 | angularjs|ng-options | 46,597 | <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('stack', []);
app.controller('MainCtrl', function($scope) {
$scope.fieldTable = [{
field: "text",
title: "Global"
}, {
field: "relatedentity",
title: "Entity"
}, {
field: "title",
title: "Title"
}, {
field: "content",
title: "Content"
}];
$scope.selected = $scope.fieldTable[0];
$scope.hasChanged = function() {
alert($scope.selected.field);
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="stack" ng-controller="MainCtrl">
<select ng-options="item.title for item in fieldTable" ng-model="selected" ng-change="hasChanged()">
</select>
</body></code></pre>
</div>
</div>
</p> |
29,716,857 | Installing nloptr on Linux | <p>I am trying to install the R package <strong>nloptr</strong> on a CentOS Linux machine that doesn't have internet connection as follows:</p>
<pre><code>install.packages("/home/ravi/nloptr_1.0.4.tar.gz", repos = NULL, type="source")
</code></pre>
<p>This command in turn looks for the following file online </p>
<pre><code>http://ab-initio.mit.edu/nlopt/nlopt-2.4.2.tar.gz
</code></pre>
<p>However, this fails since there is no internet connection to the machine. </p>
<p>I tried the suggestion from the following stackoverflow post:</p>
<p><a href="https://stackoverflow.com/questions/29296435/trouble-with-installing-nloptr-by-locally-on-ubuntu">trouble with Installing nloptr by locally on Ubuntu</a></p>
<p>I changed the URL in configure and configure.ac files as follows:</p>
<pre><code>NLOPT_URL="file:///home//ravi//${NLOPT_TGZ}"
</code></pre>
<p>However, I get the following error when I try to install the package again:</p>
<pre><code>> install.packages("/home/ravi/nloptr_1.0.4.tar.gz", repos = NULL, type="source")
* installing *source* package 'nloptr' ...
files 'configure', 'configure.ac' have the wrong MD5 checksums
ERROR: 'configure' exists but is not executable -- see the 'R Installation and Administration Manual'
* removing '/opt/vertica/R/library/nloptr'
Warning message:
In install.packages("/home/ravi/nloptr_1.0.4.tar.gz", :
installation of package '/home/ravi/nloptr_1.0.4.tar.gz' had non-zero exit status
</code></pre>
<p>Can someone guide me on how to install this R package locally?</p>
<p><strong>Update 1</strong></p>
<p>Based on the suggestion from Dirk on installing nlopt first, I followed the instructions given in the following page:</p>
<p><a href="http://ab-initio.mit.edu/wiki/index.php/NLopt_Installation" rel="noreferrer">http://ab-initio.mit.edu/wiki/index.php/NLopt_Installation</a></p>
<p>I installed nlopt as follows :</p>
<pre><code>./configure --enable-shared
make
make install
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/lib
</code></pre>
<p>When I tried to re-install nloptr in R, it doesn't look for the nlopt link anymore but throws the following error:</p>
<pre><code>Error in dyn.load(file, DLLpath = DLLpath, ...) :
unable to load shared object '/opt/vertica/R/library/nloptr/libs/nloptr.so':
/opt/vertica/R/library/nloptr/libs/nloptr.so: undefined symbol: nlopt_set_maxtime
Error: loading failed
Execution halted
ERROR: loading failed
* removing '/opt/vertica/R/library/nloptr'
Warning message:
In install.packages("/home/ravi/nloptr_1.0.4.tar.gz", :
installation of package '/home/ravi/nloptr_1.0.4.tar.gz' had non-zero exit status
</code></pre>
<p><strong>Update 2</strong></p>
<p>As suggested by Dirk, I looked into the ldconfig command and used the following reference:</p>
<p><a href="http://codeyarns.com/2014/01/14/how-to-add-library-directory-to-ldconfig-cache/" rel="noreferrer">http://codeyarns.com/2014/01/14/how-to-add-library-directory-to-ldconfig-cache/</a></p>
<p>I edited the /etc/ld.so.conf file, added the directory /usr/local/lib which contains the shared library and ran the ldconfig command. This added the relevant shared library as shown below:</p>
<pre><code>libnlopt.so.0 (libc6,x86-64) => /usr/local/lib/libnlopt.so.0
libnlopt.so (libc6,x86-64) => /usr/local/lib/libnlopt.so
</code></pre>
<p>However, when I tried reinstalling the nloptr package, I still get the same shared object error.</p>
<p>Could someone guide me on the shared library error?</p> | 29,716,984 | 8 | 0 | null | 2015-04-18 11:44:19.78 UTC | 9 | 2021-03-03 14:51:31.387 UTC | 2017-05-23 11:54:55.323 UTC | null | -1 | null | 1,002,903 | null | 1 | 30 | r|centos|nlopt | 22,586 | <p>When you say <em>[t]his command in turn looks for the following file online</em> you only get half the story. Together with Jelmer, the maintainer of the actual nloptr package, I modified the package to do the following:</p>
<ul>
<li>look for an install libnlopt library, and, if found, use it</li>
<li>if not found fall back to the old behaviour and download the library</li>
</ul>
<p>So you could simply install nlopt via</p>
<pre><code> sudo apt-get install libnlopt-dev
</code></pre>
<p>(or the equivalent <code>sudo dpkg -i /media/....</code> pointing to the file from a
USB drive etc pp) and then reinstall the <code>nloptr</code> package. It will just work. On my machine:</p>
<pre><code>edd@max:~$ install.r nloptr ## install.r is in littler
trying URL 'http://cran.rstudio.com/src/contrib/nloptr_1.0.4.tar.gz'
Content type 'application/x-gzip' length 353942 bytes (345 KB)
==================================================
downloaded 345 KB
* installing *source* package ‘nloptr’ ...
** package ‘nloptr’ successfully unpacked and MD5 sums checked
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking how to run the C++ preprocessor... g++ -E
checking whether we are using the GNU C++ compiler... (cached) yes
checking whether g++ accepts -g... (cached) yes
checking for pkg-config... yes
configure: Now testing for NLopt header file.
[...]
checking for nlopt.h... yes
configure: Suitable NLopt library found.
configure: creating ./config.status
config.status: creating src/Makevars
** libs
g++ -I/usr/share/R/include -DNDEBUG -fpic -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g -O3 -Wall -pipe -Wno-unused -pedantic -c dummy.cpp -o dummy.o
gcc -I/usr/share/R/include -DNDEBUG -fpic -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g -O3 -Wall -pipe -pedantic -std=gnu99 -c nloptr.c -o nloptr.o
g++ -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o nloptr.so dummy.o nloptr.o -lnlopt -lm -L/usr/lib/R/lib -lR
installing to /usr/local/lib/R/site-library/nloptr/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (nloptr)
The downloaded source packages are in
‘/tmp/downloaded_packages’
edd@max:~$
</code></pre>
<p>Note how it compiled only two files from the actual R packages having found the nlopt installation.</p> |
36,631,905 | How does one add a typing to typings.json for Typescript in Visual Studio 2015? | <p>I have to ask because this is driving me crazy. I see the npm way of installing typings on Google, but <a href="https://angular.io/docs/ts/latest/quickstart.html" rel="noreferrer">Angular2's tutorial</a> has one add a typings.json file then it added the typings folder and downloaded d.ts files from DefinitelyTyped automatically. I tried this with jquery but it didn't download. I also tried rebuilding the project, which I would expect the package.json to include the commands to add additional typings.</p>
<p>Here's my scripts from the package.json file:</p>
<pre><code>"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
}
</code></pre>
<p>Here's the typings.json file I tried. es6-shim and jasmine downloaded.</p>
<pre><code>{ "ambientDependencies": {
"es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
"jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
"jquery": "github:DefinitelyTyped/DefinitelyTyped/jquery/jquery.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
}}
</code></pre>
<p>It's probably something simple like not having what appears to be a checksum after the hashtag. Where would I find the correct checksum, or what command do I need to add to package.json to retrieve the typings upon compile, or what am I doing wrong?</p>
<p><a href="https://angular.io/docs/ts/latest/guide/typescript-configuration.html" rel="noreferrer">Here's another example</a> of adding a line to the typings.json file and then it installs the d.ts files for you. Scroll down until you see <strong>Manual Typings</strong></p> | 36,635,699 | 2 | 0 | null | 2016-04-14 19:09:22.12 UTC | 6 | 2016-11-25 12:17:57.047 UTC | 2016-11-25 12:17:57.047 UTC | null | 681,538 | null | 84,424 | null | 1 | 30 | angular|typescript|visual-studio-2015|typescript-typings|typescript1.8 | 34,143 | <ol>
<li>Make sure you have <a href="https://www.npmjs.com/get-npm">npm</a> installed</li>
<li>Open up your console of choice (e.g. command prompt or powershell)</li>
<li>Navigate to your project folder</li>
</ol>
<p><strong>Using only npm</strong> (TypeScript 2 and later):</p>
<ol start="4">
<li><p><code>npm install --save @types/jquery</code></p>
<p>Done: See <a href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/">this</a> for more info.</p></li>
</ol>
<p><strong>Using <a href="https://github.com/typings/typings">typings</a></strong> (Typescript before v.2):</p>
<ol start="4">
<li>Make sure you have <a href="https://www.npmjs.com/package/typings">typings</a> installed, if not run <code>npm install typings --global</code></li>
<li><p>Write <code>typings install dt~jquery --save --global</code></p>
<p>This should update your typings.json file and download the definition files.</p>
<p>In the above example for typings, 'dt~' means that it should look for jquery in the <a href="http://definitelytyped.org/">DefinitelyTyped</a> repository, the default is 'npm'. The syntax has changed slightly from version 0.x to 1.0, the flag <code>--global</code> was previously <code>--ambient</code>.</p></li>
</ol> |
28,043,957 | How to set Apache solr admin password | <p>I an not very familiar with solr. I have installed solr successfully. It is using jetty webserver. My solr version is 4.10.3. It admin page is not protected by password. Anyone can access it. I want to apply a paaword on solr admin. How I will do it? </p> | 28,046,215 | 6 | 0 | null | 2015-01-20 11:14:46.083 UTC | 11 | 2019-01-11 15:11:47.41 UTC | 2016-05-16 10:34:21.787 UTC | null | 1,606,632 | null | 2,265,190 | null | 1 | 22 | solr|sunspot-solr | 51,718 | <p><strong>For version below 5</strong></p>
<p>If you are using solr-webapp then you need to modify <em>web.xml</em> file and add these lines:</p>
<pre><code><security-constraint>
<web-resource-collection>
<web-resource-name>Solr Lockdown</web-resource-name>
<url-pattern>/</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>solr_admin</role-name>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Solr</realm-name>
</login-config>
</code></pre>
<p>For Jetty server, you need to add below lines in <em>/example/etc/webdefault.xml</em></p>
<pre><code><security-constraint>
<web-resource-collection>
<web-resource-name>Solr authenticated application</web-resource-name>
<url-pattern>/</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>**admin-role**</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Test Realm</realm-name>
</login-config>
</code></pre>
<p>Update <em>/example/etc/jetty.xml</em> file</p>
<pre><code><Call name="addBean">
<Arg>
<New class="org.eclipse.jetty.security.HashLoginService">
<Set name="name">Test Realm</Set>
<Set name="config"><SystemProperty name="jetty.home" default="."/>/etc/realm.properties</Set>
<Set name="refreshInterval">0</Set>
</New>
</Arg>
</Call>
</code></pre>
<p><code>/example/etc/realm.properties</code> :</p>
<pre><code>admin: s3cr3t, admin-role
</code></pre>
<p>Username = <em>admin</em>
password = <em>s3cr3t</em>.
Role name = admin-role</p>
<p><strong>Solr version 5+</strong></p>
<p>In latest Solr version folder structure got changed. You will find all files in below folder-path.</p>
<p>{SOLR_HOME}/server/etc/jetty.xml
{SOLR_HOME}/server/etc/webdefault.xml</p>
<p>Create new credential file at <code>{SOLR_HOME}/server/etc/realm.properties</code>:</p>
<pre><code>admin: s3cr3t, admin-role
</code></pre>
<p>For more info you can help solr <a href="https://wiki.apache.org/solr/SolrSecurity" rel="nofollow noreferrer">wiki docs</a></p> |
28,053,140 | UITextView is not scrolled to top when loaded | <p>When I have text that does not fill the UITextView, it is scrolled to the top working as intended. When there is more text than will fit on screen, the UITextView is scrolled to the middle of the text, rather than the top.</p>
<p>Here are some potentially relevant details:</p>
<p>In viewDidLoad to give some padding on top and bottom of UITextView:</p>
<pre><code>self.mainTextView.textContainerInset = UIEdgeInsetsMake(90, 0, 70, 0);
</code></pre>
<p>The UITextView uses auto layout to anchor it 20px from top, bottom and each side of the screen (done in IB) to allow for different screen sizes and orientations.</p>
<p>I can still scroll it with my finger once its loaded.</p>
<p>EDIT
I found that removing the auto layout constraints and then fixing the width only seems to fix the issue, but only for that screen width.</p> | 28,053,364 | 13 | 0 | null | 2015-01-20 18:59:07.19 UTC | 7 | 2022-06-20 12:12:30.347 UTC | 2015-01-20 19:04:29.147 UTC | null | 1,102,948 | null | 1,102,948 | null | 1 | 51 | ios|autolayout|uitextview | 19,775 | <p>UITextView is a subclass of UIScrollView, so you can use its methods. If all you want to do is ensure that it's scrolled to the top, then wherever the text is added try:</p>
<pre><code>[self.mainTextView setContentOffset:CGPointZero animated:NO];
</code></pre>
<p>EDIT: AutoLayout with any kind of scrollview gets wonky fast. That setting a fixed width solves it isn't surprising. If it doesn't work in <code>-viewDidLayoutSubviews</code> then that is odd. Setting a layout constraint manually may work. First create the constraints in IB: </p>
<pre><code>@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
</code></pre>
<p>then in the ViewController</p>
<pre><code> -(void)updateViewConstraints {
self.textViewWidthConstraint.constant = self.view.frame.size.width - 40.0f;
self.textViewHeightConstraint.constant = self.view.frame.size.height - 40.0f;
[super updateViewConstraints];
}
</code></pre>
<p>May still be necessary to setContentOffset in <code>-viewDidLayoutSubviews</code>.</p>
<p>(Another method would be to create a layout constraint for "'equal' widths" and "'equal' heights" between the textView and its superView, with a constant of "-40". It's only 'equal' if the constant is zero, otherwise it adjusts by the constant. But because you can only add this constraint to a view that constraints both views, you can't do this in IB.) </p>
<p>You may ask yourself, if I have to do this, what's the point of AutoLayout? I've studied AutoLayout in depth, and that is an excellent question. </p> |
22,583,264 | Rectangle detection in image | <p>I'd like to program a detection of a rectangular sheet of paper which doesn't absolutely need to be perfectly straight on each side as I may take a picture of it "in the air" which means the single sides of the paper might get distorted a bit.</p>
<p>The app (iOs and android) CamScanner does this very very good and Im wondering how this might be implemented. First of all I thought of doing:</p>
<ul>
<li>smoothing / noise reduction</li>
<li>Edge detection (canny etc) OR thresholding (global / adaptive)</li>
<li>Hough Transformation</li>
<li>Detecting lines (only vertically / horizontally allowed)</li>
<li>Calculate the intercept point of 4 found lines</li>
</ul>
<p>But this gives me much problems with different types of images.
And I'm wondering if there's maybe a better approach in directly detecting a rectangular-like shape in an image and if so, if maybe camscanner does implement it like this as well!?</p>
<p>Here are some images taken in CamScanner.
These ones are detected quite nicely even though in a) the side is distorted (but the corner still gets shown in the overlay but doesnt really fit the corner of the white paper) and in b) the background is pretty close to the actual paper but it still gets recognized correctly:</p>
<p><img src="https://i.stack.imgur.com/h3pP8.jpg" alt="a)"> <img src="https://i.stack.imgur.com/5QBCa.jpg" alt="b)"></p>
<p>It even gets the rotated pictures correctly:</p>
<p><img src="https://i.stack.imgur.com/BBkeg.png" alt="enter image description here"></p>
<p>And when Im inserting some testing errors, it fails but at least detects some of the contour, but always try to detect it as a rectangle:</p>
<p><img src="https://i.stack.imgur.com/15x9U.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/GUiew.png" alt="enter image description here"></p>
<p>And here it fails completely:</p>
<p><img src="https://i.stack.imgur.com/VEGlh.png" alt="enter image description here"></p>
<p>I suppose in the last three examples, if it would do hough transformation, it could have detected at least two of the four sides of the rectangle.</p>
<p>Any ideas and tips?
Thanks a lot in advance</p> | 35,966,827 | 1 | 0 | null | 2014-03-22 20:39:02.317 UTC | 10 | 2016-05-10 12:31:16.287 UTC | null | null | null | null | 701,049 | null | 1 | 10 | image|image-processing|rectangles|edge-detection|hough-transform | 3,684 | <p><a href="http://opencv-code.com/tutorials/detecting-simple-shapes-in-an-image/" rel="nofollow noreferrer">OpenCV</a> framework may help your problem. Also, you can look to <a href="http://opencv.org/platforms/android.html" rel="nofollow noreferrer">this document</a> for the <code>Android</code> platform.</p>
<p><a href="https://i.stack.imgur.com/rYNyU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rYNyU.png" alt="Detecting simple shapes in an image"></a></p>
<p>The full source code is available on <a href="https://github.com/bsdnoobz/opencv-code/blob/master/shape-detect.cpp" rel="nofollow noreferrer">Github</a>.</p> |
39,106,633 | How do I get the value in TextInput when onBlur is called? | <p>In React Native, I want to pass the value of the <code>TextInput</code> in the <code>onBlur</code> event handler.</p>
<pre><code>onBlur={(e) => this.validateText(e.target.value)}
</code></pre>
<p><code>e.target.value</code> works for plain React. But, in react-native, <code>e.target.value</code> is undefined. What is the structure of event args available in React Native?</p> | 39,106,771 | 4 | 0 | null | 2016-08-23 16:42:55.67 UTC | 8 | 2021-12-18 14:13:13.963 UTC | 2021-06-04 07:03:15.49 UTC | null | 6,904,888 | null | 558,972 | null | 1 | 32 | react-native | 37,152 | <p>In React Native, you can get the value of the TextInput from <code>e.nativeEvent.text</code>.</p>
<p>Unfortunately, this doesn't work for <code>multiline={true}</code>. One hack around this is to maintain a ref to your <code>TextInput</code> and access the text value through the <code>_lastNativeText</code> property of the component. For example (assuming you've assigned your <code>TextInput</code> component a ref of "textInput"):</p>
<p><code>onBlur={() => console.log(this.refs.textInput._lastNativeText)}</code></p> |
2,975,091 | jQuery Droppable, get the element dropped | <p>A small question hopefully with a simple answer, I am using jQuery draggable and droppable to place items into a dock. Using the below code for the drop.</p>
<pre><code>$("#dock").droppable({
drop: function(event, ui) {
//Do something to the element dropped?!?
}
});
</code></pre>
<p>However I couldn't find a way to get what element was actually dropped, so I can do something do it. Is this possible?</p> | 2,975,132 | 1 | 0 | null | 2010-06-04 14:36:01.43 UTC | 9 | 2021-05-21 11:57:28.713 UTC | 2017-08-10 00:12:08.953 UTC | null | 881,229 | null | 193,376 | null | 1 | 56 | jquery|jquery-ui|jquery-ui-draggable|jquery-ui-droppable | 64,411 | <p>From the <a href="http://jqueryui.com/demos/droppable/#event-drop" rel="nofollow noreferrer">drop event documentation</a>:</p>
<blockquote>
<p>This event is triggered when an
accepted draggable is dropped 'over'
(within the tolerance of) this
droppable. In the callback, <code>$(this)</code>
represents the droppable the draggable
is dropped on. While <code>ui.draggable</code> represents
the draggable.</p>
</blockquote>
<p>So:</p>
<pre><code>$("#dock").droppable({
drop: function(event, ui) {
// do something with the dock
$(this).doSomething();
// do something with the draggable item
$(ui.draggable).doSomething();
}
});
</code></pre> |
38,022,658 | Selenium Python - Handling No such element exception | <p>I am writing automation test in Selenium using Python. One element may or may not be present. I am trying to handle it with below code, it works when element is present. But script fails when element is not present, I want to continue to next statement if element is not present.</p>
<pre><code>try:
elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
elem.click()
except nosuchelementexception:
pass
</code></pre>
<p>Error - </p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}
</code></pre> | 38,023,345 | 5 | 0 | null | 2016-06-24 21:56:48.827 UTC | 8 | 2022-08-25 20:36:06.623 UTC | 2016-07-01 02:23:15.027 UTC | null | 5,409,601 | null | 6,510,843 | null | 1 | 27 | python|python-3.x|selenium|selenium-webdriver | 83,502 | <p>You can see if the element exists and then click it if it does. No need for exceptions. Note the plural "s" in <code>.find_elements_*</code>.</p>
<pre><code>elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
if len(elem) > 0
elem[0].click()
</code></pre> |
981,375 | Using a Django custom model method property in order_by() | <p>I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()?</p>
<p>Here is an example that demonstrates how the property is implemented.</p>
<pre><code>class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def _get_full_name(self):
return u'%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
def __unicode__(self):
return self.full_name
</code></pre>
<p>With this model I can do:</p>
<pre><code>>>> Author.objects.all()
[<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>]
>>> Author.objects.order_by('first_name')
[<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>]
</code></pre>
<p>But I cannot do:</p>
<pre><code>>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name
</code></pre>
<p>What would be the correct way to use order_by on a custom property like this?</p> | 981,802 | 1 | 0 | null | 2009-06-11 14:18:10.93 UTC | 11 | 2016-01-29 14:22:43.22 UTC | null | null | null | null | 112,517 | null | 1 | 44 | python|django|django-models | 18,804 | <p>No, you can't do that. <code>order_by</code> is applied at the database level, but the database can't know anything about your custom Python methods.</p>
<p>You can either use the separate fields to order:</p>
<pre><code>Author.objects.order_by('first_name', 'last_name')
</code></pre>
<p>or do the ordering in Python:</p>
<pre><code>sorted(Author.objects.all(), key=lambda a: a.full_name)
</code></pre> |
2,351,630 | Fuzzy Regular Expressions | <p>In my work I have with great results used approximate string matching algorithms such as Damerau–Levenshtein distance to make my code less vulnerable to spelling mistakes.</p>
<p>Now I have a need to match strings against simple regular expressions such <code>TV Schedule for \d\d (Jan|Feb|Mar|...)</code>. This means that the string <code>TV Schedule for 10 Jan</code> should return 0 while <code>T Schedule for 10. Jan</code> should return 2.</p>
<p>This could be done by generating all strings in the regex (in this case 100x12) and find the best match, but that doesn't seam practical.</p>
<p>Do you have any ideas how to do this effectively?</p> | 2,378,624 | 6 | 0 | null | 2010-02-28 16:08:14.513 UTC | 20 | 2020-08-21 11:34:48.087 UTC | 2015-11-16 22:23:59.683 UTC | null | 1,505,120 | null | 205,521 | null | 1 | 51 | regex|string|fuzzy-search|fuzzy-comparison|tre-library | 24,811 | <p>I found the <a href="http://laurikari.net/tre/about/" rel="noreferrer">TRE library</a>, which seems to be able to do exactly fuzzy matching of regular expressions. Example: <a href="http://hackerboss.com/approximate-regex-matching-in-python/" rel="noreferrer">http://hackerboss.com/approximate-regex-matching-in-python/</a>
It only supports insertion, deletion and substitution though. No transposition. But I guess that works ok.</p>
<p>I tried the accompanying agrep tool with the regexp on the following file:</p>
<pre><code>TV Schedule for 10Jan
TVSchedule for Jan 10
T Schedule for 10 Jan 2010
TV Schedule for 10 March
Tv plan for March
</code></pre>
<p>and got</p>
<pre><code>$ agrep -s -E 100 '^TV Schedule for \d\d (Jan|Feb|Mar)$' filename
1:TV Schedule for 10Jan
8:TVSchedule for Jan 10
7:T Schedule for 10 Jan 2010
3:TV Schedule for 10 March
15:Tv plan for March
</code></pre>
<p>Thanks a lot for all your suggestions.</p> |
2,855,884 | Use the right tool for the job: embedded programming | <p>I'm interested in programming languages well suited for embedded programming.
In particular:</p>
<p>Is it possible to program embedded systems in C++?
Or is it better to use pure C?
Or is C++ OK only if some features of the language (e.g. RTTI, exceptions and templates) are excluded?</p>
<p>What about Java in this domain?</p>
<p>Thanks.</p> | 2,860,753 | 8 | 1 | null | 2010-05-18 09:19:36.787 UTC | 12 | 2014-09-01 14:08:27.587 UTC | null | null | null | null | 343,841 | null | 1 | 17 | java|c++|c|embedded | 4,379 | <blockquote>
<p>Is it possible to program embedded
systems in C++? </p>
</blockquote>
<p>Yes, of course, even on 8bit systems. C++ only has a slightly different run-time initialisation requirements than C, that being that before main() is invoked constructors for any static objects must be called. The overhead (not including the constructors themselves which is within your control) for that is tiny, though you do have to be careful since the order of construction is not defined.</p>
<p>With C++ you only pay for what you use (and much that is useful may be free). That is to say for example, a piece of C code that is also C++ compilable will generally require no more memory and execute no slower when compiled as C++ than when compiled as C. There are some elements of C++ that you may need to be careful with, but much of the most useful features come at little or no cost, and great benefit. </p>
<blockquote>
<p>Or is it better to use
pure C? </p>
</blockquote>
<p>Possibly, in some cases. Some smaller 8 and even 16 bit targets have no C++ compiler (or at least not one of any repute), using C code will give greater portability should that be an issue. Moreover on severely resource constrained targets with small applications, the benefits that C++ can bring over C are minimal. The extra features in C++ (primarily those that enable OOP) make it suited to relatively large and complex software construction.</p>
<blockquote>
<p>Or is C++ OK only if some
features of the language (e.g. RTTI,
exceptions and templates) are
excluded?</p>
</blockquote>
<p>The language features that may be acceptable depend entirely on the target and the application. If you are memory constrained, you might avoid expensive features or libraries, and even then it may depend on whether it is code or data space you are short of (on targets where these are separate). If the application is <a href="http://en.wikipedia.org/wiki/Hard_real_time#Hard_and_soft_real-time_systems" rel="noreferrer">hard real-time</a>, you would avoid those features and library classes that are non-deterministic.</p>
<p>In general, I suggest that if your target will be 32bit, always use C++ in preference to C, then cut your C++ to suit the memory and performance constraints. For smaller parts be a little more circumspect when choosing C++, though do not discount it altogether; it can make life easier. </p>
<p>If you do choose to use C++, make sure you have decent debugger hardware/software that is C++ aware. The relative ease with which complex software can be constructed in C++, make a decent debugger even more valuable. Not all tools in the embedded arena are C++ aware or capable.</p>
<p>I always recommend digging in the archives at <a href="http://embedded.com" rel="noreferrer">Embedded.com</a> on any embedded subject, it has a wealth of articles, including a number of just this question, including:</p>
<ul>
<li><a href="http://www.embedded.com/electronics-blogs/programming-pointers/4027504/Poor-reasons-for-rejecting-C-" rel="noreferrer">Poor reasons for rejecting C++</a></li>
<li><a href="http://www.embedded.com/electronics-blogs/barr-code/4027479/Real-men-program-in-C" rel="noreferrer">Real men program in C</a></li>
<li><a href="http://www.embedded.com/design/prototyping-and-development/4008235/Dive-in-to-C--and-survive" rel="noreferrer">Dive in to C++ and survive</a></li>
<li><a href="http://www.embedded.com/design/mcus-processors-and-socs/4007552/Guidelines-for-using-C--as-an-alternative-to-C-in-embedded-designs-Part-1" rel="noreferrer">Guidelines for using C++ as an alternative to C in embedded designs</a></li>
<li><a href="http://www.embedded.com/design/prototyping-and-development/4008168/Why-C--is-a-viable-alternative-to-C-in-embedded-systems-design" rel="noreferrer">Why C++ is a viable alternative to C in embedded systems design</a></li>
<li><a href="http://www.embedded.com/electronics-blogs/programming-pointers/4026943/Better-even-at-the-lowest-levels" rel="noreferrer">Better even at the lowest levels</a></li>
</ul>
<p>Regarding Java, I am no expert, but it has significant run-time requirements that make it unsuited to resource constrained systems. You will probably constrain yourself to relatively expensive hardware using Java. Its primary benefit is platform independence, but that portability does not extend to platforms that cannot support Java (of which there are many), so it is arguably less portable than a well designed C or C++ implementation with an abstracted hardware interface.</p>
<p><strong>[edit]</strong> Concidentally I just received this in the TechOnline newsletter: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/ESC_San_Jose_98_401_paper.pdf" rel="noreferrer">Using C++ Efficiently in Embedded Applications</a></p> |
2,589,949 | String literals: Where do they go? | <p>I am interested in where string literals get allocated/stored.</p>
<p>I did find one intriguing answer <a href="https://stackoverflow.com/questions/51592/is-there-a-need-to-destroy-char-string-or-char-new-char6/51607#51607">here</a>, saying:</p>
<blockquote>
<p>Defining a string inline actually embeds the data in the program itself and cannot be changed (some compilers allow this by a smart trick, don't bother).</p>
</blockquote>
<p>But, it had to do with C++, not to mention that it says not to bother.</p>
<p>I am bothering. =D</p>
<p>So my question is where and how is my string literal kept? Why should I not try to alter it? Does the implementation vary by platform? Does anyone care to elaborate on the "smart trick?"</p> | 2,589,963 | 8 | 0 | null | 2010-04-07 04:11:10.083 UTC | 94 | 2021-09-02 07:18:29.753 UTC | 2017-05-23 12:18:23.85 UTC | null | -1 | null | 300,807 | null | 1 | 182 | c|memory|string-literals | 93,359 | <p>A common technique is for string literals to be put in "read-only-data" section which gets mapped into the process space as read-only (which is why you can't change it).</p>
<p>It does vary by platform. For example, simpler chip architectures may not support read-only memory segments so the data segment will be writable.</p>
<p>Rather than try to figure out a trick to make string literals changeable (it will be highly dependent on your platform and could change over time), just use arrays:</p>
<pre><code>char foo[] = "...";
</code></pre>
<p>The compiler will arrange for the array to get initialized from the literal and you can modify the array.</p> |
3,129,322 | How do I get monitor resolution in Python? | <p>What is the simplest way to get monitor resolution (preferably in a tuple)? </p> | 3,129,330 | 32 | 3 | null | 2010-06-27 23:39:21.63 UTC | 55 | 2022-06-07 11:53:37.637 UTC | 2015-05-18 01:44:42.84 UTC | null | 3,924,118 | null | 433,417 | null | 1 | 177 | python|screen|resolution | 265,797 | <p>On Windows:</p>
<pre><code>from win32api import GetSystemMetrics
print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))
</code></pre>
<p>If you are working with high resolution screen, make sure your python interpreter is HIGHDPIAWARE.</p>
<p>Based on <a href="https://bytes.com/topic/python/answers/618587-screen-size-resolution-win32-python#post2443223" rel="noreferrer">this</a> post.</p> |
40,055,764 | Setting arrays in Firebase using Firebase console | <p>I am using Firebase console for preparing data for a demo app. One of the data item is attendees. Attendees is an array. I want to add a few attendees as an array in Firebase. I understand Firebase does not have arrays, but object with keys (in chronological order). How do I do that for preparing sample data? My current Firebase data looks like the below.
<a href="https://i.stack.imgur.com/bfoeC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bfoeC.png" alt="enter image description here"></a></p> | 40,055,996 | 4 | 0 | null | 2016-10-15 06:28:14.703 UTC | 13 | 2021-03-05 19:35:28.86 UTC | null | null | null | null | 558,972 | null | 1 | 23 | arrays|firebase|firebase-realtime-database|firebase-console | 39,900 | <p>The Firebase Database doesn't store arrays. It stores dictionaries/associate arrays. So the closest you can get is:</p>
<pre><code>attendees: {
0: "Bill Gates",
1: "Larry Page",
2: "James Tamplin"
}
</code></pre>
<p>You can build this structure in the Firebase Console. And then when you read it with one of the Firebase SDKs, it will be translated into an array.</p>
<pre><code>firebase.database().ref('attendees').once('value', function(snapshot) {
console.log(snapshot.val());
// ["Bill Gates", "Larry Page", "James Tamplin"]
});
</code></pre>
<p>So this may be the result that you're look for. But I recommend reading this blog post on why Firebase prefers it if you don't store arrays: <a href="https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html">https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html</a>.</p>
<h1>Don't use an array, when you actually need a set</h1>
<p>Most developers are not actually trying to store an array and I think your case might be one of those. For example: can "Bill Gates" be an attendee twice? </p>
<pre><code>attendees: {
0: "Bill Gates",
1: "Larry Page",
2: "James Tamplin",
3: "Bill Gates"
}
</code></pre>
<p>If not, you're going to have to check whether he's already in the array before you add him.</p>
<pre><code>if (!attendees.contains("Bill Gates")) {
attendees.push("Bill Gates");
}
</code></pre>
<p>This is a clear sign that your data structure is sub-optimal for the use-case. Having to check all existing children before adding a new one is going to limit scalability.</p>
<p>In this case, what you really want is a set: a data structure where each child can be present only once. In Firebase you model sets like this:</p>
<pre><code>attendees: {
"Bill Gates": true,
"Larry Page": true,
"James Tamplin": true
}
</code></pre>
<p>And now whenever you try to add Bill Gates a second time, it's a no-op:</p>
<pre><code>attendees["Bill Gates"] = true;
</code></pre>
<p>So instead of having to code for the uniqueness requirement, the data structure implicitly solves it.</p> |
6,285,711 | How would I model data that is heirarchal and relational in a document-oriented database system like RavenDB? | <p>Document oriented databases (particularly RavenDB) are really intriguing me, and I'm wanting to play around with them a bit. However as someone who is very used to relational mapping, I was trying to think of how to model data correctly in a document database.</p>
<p>Say I have a CRM with the following entities in my C# application (leaving out unneeded properties):</p>
<pre><code>public class Company
{
public int Id { get; set; }
public IList<Contact> Contacts { get; set; }
public IList<Task> Tasks { get; set; }
}
public class Contact
{
public int Id { get; set; }
public Company Company { get; set; }
public IList<Task> Tasks { get; set; }
}
public class Task
{
public int Id { get; set; }
public Company Company { get; set; }
public Contact Contact { get; set; }
}
</code></pre>
<p>I was thinking of putting this all in a <code>Company</code> document, as contacts and tasks do not have a purpose out side of companies, and most of the time query for a task or contacts will also show information about the associated company. </p>
<p>The issue comes with <code>Task</code> entities. Say the business requires that a task is ALWAYS associated with a company but optionally also associated with a task.</p>
<p>In a relational model this is easy, as you just have a <code>Tasks</code> table and have the <code>Company.Tasks</code> relate to all tasks for the company, while <code>Contact.Tasks</code> only show the tasks for the specific Task. </p>
<p>For modeling this in a document database, I thought of the following three ideas:</p>
<ol>
<li><p>Model Tasks as a separate document. This seems kind of anti-document db as most of the time you look at a company or contact you will want to see the list of tasks, thus having to perform joins over documents a lot.</p></li>
<li><p>Keep tasks that are not associated with a contact in the <code>Company.Tasks</code> list and put tasks assocaited with a contact in the list for each individual contacts. This unfortunately means that if you want to see all tasks for a company (which will probably be a lot) you have to combine all tasks for the company with all tasks for each individual contact. I also see this being complicated when you want to disassociate a task from a contact, as you have to move it from the contact to the company</p></li>
<li><p>Keep all tasks in the <code>Company.Tasks</code> list, and each contact has a list of id values for tasks it is associated with. This seems like a good approach except for having to manually take id values and having to make a sub-list of <code>Task</code> entities for a contact.</p></li>
</ol>
<p>What is the recommended way to model this data in a document oriented database?</p> | 6,289,992 | 2 | 0 | null | 2011-06-08 21:51:36.667 UTC | 11 | 2011-06-09 08:28:03.37 UTC | null | null | null | null | 231,002 | null | 1 | 12 | data-modeling|ravendb|document-database|document-based-database | 992 | <p>Use denormalized references:</p>
<p><a href="http://ravendb.net/faq/denormalized-references" rel="noreferrer">http://ravendb.net/faq/denormalized-references</a></p>
<p>in essence you have a DenormalizedReference class:</p>
<pre><code>public class DenormalizedReference<T> where T : INamedDocument
{
public string Id { get; set; }
public string Name { get; set; }
public static implicit operator DenormalizedReference<T> (T doc)
{
return new DenormalizedReference<T>
{
Id = doc.Id,
Name = doc.Name
}
}
}
</code></pre>
<p>your documents look like - i've implemented the INamedDocument interface - this can be whatever you need it to be though:</p>
<pre><code>public class Company : INamedDocument
{
public string Name{get;set;}
public int Id { get; set; }
public IList<DenormalizedReference<Contact>> Contacts { get; set; }
public IList<DenormalizedReference<Task>> Tasks { get; set; }
}
public class Contact : INamedDocument
{
public string Name{get;set;}
public int Id { get; set; }
public DenormalizedReference<Company> Company { get; set; }
public IList<DenormalizedReference<Task>> Tasks { get; set; }
}
public class Task : INamedDocument
{
public string Name{get;set;}
public int Id { get; set; }
public DenormalizedReference<Company> Company { get; set; }
public DenormalizedReference<Contact> Contact { get; set; }
}
</code></pre>
<p>Now saving a Task works exactly as it did before:</p>
<pre><code>var task = new Task{
Company = myCompany,
Contact = myContact
};
</code></pre>
<p>However pulling all this back will mean you're only going to get the denormalized reference for the child objects. To hydrate these I use an index:</p>
<pre><code>public class Tasks_Hydrated : AbstractIndexCreationTask<Task>
{
public Tasks_Hydrated()
{
Map = docs => from doc in docs
select new
{
doc.Name
};
TransformResults = (db, docs) => from doc in docs
let Company = db.Load<Company>(doc.Company.Id)
let Contact = db.Load<Contact>(doc.Contact.Id)
select new
{
Contact,
Company,
doc.Id,
doc.Name
};
}
}
</code></pre>
<p>And using your index to retrieve the hydrated tasks is:</p>
<pre><code>var tasks = from c in _session.Query<Projections.Task, Tasks_Hydrated>()
where c.Name == "taskmaster"
select c;
</code></pre>
<p>Which i think is quite clean :)</p>
<p>As a design conversation - the general rule is that if you <em>ever</em> need to load the child documents <em>alone</em> as in - not part of the parent document. Whether that be for editing or viewing - you should model it with it's own Id as it's own document. Using the method above makes this quite simple.</p> |
5,754,367 | using substitute to get argument name with | <p>I'm trying to get the names of arguments in the global environment within a function. I know I can use substitute to get the name of named arguments, but I would like to be able to do the same thing with ... arguments. I kinda got it to work for the first element of ... but can't figure out how to do it for the rest of the elements. Any idea how to get this working as intended.</p>
<pre><code>foo <- function(a,...)
{
print(substitute(a))
print(eval(enquote(substitute(...))))
print(sapply(list(...),function(x) eval(enquote(substitute(x)),env=.GlobalEnv)))
}
x <- 1
y <- 2
z <- 3
foo(x,y,z)
x
y
[[1]]
X[[1L]]
[[2]]
X[[2L]]
</code></pre> | 5,754,699 | 2 | 0 | null | 2011-04-22 10:06:45.98 UTC | 18 | 2011-04-22 20:13:33.903 UTC | null | null | null | null | 615,174 | null | 1 | 33 | r | 10,600 | <p>The canonical idiom here is <code>deparse(substitute(foo))</code>, but the <code>...</code> needs slightly different processing. Here is a modification that does what you want:</p>
<pre><code>foo <- function(a, ...) {
arg <- deparse(substitute(a))
dots <- substitute(list(...))[-1]
c(arg, sapply(dots, deparse))
}
x <- 1
y <- 2
z <- 3
> foo(x,y,z)
[1] "x" "y" "z"
</code></pre> |
19,720,102 | Mybatis Generator: What's the best way to separate out "auto generated" and "hand edited files" | <p>I am on a project that uses both <em>Mybatis</em> (for persisting java to database) and <em>Mybatis Generator</em> (to automatically generate the mapper xml files and java interfaces from a database schema). </p>
<p>Mybatis generator does a good job at generating the files necessary for basic crud operation.</p>
<p><strong>Context</strong></p>
<p>For some of the tables/classes, we will need more "stuff" (code queries, etc) than the "crud stuff" generated by the MyBatis Generator tool. </p>
<p>Is there any way to have "best of both worlds", i.e use auto generation as as well as "custom code". How do you separate out and structure the "hand edited files" and "automatically generated files". </p>
<p><strong>Proposal</strong></p>
<p>I was thinking about the following, i.e. for table "Foo"</p>
<p><em>Auto-Generated</em></p>
<ul>
<li>FooCrudMapper.xml </li>
<li>interface FooCrud.java</li>
</ul>
<p>(where "Crud" stands for "Create Read Update Delete")</p>
<p><em>Hand Edited</em></p>
<ul>
<li>FooMapper.xml</li>
<li>interface Foo extends FooCrud</li>
</ul>
<p>The notion: if the schema changed, you could always safely autogenerate the "Crud" xml and .java files without wiping out any of the custom changes.</p>
<p><strong>Questions</strong></p>
<ul>
<li><p>Would mybatis correctly handle this scenario, i.e. would this mapper correctly execute the auto-generated 'crud code'?</p>
<p>FooMapper fooMapper = sqlSession.getMapper(FooMapper.class);</p></li>
<li><p>What approach do you recommend?</p></li>
</ul>
<p>Edit 1:
* Our db design uses a 'core table' ("element") with other tables 'extending' that table and adding extra attributes (shared key) . I've looked at docs and source concluded that I cannot use Mybatis Generator in conjunction with such 'extension' without any hand editing:</p>
<p>i.e. This does not work.
-ElementMapper extends "ElementCrudMapper"
-FooMapper.xml extends both "ElementCrudMapper" and "FooCrudMapper"</p>
<p>thanks all!</p> | 19,851,854 | 4 | 0 | null | 2013-11-01 02:59:45.6 UTC | 24 | 2018-09-14 08:58:30.567 UTC | 2013-11-15 11:18:25.003 UTC | null | 271,236 | null | 331,465 | null | 1 | 12 | mybatis|mybatis-generator | 12,179 | <p>I can seperate out generated files and hand edited files.</p>
<p>I use mybatis-spring and spring to manage dao interfaces. This library allows MyBatis to participate in Spring transactions, takes care of building MyBatis mappers and SqlSessions and inject them into other beans, translates MyBatis exceptions into Spring DataAccessExceptions, and finally, it lets you build your application code free of dependencies on MyBatis, Spring or <a href="http://mybatis.github.io/spring/index.html" rel="noreferrer">MyBatis-Spring</a>.</p>
<p><strong>For DAO Interfaces</strong>, I write a generic MybatisBaseDao to represent base interface generated by mybatis generator.</p>
<pre><code> public interface MybatisBaseDao<T, PK extends Serializable, E> {
int countByExample(E example);
int deleteByExample(E example);
int deleteByPrimaryKey(PK id);
int insert(T record);
int insertSelective(T record);
List<T> selectByExample(E example);
T selectByPrimaryKey(PK id);
int updateByExampleSelective(@Param("record") T record, @Param("example") E example);
int updateByExample(@Param("record") T record, @Param("example") E example);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
}
</code></pre>
<p>Of course, you can custom your <code>BaseDao</code> according to your demand. For example we have a <code>UserDao</code>, Then you can defind it like this</p>
<pre><code>public interface UserDao extends MybatisBaseDao<User, Integer, UserExample>{
List<User> selectUserByAddress(String address); // hand edited query method
}
</code></pre>
<p><strong>For mapper xml files</strong>, I create two packages in mapper(.xml) base folder to separate generated files and hand edited files. For <code>UserDao</code> above, I put UserMapper.xml generated by generator in package named 'generated'. I put all hand writing mapper sqls into another UserMapper.xml file in the package named <code>manual</code>. The two mapper files start with the same header <code><mapper namespace="com.xxx.dao.UserDao" ></code>. Mybatis can scan the xml mapper files to map sql and corresponding interface method automatically.</p>
<p><strong>For generated entities and example objects</strong> I overwrite them directly.</p>
<p>I hope the method above can help you!</p> |
19,330,731 | Tree implementation in Java (root, parents and children) | <p>I need to create a tree structure similar as the attached image in Java. I've found some questions related to this one but I haven't found a convincing and well explained response.
The application business consists in food super categories (main courses, desserts and other). Each of these categories can have parent items or children items and so on.</p>
<p><img src="https://i.stack.imgur.com/5kJXf.gif" alt="Desired tree Structure"></p> | 22,419,453 | 8 | 0 | null | 2013-10-12 05:03:46.333 UTC | 29 | 2020-12-04 17:08:09.07 UTC | 2013-10-12 05:55:13.613 UTC | null | 1,431,669 | null | 1,210,389 | null | 1 | 38 | java|tree|structure | 175,550 | <pre><code>import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private List<Node<T>> children = new ArrayList<Node<T>>();
private Node<T> parent = null;
private T data = null;
public Node(T data) {
this.data = data;
}
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setParent(Node<T> parent) {
parent.addChild(this);
this.parent = parent;
}
public void addChild(T data) {
Node<T> child = new Node<T>(data);
child.setParent(this);
this.children.add(child);
}
public void addChild(Node<T> child) {
child.setParent(this);
this.children.add(child);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRoot() {
return (this.parent == null);
}
public boolean isLeaf() {
return this.children.size == 0;
}
public void removeParent() {
this.parent = null;
}
}
</code></pre>
<p>Example:</p>
<pre><code>import java.util.List;
Node<String> parentNode = new Node<String>("Parent");
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");
childNode2.setParent(parentNode);
Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1);
List<Node<String>> childrenNodes = parentNode.getChildren();
</code></pre> |
32,451,718 | WARNING: Exception encountered during context initialization - cancelling refresh attempt | <p>Error is as shown below. The problem is, occurring as below, this XmlWebApplicationContext need not occur, since it's injecting the bean again. How to avoid it?</p>
<pre><code>org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Initializing Spring root WebApplicationContext
Sep 08, 2015 12:40:44 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Sep 08, 2015 12:40:44 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Sep 08 12:40:44 IST 2015]; root of context hierarchy
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/ServiceApiContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/RuleEngineContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/applicationContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/CacheContext.xml]
Sep 08, 2015 12:40:45 PM org.springframework.web.context.support.XmlWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
... 19 more
Sep 08, 2015 12:40:45 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
... 19 more
Sep 08, 2015 12:40:45 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
... 19 more
</code></pre>
<p>Web.xml</p>
<pre><code><!-- USing the dispatcher servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- The pattern is /* -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Looking for beans in *Context.xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context/*Context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code></pre>
<p></p>
<p>Dispatcher-Servlet.xml</p>
<p></p>
<pre><code><!-- <import resource="/WEB-INF/context/*Context.xml"></import> -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</code></pre>
<p></p>
<p>Then we have a bunch of context xmls available in the folder "CONTEXT".</p>
<p>Pom: <a href="https://i.stack.imgur.com/6K1pe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6K1pe.png" alt="This is my pom"></a></p>
<p>PersistenceManager has that class:</p>
<pre><code>[![PersistenceManager is in the war][2]][2]
</code></pre> | 32,577,002 | 5 | 0 | null | 2015-09-08 07:28:21.047 UTC | 5 | 2022-06-20 21:43:58.04 UTC | 2015-09-08 07:52:09.173 UTC | null | 3,977,629 | null | 3,977,629 | null | 1 | 12 | java|xml|spring|spring-mvc | 158,633 | <p>This was my stupidity, but a stupidity that was not easy to identify :).</p>
<p>Problem:</p>
<ol>
<li>My code is compiled on Jdk 1.8.</li>
<li>My eclipse, had JDK 1.8 as the compiler.</li>
<li>My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.</li>
<li>To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
<ol start="5">
<li>Post this, clean the server, build and redeploy, start the tomcat. </li>
</ol></li>
</ol>
<p>If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war. </p>
<p>If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!</p> |
21,386,671 | Best practice cassandra setup on ec2 with large amount of data | <p>I am doing a large migration from physical machines to ec2 instances.</p>
<p>As of right now I have 3 x.large nodes each with 4 instance store drives (raid-0 1.6TB). After I set this this up I remembered that "The data on an instance store volume persists only during the life of the associated Amazon EC2 instance; if you stop or terminate an instance, any data on instance store volumes is lost."</p>
<p>What do people usually do in this situation? I am worried that if one of the boxes crash then all of the data will be lost on that box if it is not 100% replicated on another. </p>
<p><a href="http://www.hulen.com/?p=326" rel="nofollow noreferrer">http://www.hulen.com/?p=326</a>
I read in the above link that these guys use ephermal drives and periodically backup the content using the EBS drives and snapshots." </p>
<p>In this question here: <a href="https://stackoverflow.com/questions/10749099/how-to-take-backup-of-aws-ec2-instance-ephemeral-storage">How do I take a backup of aws ec2 instance/ephemeral storage?</a>
People claim that you cannot backup ephermal data onto EBS snapshots.</p>
<p>Is my best choice to use a few EBS drives and raid0 them together and be able to take snapshots directly from them? I know this is probably the most expensive solution, however, it seems to make the most sense.</p>
<p>Any info would be great. </p>
<p>Thank you for your time.</p> | 21,389,090 | 2 | 1 | null | 2014-01-27 16:51:30.197 UTC | 10 | 2014-01-30 01:07:59.423 UTC | 2017-05-23 11:45:46.413 UTC | null | -1 | null | 1,991,065 | null | 1 | 15 | amazon-web-services|amazon-ec2|cassandra|storage | 13,725 | <p>I have been running Cassandra on EC2 for over 2 years. To address your concerns, you need to form a proper availability architecture on EC2 for your Cassandra cluster. Here is a bullet list for you to consider:</p>
<ol>
<li>Consider at least 3 zones for setting up your cluster;</li>
<li>Use NetworkTopologyStrategy with EC2Snitch/EC2MultiRegionSnitch to propagate a replica of your data to each zone; this means that the machines in each zone will have your full data set combined; for example the strategy_options would be like {us-east:3}.</li>
</ol>
<p>The above two tips should satisfy basic availability in AWS and in case your queries are sent using LOCAL_QUORUM, your application will be fine even if one zone goes down.</p>
<p>If you are concerned about 2 zones going down (don't recall it happened in AWS for the past 2 years of my use), then you can also add another region to your cluster. </p>
<p>With the above, if any node dies for any reason, you can restore it from nodes in other zones. After all, CAssandra was designed to provide you with this kind of availability.</p>
<p>About EBS vs Ephemeral:</p>
<p>I have always been against using EBS volumes in anything production because it is one of the worst AWS service in terms of availability. They go down several times a year, and their downside usually cascades to other AWS services like ELBs and RDS. They are also like attached Network storage, so any read/write will have to go over the Network. Don't use them. Even DataStax doesn't recommend them:</p>
<p><a href="http://www.datastax.com/documentation/cassandra/1.2/webhelp/index.html#cassandra/architecture/../../cassandra/architecture/architecturePlanningEC2_c.html" rel="noreferrer">http://www.datastax.com/documentation/cassandra/1.2/webhelp/index.html#cassandra/architecture/../../cassandra/architecture/architecturePlanningEC2_c.html</a></p>
<p>About Backups:</p>
<p>I use a solution called Priam (<a href="https://github.com/Netflix/Priam" rel="noreferrer">https://github.com/Netflix/Priam</a>) which was written by Netflix. It can take a nightly snapshot of your cluster and copy everything to S3. If you enable incremental_backups, it also uploads incremental backups to S3. In case a node goes down, you can trigger a restore on the specific node using a simple API call. It restores a lot faster and does not put a lot of streaming load on your other nodes. I also added a patch to it which let's you do fancy things like bringing up multiple DCs inside one AWS region.</p>
<p>You can read about my setup here:
<a href="http://aryanet.com/blog/shrinking-the-cassandra-cluster-to-fewer-nodes" rel="noreferrer">http://aryanet.com/blog/shrinking-the-cassandra-cluster-to-fewer-nodes</a></p>
<p>Hope above helps.</p> |
19,185,848 | How to save an image to Database using MVC 4 | <p>So I have a project which is a Shopping Cart, I have to save images to the database instead of uploading them to the server, here is my model</p>
<pre><code>namespace ShoppingCart.Models
{
[Bind(Exclude = "ItemID")]
public class Item
{
[ScaffoldColumn(false)]
public int ItemID { get; set; }
[DisplayName("Category")]
public int CategoryID { get; set; }
[DisplayName("Brand")]
public int BrandID { get; set; }
[Required(ErrorMessage = "A Name is required")]
[StringLength(160)]
public string Title { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 500.00")]
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string ItemArtUrl { get; set; }
public byte[] Picture { get; set; }
public virtual Category Category { get; set; }
public virtual Brand Brand { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
}
</code></pre>
<p>So Im unsure how to go about the controller to insert images or the view to display them, I have search for information about this but I cant really find anything, Im using entity framework code first.</p> | 19,186,560 | 1 | 0 | null | 2013-10-04 16:06:57.41 UTC | 20 | 2014-05-23 12:25:43.003 UTC | null | null | null | null | 2,836,577 | null | 1 | 18 | entity-framework|asp.net-mvc-4 | 53,193 | <p>There are two easy ways to do images -- one is to simply return the image itself in the controller:</p>
<pre><code> [HttpGet]
[AllowAnonymous]
public ActionResult ViewImage(int id)
{
var item = _shoppingCartRepository.GetItem(id);
byte[] buffer = item.Picture;
return File(buffer, "image/jpg", string.Format("{0}.jpg", id));
}
</code></pre>
<p>And the view would just reference it:</p>
<pre><code> <img src="Home/ViewImage/10" />
</code></pre>
<p>Additionally, you can include it in the ViewModel:</p>
<pre><code> viewModel.ImageToShow = Convert.ToBase64String(item.Picture);
</code></pre>
<p>and in the view:</p>
<pre><code> @Html.Raw("<img src=\"data:image/jpeg;base64," + viewModel.ImageToShow + "\" />");
</code></pre>
<p>For the data-store, you would simply use a byte array (<code>varbinary(max)</code>) or blob or any compatible type.</p>
<p><strong>Uploading images</strong> </p>
<p>Here, an object called <code>HeaderImage</code> is an EntityFramework EntityObject. The controller would look something like:</p>
<pre><code> [HttpPost]
public ActionResult UploadImages(HttpPostedFileBase[] uploadImages)
{
if (uploadImages.Count() <= 1)
{
return RedirectToAction("BrowseImages");
}
foreach (var image in uploadImages)
{
if (image.ContentLength > 0)
{
byte[] imageData = null;
using (var binaryReader = new BinaryReader(image.InputStream))
{
imageData = binaryReader.ReadBytes(image.ContentLength);
}
var headerImage = new HeaderImage
{
ImageData = imageData,
ImageName = image.FileName,
IsActive = true
};
imageRepository.AddHeaderImage(headerImage);
}
}
return RedirectToAction("BrowseImages");
}
</code></pre>
<p>The View would look something like:</p>
<pre><code> @using (Html.BeginForm("UploadImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<span class="span4">
<input type="file" name="uploadImages" multiple="multiple" class="input-files"/>
</span>
<span class="span2">
<input type="submit" name="button" value="Upload" class="btn btn-upload" />
</span>
</div>
}
</code></pre> |
8,378,232 | How do I call a local shell script from a web server? | <p>I am running Ubuntu 11 and I would like to setup a simple webserver that responds to an http request by calling a local script with the GET or POST parameters. This script (already written) does some stuff and creates a file. This file should be made available at a URL, and the webserver should then make an http request to another server telling it to download the created file. </p>
<p>How would I go about setting this up? I'm not a total beginner with linux, but I wouldn't say I know it well either. </p>
<p>What webserver should I use? How do I give permission for the script to access local resources to create the file in question? I'm not too concerned with security or anything, this is for a personal experiment (I have control over all the computers involved). I've used apache before, but I've never set it up.</p>
<p>Any help would be appreciated..</p> | 8,378,332 | 1 | 0 | null | 2011-12-04 20:06:41.923 UTC | 9 | 2017-06-08 00:00:29.64 UTC | null | null | null | null | 304,658 | null | 1 | 11 | apache|shell|ubuntu|nginx|webserver | 43,252 | <p><a href="http://www.cyberciti.biz/faq/run-shell-script-from-web-page/" rel="noreferrer">This tutorial looks good</a>, but it's a bit brief.</p>
<p>I have apache installed. If you don't: <code>sudo apt-get install apache2</code>.</p>
<pre><code>cd /usr/lib/cgi-bin
# Make a file and let everyone execute it
sudo touch test.sh && chmod a+x test.sh
</code></pre>
<p>Then put the some code in the file. For example:</p>
<pre><code>#!/bin/bash
# get today's date
OUTPUT="$(date)"
# You must add following two lines before
# outputting data to the web browser from shell
# script
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Demo</title></head><body>"
echo "Today is $OUTPUT <br>"
echo "Current directory is $(pwd) <br>"
echo "Shell Script name is $0"
echo "</body></html>"
</code></pre>
<p>And finally open your browser and type <a href="http://localhost/cgi-bin/test.sh" rel="noreferrer">http://localhost/cgi-bin/test.sh</a></p>
<p>If all goes well (as it did for me) you should see...</p>
<blockquote>
<p>Today is Sun Dec 4 ...<br>
Current directory is /usr/lib/cgi-bin Shell<br>
Shell Script name is /usr/lib/cgi-bin/test.sh </p>
</blockquote> |
8,641,703 | How do I truncate tables properly? | <p>I'm using datamapper with ruby to store data to certain tables.</p>
<p>Several of the tables have very large amounts of information and I want to clear them out when the user 'rebuilds database' (it basically deletes everything and re-calculates data).</p>
<p>I originally tried Forum.all.destroy and did it for all the different tables, but I noticed some of them just weren't deleted from within phpmyadmin. I can only imagine it's because of foreign keys. Although I really don't know because my other table which foreing keys was successfully deleted. Not to mention, I'd rather just 'zero' it out anyway so the keys don't get to extraordinarily large numbers (like key #500,000).</p>
<p>I then tried running it with the code below, but it doesn't clear the tables out because of 'foreign key constraints'. I want to force it to work because I know for a fact I'm clearing out all the tables that rely on each other (I'm only not clearing out 2 tables, a settings table and a random storage table, neither of which use foreign keys).</p>
<p>So far I have...</p>
<pre><code>adapter = DataMapper.repository(:default).adapter
adapter.execute('TRUNCATE TABLE `forums`, `dates`, `remarks`');
</code></pre>
<p>That would be fine except the MySQL syntax is wrong apparently. So that's the first thing.</p>
<p>I did it 1 by 1 in phpmyadmin and when I did it that way it says</p>
<pre><code>Cannot truncate a table referenced in a foreign key constraint
</code></pre> | 8,642,314 | 2 | 0 | null | 2011-12-27 06:12:34.32 UTC | 15 | 2021-04-14 16:27:21.29 UTC | 2021-04-14 16:27:21.29 UTC | null | 3,964,927 | null | 794,481 | null | 1 | 42 | mysql|ruby|datamapper | 58,211 | <p>Plan A:</p>
<pre><code>SET FOREIGN_KEY_CHECKS = 0; -- Disable foreign key checking.
TRUNCATE TABLE forums;
TRUNCATE TABLE dates;
TRUNCATE TABLE remarks;
SET FOREIGN_KEY_CHECKS = 1; -- Enable foreign key checking.
</code></pre>
<p>Plan B:</p>
<p>You should truncate child tables firstly, then parent tables.</p>
<p>Disabling foreign key checks risks entering rows into your tables that don't adhere to the constraints which can cause undefined behavior.</p> |
8,928,464 | For an object, can I get all its subclasses using reflection or other ways? | <p>For an object, can I get all its subclasses using reflection?</p> | 8,928,493 | 2 | 0 | null | 2012-01-19 15:14:39.57 UTC | 11 | 2022-04-29 12:04:19.527 UTC | 2012-01-19 15:43:10.683 UTC | null | 885,920 | null | 1,136,700 | null | 1 | 61 | c#|.net|inheritance|reflection | 33,757 | <p>You can load all types in the Assembly and then enumerate them to see which ones implement the type of your object. You said 'object' so the below code sample is not for interfaces. Also, this code sample only searches the same assembly as the object was declared in.</p>
<pre><code>class A
{}
...
typeof(A).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(A)));
</code></pre>
<p>Or as suggested in the comments, use this code sample to search through all of the loaded assemblies.</p>
<pre><code>var subclasses =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsSubclassOf(typeof(A))
select type
</code></pre>
<p>Both code samples require you to add <code>using System.Linq;</code></p> |
8,537,112 | When is localStorage cleared? | <p>How long can I expect data to be kept in localStorage. How long will an average user's localStorage data persist? If the user doesn't clear it, will it last till a browser re-install?</p>
<p>Is this consistent across browsers?</p> | 8,537,188 | 5 | 0 | null | 2011-12-16 16:27:26.187 UTC | 34 | 2020-11-15 00:31:35.897 UTC | 2011-12-23 19:44:03.883 UTC | null | 946,069 | null | 946,069 | null | 1 | 164 | html|local-storage | 141,349 | <p>W3C draft says this </p>
<blockquote>
<p>User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user. User agents should always avoid deleting data while a script that could access that data is running.</p>
</blockquote>
<p>So if browsers follow the spec it should persist untill the user removes it on all browsers, I have not found any that have deleted on any off my projects.</p>
<p>A good article to read is also <a href="http://ejohn.org/blog/dom-storage/" rel="noreferrer">http://ejohn.org/blog/dom-storage/</a></p> |
48,373,119 | Change Bootstrap 4 checkbox background color | <p>I'm wondering how can I change Bootstraps 4 checkbox background color on this given example. </p>
<pre><code> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<style>
.custom-control-label::before,
.custom-control-label::after {
top: .8rem;
width: 1.25rem;
height: 1.25rem;
}
</style>
<div class="custom-control form-control-lg custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1">
<label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div>
</code></pre> | 48,373,150 | 3 | 0 | null | 2018-01-22 00:15:57.603 UTC | 8 | 2020-12-16 13:39:41.643 UTC | 2019-11-26 20:20:41.313 UTC | null | 1,839,439 | null | 8,751,234 | null | 1 | 30 | html|css|bootstrap-4 | 67,250 | <p>you can use the following css to make it red when it is not checked, and black when it is checked</p>
<pre><code>.custom-control-label:before{
background-color:red;
}
.custom-checkbox .custom-control-input:checked~.custom-control-label::before{
background-color:black;
}
</code></pre>
<p>The color of the arrow can be changed by the following code</p>
<pre><code>.custom-checkbox .custom-control-input:checked~.custom-control-label::after{
background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='red' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E");
}
</code></pre>
<p>this code will make the tick red, you can change the color by changing the <code>fill='red'</code> value to a color of your choice.</p>
<p>Edit: Note, if specifying RGB color, eg. #444444 use %23 for the hash, eg. %23444444</p>
<p>Or you could use any image you like instead.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<style>
.custom-control-label:before{
background-color:red;
}
.custom-checkbox .custom-control-input:checked~.custom-control-label::before{
background-color:black;
}
.custom-checkbox .custom-control-input:checked~.custom-control-label::after{
background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='red' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E");
}
.custom-control-input:active~.custom-control-label::before{
background-color:green;
}
/** focus shadow pinkish **/
.custom-checkbox .custom-control-input:focus~.custom-control-label::before{
box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem rgba(255, 0, 247, 0.25);
}
</style>
<div class="custom-control form-control-lg custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1">
<label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div></code></pre>
</div>
</div>
</p>
<p>EDIT: added a focus color (pinkish) after a request from @cprcrack</p> |
26,497,447 | Grep for a string that ends with specific character | <p>Is there a way to use extended regular expressions to find a specific pattern that ends with a string.</p>
<p>I mean, I want to match first 3 lines but not the last:</p>
<pre><code>file_number_one.pdf # comment
file_number_two.pdf # not interesting
testfile_number____three.pdf # some other stuff
myfilezipped.pdf.zip some comments and explanations
</code></pre>
<p>I know that in grep, metacharacter $ matches the end of a line but I'm not interested in matching a line end but string end. Groups in grep are very odd, I don't understand them well yet.</p>
<p>I tried with group matching, actually I have a similar REGEX but it does not work with grep -E</p>
<pre><code>(\w+).pdf$
</code></pre>
<p>Is there a way to do string ending match in grep/egrep?</p> | 26,498,218 | 4 | 0 | null | 2014-10-21 22:28:10.98 UTC | null | 2020-11-07 22:06:13.457 UTC | null | null | null | null | 1,939,370 | null | 1 | 9 | regex|bash|grep | 56,972 | <p>Your example works with matching the space after the string also:</p>
<pre><code>grep -E '\.pdf ' input.txt
</code></pre>
<p>What you call "string" is similar to what grep calls "word". A Word is a run of alphanumeric characters. The nice thing with words is that you can match a word end with the special <code>\></code>, which matches a word end with a march of zero characters length. That also matches at the end of line. But the word characters can not be changed, and do not contain punctuation, so we can not use it.</p>
<p>If you need to match at the end of line too, where there is no space after the word, use:</p>
<pre><code>grep -E '\.pdf |\.pdf$' input.txt
</code></pre>
<p>To include cases where the character after the file name is not a space character '<code></code>', but other whitespace, like a tab, <code>\t</code>, or the name is directly followed by a comment, starting with <code>#</code>, use:</p>
<pre><code>grep -E '\.pdf[[:space:]#]|\.pdf$' input.txt
</code></pre>
<p>I will illustrate the matching of word boundarys too, because that would be the perfect solution, except that we can not use it here because we can not change the set of characters that are seen as parts of a word.</p>
<p>The input contains <code>foo</code> as separate word, and as part of longer words, where the <code>foo</code> is not at the end of the word, and therefore not at a word boundary:</p>
<pre><code>$ printf 'foo bar\nfoo.bar\nfoobar\nfoo_bar\nfoo\n'
foo bar
foo.bar
foobar
foo_bar
foo
</code></pre>
<p>Now, to match the boundaries of words, we can use <code>\<</code> for the beginning, and <code>\></code> to match the end:</p>
<pre><code>$ printf 'foo bar\nfoo.bar\nfoobar\nfoo_bar\nfoo\n' | grep 'foo\>'
foo bar
foo.bar
foo
</code></pre>
<p>Note how <code>_</code> is matched as a word char - but otherwise, wordchars are only the alphanumerics, <code>[a-zA-Z0-9]</code>.<br>
Also note how <code>foo</code> an the end of line is matched - in the line containing only <code>foo</code>. We do not need a special case for the end of line.</p> |
12,730,664 | How can I extract a substring after a certain string in ksh? | <p>If I have a string like this:</p>
<pre><code>The important variable=123 the rest is not important.
</code></pre>
<p>I want to extract the "123" part in ksh.</p>
<p>So far I have tried:</p>
<pre><code>print awk ' {substr($line, 20) }' | read TEMP_VALUE
</code></pre>
<p>(This <code>20</code> part is just temporary, until I work out how to extract the start position of a string.)</p>
<p>But this just prints <code>awk ' {substr($line, 20) }' | read TEMP_VALUE</code> (though this format <em>does</em> work with code like this: <code>print ${line} | awk '{print $1}' | read SINGLE_FILE</code>).</p>
<p>Am I missing a simple command to do this (that is in other languages)?</p>
<p>Running Solaris 10.</p> | 12,732,140 | 6 | 0 | null | 2012-10-04 15:28:14.087 UTC | null | 2015-05-12 09:22:35.07 UTC | null | null | null | null | 283,650 | null | 1 | 1 | string|substring|ksh|solaris-10 | 47,710 | <p>Your command is failing for multiple reasons: you need something like</p>
<pre><code>TEMP_VALUE=$(print "$line" | awk '...')
</code></pre>
<p>You can use ksh parameter expansion though:</p>
<pre class="lang-sh prettyprint-override"><code>line="The important variable=123 the rest is not important."
tmp=${line#*=} # strip off the stuff up to and including the equal sign
num=${tmp%% *} # strip off a space and all following the first space
print $num # ==> 123
</code></pre>
<p>Look for "parameter substitution" in the ksh man page.</p> |
35,224,113 | react change class name on state change | <p>I have a state like this where I am setting <code>active</code> and <code>class</code> flag like this:</p>
<pre><code>constructor(props) {
super(props);
this.state = {'active': false, 'class': 'album'};
}
handleClick(id) {
if(this.state.active){
this.setState({'active': false,'class': 'album'})
}else{
this.setState({'active': true,'class': 'active'})
}
}
</code></pre>
<p>And I have a list of items with class name from state:</p>
<pre><code><div className={this.state.class} key={data.id} onClick={this.handleClick.bind(this.data.id}>
<p>{data.name}</p>
</div>
</code></pre>
<p>Here how can I change the class name of particular div?</p> | 35,225,464 | 1 | 2 | null | 2016-02-05 12:20:30.863 UTC | 13 | 2021-10-18 09:27:47.03 UTC | 2020-05-29 09:20:24.053 UTC | null | 2,390,075 | null | 3,858,177 | null | 1 | 59 | javascript|reactjs | 165,972 | <p>Below is a fully functional example of what I believe you're trying to do (with a functional snippet).</p>
<h1>Explanation</h1>
<p>Based on your question, you seem to be modifying 1 property in <code>state</code> for all of your elements. That's why when you click on one, all of them are being changed.</p>
<p>In particular, notice that the state tracks an index of <em>which</em> element is active. When <code>MyClickable</code> is clicked, it tells the <code>Container</code> its index, <code>Container</code> updates the <code>state</code>, and subsequently the <code>isActive</code> property of the appropriate <code>MyClickable</code>s.</p>
<h1>Example</h1>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Container extends React.Component {
state = {
activeIndex: null
}
handleClick = (index) => this.setState({ activeIndex: index })
render() {
return <div>
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>
</div>
}
}
class MyClickable extends React.Component {
handleClick = () => this.props.onClick(this.props.index)
render() {
return <button
type='button'
className={
this.props.isActive ? 'active' : 'album'
}
onClick={ this.handleClick }
>
<span>{ this.props.name }</span>
</button>
}
}
ReactDOM.render(<Container />, document.getElementById('app'))</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
display: block;
margin-bottom: 1em;
}
.album>span:after {
content: ' (an album)';
}
.active {
font-weight: bold;
}
.active>span:after {
content: ' ACTIVE';
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p>
<h1>Update: "Loops"</h1>
<p>In response to a comment about a "loop" version, I believe the question is about rendering an array of <code>MyClickable</code> elements. We won't use a loop, but <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer">map</a>, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.</p>
<pre><code>// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
</code></pre> |
28,549,832 | Module 'Alamofire' has no member named 'request' | <p>I'm new to iOS Development, I installed Alamofire as said in README, but I have this error as other users and I don't know how to solve it.</p>
<p><img src="https://cloud.githubusercontent.com/assets/5198677/6205016/3541530e-b55f-11e4-9b28-ae6fc815b984.png" alt="a busy cat"></p> | 29,249,550 | 6 | 1 | null | 2015-02-16 20:32:45.34 UTC | 6 | 2019-03-02 10:39:53.517 UTC | 2015-02-16 20:42:16.9 UTC | null | 801,453 | null | 3,579,107 | null | 1 | 87 | ios|alamofire | 42,952 | <p><em>Alamofire.xcodeproj -> Build Phases -> Complie Sources</em></p>
<p>If <em>(0 item)</em>, then "<strong>[+]</strong> <em>Alamofire.swift</em>".</p>
<p>It's OK :)</p> |
42,473,315 | Visual Studio : can't find "resource file" in list of items to add to project | <p>I'm on VS Community 2017 RC.
I'd like to add a resource file (.resx) to my project but this item type is not listed in the items<a href="https://i.stack.imgur.com/HeDFc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HeDFc.jpg" alt="can't find resource file type"></a></p>
<p>Have I missed something ? Do I need to install anything on top of my Visual Studio to be able to manage resource files ?</p> | 42,473,487 | 4 | 0 | null | 2017-02-26 19:44:06.867 UTC | 6 | 2021-08-23 12:00:26.563 UTC | 2017-02-26 20:12:48.797 UTC | null | 3,306,221 | null | 3,306,221 | null | 1 | 43 | c#|visual-studio|resx|visual-studio-2017|resource-files | 38,699 | <p>At the top right corner you have a searchbox, try typing it there and see if it finds anything.</p>
<p>If it doesn't, create a text file from the new item dialog and change the extension to</p>
<pre><code>resx
</code></pre>
<p>It should now open the new file with the resources designer. Now open the <strong>properties</strong> pane for that file (right click it in the solution explorer) and make sure it has the following set:</p>
<ul>
<li>Build Action: <strong>Embedded resource</strong></li>
<li>Custom tool: <strong>ResXFileCodeGenerator</strong> (or PublicResXFileCodeGenerator to generate a designer class with public visibility)</li>
</ul>
<p>NOTE:
According to the link Chris posted, my suggestion may not help if you have the express edition of visual studio.</p> |
42,263,167 | Read and write from Unix socket connection with Python | <p>I'm experimenting with Unix sockets using Python. I want to create a server that creates and binds to a socket, awaits for commands and sends a response.</p>
<p>The client would connect to the socket, send one command, print the response and close the connection.</p>
<p>This is what I'm doing server side:</p>
<pre><code># -*- coding: utf-8 -*-
import socket
import os, os.path
import time
from collections import deque
if os.path.exists("/tmp/socket_test.s"):
os.remove("/tmp/socket_test.s")
server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
server.bind("/tmp/socket_test.s")
while True:
server.listen(1)
conn, addr = server.accept()
datagram = conn.recv(1024)
if datagram:
tokens = datagram.strip().split()
if tokens[0].lower() == "post":
flist.append(tokens[1])
conn.send(len(tokens) + "")
else if tokens[0].lower() == "get":
conn.send(tokens.popleft())
else:
conn.send("-1")
conn.close()
</code></pre>
<p>But I get <code>socket.error: [Errno 95] Operation not supported</code> when trying to listen.</p>
<p>Do unix sockets support listening? Otherwise, what would be the right way for both reading and writing?</p>
<p>Any help appreciated :)</p> | 42,263,523 | 2 | 0 | null | 2017-02-16 01:23:26.273 UTC | null | 2019-05-21 14:57:50.37 UTC | null | null | null | null | 766,386 | null | 1 | 12 | python|sockets|unix-socket | 38,237 | <p><code>SOCK_DGRAM</code> sockets don't listen, they just bind. Change the socket type to <code>SOCK_STREAM</code> and your <code>listen()</code> will work.</p>
<p>Check out <a href="https://pymotw.com/2/socket/uds.html" rel="noreferrer">PyMOTW Unix Domain Sockets</a> (<code>SOCK_STREAM</code>) vs. <a href="https://pymotw.com/2/socket/udp.html" rel="noreferrer">PyMOTW User Datagram Client and Server</a> (<code>SOCK_DGRAM</code>)</p> |
60,376,438 | struct.error: unpack requires a buffer of 4 bytes | <p>I want to convert data from a device from bites to float
I use the code from this answer</p>
<p><a href="https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">bytes to float</a></p>
<pre><code>import struct
byte_file = b'+001.80\r'
print(type(byte_file))
y = struct.unpack('f' , byte_file)
print(y)
</code></pre>
<p>I get this <code>struct.error: unpack requires a buffer of 4 bytes</code></p>
<p>The correct outcome should be <code>1.80</code>
do I need to implement a buffer argument ?</p> | 60,376,646 | 1 | 0 | null | 2020-02-24 12:58:39.28 UTC | 3 | 2021-09-09 08:44:35.677 UTC | 2020-12-05 17:29:22.01 UTC | null | 11,419,075 | null | 12,753,324 | null | 1 | 13 | python-3.x|struct | 52,484 | <p><code>struct</code> is used for <em>binary packed data</em> - data that is not human-readable. <code>b'+001.80\r'</code> is 8 bytes long: <code>b'+', b'0', b'0', b'1', b'.', ...</code>.</p>
<p>You can just <code>decode</code> it and use <code>float</code>:</p>
<pre><code>>>> b'+001.80\r'.decode()
'+001.80\r'
>>> float(_)
1.8
>>> import struct
>>> struct.pack('f', _)
b'ff\xe6?' # doesn't look anything like your data!
</code></pre>
<p><em>However</em>, because your data is 8 bytes long, you could treat it as a single <code>double</code>-precision floating-point value:</p>
<pre><code>>>> struct.unpack('d', b'+001.80\r')
(3.711588247816385e-245,)
</code></pre>
<p>But that treats the data as binary-packed: <code>+001.80\r</code>, also known as <code>2b 30 30 31 2e 38 30 0d</code>, is what <code>3.711588247816385e-245</code> looks like in memory.</p> |
2,192,082 | Android: Changing an ImageView src depending on database field data | <p>I'm quite new to Android development (started 2 days ago) and have been through a number of tutorials already. I'm building a test app from the NotePad exercise (<a href="http://developer.android.com/resources/tutorials/notepad/index.html" rel="noreferrer">Link to tutorial</a>) in the Android SDK and as part of the list of notes I want to display a different image depending on the contents of a database field i've called "notetype". I'd like this image to appear in the List view before each notepad entry.</p>
<p>The code in my .java file is:</p>
<pre><code>private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
String[] from = new String[]{NotesDbAdapter.KEY_NOTENAME, NotesDbAdapter.KEY_NOTETYPE};
int[] to = new int[]{R.id.note_name, R.id.note_type};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
</code></pre>
<p>And my layout xml file (notes_row.xml) looks like this:</p>
<pre><code><ImageView android:id="@+id/note_type"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/default_note"/>
<TextView android:id="@+id/note_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</code></pre>
<p>I just really have no clue how I'd go about fetching the right drawable depending on the type of note that has been selected. At the moment I have the ability to select the type from a Spinner, so what gets stored in the database is an integer. I've created some images that correspond to these integers but it doesn't seem to pick things up.</p>
<p>Any help would be appreciated. If you need more info then please let me know.</p> | 2,193,727 | 1 | 0 | null | 2010-02-03 13:17:40.443 UTC | 14 | 2010-05-05 13:19:24.52 UTC | null | null | null | null | 265,268 | null | 1 | 10 | android | 14,338 | <p>You might want to try using a ViewBinder. <a href="http://d.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html" rel="noreferrer">http://d.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html</a></p>
<p>This example should help:</p>
<pre><code>private class MyViewBinder implements SimpleCursorAdapter.ViewBinder {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int viewId = view.getId();
switch(viewId) {
case R.id.note_name:
TextView noteName = (TextView) view;
noteName.setText(Cursor.getString(columnIndex));
break;
case R.id.note_type:
ImageView noteTypeIcon = (ImageView) view;
int noteType = cursor.getInteger(columnIndex);
switch(noteType) {
case 1:
noteTypeIcon.setImageResource(R.drawable.yourimage);
break;
case 2:
noteTypeIcon.setImageResource(R.drawable.yourimage);
break;
etc…
}
break;
}
}
</code></pre>
<p>}</p>
<p>Then add it to your adapter with </p>
<pre><code>note.setViewBinder(new MyViewBinder());
</code></pre> |
61,785,903 | Problems with debounce in useEffect | <p>I have a form with username input and I am trying to verify if the username is in use or not in a debounce function. The issue I'm having is that my debounce doesn't seem to be working as when I type "user" my console looks like</p>
<pre><code>u
us
use
user
</code></pre>
<p>Here is my debounce function</p>
<pre><code>export function debounce(func, wait, immediate) {
var timeout;
return () => {
var context = this, args = arguments;
var later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
</code></pre>
<p>And here is how I'm calling it in my React component</p>
<pre><code>import React, { useEffect } from 'react'
// verify username
useEffect(() => {
if(state.username !== "") {
verify();
}
}, [state.username])
const verify = debounce(() => {
console.log(state.username)
}, 1000);
</code></pre>
<p>The debounce function seems to be correct? Is there a problem with how I am calling it in react?</p> | 61,786,423 | 4 | 0 | null | 2020-05-13 22:19:38.563 UTC | 11 | 2022-09-15 13:53:28.61 UTC | null | null | null | null | 7,466,884 | null | 1 | 41 | reactjs|react-hooks|debounce | 34,826 | <p>Every time your component re-renders, a <strong>new</strong> debounced <code>verify</code> function is created, which means that inside <code>useEffect</code> you are actually calling different functions which defeats the purpose of debouncing.</p>
<p>It's like you were doing something like this:</p>
<pre><code>const debounced1 = debounce(() => { console.log(state.username) }, 1000);
debounced1();
const debounced2 = debounce(() => { console.log(state.username) }, 1000);
debounced2();
const debounced3 = debounce(() => { console.log(state.username) }, 1000);
debounced3();
</code></pre>
<p>as opposed to what you really want:</p>
<pre><code>const debounced = debounce(() => { console.log(state.username) }, 1000);
debounced();
debounced();
debounced();
</code></pre>
<p>One way to solve this is to use <code>useCallback</code> which will always return the same callback (when you pass in an empty array as a second argument). Also, I would pass the <code>username</code> to this function instead of accessing the state inside (otherwise you will be accessing a stale state):</p>
<pre><code>import { useCallback } from "react";
const App => () {
const [username, setUsername] = useState("");
useEffect(() => {
if (username !== "") {
verify(username);
}
}, [username]);
const verify = useCallback(
debounce(name => {
console.log(name);
}, 200),
[]
);
return <input onChange={e => setUsername(e.target.value)} />;
}
</code></pre>
<p>Also you need to slightly update your debounce function since it's not passing arguments correctly to the debounced function.</p>
<pre><code>function debounce(func, wait, immediate) {
var timeout;
return (...args) => { <--- needs to use this `args` instead of the ones belonging to the enclosing scope
var context = this;
...
</code></pre>
<p><a href="https://codesandbox.io/s/blue-bush-bh006?file=/src/App.js:484-829" rel="nofollow noreferrer">demo</a></p>
<p>Note: You will see an ESLint warning about how <code>useCallback</code> expects an inline function, you can get around this by using <code>useMemo</code> knowing that <code>useCallback(fn, deps)</code> is equivalent to <code>useMemo(() => fn, deps)</code>:</p>
<pre><code>const verify = useMemo(
() => debounce(name => {
console.log(name);
}, 200),
[]
);
</code></pre> |
50,032,000 | how to avoid ConcurrentModificationException kotlin | <p>I have a list of accounts, and when i make the long click, I want to remove the item from the arraylist. I'm trying to remove it from a alertdialog, but i'm getting the ConcurrentModificationException. This is where is crashing:</p>
<pre class="lang-kotlin prettyprint-override"><code>listAccounts.forEachIndexed { index, account ->
if (idParamether == account.id) {
listAccounts.remove(account)
}
}
</code></pre> | 50,032,140 | 10 | 2 | null | 2018-04-25 22:06:37.283 UTC | 3 | 2022-01-28 16:35:47.563 UTC | 2020-06-19 09:57:14.183 UTC | null | 4,575,671 | null | 5,818,559 | null | 1 | 55 | kotlin | 33,555 | <p>That's a common problem with the JVM, if you want to remove an item from a collection while iterating through it, you need to use the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-iterator/index.html" rel="noreferrer">Iterators</a></p>
<p>exemple:</p>
<pre><code>val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
val item = iterator.next()
if(item == 3){
iterator.remove()
}
}
</code></pre>
<p>this will avoid ConcurrentModificationExceptions</p>
<p>I hope this answered your question, have a good day</p>
<p><strong>Edit</strong>: you can find another explanation <a href="https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re">here</a>, even if it is Java code the problem is the same<br>
<strong>Edit n°2</strong> the anwser of leonardkraemer show you a more kotlin-friendly way to do so</p> |
26,672,532 | How to set local variable in list comprehension? | <p>I have a method that takes a list and returns an object:</p>
<pre><code># input a list, returns an object
def map_to_obj(lst):
a_list = f(lst)
return a_list[0] if a_list else None
</code></pre>
<p>I want to get a list that contains all the mapped elements that aren't <code>None</code>.</p>
<p>Like this:</p>
<pre><code>v_list = [v1, v2, v3, v4]
[map_to_obj(v) for v in v_list if map_to_obj(v)]
</code></pre>
<p>But it doesn't seem good to call the <code>map_to_obj</code> method twice in the list comprehension. </p>
<p>Is there a way to have local variables in list comprehensions so that it can have better performance? </p>
<p>Or does the compiler optimize it automatically?</p>
<p>Here is what I want:</p>
<pre><code>(sml like)
[let mapped = map_to_obj(v) in for v in v_list if mapped end]
</code></pre> | 55,881,984 | 7 | 0 | null | 2014-10-31 10:31:45.413 UTC | 18 | 2022-09-05 07:07:58.187 UTC | 2019-04-27 15:19:00.047 UTC | null | 9,297,144 | null | 3,374,402 | null | 1 | 70 | python|list-comprehension | 48,431 | <p>Starting in <code>Python 3.8</code>, and the introduction of <a href="https://www.python.org/dev/peps/pep-0572/" rel="nofollow noreferrer">assignment expressions (PEP 572)</a> (<code>:=</code> operator), it's possible to use a local variable within a list comprehension in order to avoid calling the same function twice.</p>
<p>In our case, we can name the evaluation of <code>map_to_obj(v)</code> as a variable <code>o</code> while using the result of the expression to filter the list; and thus use <code>o</code> as the mapped value:</p>
<pre><code>[o for v in [v1, v2, v3, v4] if (o := map_to_obj(v))]
</code></pre> |
48,386,853 | ASP.NET Core Identity Authorization using Parameter for Team Membership | <p>I have an application with tables like this:</p>
<ul>
<li>User (ASP.NET Core Identity)</li>
<li>Team</li>
<li>UserTeam (many-to-many join table)</li>
</ul>
<p>Users can be members of multiple teams, and can have different Roles within the teams. For example a User may be a TeamAdmin for TeamA but just a normal member of TeamB. Because of this, simple Role checks and Policies defined with static values won't work.</p>
<p>I'm looking for a way to authorize Controller Actions for Users based on their Team and their role in the Team, which will either be added as a Claim or with a separate RoleTeam table. Assuming a Controller action like this:</p>
<pre><code>[HttpGet]
[Authorize(???)]
public IActionResult ManageTeam(Guid teamId)
{ }
</code></pre>
<p>I would need to verify that the User has the TeamAdmin Role for the Team in question. Is there a clean way to decorate it with an Authorize attribute that can access the <code>teamId</code> parameter? Or will I have to wrap the guts of all of these Actions in <code>if (User.IsTeamAdmin(teamId)</code> ... statements?</p> | 48,390,808 | 3 | 0 | null | 2018-01-22 17:10:56.587 UTC | 9 | 2020-12-02 05:14:18.847 UTC | 2018-01-22 17:36:45.72 UTC | null | 7,897,176 | null | 7,897,176 | null | 1 | 10 | c#|asp.net-core|asp.net-core-identity | 6,228 | <p>ASP.NET Core introduces the concept of policies that you can apply to your <code>Authorize</code> attribute. works like filters, but without writing filters.</p>
<p>Each policy has one or more requirements that must all be met for the policy to pass. The <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies" rel="noreferrer">Microsoft docs</a> have a good example of setting up policies. In your case I'd do something like the following:</p>
<p>First, start with a "requirement"</p>
<pre><code>public class TeamAccessRequirement : IAuthorizationRequirement
{
}
</code></pre>
<p>Then add a requirement handler</p>
<pre><code>public class TeamAccessHandler : AuthorizationHandler<TeamAccessRequirement>
{
private readonly DbContext dbContext;
public TeamAccessHandler(DbContext dbContext)
{
// example of an injected service. Put what you need here.
this.dbContext = dbContext;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TeamAccessRequirement requirement)
{
// pattern matching is cool. if you can't do this, use context.Resource as AuthorizationFilterContext before and check for not null
if (context.Resource is AuthorizationFilterContext authContext)
{
// you can grab the team id, (but no model builder to help you, sorry)
var teamId = Guid.Parse(authContext.RouteData.Values["teamId"]);
// now you can do the code you would have done in the guts of the actions.
if (context.User.IsTeamAdmin(teamId))
{
context.Succeed(requirement);
}
else
{
context.Fail();
}
}
return Task.CompletedTask;
}
}
</code></pre>
<p>Then, you need to put this all together and enable it in the <code>Startup.cs</code> under <code>ConfigureServices</code>, like this:</p>
<pre><code> services.AddAuthorization(options =>
{
options.AddPolicy("HasAdminTeamAccess", policy =>
policy.Requirements.Add(new TeamAccessRequirement()));
});
services.AddTransient<IAuthorizationHandler, TeamAccessHandler>();
</code></pre>
<p>And finally, the usage:</p>
<pre><code>[HttpGet]
[Authorize(Policy = "HasAdminTeamAccess")]
public IActionResult ManageTeam(Guid teamId)
{ }
</code></pre>
<p>Now your actions remain nice and clean. From here you can fine tune the policy by adding functionality to the requirements that you can call from the handler, or do whatever you want.</p> |
21,205,485 | IOS7, Segue and storyboards - How to create without a button? | <p>I currently have a login View and an Application view, I have successfully implemented validation on the login view and I need to programmatically shift to the application view on successful validation. </p>
<p>I understand I can add a <strong>segue</strong> to the login button and then call it programmatically like so...</p>
<pre><code>[self performSegueWithIdentifier:@"LoginSegue" sender:sender];
</code></pre>
<p>But this will obviously be triggered whenever the button is clicked (As the segue was created attached to the button). I've just read that I should create a button (And hide it) and then make a programmatic call to the segue - this seems a bit 'wrong'.</p>
<p>How can a create a segue that isn't attached to any particular UI event? </p> | 21,205,550 | 1 | 0 | null | 2014-01-18 14:34:50.127 UTC | 16 | 2019-04-16 07:54:40.7 UTC | 2019-04-16 07:54:40.7 UTC | null | 6,444,297 | null | 184,882 | null | 1 | 70 | ios|segue|xcode-storyboard | 26,061 | <p>Delete the current segue.</p>
<p>Attach the segue from the origin <strong>view controller</strong> to the destination (and then name it).</p>
<p>Now, your button press method should look something like this:</p>
<h3>Objective-C:</h3>
<pre class="lang-objc prettyprint-override"><code>- (IBAction)validateLogin:(id)sender {
// validate login
if (validLogin) {
[self performSegueWithIdentifier:@"mySegue" sender:sender];
}
}
</code></pre>
<h3>Swift:</h3>
<pre class="lang-swift prettyprint-override"><code>@IBAction func validateLogin(sender: UIButton) {
// validate login
if validLogin {
self.performSegueWithIdentifier("mySegue", sender:sender)
}
}
</code></pre>
<p>The key here is that the origin view controller should be the one you're dragging from to create the segue, not the button or any other UI element.</p>
<p><img src="https://i.stack.imgur.com/vKOMS.png" alt="enter image description here"></p>
<p>Personally, I hook ALL of my segues up this way, even the ones that should trigger on simple button pushes without any validation or logic behind them. It's easy enough to call it from the button's method.</p>
<p>And, I usually declare all of my segue names as constant strings somewhere in the project.</p> |
43,765,381 | Where can I find the API documentation of the class Input? | <p>Where can I find the API documentation of the class <code>keras.layers.Input</code>? I couldn't find it at <a href="https://keras.io/" rel="noreferrer">https://keras.io/</a>.</p> | 43,769,694 | 2 | 0 | null | 2017-05-03 16:22:25.213 UTC | 10 | 2019-02-22 20:05:10.433 UTC | 2019-02-22 20:05:10.433 UTC | null | 3,924,118 | null | 6,521,119 | null | 1 | 26 | keras | 10,850 | <p>That documentation is really hard to go through when you're not used to Keras.</p>
<p>But there are two approaches for building keras models:</p>
<ul>
<li>The <code>Sequential</code> model</li>
<li>The <code>Model</code> functional API</li>
</ul>
<p>The <code>Input</code> layer is not used with the <code>Sequential</code> model, only with <code>Model</code>.</p>
<p>Probably, there is no clear documentation because the <code>Input</code> layer does absolutely nothing except defining the shape of the input data to your model. (In fact it creates a "tensor" that you can use as input to other layers).</p>
<p>Imagine you are creating a model taking batches with MNIST data, which has 28x28 pixel images. Your input shape is then <code>(28,28)</code> (see <code>*</code>).</p>
<p>When creating your model, you use <code>Input</code> just to define that:</p>
<pre class="lang-py prettyprint-override"><code>#inp will be a tensor with shape (?, 28, 28)
inp = Input((28,28))
</code></pre>
<p>The following layers will then use this input:</p>
<pre class="lang-py prettyprint-override"><code>x = SomeKerasLayer(blablabla)(inp)
x = SomeOtherLayer(blablabla)(x)
output = TheLastLayer(balblabla)(x)
</code></pre>
<p>And when you create the model, you define the path that the data will follow, which in this case is from the input to the output:</p>
<pre class="lang-py prettyprint-override"><code>model = Model(inp,output)
</code></pre>
<hr />
<p>With the <code>Model</code> api, it's also possible to create ramifications, multiple inputs and multiple outputs, branches, etc.</p>
<p>In case of having multiple inputs, you'd create several <code>Input</code> layers.</p>
<p>See here for more advanced examples with actual layers: <a href="https://keras.io/getting-started/functional-api-guide/" rel="noreferrer">https://keras.io/getting-started/functional-api-guide/</a></p>
<hr />
<p><code>*</code> - This is not a rule. Depending on how you format your input data, this shape can change. There are models that prefer not to care about the 2D information and use a flattened image of shape <code>(784,)</code>. Models that will use convolutional layers will often shape the input data as <code>(28,28,1)</code>, an image with one channel. (Usually, images have 3 channels, RGB).</p>
<hr />
<h2>Arguments to the <code>Input</code></h2>
<p>The code for the <code>Input</code> method is defined <a href="https://github.com/keras-team/keras/blob/master/keras/engine/topology.py/#L1377" rel="noreferrer">here</a> (December, 22 - 2017)</p>
<p>Possible arguments:</p>
<ul>
<li><strong>shape</strong>: defines the shape of a single sample, with variable batch size (as shown above)</li>
<li><strong>batch_shape</strong>: explicitly define the size of the batch in the passed shape</li>
<li><strong>tensor</strong>: instead of passing an input shape to the model, pass an existing tensor, you can for instance pass a tensor populated with values, such as a <code>K.variable()</code>.</li>
<li>Other arguments: <code>name</code>, <code>dtype</code> and <code>sparse</code>.</li>
</ul> |
7,673,988 | Rails/Bundler precompile vs lazy compile | <p>In the <code>config/application.rb</code> file in a Rails app, there's the following section of code:</p>
<pre><code>if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
</code></pre>
<p>I'm perhaps not clear what <code>Bundler.require</code> is doing. I was under the impression that it required the specified sections in the Gemfile, but I'm not clear as to why <code>Bundler.require *Rails.groups(...)</code> causes it to precompile and <code>Bundler.require(...)</code> causes assets to be lazily loaded.</p> | 7,675,331 | 1 | 0 | null | 2011-10-06 12:03:10.377 UTC | 9 | 2011-10-06 13:57:20.323 UTC | null | null | null | null | 509,271 | null | 1 | 23 | ruby-on-rails|bundler | 5,037 | <p>These lines don't actually change how your assets are used.</p>
<p>The first line,</p>
<pre><code>Bundler.require *Rails.groups(:assets => %w(development test))
</code></pre>
<p>only loads gems from the <code>assets</code> group in your development and test environment. This means that things like <code>sass-rails</code> and <code>uglifier</code> won't be available in production, which then means that you won't be able to properly compile/minify/whatever your assets on the fly in production if you're making use of those gems.</p>
<p>On the other hand,</p>
<pre><code>Bundler.require(:default, :assets, Rails.env)
</code></pre>
<p>will load the <code>assets</code> group in any environment, making those gems available in production to do asset compilation/minification/whatever on the fly.</p>
<p>So, as stated above, these lines don't actually change the behaviour of your asset pipeline - it simply means that you should use the first if you're going to precompile your assets for production, or use the second if you're going to lazily compile in production.</p> |
41,744,368 | Scrolling to element using webdriver? | <p>I am still learning and in response to one of my questions: <a href="https://stackoverflow.com/questions/41737321/same-command-works-once-when-executed-but-throws-an-exception-when-executed-a-se?noredirect=1#comment70669855_41737321">here</a>, I was told to that it might be due because the element in question is not in view. </p>
<p>I looked through the documentation and SO, here was the most relevant answer: <a href="https://stackoverflow.com/questions/3401343/scroll-element-into-view-with-selenium">here</a></p>
<p>You can use the "org.openqa.selenium.interactions.Actions" class to move to an element:</p>
<pre><code>WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
## actions.click();
actions.perform();
</code></pre>
<p>When I try to use the above to scroll to the element:
It says WebElement not defined.</p>
<p>I think this is because I have not imported the relevant module. Can someone point out what I am supposed to import?</p>
<p>Edit:
As pointed out by alecxe, this was java code.</p>
<p>But in the meantime right after trying to figure it out for some time. I have found out the import method for WebElement:</p>
<pre><code>from selenium.webdriver.remote.webelement import WebElement
</code></pre>
<p>Might help someone like me.</p>
<p>The how of it is also a good lesson, IMO:</p>
<p>Went to: <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="noreferrer">Documentation</a>
The </p>
<pre><code>class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False)
</code></pre>
<p>Need to be separated into the command form mentioned above.</p> | 41,744,403 | 7 | 0 | null | 2017-01-19 14:33:33.97 UTC | 42 | 2020-12-20 07:27:11.217 UTC | 2017-11-11 12:07:13.183 UTC | null | 7,429,447 | null | 6,387,095 | null | 1 | 107 | python|python-3.x|selenium|selenium-webdriver | 182,669 | <p>You are trying to run Java code with Python. In Python/Selenium, the <code>org.openqa.selenium.interactions.Actions</code> are reflected in <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="noreferrer"><code>ActionChains</code> class</a>:</p>
<pre><code>from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_id("my-id")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
</code></pre>
<p>Or, you can also "scroll into view" via <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView" rel="noreferrer"><code>scrollIntoView()</code></a>:</p>
<pre><code>driver.execute_script("arguments[0].scrollIntoView();", element)
</code></pre>
<p>If you are interested in the differences:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/34562095/scrollintoview-vs-movetoelement">scrollIntoView vs moveToElement</a></li>
</ul> |
24,579,580 | Laravel Session Flash persists for 2 requests | <p>Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with <code>Session::flash</code>.</p>
<p>when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator:
<img src="https://i.stack.imgur.com/aDuFV.png" alt="enter image description here"></p>
<p>my code in <code>UsersController</code>:</p>
<pre><code>function getCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController@postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
return View::make('layouts.form', $config);
}
function postCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController@postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
return View::make('layouts.form', $config);
}
return View::make('layouts.form', $config)->withErrors($validator->messages());
}
</code></pre>
<p>in <code>form.blade</code>:</p>
<pre><code>@if ( $errors->count() > 0 )
<div class="alert alert-danger">
<p>The following errors have occurred:</p>
<ul>
@foreach( $errors->all() as $message )
<li>{{ $message }}</li>
@endforeach
</ul>
</div>
@endif
</code></pre>
<p>in <code>master.blade</code>:</p>
<pre><code>@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissable"> {{ Session::get('message') }}</p>
@endif
</code></pre>
<p>Maybe I'm not alone with this issue, <a href="https://stackoverflow.com/questions/14517809/laravels-flash-session-stores-data-twice/14520060#14520060">here</a> is another unanswered question.</p>
<h2>Update</h2>
<p>For anyone in future facing this problem:
<strong>Never flash session data without redirecting.</strong></p>
<p>My code now looks like this:</p>
<pre><code>function postCreateUser(){
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
} else {
Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
Session::flash('alert-class', 'alert-danger');
}
return Redirect::action('UsersController@getCreateUser');
}
</code></pre> | 24,579,765 | 7 | 0 | null | 2014-07-04 18:51:24.073 UTC | 2 | 2022-04-13 14:18:49.76 UTC | 2017-05-23 12:02:18.99 UTC | null | -1 | null | 2,407,522 | null | 1 | 28 | php|session|laravel|laravel-4 | 27,006 | <p>You are Flashing session data and creating a view instead of redirecting, meaning the message will Flash for this request and for the next one, showing twice. </p>
<p>If you want to show the message on the current request without redirecting, I would suggest providing the errors to your <code>View::make</code> instead of trying to Flash the messages. If you MUST Flash the message on the current request, then you will need to <code>Session::forget('key')</code> or <code>Session::flush()</code> after your view.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.