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
31,342,228
PyQt Tree Widget, adding check boxes for dynamic removal
<p>I am attempting to create a tree widget that will essentially allow the user to view various breakdowns of data and have the option to delete certain items. In order to do this I want to have check boxes associated with each top level item and each child so the user can select which top level items (and thus all the children of that top level item) to delete. Or which specific children to delete. To give you a better idea I've created an example where [x] represents a checked check box and [ ] represents an empty checkbox:</p> <pre><code>&gt;Beverages Allowed in Stadium [ ] Soda [ ] Water [ ] Tea [ ] Spirits [X] Ale [ ] &gt;Tickets [X] Row A [X] Row B [X] Row C [X] Lawn [X] </code></pre> <p>Any suggestions how to implement this? I don't know if it makes a difference as far as difficulty, but i have allocated a separate column for the check box.</p>
31,342,831
4
0
null
2015-07-10 13:38:12.333 UTC
10
2019-12-16 09:24:38.833 UTC
2015-07-10 14:05:29.07 UTC
null
189,134
null
3,119,546
null
1
7
python|checkbox|pyqt|qtreeview|qtreewidgetitem
24,206
<p>In addition to the <a href="https://stackoverflow.com/a/31342537/189134">answer</a> you provided, you can simplify your logic by using the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qt.html#ItemFlag-enum" rel="noreferrer"><code>ItemIsTristate</code></a> flag on the parent elements.</p> <pre><code>from PyQt4.QtCore import * from PyQt4.QtGui import * import sys def main(): app = QApplication (sys.argv) tree = QTreeWidget () headerItem = QTreeWidgetItem() item = QTreeWidgetItem() for i in xrange(3): parent = QTreeWidgetItem(tree) parent.setText(0, "Parent {}".format(i)) parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) for x in xrange(5): child = QTreeWidgetItem(parent) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, "Child {}".format(x)) child.setCheckState(0, Qt.Unchecked) tree.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <hr> <p>The three most important lines of code are:</p> <pre><code>parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) </code></pre> <p>This one sets up the parent element to be a three state check box.</p> <pre><code>child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setCheckState(0, Qt.Unchecked) </code></pre> <p>These set up the child to be selectable and set the default to unchecked. If the child's checkbox isn't given a state, the checkbox element does not appear.</p> <hr> <p>The code above builds a very simple tree. </p> <p><img src="https://i.stack.imgur.com/lj4ZF.png" alt="Simple Tree"></p> <p>However, if I check a check box on the parent element, all the children are automatically selected:</p> <p><img src="https://i.stack.imgur.com/T5cbU.png" alt="Parent Selected"></p> <p>If, I wish to unselect a single child, the parent enters the partially selected (Tri-State):</p> <p><img src="https://i.stack.imgur.com/lJ0uK.png" alt="TriState"></p> <p>If all children are unselected, the parent is automatically unselected. If the parent is unselected, all children are automatically unselected as well.</p>
31,324,218
Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative
<p><strong>My problem:</strong></p> <p>I have a dataset which is a large JSON file. I read it and store it in the <code>trainList</code> variable.</p> <p>Next, I pre-process it - in order to be able to work with it.</p> <p>Once I have done that I start the classification:</p> <ol> <li>I use the <code>kfold</code> cross validation method in order to obtain the mean accuracy and train a classifier.</li> <li>I make the predictions and obtain the accuracy &amp; confusion matrix of that fold.</li> <li>After this, I would like to obtain the <code>True Positive(TP)</code>, <code>True Negative(TN)</code>, <code>False Positive(FP)</code> and <code>False Negative(FN)</code> values. I'll use these parameters to obtain the <strong>Sensitivity</strong> and <strong>Specificity</strong>. </li> </ol> <p>Finally, I would use this to put in HTML in order to show a chart with the TPs of each label.</p> <p><strong>Code:</strong></p> <p>The variables I have for the moment:</p> <pre><code>trainList #It is a list with all the data of my dataset in JSON form labelList #It is a list with all the labels of my data </code></pre> <p>Most part of the method:</p> <pre><code>#I transform the data from JSON form to a numerical one X=vec.fit_transform(trainList) #I scale the matrix (don't know why but without it, it makes an error) X=preprocessing.scale(X.toarray()) #I generate a KFold in order to make cross validation kf = KFold(len(X), n_folds=10, indices=True, shuffle=True, random_state=1) #I start the cross validation for train_indices, test_indices in kf: X_train=[X[ii] for ii in train_indices] X_test=[X[ii] for ii in test_indices] y_train=[listaLabels[ii] for ii in train_indices] y_test=[listaLabels[ii] for ii in test_indices] #I train the classifier trained=qda.fit(X_train,y_train) #I make the predictions predicted=qda.predict(X_test) #I obtain the accuracy of this fold ac=accuracy_score(predicted,y_test) #I obtain the confusion matrix cm=confusion_matrix(y_test, predicted) #I should calculate the TP,TN, FP and FN #I don't know how to continue </code></pre>
31,351,145
20
0
null
2015-07-09 17:19:02.967 UTC
65
2022-03-15 08:56:12.077 UTC
2019-03-17 21:49:26.037 UTC
null
3,624,671
null
4,355,092
null
1
102
python|machine-learning|scikit-learn|classification|supervised-learning
205,215
<p>If you have two lists that have the predicted and actual values; as it appears you do, you can pass them to a function that will calculate TP, FP, TN, FN with something like this:</p> <pre><code>def perf_measure(y_actual, y_hat): TP = 0 FP = 0 TN = 0 FN = 0 for i in range(len(y_hat)): if y_actual[i]==y_hat[i]==1: TP += 1 if y_hat[i]==1 and y_actual[i]!=y_hat[i]: FP += 1 if y_actual[i]==y_hat[i]==0: TN += 1 if y_hat[i]==0 and y_actual[i]!=y_hat[i]: FN += 1 return(TP, FP, TN, FN) </code></pre> <p>From here I think you will be able to calculate rates of interest to you, and other performance measure like specificity and sensitivity.</p>
54,255,431
InvalidArgumentError: cannot compute MatMul as input #0(zero-based) was expected to be a float tensor but is a double tensor [Op:MatMul]
<p>Can somebody explain, how does TensorFlow's eager mode work? I am trying to build a simple regression as follows:</p> <pre><code>import tensorflow as tf tfe = tf.contrib.eager tf.enable_eager_execution() import numpy as np def make_model(): net = tf.keras.Sequential() net.add(tf.keras.layers.Dense(4, activation='relu')) net.add(tf.keras.layers.Dense(1)) return net def compute_loss(pred, actual): return tf.reduce_mean(tf.square(tf.subtract(pred, actual))) def compute_gradient(model, pred, actual): """compute gradients with given noise and input""" with tf.GradientTape() as tape: loss = compute_loss(pred, actual) grads = tape.gradient(loss, model.variables) return grads, loss def apply_gradients(optimizer, grads, model_vars): optimizer.apply_gradients(zip(grads, model_vars)) model = make_model() optimizer = tf.train.AdamOptimizer(1e-4) x = np.linspace(0,1,1000) y = x+np.random.normal(0,0.3,1000) y = y.astype('float32') train_dataset = tf.data.Dataset.from_tensor_slices((y.reshape(-1,1))) epochs = 2# 10 batch_size = 25 itr = y.shape[0] // batch_size for epoch in range(epochs): for data in tf.contrib.eager.Iterator(train_dataset.batch(25)): preds = model(data) grads, loss = compute_gradient(model, preds, data) print(grads) apply_gradients(optimizer, grads, model.variables) # with tf.GradientTape() as tape: # loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(preds, data)))) # grads = tape.gradient(loss, model.variables) # print(grads) # optimizer.apply_gradients(zip(grads, model.variables),global_step=None) </code></pre> <p><code>Gradient output: [None, None, None, None, None, None]</code> The error is following:</p> <pre><code>---------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-3-a589b9123c80&gt; in &lt;module&gt; 35 grads, loss = compute_gradient(model, preds, data) 36 print(grads) ---&gt; 37 apply_gradients(optimizer, grads, model.variables) 38 # with tf.GradientTape() as tape: 39 # loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(preds, data)))) &lt;ipython-input-3-a589b9123c80&gt; in apply_gradients(optimizer, grads, model_vars) 17 18 def apply_gradients(optimizer, grads, model_vars): ---&gt; 19 optimizer.apply_gradients(zip(grads, model_vars)) 20 21 model = make_model() ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py in apply_gradients(self, grads_and_vars, global_step, name) 589 if not var_list: 590 raise ValueError("No gradients provided for any variable: %s." % --&gt; 591 ([str(v) for _, v, _ in converted_grads_and_vars],)) 592 with ops.init_scope(): 593 self._create_slots(var_list) ValueError: No gradients provided for any variable: </code></pre> <h3>Edit</h3> <p>I updated my code. Now, the problem comes in gradients calculation, it is returning zero. I have checked the loss value that is non-zero.</p>
54,255,819
1
0
null
2019-01-18 13:52:51.467 UTC
3
2020-01-09 22:15:39.74 UTC
2020-01-09 22:15:39.74 UTC
null
3,924,118
null
9,277,245
null
1
31
python|tensorflow|keras|eager-execution
52,833
<p><strong>Part 1:</strong> The problem is indeed the datatype of your input. By default your keras model expects float32 but you are passing a float64. You can either change the dtype of the model or change the input to float32.</p> <p>To change your model:</p> <pre><code>def make_model(): net = tf.keras.Sequential() net.add(tf.keras.layers.Dense(4, activation='relu', dtype='float32')) net.add(tf.keras.layers.Dense(4, activation='relu')) net.add(tf.keras.layers.Dense(1)) return net </code></pre> <p>To change your input: <code>y = y.astype('float32')</code></p> <p><strong>Part 2:</strong> You need to call the function that computes your model (i.e. <code>model(data)</code>) under tf.GradientTape(). For example, you can replace your <code>compute_loss</code> method with the following:</p> <pre><code>def compute_loss(model, x, y): pred = model(x) return tf.reduce_mean(tf.square(tf.subtract(pred, y))) </code></pre>
36,479,640
Time/Space Complexity of Depth First Search
<p>I've looked at various other StackOverflow answer's and they all are different to what my lecturer has written in his slides.</p> <blockquote> <p>Depth First Search has a time complexity of O(b^m), where b is the maximum branching factor of the search tree and m is the maximum depth of the state space. Terrible if m is much larger than d, but if search tree is "bushy", may be much faster than Breadth First Search.</p> </blockquote> <p>He goes on to say..</p> <blockquote> <p>The space complexity is O(bm), i.e. space linear in length of action sequence! Need only store a single path from the root to the leaf node, along with remaining unexpanded sibling nodes for each node on path.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/10118580/time-complexity">Another answer</a> on StackOverflow states that it is O(n + m).</p>
36,480,122
3
1
null
2016-04-07 14:44:53.857 UTC
10
2019-10-18 15:02:29.683 UTC
2018-10-05 16:23:38.35 UTC
null
1,835,769
null
4,561,292
null
1
21
algorithm|time-complexity|depth-first-search|space-complexity
62,219
<p><strong>Time Complexity:</strong> If you can access each node in O(1) time, then with branching factor of b and max depth of m, the total number of nodes in this tree would be worst case = 1 + b + b<sup>2</sup> + … + b<sup>m-1</sup>. Using the formula for summing a geometric sequence (or even solving it ourselves) tells that this sums to = (b<sup>m</sup> - 1)/(b - 1), resulting in total time to visit each node proportional to b<sup>m</sup>. Hence the complexity = O(b<sup>m</sup>).</p> <p>On the other hand, if instead of using the branching factor and max depth you have the number of nodes <em>n</em>, then you can directly say that the complexity will be proportional to <em>n</em> or equal to <em>O(n)</em>.</p> <p>The other answers that you have linked in your question are similarly using different terminologies. The idea is same everywhere. Some solutions have added the edge count too to make the answer more precise, but in general, node count is sufficient to describe the complexity.</p> <hr> <p><strong>Space Complexity:</strong> The length of longest path = m. For each node, you have to store its siblings so that when you have visited all the children, and you come back to a parent node, you can know which sibling to explore next. For m nodes down the path, you will have to store b nodes extra for each of the m nodes. That’s how you get an O(bm) space complexity.</p>
38,182,501
How to get current datetime with format Y-m-d H:M:S using node-datetime library of nodejs?
<p>I'm using <a href="https://www.npmjs.com/package/node-datetime/" rel="noreferrer">node-datetime</a> library. I want to get current datetime with format such as Year-month-day hour-minute-second </p> <p>ex : <em>2016-07-04 17:19:11</em></p> <pre><code>var dateTime = require('node-datetime'); var dt = dateTime.create(); dt.format('m/d/Y H:M:S'); console.log(new Date(dt.now())); </code></pre> <p>But my result such as:</p> <blockquote> <p>Mon Jul 04 2016 17:19:11 GMT+0700 (SE Asia Standard Time)</p> </blockquote>
38,182,551
1
0
null
2016-07-04 10:29:59.987 UTC
null
2022-04-20 08:33:27.977 UTC
null
null
null
null
4,766,534
null
1
21
node.js|datetime
60,564
<p>See <a href="https://www.npmjs.com/package/node-datetime#methods" rel="nofollow noreferrer">the docs</a> for details on <code>format</code>:</p> <blockquote> <p>Returns a formatted date time string.</p> </blockquote> <p>Store the result of your call to <code>dt.format</code> and don't pass this to the <code>Date</code> constructor:</p> <pre><code>var dateTime = require('node-datetime'); var dt = dateTime.create(); var formatted = dt.format('Y-m-d H:M:S'); console.log(formatted); </code></pre> <p>[ Run the example above: <a href="https://replit.com/@SamGluck1/so-node-datetime" rel="nofollow noreferrer">https://replit.com/@SamGluck1/so-node-datetime</a> ]</p> <p>I have amended the format string from <code>'m/d/Y'</code> to <code>'Y-m-d'</code> as per your question.</p>
38,253,804
How to make a circular slider in react-native
<p>I want to add a like range component. But one that is actually circular and i have no idea how to do it. Can you point me to some help please.</p> <p>Te example of what i want:</p> <p><a href="https://i.stack.imgur.com/LwH9G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LwH9G.png" alt="Circle range"></a></p>
39,041,997
2
0
null
2016-07-07 19:29:11.347 UTC
9
2016-08-19 14:58:54.75 UTC
null
null
null
null
4,254,647
null
1
11
javascript|reactjs|react-native|reactive-programming
9,151
<p>I've been working with react-native-svg lately and I think it is fantastic - SVG and React are a match made in geek-heaven, just perfect for creating custom UI's with no need to drop down to native drawing code.</p> <p>Here's a little <code>CircularSlider</code> component that implements what you described above:</p> <pre><code>import React,{Component} from 'react' import {PanResponder,View} from 'react-native' import Svg,{Path,Circle,G,Text} from 'react-native-svg' class CircularSlider extends Component { constructor(props){ super(props) this.handlePanResponderMove = this.handlePanResponderMove.bind(this) this.cartesianToPolar = this.cartesianToPolar.bind(this) this.polarToCartesian = this.polarToCartesian.bind(this) const {width,height} = props const smallestSide = (Math.min(width,height)) this.state = { cx: width/2, cy: height/2, r: (smallestSide/2)*0.85 } } componentWillMount = () =&gt; { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: () =&gt; true, onMoveShouldSetPanResponder: () =&gt; true, onPanResponderMove: this.handlePanResponderMove }) } polarToCartesian(angle){ const {cx,cy,r} = this.state , a = (angle-270) * Math.PI / 180.0 , x = cx + (r * Math.cos(a)) , y = cy + (r * Math.sin(a)) return {x,y} } cartesianToPolar(x,y){ const {cx,cy} = this.state return Math.round((Math.atan((y-cy)/(x-cx)))/(Math.PI/180)+((x&gt;cx) ? 270 : 90)) } handlePanResponderMove({nativeEvent:{locationX,locationY}}){ this.props.onValueChange(this.cartesianToPolar(locationX,locationY)) } render(){ const {width,height,value,meterColor,textColor,onValueChange} = this.props , {cx,cy,r} = this.state , startCoord = this.polarToCartesian(0) , endCoord = this.polarToCartesian(value) return ( &lt;Svg onLayout={this.onLayout} width={width} height={height}&gt; &lt;Circle cx={cx} cy={cy} r={r} stroke='#eee' strokeWidth={0.5} fill='none'/&gt; &lt;Path stroke={meterColor} strokeWidth={5} fill='none' d={`M${startCoord.x} ${startCoord.y} A ${r} ${r} 0 ${value&gt;180?1:0} 1 ${endCoord.x} ${endCoord.y}`}/&gt; &lt;G x={endCoord.x-7.5} y={endCoord.y-7.5}&gt; &lt;Circle cx={7.5} cy={7.5} r={10} fill={meterColor} {...this._panResponder.panHandlers}/&gt; &lt;Text key={value+''} x={7.5} y={1} fontSize={10} fill={textColor} textAnchor="middle"&gt;{value+''}&lt;/Text&gt; &lt;/G&gt; &lt;/Svg&gt; ) } } export default CircularSlider </code></pre> <p>The full sample project code is in github <a href="https://github.com/steveliles/react-native-circular-slider-example" rel="noreferrer">here</a>.</p> <p>This is just a quick prototype to give you the idea, but here's how it looks (two instances of CircularSlider, absolutely positioned so they have the same centres):</p> <p><a href="https://i.stack.imgur.com/ywzhp.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ywzhp.gif" alt="enter image description here"></a></p>
183,002
Protect Excel Worksheet for format and size and allow only for entry
<p>I am creating an XLS worksheet that would be used to collect data from the users. I have restricted the user input using validations. In order to easily be able to print the worksheet i have set the lenghts of the columns. Have made the relevant columns wrap. However i would like to protect the worksheet such that User is not allowed to 1. Change the format 2. Change the Validations 3. Change the column size User should be allowed to 1. Enter input values 2. Select the value (from drop down whereever applicable)</p> <p>The protect sheet always restricts user inputs.</p>
183,172
2
0
null
2008-10-08 14:16:42.06 UTC
1
2008-10-08 14:48:34.117 UTC
null
null
null
Dheer
17,266
null
1
5
excel
38,367
<p>The key is <em>after</em> you protect the sheet to use the interface exposed in "Allow Users To Edit Ranges". I'm going to assume you are using Office 2003 since you didn't specify, so you find it in <strong>Tools -> Protection -> Allow Users to Edit Ranges</strong>.<br><br>From there it should be pretty obvious - you create named ranges and give edit access to users based on that.<br><br>On the second issue of having users pick values from combo-boxes, you control that through <strong>Data -> Validation</strong> then create a Custom list.</p>
601,658
How can I implement the Iterable interface?
<p>Given the following code, how can I iterate over an object of type ProfileCollection?</p> <pre><code>public class ProfileCollection implements Iterable { private ArrayList&lt;Profile&gt; m_Profiles; public Iterator&lt;Profile&gt; iterator() { Iterator&lt;Profile&gt; iprof = m_Profiles.iterator(); return iprof; } ... public Profile GetActiveProfile() { return (Profile)m_Profiles.get(m_ActiveProfile); } } public static void main(String[] args) { m_PC = new ProfileCollection("profiles.xml"); // properly outputs a profile: System.out.println(m_PC.GetActiveProfile()); // not actually outputting any profiles: for(Iterator i = m_PC.iterator();i.hasNext();) { System.out.println(i.next()); } // how I actually want this to work, but won't even compile: for(Profile prof: m_PC) { System.out.println(prof); } } </code></pre>
601,671
2
0
null
2009-03-02 08:48:16.367 UTC
19
2015-10-29 15:29:24.307 UTC
2015-10-29 15:29:24.307 UTC
null
304,151
Dewayne
67,117
null
1
52
java|iterator
106,135
<p>Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in <a href="https://stackoverflow.com/questions/449103/non-generic-reference-to-generic-class-results-in-non-generic-return-types/449115#449115">Non-generic reference to generic class results in non-generic return types</a>.</p> <p>So I would at least change it to:</p> <pre><code>public class ProfileCollection implements Iterable&lt;Profile&gt; { private ArrayList&lt;Profile&gt; m_Profiles; public Iterator&lt;Profile&gt; iterator() { Iterator&lt;Profile&gt; iprof = m_Profiles.iterator(); return iprof; } ... public Profile GetActiveProfile() { return (Profile)m_Profiles.get(m_ActiveProfile); } } </code></pre> <p>and this should work:</p> <pre><code>for (Profile profile : m_PC) { // do stuff } </code></pre> <p>Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:</p> <pre><code>for (Object profile : m_PC) { // do stuff } </code></pre> <p>This is a pretty obscure corner case of Java generics.</p> <p>If not, please provide some more info about what's going on.</p>
2,518,695
How to get iPhones current orientation?
<p>Is there a special method to get iPhones orientation? I don't need it in degrees or radians, I want it to return an UIInterfaceOrientation object. I just need it for an if-else construction like </p> <pre><code>if(currentOrientation==UIInterfaceOrientationPortrait ||currentOrientation==UIInterfaceOrientationPortraitUpsideDown) { //Code } if (currentOrientation==UIInterfaceOrientationLandscapeRight ||currentOrientation==UIInterfaceOrientationLandscapeLeft ) { //Code } </code></pre> <p>Thanks in advance!</p>
2,518,766
5
0
null
2010-03-25 19:25:33.03 UTC
14
2020-08-11 22:45:17.547 UTC
null
null
null
null
299,901
null
1
44
objective-c|accelerometer
49,497
<p>This is most likely what you want:</p> <pre><code>UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation]; </code></pre> <p>You can then use system macros like: </p> <pre><code>if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) { } </code></pre> <p>If you want the device orientation use:</p> <pre><code>UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation]; </code></pre> <p>This includes enumerations like <code>UIDeviceOrientationFaceUp</code> and <code>UIDeviceOrientationFaceDown</code></p>
3,150,293
How does a parser (for example, HTML) work?
<p>For argument's sake lets assume a HTML parser.</p> <p>I've read that it <em>tokenizes</em> everything first, and then parses it.</p> <p>What does tokenize mean?</p> <p>Does the parser read every character each, building up a multi dimensional array to store the structure?</p> <p>For example, does it read a <code>&lt;</code> and then begin to capture the element, and then once it meets a closing <code>&gt;</code> (outside of an attribute) it is pushed onto a array stack somewhere?</p> <p>I'm interested for the sake of knowing (I'm curious).</p> <p>If I were to read through the source of something like <a href="http://htmlpurifier.org/" rel="noreferrer">HTML Purifier</a>, would that give me a good idea of how HTML is parsed?</p>
3,150,450
5
6
null
2010-06-30 14:36:53.693 UTC
20
2017-02-12 18:07:21.92 UTC
2014-07-21 00:23:24.207 UTC
null
31,671
null
31,671
null
1
45
html|browser|parsing|html-parsing|tokenize
13,154
<p>First of all, you should be aware that parsing HTML is particularly ugly -- HTML was in wide (and divergent) use before being standardized. This leads to all manner of ugliness, such as the standard specifying that some constructs aren't allowed, but then specifying required behavior for those constructs anyway.</p> <p>Getting to your direct question: tokenization is roughly equivalent to taking English, and breaking it up into words. In English, most words are consecutive streams of letters, possibly including an apostrophe, hyphen, etc. Mostly words are surrounded by spaces, but a period, question mark, exclamation point, etc., can also signal the end of a word. Likewise for HTML (or whatever) you specify some rules about what can make up a token (word) in this language. The piece of code that breaks the input up into tokens is normally known as the lexer.</p> <p>At least in a normal case, you do <em>not</em> break all the input up into tokens before you start parsing. Rather, the parser calls the lexer to get the next token when it needs one. When it's called, the lexer looks at enough of the input to find one token, delivers that to the parser, and no more of the input is tokenized until the next time the parser needs more input.</p> <p>In a general way, you're right about how a parser works, but (at least in a typical parser) it uses a stack during the act of parsing a statement, but what it builds to represent a statement is normally a tree (and Abstract Syntax Tree, aka AST), not a multidimensional array.</p> <p>Based on the complexity of parsing HTML, I'd reserve looking at a parser for it until you've read through a few others first. If you do some looking around, you should be able to find a fair number of parsers/lexers for things like mathematical expressions that are probably more suitable as an introduction (smaller, simpler, easier to understand, etc.)</p>
2,838,979
Where do I control the behavior of the "X" close button in the upper right of a winform?
<p>I'm venturing into making my VB.NET application a little better to use by making some of the forms modeless.</p> <p>I think I've figured out how to use dlg.Show() and dlg.Hide() instead of calling dlg.ShowDialog(). I have an instance of my modeless dialog in my main application form:</p> <pre><code>Public theModelessDialog As New dlgModeless </code></pre> <p>To fire up the modeless dialog I call</p> <pre><code>theModelessDialog.Show() </code></pre> <p>and within the OK and Cancel button handlers in <code>dlgModeless</code> I have</p> <pre><code>Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click Me.DialogResult = System.Windows.Forms.DialogResult.OK Me.Hide() End Sub Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click Me.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Hide() End Sub </code></pre> <p>and that seems to work fine.</p> <p>The "X" button in the upper right is getting me, though. When I close the form with that button, then try to reopen the form, I get</p> <blockquote> <p>ObjectDisposedException was unhandled. Cannot access a disposed object.</p> </blockquote> <p>I feel like I'm most of the way there but I can't figure out how to do either of the following:</p> <ul> <li>Hide that "X" button</li> <li>Catch the event so I don't dispose of the object (just treat it like I hit Cancel)</li> </ul> <p>Any ideas?</p> <p>The class of this dialog is <code>System.Windows.Forms.Form</code>.</p>
2,838,990
6
0
null
2010-05-15 05:01:49.837 UTC
1
2018-06-04 10:19:42.387 UTC
2014-02-27 14:50:33.25 UTC
null
321,731
null
13,895
null
1
17
vb.net|winforms|visual-studio-2005|modeless
67,394
<p>Use <code>Me.Close()</code> to hide the form. To open it, use the following snippet:</p> <pre><code>If theModelessDialog.IsDisposed Then theModelessDialog = New dlgModeless End If dlgModeless.Show() </code></pre> <p>If this is saving data, then you'll need to figure some way of storing it (perhaps in a static variable/s in the form). This is the proper way to do what you are trying to achieve though.</p> <p>You'll also have to forgive me if my VB is off, it's been a while.</p>
3,065,095
How do I efficiently parse a CSV file in Perl?
<p>I'm working on a project that involves parsing a large csv formatted file in Perl and am looking to make things more efficient.</p> <p>My approach has been to <code>split()</code> the file by lines first, and then <code>split()</code> each line again by commas to get the fields. But this suboptimal since at least two passes on the data are required. (once to split by lines, then once again for each line). This is a very large file, so cutting processing in half would be a significant improvement to the entire application.</p> <p>My question is, what is the most time efficient means of parsing a large CSV file using only built in tools?</p> <p>note: Each line has a varying number of tokens, so we can't just ignore lines and split by commas only. Also we can assume fields will contain only alphanumeric ascii data (no special characters or other tricks). Also, i don't want to get into parallel processing, although it might work effectively.</p> <p><strong>edit</strong></p> <p>It can only involve built-in tools that ship with Perl 5.8. For bureaucratic reasons, I cannot use any third party modules (even if hosted on cpan)</p> <p><strong>another edit</strong></p> <p>Let's assume that our solution is only allowed to deal with the file data once it is entirely loaded into memory.</p> <p><strong>yet another edit</strong></p> <p>I just grasped how stupid this question is. Sorry for wasting your time. Voting to close.</p>
3,065,232
6
9
null
2010-06-17 19:49:02.043 UTC
6
2018-11-14 17:46:10.62 UTC
2010-06-17 22:20:01.733 UTC
null
8,454
null
357,024
null
1
25
perl|parsing|text|csv|split
77,861
<p>The right way to do it -- by an order of magnitude -- is to use <a href="https://metacpan.org/pod/Text::CSV_XS" rel="noreferrer">Text::CSV_XS</a>. It will be much faster and much more robust than anything you're likely to do on your own. If you're determined to use only core functionality, you have a couple of options depending on speed vs robustness.</p> <p>About the fastest you'll get for pure-Perl is to read the file line by line and then naively split the data:</p> <pre><code>my $file = 'somefile.csv'; my @data; open(my $fh, '&lt;', $file) or die "Can't read file '$file' [$!]\n"; while (my $line = &lt;$fh&gt;) { chomp $line; my @fields = split(/,/, $line); push @data, \@fields; } </code></pre> <p>This will fail if any fields contain embedded commas. A more robust (but slower) approach would be to use Text::ParseWords. To do that, replace the <code>split</code> with this:</p> <pre><code> my @fields = Text::ParseWords::parse_line(',', 0, $line); </code></pre>
2,987,465
Newline in error_log() in PHP
<p>How can I insert a newline while using <code>error_log()</code> in PHP?</p> <p>I tried to use <code>&lt;br&gt;</code> and <code>\n</code>, but those didn't work.</p>
2,987,491
6
2
null
2010-06-07 06:26:49.677 UTC
5
2021-09-25 21:06:48.16 UTC
2021-09-25 20:45:35.043 UTC
null
63,550
null
252,929
null
1
45
php
41,933
<p>Use double quotes when adding the error message.</p> <pre><code>error_log(&quot;This is a two lined message. \nThis is line two.&quot;); </code></pre> <p>should work.</p> <pre><code>error_log('This is a one lined message. \nThis is the same line still.'); </code></pre> <p>will not work: notice the single quotes.</p>
2,554,445
How to fix "Byte-Order Mark found in UTF-8 File" validation warning
<p>I've got an xhtml page validating under xhtml strict doctype -- but, I getting this warning which I trying to understand -- and correct.</p> <p>Just, how do I locate this errant &quot;Byte-Order Mark&quot;. I'm editing my file using Visual Studio--not sure if that helps.</p> <blockquote> <p>Warning Byte-Order Mark found in UTF-8 File.</p> <p>The Unicode Byte-Order Mark (BOM) in UTF-8 encoded files is known to cause problems for some text editors and older browsers. You may want to consider avoiding its use until it is better supported.</p> </blockquote>
2,554,498
6
0
null
2010-03-31 15:58:13.95 UTC
10
2021-09-29 19:56:20.693 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
223,134
null
1
58
html|css|validation
71,971
<p>The location part of your question is easy: The <a href="http://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">byte-order mark</a> (BOM) will be at the very beginning of the file.</p> <p>When editing the file, in the bottom status bar toward the right VS Code shows you what encoding is being used for the current file:</p> <p><a href="https://i.stack.imgur.com/Kn7SL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Kn7SL.png" alt="Status bar showing &quot;UTF-8 with BOM&quot;" /></a></p> <p>Click it to open the command palette with the options &quot;Reopen with encoding&quot; and &quot;Save with encoding&quot;:</p> <p><a href="https://i.stack.imgur.com/gc9CU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gc9CU.png" alt="The command palette showing the options" /></a></p> <p>Click &quot;Save with Encoding&quot; to get a list of encodings:</p> <p><a href="https://i.stack.imgur.com/QX0gK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QX0gK.png" alt="Command palette showing list of file encodings such as UTF-8, UTF-16 LE, UTF-16 BE" /></a></p> <p>Choosing an encoding saves the file with that encoding.</p> <p>See also <a href="http://unicode.org/faq/utf_bom.html#bom5" rel="noreferrer">this note</a> in the Unicode site's FAQ about the BOM and UTF-8 files. It has no function other than to call out that the file is, in fact, UTF-8. In particular, it has no effect on the byte order (the main reason we have BOMs), because the byte order of UTF-8 is fixed.</p>
2,998,336
How to create a UIScrollView Programmatically?
<p>Alright, so the key here is I'm not using IB at all, because the View I'm working with is created programmatically. The <code>UIView</code> covers the lower half the screen, and has a bunch of buttons on it. However, I want to add more buttons to the <code>UIView</code>, without making it any larger. To do so, I want to make a <code>UIScrollView</code> inside the view, which will allow me to add more buttons off screen so the user can scroll to them. I think that's how it works.</p> <pre><code>self.manaView = [[[UIView alloc] initWithFrame:frame] autorelease]; self.manaView.backgroundColor = [UIColor purpleColor]; UIScrollView *scroll = [UIScrollView alloc]; scroll.contentSize = CGSizeMake(320, 400); scroll.showsHorizontalScrollIndicator = YES; [self.manaView addSubview:scroll]; </code></pre> <p>The first part of the code iniates my <code>UIView</code>, which works great, but I can't figure out how to make the <code>UIScrollView</code> programmatically and add it to the view, and then add the buttons to it.</p> <pre><code>UIButton *ret2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; ret2.tag = 102; ret2.frame = CGRectMake(255, 5, 60, 50); [ret2 setTitle:@"Return" forState:UIControlStateNormal]; [ret2 addTarget:self action:@selector(flipAction:) forControlEvents:UIControlEventTouchUpInside]; [scroll addSubview:ret2]; </code></pre> <p>When I did that, the button simply disappeared off my screen. So How do I do this correctly? Thank you for your help!</p>
2,998,765
7
0
null
2010-06-08 14:40:03.483 UTC
19
2019-11-21 13:27:13.357 UTC
2016-02-13 05:52:23.777 UTC
null
3,095,498
null
200,567
null
1
39
iphone|objective-c|uiscrollview
83,292
<p>Instead of:</p> <pre><code>UIScrollView *scroll = [UIScrollView alloc]; </code></pre> <p>do this (setting the frame to however big you want the scroll view to be):</p> <pre><code>UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:...]; </code></pre>
3,034,392
What use does the JavaScript forEach method have (that map can't do)?
<p>The only difference I see in map and foreach is that <code>map</code> is returning an array and <code>forEach</code> is not. However, I don't even understand the last line of the <code>forEach</code> method &quot;<code>func.call(scope, this[i], i, this);</code>&quot;. For example, isn't &quot;<code>this</code>&quot; and &quot;<code>scope</code>&quot; referring to same object and isn't <code>this[i]</code> and <code>i</code> referring to the current value in the loop?</p> <p>I noticed on another post someone said &quot;Use <code>forEach</code> when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want &quot;side effects&quot;. I don't know what is meant by side effects.</p> <pre><code>Array.prototype.map = function(fnc) { var a = new Array(this.length); for (var i = 0; i &lt; this.length; i++) { a[i] = fnc(this[i]); } return a; } Array.prototype.forEach = function(func, scope) { scope = scope || this; for (var i = 0, l = this.length; i &lt; l; i++) { func.call(scope, this[i], i, this); } } </code></pre> <p>Finally, are there any real uses for these methods in JavaScript (since we aren't updating a database) other than to manipulate numbers like the following?</p> <pre><code>alert([1,2,3,4].map(function(x){ return x + 1})); // This is the only example I ever see of map in JavaScript. </code></pre>
3,034,430
8
2
null
2010-06-13 23:58:53.947 UTC
36
2022-01-14 18:03:20.617 UTC
2022-01-12 19:15:10.647 UTC
null
63,550
null
1,392,690
null
1
95
javascript|arrays|dictionary|foreach|prototype
40,965
<p>The essential difference between <code>map</code> and <code>forEach</code> in your example is that <code>forEach</code> operates on the original array elements, whereas <code>map</code> explicitly returns a new array as a result. </p> <p>With <code>forEach</code> you are taking some action with -- and optionally changing -- each element in the original array. The <code>forEach</code> method runs the function you provide for each element, but returns nothing (<code>undefined</code>). On the other hand, <code>map</code> walks through the array, applies a function to each element, and <em>emits the result as a new array</em>. </p> <p>The "side effect" with <code>forEach</code> is that the original array is being changed. "No side effect" with <code>map</code> means that, in idiomatic usage, the original array elements are <em>not</em> changed; the new array is a one-to-one mapping of each element in the original array -- the mapping transform being your provided function.</p> <p>The fact that there's no database involved does not mean that you won't have to operate on data structures, which, after all, is one of the essences of programming in any language. As for your last question, your array can contain not only numbers, but objects, strings, functions, etc.</p>
2,841,484
How can a <label> completely fill its parent <td>?
<p>Here is the relevant code (doesn't work):</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;testing td checkboxes&lt;/title&gt; &lt;style type="text/css"&gt; td { border: 1px solid #000; } label { border: 1px solid #f00; width: 100%; height: 100% } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Some column title&lt;/td&gt; &lt;td&gt;Another column title&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Value 1&lt;br&gt;(a bit more info)&lt;/td&gt; &lt;td&gt;&lt;label&gt;&lt;input type="checkbox" /&gt; &amp;nbsp;&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Value 2&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The reason is that I want a click anywhere in the table cell to check/uncheck the checkbox.</p> <p>edits: By the way, no javascript solutions please, for accessibility reasons. I tried using display: block; but that only works for the width, not for the height</p>
3,081,445
11
3
null
2010-05-15 19:36:55.647 UTC
4
2021-10-05 10:52:00.257 UTC
2014-07-21 14:20:36.05 UTC
null
895,245
null
157,949
null
1
41
css
65,564
<p>I have only tested this in IE 6, 7, 8 and FF 3.6.3.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;testing td checkboxes&lt;/title&gt; &lt;style type=&quot;text/css&quot;&gt; tr { height: 1px; } td { border: 1px solid #000; height: 100%; } label { display: block; border: 1px solid #f00; min-height: 100%; /* for the latest browsers which support min-height */ height: auto !important; /* for newer IE versions */ height: 100%; /* the only height-related attribute that IE6 does not ignore */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Some column title&lt;/td&gt; &lt;td&gt;Another column title&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Value 1&lt;br&gt;(a bit more info)&lt;/td&gt; &lt;td&gt;&lt;label&gt;&lt;input type=&quot;checkbox&quot; /&gt; &amp;nbsp;&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The main trick here is to define the height of the rows so we can use a 100% height on their children (the cells) and in turns, a 100% height on the cells' children (the labels). This way, no matter how much content there is in a cell, it will forcibly expand its parent row, and its sibling cells will follow. Since the label has a 100% height of its parent which has its height defined, it will also expand vertically.</p> <p>The second and last trick (but just as important) is to use a CSS hack for the min-height attribute, as explained in the comments.</p>
2,568,507
How to log SQL statements in Grails
<p>I want to log in the console or in a file, all the queries that Grails does, to check performance.</p> <p>I had configured <a href="http://www.grails.org/FAQ#Q:%20How%20can%20I%20turn%20on%20logging%20for%20hibernate%20in%20order%20to%20see%20SQL%20statements,%20input%20parameters%20and%20output%20results?" rel="noreferrer">this</a> without success.</p> <p>Any idea would help.</p>
2,568,617
11
1
null
2010-04-02 18:51:04.193 UTC
25
2022-08-30 12:59:54.21 UTC
2015-03-19 22:57:00.217 UTC
null
2,390,083
null
1,356,709
null
1
90
sql|logging|grails
58,891
<p>Setting</p> <pre><code>datasource { ... logSql = true } </code></pre> <p>in <code>DataSource.groovy</code> (as per <a href="http://docs.grails.org/latest/guide/conf.html#dataSource" rel="nofollow noreferrer">these</a> instructions) was enough to get it working in my environment. It seems that parts of the FAQ are out of date (e.g. <em>the many-to-many columns backwards</em> question) so this might also be something that changed in the meantime.</p>
40,222,162
TypeScript 2: custom typings for untyped npm module
<p>After trying suggestions posted in <a href="https://stackoverflow.com/questions/37641960/typescript-how-to-define-custom-typings-for-installed-npm-package">other places</a>, I find myself unable to get a typescript project running that uses an untyped NPM module. Below is a minimal example and the steps that I tried.</p> <p>For this minimal example, we will pretend that <code>lodash</code> does not have existing type definitions. As such, we will ignore the package <code>@types/lodash</code> and try to manually add its typings file <code>lodash.d.ts</code> to our project.</p> <p>Folder structure</p> <ul> <li>node_modules <ul> <li>lodash</li> </ul></li> <li>src <ul> <li>foo.ts</li> </ul></li> <li>typings <ul> <li>custom <ul> <li>lodash.d.ts</li> </ul></li> <li>global</li> <li>index.d.ts</li> </ul></li> <li>package.json</li> <li>tsconfig.json</li> <li>typings.json</li> </ul> <p>Next, the files. </p> <p>File <code>foo.ts</code></p> <pre><code>///&lt;reference path="../typings/custom/lodash.d.ts" /&gt; import * as lodash from 'lodash'; console.log('Weeee'); </code></pre> <p>File <code>lodash.d.ts</code> is copied directly from the original <code>@types/lodash</code> package.</p> <p>File <code>index.d.ts</code></p> <pre><code>/// &lt;reference path="custom/lodash.d.ts" /&gt; /// &lt;reference path="globals/lodash/index.d.ts" /&gt; </code></pre> <p>File <code>package.json</code></p> <pre><code>{ "name": "ts", "version": "1.0.0", "description": "", "main": "index.js", "typings": "./typings/index.d.ts", "dependencies": { "lodash": "^4.16.4" }, "author": "", "license": "ISC" } </code></pre> <p>File <code>tsconfig.json</code></p> <pre><code>{ "compilerOptions": { "target": "ES6", "jsx": "react", "module": "commonjs", "sourceMap": true, "noImplicitAny": true, "experimentalDecorators": true, "typeRoots" : ["./typings"], "types": ["lodash"] }, "include": [ "typings/**/*", "src/**/*" ], "exclude": [ "node_modules", "**/*.spec.ts" ] } </code></pre> <p>File <code>typings.json</code></p> <pre><code>{ "name": "TestName", "version": false, "globalDependencies": { "lodash": "file:typings/custom/lodash.d.ts" } } </code></pre> <p>As you can see, I have tried many different ways of importing typings:</p> <ol> <li>By directly importing it in <code>foo.ts</code></li> <li>By a <code>typings</code> property in <code>package.json</code></li> <li>By using <code>typeRoots</code> in <code>tsconfig.json</code> with a file <code>typings/index.d.ts</code></li> <li>By using an explicit <code>types</code> in <code>tsconfig.json</code></li> <li>By including the <code>types</code> directory in <code>tsconfig.json</code></li> <li>By making a custom <code>typings.json</code> file and running <code>typings install</code></li> </ol> <p>Yet, when I run Typescript:</p> <pre><code>E:\temp\ts&gt;tsc error TS2688: Cannot find type definition file for 'lodash'. </code></pre> <p>What am I doing wrong?</p>
40,326,719
4
0
null
2016-10-24 15:29:46.667 UTC
55
2020-07-03 18:55:41.31 UTC
2017-05-23 11:33:26.967 UTC
null
-1
null
1,235,281
null
1
102
typescript|npm|typescript-typings
49,071
<p>Unfortunately these things are not currently very well documented, but even if you were able to get it working, let's go over your configuration so that you understand what each part is doing and how it relates to how typescript processes and loads typings.</p> <p>First let's go over the error you are receiving:</p> <pre class="lang-none prettyprint-override"><code>error TS2688: Cannot find type definition file for 'lodash'. </code></pre> <p>This error is actually not coming from your imports or references or your attempt to use lodash anywhere in your ts files. Rather it is coming from a misunderstanding of how to use the <code>typeRoots</code> and <code>types</code> properties, so let's go into a little more detail on those.</p> <p>The thing about <code>typeRoots:[]</code> and <code>types:[]</code> properties is that they are <strong>NOT</strong> general-purpose ways to load arbitrary declaration (<code>*.d.ts</code>) files.</p> <p>These two properties are directly related to the new TS 2.0 feature which allows packaging and loading typing declarations from <strong>NPM packages</strong>. </p> <p>This is very important to understand, that these work only with folders in NPM format (i.e. a folder containing a <em>package.json</em> or <em>index.d.ts</em>). </p> <p>The default for <code>typeRoots</code> is:</p> <pre><code>{ "typeRoots" : ["node_modules/@types"] } </code></pre> <p>By default this means that typescript will go into the <code>node_modules/@types</code> folder and try to load every sub-folder it finds there as a <strong>npm package</strong>. </p> <p>It is important to understand that this will fail if a folder does not have an npm package-like structure.</p> <p>This is what is happening in your case, and the source of your initial error. </p> <p>You have switched typeRoot to be:</p> <pre><code>{ "typeRoots" : ["./typings"] } </code></pre> <p>This means that typescript will now scan the <code>./typings</code> folder for <strong>subfolders</strong> and try to load each subfolder it finds as an npm module.</p> <p>So let's pretend you just had <code>typeRoots</code> setup to point to <code>./typings</code> but did not yet have any <code>types:[]</code> property setup. You would likely see these errors:</p> <pre class="lang-none prettyprint-override"><code>error TS2688: Cannot find type definition file for 'custom'. error TS2688: Cannot find type definition file for 'global'. </code></pre> <p>This is because <code>tsc</code> is scanning your <code>./typings</code> folder and finding the sub-folders <code>custom</code> and <code>global</code>. It then is trying to interpret these as npm package-type typing, but there is no <code>index.d.ts</code> or <code>package.json</code> in these folders and so you get the error.</p> <p>Now let's talk a bit about the <code>types: ['lodash']</code> property you are setting. What does this do? By default, typescript will load <strong>all</strong> sub-folders it finds within your <code>typeRoots</code>. If you specify a <code>types:</code> property it will only load those specific sub-folders.</p> <p>In your case you are telling it to load the <code>./typings/lodash</code> folder but it doesn't exist. This is why you get:</p> <pre class="lang-none prettyprint-override"><code>error TS2688: Cannot find type definition file for 'lodash' </code></pre> <p>So let's summarize what we've learned. Typescript 2.0 introduced <code>typeRoots</code> and <code>types</code> for loading declaration files packaged in <em>npm packages</em>. If you have custom typings or single loose <code>d.ts</code> files that are not contained withing a folder following npm package conventions, then these two new properties are not what you want to use. Typescript 2.0 does not really change how these would be consumed. You just have to include these files in your compilation context in one of the many standard ways:</p> <ol> <li><p>Directly including it in a <code>.ts</code> file: <code>///&lt;reference path="../typings/custom/lodash.d.ts" /&gt;</code></p></li> <li><p>Including <code>./typings/custom/lodash.d.ts</code> in your <code>files: []</code> property.</p></li> <li><p>Including <code>./typings/index.d.ts</code> in your <code>files: []</code> property (which then recursively includes the other typings.</p></li> <li><p>Adding <code>./typings/**</code> to your <code>includes:</code></p></li> </ol> <p>Hopefully, based on this discussion you'll be able to tell why the changes you mad to your <code>tsconfig.json</code> made things work again. </p> <h2>EDIT:</h2> <p>One thing that I forgot to mention is that <code>typeRoots</code> and <code>types</code> property are really only useful for the <strong>automatic</strong> loading of global declarations. </p> <p>For example if you </p> <pre class="lang-none prettyprint-override"><code>npm install @types/jquery </code></pre> <p>And you are using the default tsconfig, then that jquery types package will be loaded automatically and <code>$</code> will be available throughout all your scripts wihtout having to do any further <code>///&lt;reference/&gt;</code> or <code>import</code></p> <p>The <code>typeRoots:[]</code> property is meant to add additional locations from where type <em>packages</em> will be loaded frrom automatically.</p> <p>The <code>types:[]</code> property's primary use-case is to disable the automatic loading behavior (by setting it to an empty array), and then only listing specific types you want to include globally.</p> <p>The other way to load type packages from the various <code>typeRoots</code> is to use the new <code>///&lt;reference types="jquery" /&gt;</code> directive. Notice the <code>types</code> instead of <code>path</code>. Again, this is only useful for global declaration files, typically ones that don't do <code>import/export</code>. </p> <p>Now, here's one of the things that causes confusion with <code>typeRoots</code>. Remember, I said that <code>typeRoots</code> is about the global inclusion of modules. But <code>@types/folder</code> is also involved in standard module-resolution (regardless of your <code>typeRoots</code> setting). </p> <p>Specifically, explicitly importing modules always bypasses all <code>includes</code>, <code>excludes</code>, <code>files</code>, <code>typeRoots</code> and <code>types</code> options. So when you do:</p> <pre class="lang-js prettyprint-override"><code>import {MyType} from 'my-module'; </code></pre> <p>All the above mentioned properties are completely ignored. The relevant properties during <strong>module resolution</strong> are <code>baseUrl</code>, <code>paths</code>, and <code>moduleResolution</code>.</p> <p>Basically, when using <code>node</code> module resolution, it will start searching for a file name <code>my-module.ts</code>, <code>my-module.tsx</code>, <code>my-module.d.ts</code> starting at the folder pointed to by your <code>baseUrl</code> configuration.</p> <p>If it doesn't find the file, then it will look for a folder named <code>my-module</code> and then search for a <code>package.json</code> with a <code>typings</code> property, if there is <code>package.json</code> or no <code>typings</code> property inside telling it which file to load it will then search for <code>index.ts/tsx/d.ts</code> within that folder.</p> <p>If that's still not successful it will search for these same things in the <code>node_modules</code> folder starting at your <code>baseUrl/node_modules</code>. </p> <p>In addition, if it doesn't find these, it will search <code>baseUrl/node_modules/@types</code> for all the same things.</p> <p>If it still didn't find anything it will start going to the parent directory and search <code>node_modules</code> and <code>node_modules/@types</code> there. It will keep going up the directories until it reaches the root of your file system (even getting node-modules outside your project). </p> <p>One thing I want to emphasize is that module resolution completely ignores any <code>typeRoots</code> you set. So if you configured <code>typeRoots: ["./my-types"]</code>, this will not get searched during explicit module resolution. It only serves as a folder where you can put global definition files you want to make available to the whole application without further need to import or reference.</p> <p>Lastly, you can override the module behavior with path mappings (i.e. the <code>paths</code> property). So for example, I mentioned that any custom <code>typeRoots</code> is not consulted when trying to resolve a module. But if you liked you can make this behavior happen as so:</p> <pre><code>"paths" :{ "*": ["my-custom-types/*", "*"] } </code></pre> <p>What this does is for all imports that match the left-hand side, try modifying the import as in the right side before trying to include it (the <code>*</code> on the right hand side represents your initial import string. For example if you import:</p> <pre class="lang-js prettyprint-override"><code>import {MyType} from 'my-types'; </code></pre> <p>It would first try the import as if you had written:</p> <pre class="lang-js prettyprint-override"><code>import {MyType} from 'my-custom-types/my-types' </code></pre> <p>And then if it didn't find it would try again wihtout the prefix (second item in the array is just <code>*</code> which means the initial import. </p> <p>So this way you can add additional folders to search for custom declaration files or even custom <code>.ts</code> modules that you want to be able to <code>import</code>. </p> <p>You can also create custom mappings for specific modules:</p> <pre><code>"paths" :{ "*": ["my-types", "some/custom/folder/location/my-awesome-types-file"] } </code></pre> <p>This would let you do</p> <pre class="lang-js prettyprint-override"><code>import {MyType} from 'my-types'; </code></pre> <p>But then read those types from <code>some/custom/folder/location/my-awesome-types-file.d.ts</code></p>
40,055,439
Check if Logged in - React Router App ES6
<p>I am writing a <strong>React</strong>.js application (v15.3) using <strong>react-router</strong> (v2.8.1) and <strong>ES6 syntax</strong>. I cannot get the router code to intercept all transitions between pages to check if the user needs to login first.</p> <p>My top level render method is very simple (the app is trivial as well):</p> <pre><code> render() { return ( &lt;Router history={hashHistory}&gt; &lt;Route path="/" component={AppMain}&gt; &lt;Route path="login" component={Login}/&gt; &lt;Route path="logout" component={Logout}/&gt; &lt;Route path="subject" component={SubjectPanel}/&gt; &lt;Route path="all" component={NotesPanel}/&gt; &lt;/Route&gt; &lt;/Router&gt; ); } </code></pre> <p>All the samples on the web use ES5 code or older versions of react-router (older than version 2), and my various attempts with mixins (deprecated) and willTransitionTo (never gets called) have failed.</p> <p>How can I set up a global 'interceptor function' to force users to authenticate before landing on the page they request?</p>
40,064,677
6
1
null
2016-10-15 05:42:02.067 UTC
16
2022-03-23 06:13:02.91 UTC
null
null
null
null
294,439
null
1
31
javascript|authentication|reactjs|ecmascript-6|react-router
71,220
<p>This version of the onEnter callback finally worked for react-router (v2.8):</p> <pre><code> requireAuth(nextState, replace) { if(!this.authenticated()) // pseudocode - SYNCHRONOUS function (cannot be async without extra callback parameter to this function) replace('/login') } </code></pre> <p>The link which explains react-router redirection differences between V1 vs v2 is <a href="https://github.com/ReactTraining/react-router/blob/master/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors" rel="nofollow">here</a>. Relevant section quoted below:</p> <pre><code>Likewise, redirecting from an onEnter hook now also uses a location descriptor. // v1.0.x (nextState, replaceState) =&gt; replaceState(null, '/foo') (nextState, replaceState) =&gt; replaceState(null, '/foo', { the: 'query' }) // v2.0.0 (nextState, replace) =&gt; replace('/foo') (nextState, replace) =&gt; replace({ pathname: '/foo', query: { the: 'query' } }) </code></pre> <p><strong>Full Code Listing Below (react-router version 2.8.1):</strong></p> <pre><code>requireAuth(nextState, replace) { if(!this.authenticated()) // pseudocode - SYNCHRONOUS function (cannot be async without extra callback parameter to this function) replace('/login'); } render() { return ( &lt;Router history={hashHistory}&gt; &lt;Route path="/" component={AppMain}&gt; &lt;Route path="login" component={Login}/&gt; &lt;Route path="logout" component={Logout}/&gt; &lt;Route path="subject" component={SubjectPanel} onEnter={this.requireAuth}/&gt; &lt;Route path="all" component={NotesPanel} onEnter={this.requireAuth}/&gt; &lt;/Route&gt; &lt;/Router&gt; ); } </code></pre>
10,597,629
Make our own List<string, string, string>
<p>Can we make our own <code>List&lt;string, string, string&gt;</code> in C#.NET? I need to make a list having 3 different strings as a single element in the list.</p>
10,597,685
11
0
null
2012-05-15 09:16:19.093 UTC
2
2016-07-28 07:22:52.147 UTC
2014-06-28 06:36:38.63 UTC
null
661,933
null
238,779
null
1
9
c#|.net|list
62,745
<p>You can certainly create your own class called <code>List</code> with three generic type parameters. I would <em>strongly</em> discourage you from doing so though. It would confuse the heck out of anyone using your code.</p> <p>Instead, <em>either</em> use <code>List&lt;Tuple&lt;string, string, string&gt;&gt;</code> (if you're using .NET 4, anyway) or (preferrably) create your own class to encapsulate those three strings in a meaningful way, then use <code>List&lt;YourNewClass&gt;</code>.</p> <p>Creating your own class will make it much clearer when you're writing and reading the code - by giving names to the three different strings involved, everyone will know what they're meant to mean. You can also give more behaviour to the class as and when you need to.</p>
10,559,035
How to rotate a video with OpenCV
<p>How do you rotate all frames in a video stream using OpenCV? I tried using the code provided in a <a href="https://stackoverflow.com/questions/9041681/opencv-python-rotate-image-by-x-degrees-around-specific-point">similar question</a>, but it doesn't seem to work with the Iplimage image object returned cv.RetrieveFrame.</p> <p>This is the code I currently have:</p> <pre><code>import cv, cv2 import numpy as np def rotateImage(image, angle): if hasattr(image, 'shape'): image_center = tuple(np.array(image.shape)/2) shape = image.shape elif hasattr(image, 'width') and hasattr(image, 'height'): image_center = (image.width/2, image.height/2) shape = np.array((image.width, image.height)) else: raise Exception, 'Unable to acquire dimensions of image for type %s.' % (type(image),) rot_mat = cv2.getRotationMatrix2D(image_center, angle,1.0) result = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR) return result cap = cv.CaptureFromCAM(cam_index) #cap = cv.CaptureFromFile(path) fps = 24 width = int(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_WIDTH)) height = int(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_HEIGHT)) fourcc = cv.CV_FOURCC('P','I','M','1') #is a MPEG-1 codec writer = cv.CreateVideoWriter('out.avi', fourcc, fps, (width, height), 1) max_i = 90 for i in xrange(max_i): print i,max_i cv.GrabFrame(cap) frame = cv.RetrieveFrame(cap) frame = rotateImage(frame, 180) cv.WriteFrame(writer, frame) </code></pre> <p>But this just gives the the error:</p> <pre><code> File "test.py", line 43, in &lt;module&gt; frame = rotateImage(frame, 180) File "test_record_room.py", line 26, in rotateImage result = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR) TypeError: &lt;unknown&gt; is not a numpy array </code></pre> <p>Presumably because warpAffine takes a CvMat and not a Iplimage. According to the <a href="http://opencv.willowgarage.com/documentation/cpp/c++_cheatsheet.html" rel="noreferrer">C++ cheatsheet</a>, converting between the two is trivial, but I can't find any documentation on doing the equivalent in Python. How do I convert an Iplimage to Mat in Python?</p>
10,560,448
5
0
null
2012-05-11 21:43:54.123 UTC
3
2020-07-26 21:14:34.23 UTC
2017-05-23 12:34:54.003 UTC
null
-1
null
247,542
null
1
10
python|image-processing|opencv
38,045
<p>If you are just after a 180 degree rotation, you can use <code>Flip</code> on both axes,</p> <p>replace:</p> <pre><code>frame = rotateImage(frame, 180) </code></pre> <p>with:</p> <pre><code>cv.Flip(frame, flipMode=-1) </code></pre> <p>This is 'in place', so its quick, and you won't need your <code>rotateImage</code> function any more :)</p> <p>Example:</p> <pre><code>import cv orig = cv.LoadImage("rot.png") cv.Flip(orig, flipMode=-1) cv.ShowImage('180_rotation', orig) cv.WaitKey(0) </code></pre> <p>this: <img src="https://i.stack.imgur.com/502BU.png" alt="enter image description here"> becomes, this:<img src="https://i.stack.imgur.com/0lXx3.png" alt="enter image description here"></p>
6,102,909
Entity Framework Include() strongly typed
<p>Is there a way to make this strongly typed using the System.Data.Entity.Include method? In the method below Escalation is a ICollection&lt;>.</p> <pre><code>public IEnumerable&lt;EscalationType&gt; GetAllTypes() { Database.Configuration.LazyLoadingEnabled = false; return Database.EscalationTypes .Include("Escalation") .Include("Escalation.Primary") .Include("Escalation.Backup") .Include("Escalation.Primary.ContactInformation") .Include("Escalation.Backup.ContactInformation").ToList(); } </code></pre>
10,843,340
2
2
null
2011-05-23 20:54:02.12 UTC
8
2013-03-11 05:57:19.377 UTC
2011-05-23 21:06:44.833 UTC
user342706
null
user342706
null
null
1
53
c#|asp.net|entity-framework
21,750
<p>This is already available in Entity Framework 4.1.</p> <p>See here for a reference for how to use the include feature, it also shows how to include multiple levels: <a href="http://msdn.microsoft.com/en-us/library/gg671236%28VS.103%29.aspx">http://msdn.microsoft.com/en-us/library/gg671236(VS.103).aspx</a></p> <p>The strongly typed <code>Include()</code> method is an extension method so you have to remember to declare the <code>using System.Data.Entity;</code> statement.</p>
33,242,378
Rendering React components with promises inside the render method
<p>I have a component which gets a collection of items as props and <code>map</code>s them to a collection of components which are rendered as children of a parent component. We use images stored in <code>WebSQL</code> as byte arrays. Within the <code>map</code> function I get an image Id from the item and make an async call to the <code>DAL</code> in order to get the byte array for the image. My problem is that I cannot propagate the promise in to React, since it was not designed to deal with promises in rendering (not as far as I can tell anyway). I come from a <code>C#</code> background, so I guess I'm looking for something like the <code>await</code> keyword for resync-ing branched code.</p> <p>The <code>map</code> function looks something like this (simplified):</p> <pre><code>var items = this.props.items.map(function (item) { var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // &lt;-- this contains an async call return ( &lt;MenuItem text={item.get('ItemTitle')} imageUrl={imageSrc} /&gt; ); }); </code></pre> <p>and the <code>getImageUrlById</code> method looks like this:</p> <pre><code>getImageUrlById(imageId) { return ImageStore.getImageById(imageId).then(function (imageObject) { //&lt;-- getImageById returns a promise var completeUrl = getLocalImageUrl(imageObject.StandardConImage); return completeUrl; }); } </code></pre> <p>This doesn't work, but I don't know what I need to modify to make this work. I tried adding another promise to the chain, but then I get an error because my render function return a promise instead of legal JSX. I was thinking that maybe I need to leverage one of the <code>React</code> life-cycle methods to fetch the data, but since I need the <code>props</code> to already be there, I can't figure out where I can do this.</p>
33,242,831
2
0
null
2015-10-20 16:51:34.397 UTC
21
2020-01-08 12:54:24.05 UTC
null
null
null
null
625,242
null
1
84
javascript|reactjs|q
106,986
<p><code>render()</code> method should render UI from <code>this.props</code> and <code>this.state</code>, so to asynchronously load data, you can use <code>this.state</code> to store <code>imageId: imageUrl</code> mapping.</p> <p>Then in your <code>componentDidMount()</code> method, you can populate <code>imageUrl</code> from <code>imageId</code>. Then the <code>render()</code> method should be pure and simple by rendering the <code>this.state</code> object </p> <p>Note that the <code>this.state.imageUrls</code> is populated asynchronously, so the rendered image list item will appear one by one after its url is fetched. You can also initialize the <code>this.state.imageUrls</code> with all image id or index (without urls), this way you can show a loader when that image is being loaded.</p> <pre><code>constructor(props) { super(props) this.state = { imageUrls: [] }; } componentDidMount() { this.props.items.map((item) =&gt; { ImageStore.getImageById(item.imageId).then(image =&gt; { const mapping = {id: item.imageId, url: image.url}; const newUrls = this.state.imageUrls.slice(); newUrls.push(mapping); this.setState({ imageUrls: newUrls }); }) }); } render() { return ( &lt;div&gt; {this.state.imageUrls.map(mapping =&gt; ( &lt;div&gt;id: {mapping.id}, url: {mapping.url}&lt;/div&gt; ))} &lt;/div&gt; ); } </code></pre>
23,409,993
Defining sbt task that invokes method from project code?
<p>I'm using SBT to build a scala project. I want to define a very simple task, that when I input <code>generate</code> in sbt:</p> <pre><code>sbt&gt; generate </code></pre> <p>It will invoke my <code>my.App.main(..)</code> method to generate something.</p> <p>There is a <code>App.scala</code> file in <code>myproject/src/main/scala/my</code>, and the simplified code is like this:</p> <pre><code>object App { def main(args: Array[String]) { val source = readContentOfFile("mysource.txt") val result = convert(source) writeToFile(result, "mytarget.txt"); } // ignore some methods here } </code></pre> <p>I tried to add following code into <code>myproject/build.sbt</code>:</p> <pre><code>lazy val generate = taskKey[Unit]("Generate my file") generate := { my.App.main(Array()) } </code></pre> <p>But which doesn't compile since it can't find <code>my.App</code>.</p> <p>Then I tried to add it to <code>myproject/project/build.scala</code>:</p> <pre><code>import sbt._ import my._ object HelloBuild extends Build { lazy val generate = taskKey[Unit]("Generate my file") generate := { App.main(Array()) } } </code></pre> <p>But it still can't be compiled, that it can't find package <code>my</code>.</p> <p>How to define such a task in SBT?</p>
23,411,660
3
0
null
2014-05-01 14:43:06.13 UTC
9
2014-05-02 13:00:01.787 UTC
2014-05-01 20:29:13.87 UTC
null
1,305,344
null
342,235
null
1
21
scala|sbt
6,074
<p>In <code>.sbt</code> format, do:</p> <pre><code>lazy val generate = taskKey[Unit]("Generate my file") fullRunTask(generate, Compile, "my.App") </code></pre> <p>This is documented at <a href="http://www.scala-sbt.org/0.13.2/docs/faq.html">http://www.scala-sbt.org/0.13.2/docs/faq.html</a>, “How can I create a custom run task, in addition to run?”</p> <p>Another approach would be:</p> <pre><code>lazy val generate = taskKey[Unit]("Generate my file") generate := (runMain in Compile).toTask(" my.App").value </code></pre> <p>which works fine in simple cases but isn't as customizable.</p> <p><strong>Update:</strong> Jacek's advice to use <code>resourceGenerators</code> or <code>sourceGenerators</code> instead is good, if it fits your use case — can't tell from your description whether it does.</p>
58,498,651
What is FLOPS in field of deep learning?
<p>What is FLOPS in field of deep learning? Why we don't use the term just FLO?</p> <p>We use the term FLOPS to measure the number of operations of a frozen deep learning network.</p> <p>Following Wikipedia, FLOPS = floating point operations per second. When we test computing units, we should consider of the time. But in case of measuring deep learning network, how can I understand this concept of time? Shouldn't we use the term just FLO(floating point operations)?</p> <p>Why do people use the term FLOPS? If there is anything I don't know, what is it?</p> <p>==== attachment ===</p> <p>Frozen deep learning networks that I mentioned is just a kind of software. It's not about hardware. In the field of deep learning, people use the term FLOPS to measure how many operations are needed to run the network model. In this case, in my opinion, we should use the term FLO. I thought people confused about the term FLOPS and I want to know if others think the same or if I'm wrong.</p> <p>Please look at these cases:</p> <p><a href="https://stackoverflow.com/questions/43490555/how-to-calculate-a-nets-flops-in-cnn">how to calculate a net&#39;s FLOPs in CNN</a></p> <p><a href="https://iq.opengenus.org/floating-point-operations-per-second-flops-of-machine-learning-models/" rel="noreferrer">https://iq.opengenus.org/floating-point-operations-per-second-flops-of-machine-learning-models/</a></p>
60,275,432
3
0
null
2019-10-22 06:57:14.353 UTC
6
2020-05-26 18:29:08.05 UTC
2019-10-24 02:17:35.85 UTC
null
10,258,755
null
10,258,755
null
1
31
performance|deep-learning|flops
28,410
<p>I not sure my answer is 100% correct. but this is what i understand.</p> <ul> <li><p>FLOPS = <strong>Fl</strong>oating point <strong>op</strong>erations per <strong>s</strong>econd</p></li> <li><p>FLOPs = <strong>Fl</strong>oating point <strong>op</strong>eration<strong>s</strong></p></li> </ul> <p>FLOPS is a unit of speed. FLOPs is a unit of amount.</p>
58,675,993
Typescript React <Select> onChange handler type error
<p>I'm trying to add an onChange event handler to the Select component from material-ui:</p> <pre><code>&lt;Select labelId="demo-simple-select-label" id="demo-simple-select" value={values.country} onChange={handleCountryChange} &gt; {countries.map(c =&gt; { return ( &lt;MenuItem value={c}&gt;{c}&lt;/MenuItem&gt; ) })} &lt;/Select&gt; </code></pre> <p>and my event handler:</p> <pre><code>const handleCountryChange = (event: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; { setValues({...values, country: event.target.value}); }; </code></pre> <p>but I get the following error:</p> <blockquote> <p>Type '(event: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent&lt;{ name?: string | undefined; value: unknown; }>, child: ReactNode) => void'. </p> </blockquote> <p>What's wrong?</p>
58,676,067
7
0
null
2019-11-02 22:57:12.6 UTC
7
2022-09-19 17:34:33.5 UTC
null
null
null
null
9,397,534
null
1
29
javascript|reactjs|typescript|material-ui
28,810
<p>Since MUI Select in not a real select element you will need to cast <code>e.target.value</code> using <code>as Type</code> and type the handler as <code>React.ChangeEvent&lt;{ value: unknown }&gt;</code></p> <pre><code>const handleCountryChange = (event: React.ChangeEvent&lt;{ value: unknown }&gt;) =&gt; { setValues({...values, country: event.target.value as string}); }; </code></pre>
41,138,820
lodash orderby with null and real values not ordering correctly
<p>I have an Angular 2 typescript application that is using lodash for various things.</p> <p>I have an array of objects that I am ordering using a property in the object...</p> <pre><code>_.orderBy(this.myArray, ['propertyName'], ['desc']); </code></pre> <p>This works well however my problem is that sometimes 'propertyName' can have a null value. These are ordered as the first item in a descending list, the highest real values then follow.</p> <p>I want to make these null values appear last in the descending ordering.</p> <p>I understand why the nulls come first.</p> <p>Does anyone know how to approach this?</p>
41,139,912
8
0
null
2016-12-14 09:18:28.333 UTC
4
2022-05-12 21:39:54.147 UTC
null
null
null
null
574,130
null
1
33
javascript|typescript|lodash
20,938
<p>The code I needed looks like this...</p> <pre><code>_.orderBy(this.myArray, [( o ) =&gt; { return o.myProperty || ''}], ['desc']); </code></pre>
20,947,806
How can I call from one servlet file to another servlet file?
<p>I am using net beans 7.1 and I create one JSP file with two servlet files. like:</p> <pre><code>index.jsp ---&gt;servlet1.java ---&gt;servlet2.java </code></pre> <p>I give some value from <code>index.jsp</code> file and send to <code>servlet1.java</code>.</p> <p>In this <code>servlet1.java</code> file I call <code>servlet2.java</code> file.</p> <p>Then it throws <code>NullPointerException</code>. How can I solve this?</p> <p>My code like this:</p> <h2>index.jsp</h2> <pre><code>&lt;form action=&quot;servlet1&quot; method=&quot;post&quot;&gt; </code></pre> <h2>servlet1.java</h2> <pre><code>@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { .................. .................. .................. servlet2 ob=new servlet2(); ob.doPost(request, response); .................. .................. .................. } </code></pre> <p>Then it throws <code>NullPointerException</code>.</p>
20,947,869
2
1
null
2014-01-06 10:21:53.633 UTC
3
2021-01-06 23:58:16.713 UTC
2021-01-06 23:58:16.713 UTC
null
1,783,163
null
1,914,757
null
1
8
java|jsp|servlets|nullpointerexception
53,016
<p>Use <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html" rel="noreferrer">RequestDispatcher</a> </p> <pre><code>RequestDispatcher rd = request.getRequestDispatcher("servlet2"); rd.forward(request,response); </code></pre> <h3>RequestDispatcher</h3> <blockquote> <p>Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. </p> </blockquote> <hr> <h1>Update</h1> <p>No need to create an object of servlet manually, just simply use <code>RequestDispatcher</code> to call servlet because web container controls the <em>lifecycle</em> of servlet.</p> <p>From Oracle JavaEE docs <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnafi.html" rel="noreferrer">Servlet Lifecycle</a> </p> <p>The lifecycle of a servlet is controlled by the container in which the servlet has been deployed.<br> When a request is mapped to a servlet, the container performs the following steps.</p> <ol> <li><p>If an instance of the servlet does not exist, the web container</p> <ul> <li><p>Loads the servlet class.</p></li> <li><p>Creates an instance of the servlet class.</p></li> <li><p>Initializes the servlet instance by calling the init method. Initialization is covered in <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnafu.html" rel="noreferrer">Creating and Initializing a Servlet</a>.</p></li> </ul></li> <li><p>Invokes the service method, passing request and response objects. Service methods are discussed in <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnafv.html" rel="noreferrer">Writing Service Methods</a>.</p></li> </ol>
21,294,889
how to get access to error message from abort command when using custom error handler
<p>Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the body</p> <pre><code>@app.errorhandler(400) def custom400(error): response = jsonify({'message': error.message}) response.status_code = 404 response.status = 'error.Bad Request' return response abort(400,'{"message":"custom error message to appear in body"}') </code></pre> <p>But the error.message variable comes up as an empty string. I can't seem to find documentation on how to get access to the second variable of the abort function with a custom error handler</p>
21,301,229
4
1
null
2014-01-22 21:59:36.013 UTC
8
2019-09-09 19:45:55.613 UTC
null
null
null
null
741,808
null
1
61
python|http|flask|http-error
45,498
<p>If you look at <a href="https://github.com/mitsuhiko/flask/blob/d517f35d60a14fcea2e503f578e65b68eafa6577/flask/__init__.py#L17"><code>flask/__init__.py</code></a> you will see that <code>abort</code> is actually imported from <a href="https://github.com/mitsuhiko/werkzeug/blob/5eed9385b861a1ae53c03eaae5a8dea4480113d6/werkzeug/exceptions.py#L602"><code>werkzeug.exceptions</code></a>. Looking at the <a href="https://github.com/mitsuhiko/werkzeug/blob/5eed9385b861a1ae53c03eaae5a8dea4480113d6/werkzeug/exceptions.py#L578-600"><code>Aborter</code> class</a>, we can see that when called with a numeric code, the particular <code>HTTPException</code> subclass is looked up and called with all of the arguments provided to the <code>Aborter</code> instance. Looking at <a href="https://github.com/mitsuhiko/werkzeug/blob/5eed9385b861a1ae53c03eaae5a8dea4480113d6/werkzeug/exceptions.py#L74-160"><code>HTTPException</code></a>, paying particular attention to <a href="https://github.com/mitsuhiko/werkzeug/blob/5eed9385b861a1ae53c03eaae5a8dea4480113d6/werkzeug/exceptions.py#L85-89">lines 85-89</a> we can see that the second argument passed to <code>HTTPException.__init__</code> is stored in the <code>description</code> property, as @dirn pointed out.</p> <p>You can either access the message from the <code>description</code> property:</p> <pre><code>@app.errorhandler(400) def custom400(error): response = jsonify({'message': error.description['message']}) # etc. abort(400, {'message': 'custom error message to appear in body'}) </code></pre> <p>or just pass the description in by itself:</p> <pre><code>@app.errorhandler(400) def custom400(error): response = jsonify({'message': error.description}) # etc. abort(400, 'custom error message to appear in body') </code></pre>
21,871,090
Difference between DesignWidth and Width in UserControl in WPF
<p>When I create a new <code>UserControl</code> in WPF, studio creates some XAML:</p> <pre><code>&lt;UserControl x:Class="MOG.Objects.Date.Calender" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;Grid&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>In <code>UserContol</code> I can also add Width property. What is difference between <code>DesignWidth</code> and <code>Width</code>?</p>
21,871,117
2
0
null
2014-02-19 04:32:13.343 UTC
4
2015-11-17 20:02:21.04 UTC
2014-02-19 04:59:56.227 UTC
null
2,176,945
null
2,524,701
null
1
35
c#|wpf|xaml|user-controls
38,017
<p><code>d:DesignHeight</code> and <code>d.DesignWidth</code> are for the Designer (the WYSIWYG), in Visual Studio or in Expression Blend. <em><code>Height</code></em> and <em><code>Width</code></em> are actually for runtime.</p>
35,370,810
How do I use Jenkins Pipeline properties step?
<p>I am studying capabilities of Jenkins Pipeline:Multibranch. It is said that a recently introduced <code>properties</code> step might be useful there, but I can't catch how it works and what is its purpose.</p> <p>Its hint message doesn't seem to be very clear:</p> <blockquote> <p>Updates the properties of the job which runs this step. Mainly useful from multibranch workflows, so that Jenkinsfile itself can encode what would otherwise be static job configuration.</p> </blockquote> <p>So I created a new Pipeline with this as a script (pasted directly into Jenkins not in SCM):</p> <pre><code>properties [[$class: 'ParametersDefinitionProperty', parameterDefinitions: [[$class: 'StringParameterDefinition', defaultValue: '', description: '', name: 'PARAM1']] ]] </code></pre> <p>I ran it and nothing happened, job didn't received a new parameter and even if it did I don't get why I might need this. Could anyone please explain?</p> <p><strong>UPDATE1</strong>: I tried putting a dummy Pipeline with properties step into my git repo, then configured a multibranch job.</p> <pre class="lang-groovy prettyprint-override"><code>println 1 properties [[$class: 'ParametersDefinitionProperty', parameterDefinitions: [[$class: 'StringParameterDefinition', defaultValue: 'str1', description: '', name: 'PARAM1']]], [$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false]] println 2 </code></pre> <p>It found my branch, created a job but the build failed with:</p> <pre><code>groovy.lang.MissingPropertyException: No such property: properties for class: groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:62) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:185) at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238) at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:23) at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:17) at WorkflowScript.run(WorkflowScript:2) at ___cps.transform___(Native Method) at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:62) at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30) at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72) at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21) at com.cloudbees.groovy.cps.Next.step(Next.java:58) at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:19) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:106) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30) at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:277) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:77) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:186) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:184) at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112) at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) </code></pre> <p><strong>UPDATE2</strong>: when I put the same script (as in UPD1) back into Jenkins and runs it, it asked for new permission <code>method groovy.lang.GroovyObject getProperty java.lang.String</code>. I approved it, the build went green, however, still no changes to the job configuration appeared.</p> <p>My env is: Jenkins 1.625.3, Pipeline+Multibranch 1.13</p>
35,471,196
3
0
null
2016-02-12 19:33:39.917 UTC
8
2022-06-10 12:07:01.13 UTC
2016-11-09 21:40:22.813 UTC
null
234,938
null
1,579,623
null
1
54
jenkins|jenkins-pipeline|jenkins-workflow
91,803
<p>Using <code>properties</code> with explicit method syntax will work, i.e.:<br> <code>properties( [ ... ] )</code> rather than <code>properties [ ... ]</code></p> <p>Alternatively, it will work without if you specify the parameter name, e.g.: </p> <pre><code>properties properties: [ ... ] </code></pre> <p>For example defining three properties is as easy as : </p> <pre><code>properties([ parameters([ string(name: 'submodule', defaultValue: ''), string(name: 'submodule_branch', defaultValue: ''), string(name: 'commit_sha', defaultValue: ''), ]) ]) /* Accessible then with : params.submodule, params.submodule_branch... */ </code></pre>
30,058,927
Format a phone number as a user types using pure JavaScript
<p>I've got an input field in the body of my document, and I need to format it as the user types. It should have parenthesis around the area code and a dash between the three and four digits after that.</p> <p>Ex: <code>(123) 456 - 7890</code></p> <p>As the user types it should look something like:</p> <p><code>(12</code><br> <code>(123)</code><br> <code>(123) 456</code><br> <code>(123) 456 - 78</code><br> <code>(123) 456 - 7890</code></p>
30,058,928
13
2
null
2015-05-05 16:55:23.233 UTC
16
2022-01-14 16:13:59.293 UTC
null
null
null
null
2,544,376
null
1
32
javascript|formatting
64,256
<h1>New ES6 Answer</h1> You can still do this using some simple JavaScript. <h3>HTML</h3> <pre><code>&lt;input id=&quot;phoneNumber&quot; maxlength=&quot;16&quot; /&gt; </code></pre> <h3>JavaScript (ES6)</h3> <pre><code>const isNumericInput = (event) =&gt; { const key = event.keyCode; return ((key &gt;= 48 &amp;&amp; key &lt;= 57) || // Allow number line (key &gt;= 96 &amp;&amp; key &lt;= 105) // Allow number pad ); }; const isModifierKey = (event) =&gt; { const key = event.keyCode; return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End (key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete (key &gt; 36 &amp;&amp; key &lt; 41) || // Allow left, up, right, down ( // Allow Ctrl/Command + A,C,V,X,Z (event.ctrlKey === true || event.metaKey === true) &amp;&amp; (key === 65 || key === 67 || key === 86 || key === 88 || key === 90) ) }; const enforceFormat = (event) =&gt; { // Input must be of a valid number format or a modifier key, and not longer than ten digits if(!isNumericInput(event) &amp;&amp; !isModifierKey(event)){ event.preventDefault(); } }; const formatToPhone = (event) =&gt; { if(isModifierKey(event)) {return;} const input = event.target.value.replace(/\D/g,'').substring(0,10); // First ten digits of input only const areaCode = input.substring(0,3); const middle = input.substring(3,6); const last = input.substring(6,10); if(input.length &gt; 6){event.target.value = `(${areaCode}) ${middle} - ${last}`;} else if(input.length &gt; 3){event.target.value = `(${areaCode}) ${middle}`;} else if(input.length &gt; 0){event.target.value = `(${areaCode}`;} }; const inputElement = document.getElementById('phoneNumber'); inputElement.addEventListener('keydown',enforceFormat); inputElement.addEventListener('keyup',formatToPhone); </code></pre> <p>And if you'd like to fiddle with it:<br /> <a href="https://jsfiddle.net/rafj3md0/" rel="noreferrer">https://jsfiddle.net/rafj3md0/</a></p> <p><em>Disclaimer:</em><br /> It's worth noting this gets a little weird if you attempt to modify the middle of the number because of the way browsers handle caret placement after you set an element's value. Solving that problem is doable, but would require more time than I have right now, and there are libraries out there that handle things like that.</p> <hr /><h1>Old ES5 Answer</h1> You can do this using a quick javascript function. <p>If your HTML looks like:<br /> <code>&lt;input type=&quot;text&quot; id=&quot;phoneNumber&quot;/&gt;</code></p> <p>Your JavaScript function can simply be:</p> <pre><code>// A function to format text to look like a phone number function phoneFormat(input){ // Strip all characters from the input except digits input = input.replace(/\D/g,''); // Trim the remaining input to ten characters, to preserve phone number format input = input.substring(0,10); // Based upon the length of the string, we add formatting as necessary var size = input.length; if(size == 0){ input = input; }else if(size &lt; 4){ input = '('+input; }else if(size &lt; 7){ input = '('+input.substring(0,3)+') '+input.substring(3,6); }else{ input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10); } return input; } </code></pre> <p>Of course, you'll need an event listener:</p> <pre><code>document.getElementById('phoneNumber').addEventListener('keyup',function(evt){ var phoneNumber = document.getElementById('phoneNumber'); var charCode = (evt.which) ? evt.which : evt.keyCode; phoneNumber.value = phoneFormat(phoneNumber.value); }); </code></pre> <p>And unless you're okay storing phone numbers as formatted strings (I don't recommend this), you'll want to purge the non-numeric characters before submitting the value with something like:<br /> <code>document.getElementById('phoneNumber').value.replace(/\D/g,'');</code></p> <p>If you'd like to see this in action with bonus input filtering, check out this fiddle:<br /> <a href="http://jsfiddle.net/rm9vg16m/" rel="noreferrer">http://jsfiddle.net/rm9vg16m/</a></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Format the phone number as the user types it document.getElementById('phoneNumber').addEventListener('keyup', function(evt) { var phoneNumber = document.getElementById('phoneNumber'); var charCode = (evt.which) ? evt.which : evt.keyCode; phoneNumber.value = phoneFormat(phoneNumber.value); }); // We need to manually format the phone number on page load document.getElementById('phoneNumber').value = phoneFormat(document.getElementById('phoneNumber').value); // A function to determine if the pressed key is an integer function numberPressed(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode &gt; 31 &amp;&amp; (charCode &lt; 48 || charCode &gt; 57) &amp;&amp; (charCode &lt; 36 || charCode &gt; 40)) { return false; } return true; } // A function to format text to look like a phone number function phoneFormat(input) { // Strip all characters from the input except digits input = input.replace(/\D/g, ''); // Trim the remaining input to ten characters, to preserve phone number format input = input.substring(0, 10); // Based upon the length of the string, we add formatting as necessary var size = input.length; if (size == 0) { input = input; } else if (size &lt; 4) { input = '(' + input; } else if (size &lt; 7) { input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6); } else { input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + ' - ' + input.substring(6, 10); } return input; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>Enter a phone number here: &lt;input type="text" id="phoneNumber" onkeypress="return numberPressed(event);" /&gt;</code></pre> </div> </div> </p>
25,869,428
Classpath resource not found when running as jar
<p>Having this problem both in Spring Boot 1.1.5 and 1.1.6 - I'm loading a classpath resource using an @Value annotation, which works just fine when I run the application from within STS (3.6.0, Windows). However, when I run a mvn package and then try to run the jar, I get FileNotFound exceptions.</p> <p>The resource, message.txt, is in src/main/resources. I've inspected the jar and verified that it contains the file "message.txt" at the top level (same level as application.properties).</p> <p>Here's the application:</p> <pre class="lang-java prettyprint-override"><code>@Configuration @ComponentScan @EnableAutoConfiguration public class Application implements CommandLineRunner { private static final Logger logger = Logger.getLogger(Application.class); @Value("${message.file}") private Resource messageResource; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... arg0) throws Exception { // both of these work when running as Spring boot app from STS, but // fail after mvn package, and then running as java -jar testResource(new ClassPathResource("message.txt")); testResource(this.messageResource); } private void testResource(Resource resource) { try { resource.getFile(); logger.debug("Found the resource " + resource.getFilename()); } catch (IOException ex) { logger.error(ex.toString()); } } } </code></pre> <p>The exception:</p> <pre><code>c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble m\target&gt;java -jar demo-0.0.1-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.1.5.RELEASE) 2014-09-16 08:46:34.635 INFO 5976 --- [ main] demo.Application : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo -0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s ts-3.5.1.RELEASE\classpath-resource-problem\target) 2014-09-16 08:46:34.640 DEBUG 5976 --- [ main] demo.Application : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA SE 2014-09-16 08:46:34.681 INFO 5976 --- [ main] s.c.a.AnnotationConfigA pplicationContext : Refreshing org.springframework.context.annotation.Annotation ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; root of context hierarchy 2014-09-16 08:46:35.196 INFO 5976 --- [ main] o.s.j.e.a.AnnotationMBe anExporter : Registering beans for JMX exposure on startup 2014-09-16 08:46:35.210 ERROR 5976 --- [ main] demo.Application : java.io.FileNotFoundException: class path resource [message. txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt 2014-09-16 08:46:35.211 ERROR 5976 --- [ main] demo.Application : java.io.FileNotFoundException: class path resource [message. txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt 2014-09-16 08:46:35.215 INFO 5976 --- [ main] demo.Application : Started Application in 0.965 seconds (JVM running for 1.435) 2014-09-16 08:46:35.217 INFO 5976 --- [ Thread-2] s.c.a.AnnotationConfigA pplicationContext : Closing org.springframework.context.annotation.AnnotationCon figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo t of context hierarchy 2014-09-16 08:46:35.218 INFO 5976 --- [ Thread-2] o.s.j.e.a.AnnotationMBe anExporter : Unregistering JMX-exposed beans on shutdown </code></pre>
25,873,705
16
0
null
2014-09-16 12:57:51.043 UTC
64
2022-07-11 18:10:34.31 UTC
2018-10-02 14:36:35.133 UTC
null
1,515,052
null
843,273
null
1
181
java|spring-boot
220,069
<p><a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html#getFile--" rel="noreferrer"><code>resource.getFile()</code></a> expects the resource itself to be available on the file system, i.e. it can't be nested inside a jar file. This is why it works when you run your application in STS (Spring Tool Suite) but doesn't work once you've built your application and run it from the executable jar. Rather than using <code>getFile()</code> to access the resource's contents, I'd recommend using <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/InputStreamSource.html#getInputStream--" rel="noreferrer"><code>getInputStream()</code></a> instead. That'll allow you to read the resource's content regardless of where it's located.</p>
8,900,005
How do I get msdeploy to create App_Data if it doesn't exist, but not delete any contents of the remote directory?
<p>I have an application setup with the following Package/Publish Web settings:</p> <ul> <li>Only files needed to run this application</li> <li>(unchecked) Exclude generated debug symbols</li> <li>(checked) Exclude files from the App_Data folder</li> <li>(checked) Include all databases configured in Package/Publish SQL tab - note I do <em>not</em> have any databases configured</li> <li>(unchecked) include IIS settings as configured in IIS Express</li> </ul> <p>In the project, I have an App_Data folder setup, primarily to handle application logs.</p> <p>The behavior I'd like to see (and expect) is the following:</p> <ol> <li>On initial deploy to a brand new server, the application is copied and an App_Data folder is created with write permissions assigned for the application.</li> <li>On subsequent deployments, the App_Data folder is ignored because it already exists and the "Exclude files from the App_Data folder" is checked.</li> </ol> <p>However, msdeploy does not appear to do step #1 (step 2 is fine if I create the folder manually). I've been unable to find any documentation on the web besides this <a href="https://stackoverflow.com/questions/7059880/mvc-code-first-app-data-folder-not-being-created">unanswered so question</a> that seems to confirm the behavior I see.</p> <p>How do I get msdeploy to create App_Data and assign permissions on initial deployment in this scenario?</p>
8,931,695
4
0
null
2012-01-17 18:50:26.663 UTC
10
2018-09-05 22:11:24.593 UTC
2017-05-23 12:00:29.203 UTC
null
-1
null
113,225
null
1
28
asp.net|.net|msdeploy
14,603
<h3>Getting App_Data deployed when starting from scratch</h3> <p>@tdykstra got <a href="https://stackoverflow.com/a/8901845/113225">this part right</a>. To get App_Data out there (and ACLs set automatically), I did the following:</p> <ol> <li>Adding a placeholder file in App_Data </li> <li>Set the build action to content on the placeholder (my placeholder file has text in it to let people stumbling across it know why it's there). </li> <li><strong>Unchecked</strong> "Exclude files from the App_Data folder" on the Package/Publish Web tab of the project properties in VS 2010</li> </ol> <p>This gets my App_Data folder created and ready for use on the server. However, it will result in all my files getting deleted whenever I republish. This is problem #2 in my question above, and pretty closely resembles this other SO <a href="https://stackoverflow.com/questions/4289440/make-msdeploy-visual-studio-not-delete-app-data-folder-but-delete-everything-e">question</a>/<a href="https://stackoverflow.com/a/5659390/113225">answer</a>.</p> <h3>Preventing data on the server from being deleted on subsequent publish events</h3> <p>There are two mechanisms in MsDeploy that can get confused (at least I confused them):</p> <ol> <li>Excluding files</li> <li>MsDeploy skip rules</li> </ol> <p>These can both be used to solve the problem, depending on the scenario:</p> <ol> <li><a href="https://stackoverflow.com/a/8901845/113225">@tdykstra's solution</a> will likely work if you: <ol> <li>Know the names of the files in App_Data in advance (e.g. a sqllite database)</li> <li>Have the files included in the App_Data folder in your project</li> </ol></li> <li>The use MsDeploy skip rules to tell MsDeploy to completely skip all deletes on the server for that directory and files in that directory. This solves the problem in all cases, but is much more involved. </li> </ol> <h3>Implementing MsDeploy skip rules</h3> <p>To implement skip rules you'll have to abandon the right-click, Deploy option in VS 2010 in favor of right-click, Package, go into a command line, re-jigger a batch file and run a command line). If you're willing to put up with this experience (I am, because I'm automating it all through a CI process), here are the details:</p> <ol> <li><p><a href="https://stackoverflow.com/questions/7100751/how-to-set-msdeploy-settings-in-csproj-file">Edit the project file and add the following</a>. Note that the AbsolutePath argument is a regular expression, so you can get way fancy:</p> <pre><code>&lt;Target Name="AddCustomSkipRules"&gt; &lt;ItemGroup&gt; &lt;MsDeploySkipRules Include="SkipDeleteAppData"&gt; &lt;SkipAction&gt;Delete&lt;/SkipAction&gt; &lt;ObjectName&gt;filePath&lt;/ObjectName&gt; &lt;AbsolutePath&gt;$(_Escaped_PackageTempDir)\\App_Data\\.*&lt;/AbsolutePath&gt; &lt;XPath&gt; &lt;/XPath&gt; &lt;/MsDeploySkipRules&gt; &lt;MsDeploySkipRules Include="SkipDeleteAppData"&gt; &lt;SkipAction&gt;Delete&lt;/SkipAction&gt; &lt;ObjectName&gt;dirPath&lt;/ObjectName&gt; &lt;AbsolutePath&gt;$(_Escaped_PackageTempDir)\\App_Data\\.*&lt;/AbsolutePath&gt; &lt;XPath&gt; &lt;/XPath&gt; &lt;/MsDeploySkipRules&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; </code></pre></li> <li>Package, <strong>do not deploy</strong> the project. This will create a zip file and .cmd file in the target directory (defined by "Location where package will be created" on the Package/Publish Web Tab). By default, this is obj\Debug\Package (or obj\Release\Package)</li> <li>Deploy the site using the the resulting command file</li> </ol> <p>In my testing, you must package and run the command file. The project file tweaks will tell msbuild to put the necessary -skip rule into the command file. However, using the "publish" feature straight from VS 2010 <a href="https://stackoverflow.com/a/5659390/113225">doesn't seem to run the command file</a> (see the warning on <a href="http://blog.alanta.nl/2011/02/web-deploy-customizing-deployment.html" rel="nofollow noreferrer">this walkthrough</a>)...it calls msdeploy directly and doesn't seem to honor the project file skip rules. I believe this is the difference between VS using msbuild -T:Package and msbuild -T:MsDeployPublish to build the project, but I have not tested this.</p> <p>Finally, the command file isn't quite correct, at least in VS 2010 SP1. There's a great description of what goes wrong in <a href="https://stackoverflow.com/a/4898553/113225">this SO answer</a>, but basically, VS (or maybe the /t:Package target is a better culprit) sets up the command file to publish to the machine without specifying a site. To fix that, you'll need to somehow get "?site=<em>sitename</em>" (probably this is ?site=Default+Web+Site, for a full URL of https://<em>machine</em>:8172/MsDeploy.axd?site=Default+Web+Site) onto the end of the computerName argument. </p> <p>The problem I had was that the command file (batch file) has a hard time with using site= anything on the command line since it mis-parses the command line argument (even if escaped). I don't see a way around this problem other than modifying the cmd file directly, but for testing I copied the msdeploy.exe output I saw from my failed test run and modified that to call msdeploy.exe directly without the script.</p> <p>Now that it's working, my intention is to work this into my CI build processes. What I'll be doing for the final solution is:</p> <ol> <li>Change my build script to use /T:Package (right now it's /T:MsDeploy)</li> <li>Have a scripted search/replace routine alter the generated cmd deployment script</li> <li>Run the altered deployment script</li> </ol> <p>This really should be easier.</p> <p><strong>Update</strong></p> <p>Here's the scripted search/replace routine I've come up with in PowerShell:</p> <pre><code>(Get-Content "project.deploy.cmd") -replace('^set _ArgComputerName=$' ,"set ArgComputerName=https://server:8172/MsDeploy.axd?Site=Default+Web+Site") | Out-File -Encoding ascii deploy.cmd </code></pre> <p>Once that is run, deploy.cmd can be called (without the /M option) and it will work as expected.</p>
8,724,816
Is it possible to define {$IFDEF} for more than one directive at once?
<p>Is it possible to define more than one conditional in one {$IFDEF} directive ?<br> I would like to have syntax like this:</p> <pre><code>{$IFDEF Condition1 OR Condition2} DoSomething; {$ENDIF} {$IFDEF Condition1 AND Condition2} DoSomethingElse; {$ENDIF} </code></pre> <p>Thanks</p>
8,724,987
3
0
null
2012-01-04 09:47:58.717 UTC
10
2012-01-04 11:19:38.193 UTC
null
null
null
null
1,096,812
null
1
46
delphi|logical-operators|conditional-compilation
18,780
<p>You would need to use <a href="http://docwiki.embarcadero.com/RADStudio/en/IF_directive_%28Delphi%29"><code>$IF</code></a> instead:</p> <pre><code>{$IF Defined(Condition1) or Defined(Condition2)} DoSomething; {$IFEND} </code></pre>
48,362,864
How to insert QChartView in form with Qt Designer?
<p>I want to add <code>QChart</code> to the form. But I can't find it in the Widget Box. So I created it in the code. How can I insert it in <code>QWidget</code> or <code>QFrame</code> or something else? </p> <p>I want to set area of that widget in QtDesigner.</p>
48,363,007
2
0
null
2018-01-21 01:35:53.307 UTC
6
2022-02-12 14:57:45.003 UTC
2018-01-21 02:32:59.74 UTC
null
6,622,587
null
1,034,253
null
1
28
qt|qt5|qt-designer|qchart|qchartview
22,245
<h1>Option 1: Promoted</h1> <p>I suppose you mean inserting a QChartView, because QChartView inherits from QGraphicsView, this would be a good option, for this we do the following:</p> <ol> <li>first add <code>QT += charts</code> in the .pro</li> <li>place the QGraphicsView to the design.</li> <li>Right click on the QGraphicsView and select <code>Promote to...</code></li> <li>When doing the above, a menu appears, in the menu it should be set in <code>QChartView</code> in <code>Promoted Class Name</code>, and <code>QtCharts</code> in <code>Header file</code>, then press the <code>add</code> button and finally press <code>promote</code>.</li> </ol> <p>Screenshots of some steps:</p> <p>[3.]</p> <p><a href="https://i.stack.imgur.com/aPot0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aPot0.png" alt="enter image description here"></a></p> <p>[4.1]</p> <p><a href="https://i.stack.imgur.com/DDrUj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DDrUj.png" alt="enter image description here"></a></p> <p>[4.2]</p> <p><a href="https://i.stack.imgur.com/Z3eim.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z3eim.png" alt="enter image description here"></a></p> <p>The same could be done using <code>QWidget</code> as a base instead of <code>QGraphicsView</code>.</p> <p><strong>Why is one or another widget chosen as a base?</strong></p> <p>It is chosen because Qt Designer through moc establishes certain properties by default, and if the widget does not have that method then it will not compile. as all widgets inherit from QWidget this would be the basis for any new widget to promote it in Qt Designer.</p> <p><sub>In the following <a href="https://github.com/eyllanesc/stackoverflow/tree/master/questions/48362864" rel="noreferrer">link</a> you will find an example.</sub></p> <hr> <h1>Option 2: QtChart plugin</h1> <p>Another option would be to compile the <code>QtChart</code> plugin for <code>QtDesigner</code>, for it you must download the 5 files from the following <a href="https://github.com/qt/qtcharts/tree/5.10/plugins/designer" rel="noreferrer">link</a>:</p> <p><a href="https://i.stack.imgur.com/Iivsx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Iivsx.png" alt="enter image description here"></a></p> <p>Then you execute the following:</p> <pre><code>qmake make sudo make install </code></pre> <p>At the end you can access <code>QtCharts::QChartView</code> in Qt Designer</p> <p><a href="https://i.stack.imgur.com/pCs1I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pCs1I.png" alt="enter image description here"></a></p>
27,131,984
How can I only keep items of an array that match a certain condition?
<p>I have an array, and I want to filter it to only include items which match a certain condition. Can this be done in JavaScript?</p> <p>Some examples:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8] // I only want [2, 4, 6, 8], i.e. the even numbers ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."] // I only want words with 2 or fewer letters: ["is", "an", "up", "a"] [true, false, 4, 0, "abc", "", "0"] // Only keep truthy values: [true, 4, "abc", "0"] </code></pre>
27,131,985
3
1
null
2014-11-25 16:34:00.933 UTC
5
2017-10-06 08:00:09.87 UTC
null
null
null
null
3,187,556
null
1
11
javascript|arrays|filter
40,686
<p>For this, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer"><code>Array#filter()</code></a> method, introduced in ECMAScript5. It is supported in all browsers, except for IE8 and lower, and ancient versions of Firefox. If, for whatever reason, you need to support those browsers, you can use a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill" rel="noreferrer">polyfill</a> for the method.</p> <p><code>filter()</code> takes a function as its first argument. For every item of the array, your function is passed three arguments - the value of the current item, its index in the array, and the array itself. If your function returns <code>true</code> (or a truthy value, e.g. <code>1</code>, <code>"pizza"</code>, or <code>42</code>), that item will be included in the result. Otherwise, it won't. <code>filter()</code> returns a <em>new</em> array - your original array will be left unmodified. That means that you'll need to save the value somewhere, or it'll be lost.</p> <p>Now, in the examples from the question:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var myNumbersArray = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(myNumbersArray.filter(function(num){ return !(num % 2); // keep numbers divisible by 2 })); console.log(myNumbersArray); // see - it hasn't changed! var myStringArray = ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."]; console.log(myStringArray.filter(function(str){ return str.length &lt; 3; // keep strings with length &lt; 3 })); console.log(myStringArray); var myBoolArray = [true, false, 4, 0, "abc", "", "0"]; console.log(myBoolArray.filter(Boolean)); // wow, look at that trick! console.log(myBoolArray);</code></pre> </div> </div> </p> <p>And for completeness, an example that also uses the index and array parameters: Removing duplicates from the array:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray = [1,1,2,3,4,5,6,1,2,8,2,5,2,52,48,123,43,52]; console.log(myArray.filter(function(value, index, array) { return array.indexOf(value) === index; }));</code></pre> </div> </div> </p>
26,532,137
jsonschema multiple values for string property
<p>I have a json schema which describes a fairly complex API querying syntax. A few of the properties are pattern matched but also need to accept other values (i.e. other explicit strings) other than just the pattern. I can't seem to find anywhere in the multitude of json schema sites any examples of this.</p> <p>An example:</p> <pre><code>{ "type": "object", "properties": { "$gte": { "type": "string", "pattern": "&lt;some-pattern&gt;" } } } </code></pre> <p>What i'd like to be able to do in the example above is specify that <code>$gte</code> can be any of a certain set of constrained values. For example, this specific implementation requires that "$gte"'s values be constrained to one of the following:</p> <ol> <li>A specific date format</li> <li>A token <code>{token}</code> which gets replaced with a special value on the server-side</li> </ol> <p>I've seen the <code>oneOf</code> property used in this situation but only with the <code>format</code> property so I'm assuming that this is possible, just not sure of the syntax of how to implement it, for instance it could be something like this:</p> <pre><code>{ "type": "object", "properties": { "$gte": { "type": "string", "oneOf": [ {"pattern": "&lt;some-pattern&gt;"}, "{token}", "{another_token}" ] } } } </code></pre> <p>Any clarity on how to accomplish this would be greatly appreciated as I'm not having much luck with the specification Draft 4 for json schema or in finding any examples.</p>
26,532,777
2
0
null
2014-10-23 15:51:16.203 UTC
3
2021-06-15 12:59:24.74 UTC
null
null
null
null
4,174,525
null
1
30
json|validation|jsonschema
31,115
<p>If you want data to be one of a fixed set of exact values, you can use <code>enum</code>:</p> <pre><code>{ "type": "string", "enum": ["stop", "go"] } </code></pre> <p>So, to fit this in your example, try:</p> <pre><code>{ "type": "object", "properties": { "$gte": { "type": "string", "oneOf": [ {"pattern": "&lt;some-pattern&gt;"}, {"enum": ["TOKEN", "ANOTHER_TOKEN"]} ] } } } </code></pre>
1,151,903
Invalid Operation Exception from C# Process Class
<p>When I use VSTS debugger to see the properties of instance of class <code>Process</code>, many of the properties are marked with <code>InvalidOperationException</code>. Why? Am I doing anything wrong?</p> <p>I am using VSTS 2008 + C# + .Net 2.0 to develop a console application.</p> <p>Here is my code:</p> <pre><code>System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); myProcess.StartInfo.FileName = "IExplore.exe"; myProcess.StartInfo.Arguments = @"www.google.com"; myProcess.StartInfo.Verb = "runas"; myProcess.Start(); </code></pre> <p>And a screenshot of the debugger:</p> <p><a href="https://i.stack.imgur.com/SrHEj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SrHEj.png" alt="enter image description here"></a></p>
1,151,926
3
5
null
2009-07-20 05:57:49.37 UTC
1
2018-06-03 20:04:20.23 UTC
2018-06-03 20:04:20.23 UTC
null
24,874
null
63,235
null
1
22
c#|.net|visual-studio-2008|process|invalidoperationexception
50,033
<p>Had you actually started the process when the debugger picture was taken? That's the screenshot I'd expect to see before the <code>Start()</code> method is called.</p> <p>Note that the common pattern is to create a <code>ProcessStartInfo</code>, populate it, and then call the static <code>Process.Start(startInfo)</code> method. That makes it conceptually simpler: you don't see the <code>Process</code> object until it's been started.</p>
1,002,934
jQuery x y document coordinates of DOM object
<p>I need to get the X,Y coordinates (relative to the document's top/left) for a DOM element. I can't locate any plugins or jQuery property or method that can give these to me. I can get the top and left of the DOM element, but that can be either relative to its current container/parent or to document. </p>
1,002,941
3
0
null
2009-06-16 17:41:06.777 UTC
20
2015-10-07 16:15:12.383 UTC
null
null
null
null
52,087
null
1
52
javascript|jquery|user-interface|location
94,098
<p><strike>you can use <a href="http://plugins.jquery.com/project/dimensions" rel="noreferrer">Dimensions</a> plugin</strike> [Deprecated... included in jQuery 1.3.2+]</p> <blockquote> <p><strong>offset()</strong><br> Get the current offset of the first matched element, in pixels, relative to the <strong>document</strong>.</p> <p><strong>position()</strong><br>Gets the top and left position of an element relative to its <strong>offset parent</strong>.</p> </blockquote> <p>knowing this, then it's easy... (using my little <a href="https://stackoverflow.com/questions/536676">svg project</a> as an <a href="https://github.com/balexandre/Draggable-Line-to-Droppable/blob/master/index.htm" rel="noreferrer">example page</a>)</p> <pre><code>var x = $("#wrapper2").offset().left; var y = $("#wrapper2").offset().top; console.log('x: ' + x + ' y: ' + y); </code></pre> <p>output:</p> <pre><code>x: 53 y: 177 </code></pre> <p>hope it helps what you're looking for.</p> <p><strong>here's an image of offset() and position()</strong></p> <p>using <a href="https://addons.mozilla.org/en-US/firefox/addon/1802" rel="noreferrer">XRay</a></p> <p><img src="https://i.stack.imgur.com/buCcL.png" alt="alt text"></p> <p>using <a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="noreferrer">Web Developer</a> toolbar</p> <p><img src="https://i.stack.imgur.com/fFTEm.png" alt="alt text"></p>
1,024,748
How do I fix NSURLErrorDomain error -999 in iPhone 3.0 OS
<p>I am trying to update my iPhone app to work with OS 3.0. I have a UIWebView that shows a page fine. But when I click a link it calls my delegate for didFailLoadWithError and the error is Operation could not be completed. (NSURLErrorDomain error -999.) I verified this is still working with OS 2.2.1, so it is something changed in 3.0.</p> <p>Any ideas?</p>
1,053,411
3
3
null
2009-06-21 21:05:18.073 UTC
22
2018-09-24 06:56:57.457 UTC
2009-06-22 18:25:42.45 UTC
null
459
null
126,566
null
1
52
iphone|iphone-sdk-3.0
54,433
<p>I was able to find the answer <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/6280-uiwebview-didfailloadwitherror-how-get-errors-code-list.html" rel="noreferrer">here</a>.</p> <p>This thread contained this description for this error: <code>This error may occur if an another request is made before the previous request of WebView is completed...</code></p> <p>I worked around this by ignoring this error and letting the webview continue to load.</p> <pre><code>if ([error code] != NSURLErrorCancelled) { //show error alert, etc. } </code></pre>
286,297
Javascript error handling with try .. catch .. finally
<p>I have a suspicion that I'm using the <code>finally</code> block incorrectly, and that I don't understand the fundamentals of its purpose...</p> <pre><code> function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally { return true; } } </code></pre> <p>This function will run the <code>catch</code> block, alert "An error", but then return true. Why doesn't it return false?</p>
286,306
3
0
null
2008-11-13 05:01:39.923 UTC
18
2018-06-22 05:18:05.633 UTC
null
null
null
nickf
9,021
null
1
56
javascript|error-handling|finally
42,638
<blockquote> <p>The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#The_finally_Block" rel="noreferrer">more</a></p> </blockquote> <p>The <code>finally</code> block will always run, try returning <code>true</code> after your <code>try</code> block</p> <pre><code>function myFunc() { try { if (true) { throw "An error"; } return true; } catch (e) { alert (e); return false; } finally { //do cleanup, etc here } } </code></pre>
683,620
What is the best resource for learning C# expression trees in depth?
<p>When I first typed this question, I did so in order to find the duplicate questions, feeling sure that someone must have already asked this question. My plan was to follow those dupe links instead of posting this question. But this question has not been asked before as far as I can see ... it did not turn up in the "Related Questions" list.</p> <p><strong>What are some of the best resources you've found (articles, books, blog posts, etc.) for gaining an in-depth understanding of Expression Trees in C#?</strong> I keep getting surprised by their capabilities, and now I'm at the point where I'm saying, "OK, enough surprise. I want to stop right now and get a PhD in these things." I'm looking for material that systematically, methodically covers the capabilities and then walks through detailed examples of what you can do with them.</p> <p>Note: I'm not talking about lambda expressions. I'm talking about Expression&lt; T > and all the things that go with it and arise from it.</p> <p>Thanks.</p>
683,747
3
0
null
2009-03-25 21:47:11.713 UTC
62
2017-07-15 18:11:50.223 UTC
2009-03-25 23:43:30.2 UTC
Charlie Flowers
80,112
Charlie Flowers
80,112
null
1
57
c#|c#-3.0|lambda|expression-trees
9,212
<p>Chapter 11 (Inside Expression Trees) and chapter 12 (Extending Linq) of Programming Microsoft Linq (ISBN 13: 978-0-7356-2400-9 or ISBN 10: 0-7356-2400-3) has been invaluable for me. I haven't read Jons book, but he is a quality guy and explains things well, so I assume that his coverage would also be good.</p> <p>Another great resource is <a href="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx" rel="noreferrer">Bart De Smet's blog</a> </p> <p>Also, keep your eye on MSDN, the sample code for building a <a href="http://code.msdn.microsoft.com/SimpleLingToDatabase/Release/ProjectReleases.aspx?ReleaseId=1471" rel="noreferrer">Simple Linq to Database</a> (by Pedram Rezaei) is about to get about 40 pages of Doco explaining it.</p> <p>A really, really useful resource for Expression Tree's in fact I would regard it as a <em>must have</em> is the <a href="http://msdn.microsoft.com/en-us/library/bb397975.aspx" rel="noreferrer">Expression Tree Visualiser</a> debugging tool.</p> <p>You should also learn as much as you can about Expression Tree Visitors, there is a pretty good base class inplementation <a href="http://msdn.microsoft.com/en-us/library/bb882521.aspx" rel="noreferrer">here</a>. </p> <p>Here is some sample code derived from that Visitor class to do some debugging (I based this on some sample code in the book I mentioned) the prependIndent method call is just an extension method on a string to put a "--" at each indent level.</p> <pre><code> internal class DebugDisplayTree : ExpressionVisitor { private int indentLevel = 0; protected override System.Linq.Expressions.Expression Visit(Expression exp) { if (exp != null) { Trace.WriteLine(string.Format("{0} : {1} ", exp.NodeType, exp.GetType().ToString()).PrependIndent(indentLevel)); } indentLevel++; Expression result = base.Visit(exp); indentLevel--; return result; } ... </code></pre>
51,021
What is the difference between Raising Exceptions vs Throwing Exceptions in Ruby?
<p>Ruby has two different exceptions mechanisms: Throw/Catch and Raise/Rescue.</p> <p>Why do we have two?</p> <p>When should you use one and not the other? </p>
51,037
3
1
null
2008-09-09 00:41:03.07 UTC
40
2018-01-08 22:07:48.943 UTC
2010-09-15 10:55:06.303 UTC
null
120,518
Nick Retallack
2,653
null
1
188
ruby|exception
55,773
<p>I think <a href="http://hasno.info/ruby-gotchas-and-caveats" rel="noreferrer">http://hasno.info/ruby-gotchas-and-caveats</a> has a decent explanation of the difference:</p> <blockquote> <p>catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.</p> </blockquote>
21,936,091
How to install oracle instantclient and pdo_oci on ubuntu machine?
<p>I need to install PDO_OCI in ubuntu machine, there is no default package that I could install with apt-get.</p> <p>There are a lot of tutorials showing how to do it, but when I follow them, I have problems related to compilation (configure, make,...)</p> <p>Here what I did:</p> <ol> <li><p>I followed <a href="https://help.ubuntu.com/community/Oracle%20Instant%20Client" rel="noreferrer">this Tutorial</a> to install instant client</p></li> <li><p>Install oci8</p> <pre><code>pecl install oci8 </code></pre> <p>I get error:</p> <blockquote> <p>error: oci.h not found</p> </blockquote></li> <li><p>Install PDO_OCI</p> <pre><code>mkdir -p /tmp/pear/download/ cd /tmp/pear/download/ pecl download pdo_oci phpize ./configure –with-pdo-oci=instantclient,/usr,11.2 </code></pre> <p>error:</p> <blockquote> <p>pdo_driver.h not found ...</p> </blockquote></li> </ol> <p>Please do you have any serious tutorial that works perfectly on UBUNTU 12.04?</p>
26,842,904
4
0
null
2014-02-21 13:42:24.223 UTC
6
2018-07-14 18:41:48.423 UTC
2014-02-23 12:22:14.887 UTC
null
447,356
null
1,430,327
null
1
5
php|oracle|ubuntu|pdo|instantclient
44,689
<p>The PDO, PDO_OCI extensions from <code>pecl install</code> are obsolete because latest PHP version has them built-in its core &amp; installation these extensions by this way mostly failed.</p> <p>I've spent a lot of time to try to do this following several approach with no luck, and finally find it out by myself a clean way to do this: <strong>compile &amp; install the extensions from PHP source</strong>.</p> <p>During the compilation, there are some tricks as well, I've described the process in detail in my post: <a href="https://medium.com/@thucnc/how-to-install-php5-pdo-oci-oci8-and-other-extensions-for-ubuntu-f405eadfe784" rel="nofollow noreferrer">https://medium.com/@thucnc/how-to-install-php5-pdo-oci-oci8-and-other-extensions-for-ubuntu-f405eadfe784</a></p> <p>Short steps are listed here:</p> <ol> <li>Download &amp; install Oracle instant Client, then export <code>ORACLE_HOME</code> environment variable</li> <li><p>Download &amp; compile PDO_OCI (and OCI8 if needed) form PHP source packages, there are some tricks that you need to applied here, including:</p> <p><code>sudo ln -s /usr/include/php5/ /usr/include/php</code></p> <p>and edit the Makefile:</p> <p><code>EXTRA_INCLUDES = -I/usr/include/oracle/11.2/client64</code></p></li> <li><p>Enable the extensions and restart web server</p></li> </ol> <p>This has been tested for Debian 7.6 as well</p> <p>Hope this helps. </p>
22,184,403
How to cast the size_t to double or int C++
<p>My question is that</p> <p>I have a size_t data, but now I want to convert it to double or int.</p> <p>If I do something like </p> <pre><code> size_t data = 99999999; int convertdata = data; </code></pre> <p>the compiler will report warning. because it maybe overflow.</p> <p>Do you have some method like the boost or some other method to do the convert?</p>
22,184,543
5
0
null
2014-03-04 22:20:48.117 UTC
10
2021-02-02 09:06:47.16 UTC
2016-12-03 00:57:58.557 UTC
null
6,410,484
null
2,701,639
null
1
68
c++|casting|double|size-t
168,344
<p>A cast, <a href="https://stackoverflow.com/a/22184461/827263">as Blaz Bratanic suggested</a>:</p> <pre><code>size_t data = 99999999; int convertdata = static_cast&lt;int&gt;(data); </code></pre> <p>is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).</p> <p>But it doesn't solve the problem that the warning was telling you about, namely that a conversion from <code>size_t</code> to <code>int</code> really could overflow.</p> <p>If at all possible, design your program so you don't <em>need</em> to convert a <code>size_t</code> value to <code>int</code>. Just store it in a <code>size_t</code> variable (as you've already done) and use that.</p> <p>Converting to <code>double</code> will not cause an overflow, but it could result in a loss of precision for a very large <code>size_t</code> value. Again, it doesn't make a lot of sense to convert a <code>size_t</code> to a <code>double</code>; you're still better off keeping the value in a <code>size_t</code> variable.</p> <p>(<a href="https://stackoverflow.com/a/22184657/827263">R Sahu's answer</a> has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)</p>
6,959,225
Core Data merge two Managed Object Context
<p>My Cocoa/Application has a Managed Object Context on the main thread. When I need to update my data my program will: </p> <ol> <li>Start a new thread</li> <li>Receive new data from a server</li> <li>Create a new Managed Object Context</li> <li>Send a notification to the main thread in order to merge the two context</li> </ol> <p>This is the function that receive the notification on the main thread</p> <pre><code>- (void)loadManagedObjectFromNotification:(NSNotification *)saveNotification { if ([NSThread isMainThread]) { [self.managedObjectContext mergeChangesFromContextDidSaveNotification:saveNotification]; } else { [self performSelectorOnMainThread:@selector(loadManagedObjectFromNotification:) withObject:saveNotification waitUntilDone:YES]; } } </code></pre> <p>I do not receive any error. My problem is the merge result, it actually concatenate Managed Objects from both context.</p> <p>My Entity are a really simple list of attribute and relationship.</p> <p>Maybe the merge need some instructions in order to understand when an updated Managed Object IS NOT a new one, but a edited version of the first one. I imagine that somewhere I need to specify a way to univocally identify an Entity, (an attribute for example can act like an ID) and something like a merge policy (if 2 managed object represent the same object, take the one with the lastModificationDate more recent).</p> <p>I just need to understand how to correctly merge the 2 contexts in order to have a single updated copy for each object.</p> <h1>UPDATE 1</h1> <p>The problem is now clear to me. The 2 context has a big difference: the ObjectID. While the context on the main thread fetched the ManagedObjects with the Persistent Store coordinator, the second thread create those object by fetching a remote URL. Even if the objects have the same contents, they will have 2 different objectID.</p> <p>My objects had already an unique identificator, I could use setObjectId in order to set this value. (Apple documentation says this is NOT a good idea).</p>
6,959,868
1
6
null
2011-08-05 16:03:05.533 UTC
21
2012-05-05 18:26:31.937 UTC
2011-08-08 08:16:59.78 UTC
null
812,568
null
812,568
null
1
23
objective-c|cocoa|core-data|nsmanagedobject|nsmanagedobjectcontext
19,449
<p>Here is what you need to do in order to correctly merge the contexts. First, you do not need your own notification. Performing a save operation on a context automatically forwards the following notification to registered observers:</p> <pre><code>NSManagedObjectContextDidSaveNotification </code></pre> <p>Therefore, all you need to do is:</p> <p>1) in your main thread, may be in the <code>viewDidLoad</code> method, register for this notification:</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:nil]; </code></pre> <p>2) implement the <code>contextDidSave:</code> method in your main thread as follows:</p> <pre><code>- (void)contextDidSave:(NSNotification *)notification { SEL selector = @selector(mergeChangesFromContextDidSaveNotification:); [managedObjectContext performSelectorOnMainThread:selector withObject:notification waitUntilDone:YES]; } </code></pre> <p>3) in your <code>dealloc</code> method add the following:</p> <pre><code>[[NSNotificationCenter defaultCenter] removeObserver:self]; </code></pre> <p>4) create a new context in your other thread using something like the following method:</p> <pre><code>- (NSManagedObjectContext*)createNewManagedObjectContext { NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init]; [moc setPersistentStoreCoordinator:[self persistentStoreCoordinator]]; [moc setUndoManager:nil]; return [moc autorelease]; } </code></pre> <p>5) upon receiving the new data, the proper way to handle this situation is the use of managed object IDs. Since managed object IDs are thread safe, you can pass them from your main thread to the other thread, then use <code>existingObjectWithID:error:</code> to retrieve the object associated to a specific ID, update it and save the context. Now the merge will operate as you expect. Alternatively, if you do not know in advance what managed object IDs must be passed between the threads, then in your other thread you simply fetch the objects using a predicate to retrieve the ones corresponding to the objects retrieved from the server, then you update them and save the context.</p>
34,874,347
What does an asterisk in a scanf format specifier mean?
<p>So I stumbled across this code and I haven't been able to figure out what the purpose of it is, or how it works:</p> <pre><code>int word_count; scanf("%d%*c", &amp;word_count); </code></pre> <p>My first thought was that <code>%*d</code> was referencing a <code>char</code> pointer or disallowing <code>word_count</code> from taking <code>char</code> variables. </p> <p>Can someone please shed some light on this? </p>
34,874,569
3
2
null
2016-01-19 10:28:12.237 UTC
4
2016-06-14 21:33:47.153 UTC
2016-01-19 16:23:19.43 UTC
null
123,109
null
2,902,996
null
1
31
c|char|scanf|format-specifiers
7,982
<p><code>*c</code> means, that a char will be read but won't be assigned, for example for the input "30a" it will assign 30 to <code>word_count</code>, but 'a' will be ignored.</p>
36,221,038
How to debug a forked child process using CLion
<p>I was debugging a Linux C program with CLion's internal debugger (which is gdb on Linux). The program forked a child process that was supposed to get suspended at the break point I set. But the debugger didn't stop there even if I had entered <code>set follow-fork-mode child</code> inside the gdb panel. So how can I make that happen with CLion? </p>
49,468,112
4
1
null
2016-03-25 13:38:28.717 UTC
12
2022-03-08 15:51:23.583 UTC
2016-06-06 09:27:06.51 UTC
null
2,990,350
null
2,990,350
null
1
30
c|linux|clion
11,994
<p>I followed <a href="https://stackoverflow.com/a/34122405/8165307">answer</a> posted by @MarkusParker, but instead of <code>set auto-load safe-path /</code> I used <a href="https://visualgdb.com/gdbreference/commands/set_detach-on-fork" rel="noreferrer"><code>set detach-on-fork off</code></a> to prevent disconnect from child process. This instruction works for me: </p> <ol> <li><p>Set a break point at the beginning of your program (ie. the parent program, not the child program).</p></li> <li><p>Start the program in the debugger.</p></li> <li><p>Go to the debugger console (tab with the label gdb) in clion and enter <code>set follow-fork-mode child</code> and <code>set detach-on-fork off</code>.</p></li> <li><p>Continue debugging.</p></li> </ol>
6,069,212
ADB, Wifi and Eclipse: how I can configure?
<p>Recently I see that is possible to debug app development by use WIFI instead of USB debug method. I make a search and I found an app called <a href="https://market.android.com/details?id=siir.es.adbWireless" rel="noreferrer">abdWireless</a> but I have a problem.</p> <p>How I can tell to Eclipse to connect via Wifi method?</p> <p>I think that it is an automatic process, but on start debug it open the Emulator.</p> <p>Someone? :) Bye</p>
6,070,095
3
1
null
2011-05-20 08:15:25.923 UTC
21
2021-05-01 04:09:04.043 UTC
null
null
null
null
755,393
null
1
43
android|eclipse|wifi|adb|ddms
53,405
<p>First, run 'adb connect ip:port', like <code>adb connect &lt;phone-ip-address&gt;</code>, from console/terminal (with your IP address and port of cause). This makes <code>adb</code> service to connect to your device via network. Port 5555 is used by default if no port number is specified.</p> <p>Then check that device is correctly connected: run <code>adb devices</code> from console/terminal (make sure you remove usb cable from device). If <code>adb devices</code> does not list your device, then you have some entirely different issue.</p> <hr> <p>If you've connected your device via <code>adb</code> and you can see the device in <code>adb devices</code> list, but your eclipse still starts emulator,:</p> <ol> <li>Go to Run->Debug Configuration -> [your configuration]</li> <li>In your configuration go to <code>Target</code> tab and select <code>Manual</code> </li> </ol> <p><img src="https://i.stack.imgur.com/BuSqH.png" alt="enter image description here"></p> <p>This will popup device selection each time you start the app from eclipse. So you will be able to explicitly state which emulator/device to use. </p> <p>To <strong>disconnect</strong> your device, <code>adb disconnect &lt;phone-ip-address&gt;</code></p>
5,886,872
Android AudioRecord vs. MediaRecorder for recording audio
<p>I want to record human voice on my Android phone. I noticed that Android has two classes to do this: <a href="http://developer.android.com/reference/android/media/AudioRecord.html" rel="noreferrer">AudioRecord</a> and <a href="http://developer.android.com/reference/android/media/MediaRecorder.html" rel="noreferrer">MediaRecorder</a>. Can someone tell me what's the difference between the two and what are appropriate use cases for each?</p> <p>I want to be able to analyse human speech in real-time to measure amplitude, etc. Am I correct in understanding that AudioRecord is better suited for this task?</p> <p>I noticed on the official Android <a href="http://developer.android.com/guide/topics/media/index.html" rel="noreferrer">guide webpage for recording audio</a>, they use MediaRecorder with no mention of AudioRecord.</p>
5,888,564
3
0
null
2011-05-04 16:44:15.863 UTC
22
2018-07-13 07:22:13.723 UTC
2016-06-10 17:55:13.703 UTC
null
4,561,314
null
4,561,314
null
1
98
android|audio-recording|audiorecord
27,182
<p>If you want to do your analysis while recording is still in progress, you need to use <code>AudioRecord</code>, as <code>MediaRecorder</code> automatically records into a file. <code>AudioRecord</code> has the disadvantage, that after calling <code>startRecording()</code> you need to poll the data yourself from the <code>AudioRecord</code> instance. Also, you must read and process the data fast enough such that the internal buffer is not overrun (look in the logcat output, <code>AudioRecord</code> will tell you when that happens). </p>
5,719,424
HTML5 Boilerplate vs. HTML5 Reset
<p>Hey everyone &mdash; <a href="http://html5boilerplate.com/" rel="noreferrer">HTML5 Boilerplate</a> and <a href="http://html5reset.org/" rel="noreferrer">HTML5 Reset</a> are two HTML, CSS, and JavaScript templates with a lot of modern best practices built-in. Their goals are largely the same:</p> <ul> <li>Fast, robust, modern Web development </li> <li>HTML5 (duh!)</li> <li>Cross-browser normalization (including support for IE6 and mobile browsers)</li> <li>Progressive enhancement and graceful degradation</li> <li>Performance optimizations</li> <li>Not a framework, but the starting point for your next project</li> </ul> <p>Obviously, they're very similar in function. In what ways are their implementations different (for example, perhaps IE-specific CSS fixes are achieved using different techniques)? Are they at all different in scope? It seems like HTML5 Boilerplate is a bit larger (build tools, server configuration, etc.), but it's hard to know where it goes beyond HTML5 Reset when it comes to the actual site that people will see.</p>
5,719,623
4
0
null
2011-04-19 16:13:29.343 UTC
23
2013-04-15 13:48:22.13 UTC
null
null
null
null
203,104
null
1
54
javascript|css|html|boilerplate
7,569
<p>In general, both projects set out to provide a solid starting point for developers working on web projects. They both get rid of a lot of the tedious, some-what error-prone boilerplate that many developers find themselves re-creating for each project. The details in how they go about it are slightly different, but for the most part, they achieve the same results.</p> <p>HTML5Boilerplate has, as you noted, added in some build-script pieces to help developers follow best practices to speed up their pages in terms of server-side items, such as far-future expires headers, etc. where-as the HTML5Reset project is more focused on the semantics, content, and styling. For example, HTML5Reset has more example structure for the content of the page in HTML5 (to help show people how to use some of the new elements), whereas HTML5Boilerplate does not.</p> <p>The response-time and page speed parts that HTML5Boilerplate includes get more and more important as more users find themselves on mobile platforms, and as Google increases the effect <a href="http://googlewebmastercentral.blogspot.com/2010/04/using-site-speed-in-web-search-ranking.html" rel="noreferrer">page response times have on page rank</a>. There are lots of papers that show a small increase in the page response time has a measurable negative impact on how your site is <a href="http://googleresearch.blogspot.com/2009/06/speed-matters.html" rel="noreferrer">used and perceived</a> (<a href="http://answers.google.com/answers/threadview/id/716510.html" rel="noreferrer">especially in an eCommerce setting</a>...often a 100ms slower page will get percentage less things sold).</p> <p>On the CSS front, the majority of the reset style section for both projects is very much the same, with some minor differences in what the baseline is set to. The IE specific fixes, however, are largely the same, with HTML5Boilerplate asserting a bit more control than HTML5Reset over how IE styles some things like form elements (ie. check box / radio buttons and valid / invalid states)</p> <p>Two major CSS areas that HTML5Boilerplate covers that HTML5Reset does not are common helper classes to assist with making sites more accessible, such as <code>.hidden</code> and <code>.visuallyhidden</code>, as well as some substantial adjustments to the print styles that serve to both make printing more similar across browsers, as well as some cost-savings and accessibility things like making background images transparent (to not waste toner), and adding the actual URL to links and the title to abbreviations.</p> <p>I would highly suggest reading through both projects' info and how they do things in a side-by-side comparison because the similarities, and also the differences (and the reasoning behind them) is quite informative and has helped me to better decide what parts of each I wanted to use.</p> <p>Ultimately, just like any "library" sort of project, you as the developer need to understand what you are doing and probably should tweak your baseline to meet the particular needs of the project.</p>
6,120,902
How do I automatically install missing python modules?
<p>I would like to be able to write:</p> <pre><code>try: import foo except ImportError: install_the_module("foo") </code></pre> <p>What is the recommended/idiomatic way to handle this scenario?</p> <p>I've seen a lot of scripts simply print an error or warning notifying the user about the missing module and (sometimes) providing instructions on how to install. However, if I know the module is available on <a href="http://pypi.python.org/pypi" rel="noreferrer">PyPI</a>, then I could surely take this a step further an initiate the installation process. No?</p>
6,120,975
4
6
null
2011-05-25 07:24:04.98 UTC
19
2017-01-05 05:37:38.373 UTC
null
null
null
null
172,218
null
1
56
python|module|pypi
95,246
<p>Installation issues are not subject of the source code!</p> <p>You define your dependencies properly inside the <code>setup.py</code> of your package using the <code>install_requires</code> configuration.</p> <p>That's the way to go...installing something as a result of an <code>ImportError</code> is kind of weird and scary. Don't do it.</p>
1,759,554
Examples or Uses Cases to explain EJB Transaction Attributes
<p>There are some good explanations of EJB Transaction Attributes (and annotations) out there, for example, <a href="http://openejb.apache.org/3.0/transaction-annotations.html" rel="noreferrer">OpenEJB's</a>.</p> <p>But sometimes when I try to cover this with someone who hasn't worked with many transactional resources, I see their eyes start to glaze over. </p> <p>So my question - how would you explain EJB Transaction Attributes to your grandmother?</p> <ul> <li>Required</li> <li>RequiresNew</li> <li>Mandatory</li> <li>NotSupported</li> <li>Supports</li> <li>Never</li> </ul> <p>I'm thinking a contrived example, analogy, or a concise real-world use case would be helpful.</p>
2,970,061
2
0
null
2009-11-18 22:18:42.22 UTC
12
2011-05-27 13:16:55.657 UTC
2009-11-19 20:18:47.313 UTC
null
59,561
null
59,561
null
1
22
java|transactions|jakarta-ee|ejb-3.0
13,492
<p>I think it makes sense to think about this in terms of the container's interaction with a caller to the EJB method as a true <em>monitor</em>... so I'd like to use a <strong>bouncer metaphor</strong> in various different scenarios. </p> <p>See <a href="http://www.caughtbyjava.com/ejb-3-0-transaction-attributes-explained/" rel="noreferrer">this page</a> for a good description/overview of the transaction attributes.</p> <p><strong>Required (REQUIRED @TransactionAttribute)</strong><br> <em>Night club</em> </p> <p>Show up at the club, need a ticket to enter. If you don't have one it will be (purchased?) given to you at the door.</p> <blockquote> <p>Transaction is the TICKET.<br> Container is the BOUNCER.</p> </blockquote> <p><strong>Requires New (REQUIRES_NEW @TransactionAttribute)</strong><br> <em>Comedy clubs, 1 drink-minimum, no re-entry</em> </p> <p>Show up at the club, no outside food/drink, you must leave them at the door. To get in you must purchase 1-drink minimum every time you leave and re-enter.</p> <blockquote> <p>Transaction is the DRINK.<br> Container is the BOUNCER.<br> Suspending the transaction is LEAVING AT THE DOOR.</p> </blockquote> <p><strong>Supports (SUPPORTS @TransactionAttribute)</strong><br> <em>House party</em> </p> <p>Show up at the party, alcohol is permitted. We'll let you in with it if you have your own alcohol, if you don't we'll let you in too.</p> <blockquote> <p>Transaction is the ALCOHOL.<br> Container is the HOST.</p> </blockquote> <p><strong>Mandatory (MANDATORY @TransactionAttribute)</strong><br> <em>Invite-only party</em> </p> <p>Show up at the party, need a invitation to enter: If you don't have one and try to get in, the bouncer calls the authorities.</p> <blockquote> <p>Transaction is the INVITATION.<br> Container is the HOST.<br> Throwing an exception is CALLING THE AUTHORITIES.</p> </blockquote> <p><strong>Not Supported (NOT_SUPPORTED @TransactionAttribute)</strong><br> <em>Concert, cameras are prohibited.</em> </p> <p>Show up at the concert, cameras are prohibited. You can leave it at the door and pick it up when you leave.</p> <blockquote> <p>Transaction is the CAMERA.<br> Container is the DOORMAN.<br> Suspending the transaction is LEAVING AT THE DOOR.</p> </blockquote> <p><strong>Never (NEVER @TransactionAttribute)</strong><br> <em>High school dance</em> </p> <p>Show up at the dance, alcohol is prohibited. If you try to get in with it and are caught, the chaperone calls the authorities.</p> <blockquote> <p>Transaction is the ALCOHOL.<br> Container is the CHAPERONE. Throwing an exception is CALLING THE AUTHORITIES.</p> </blockquote>
50,458,507
C# Web API Sending Body Data in HTTP Post REST Client
<p>I need to send this HTTP Post Request:</p> <pre><code> POST https://webapi.com/baseurl/login Content-Type: application/json {"Password":"password", "AppVersion":"1", "AppComments":"", "UserName":"username", "AppKey":"dakey" } </code></pre> <p>It works great in RestClient and PostMan just like above.</p> <p>I need to have this pro-grammatically and am not sure if to use </p> <p>WebClient, HTTPRequest or WebRequest to accomplish this.</p> <p>The problem is how to format the Body Content and send it above with the request.</p> <p>Here is where I am with example code for WebClient...</p> <pre><code> private static void Main(string[] args) { RunPostAsync(); } static HttpClient client = new HttpClient(); private static void RunPostAsync(){ client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Inputs inputs = new Inputs(); inputs.Password = "pw"; inputs.AppVersion = "apv"; inputs.AppComments = "apc"; inputs.UserName = "user"; inputs.AppKey = "apk"; var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs))); try { res.Result.EnsureSuccessStatusCode(); Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine); } catch (Exception ex) { Console.WriteLine("Error " + res + " Error " + ex.ToString()); } Console.WriteLine("Response: {0}", result); } public class Inputs { public string Password; public string AppVersion; public string AppComments; public string UserName; public string AppKey; } </code></pre> <p>This DOES NOW WORK and responses with a (200) OK Server and Response</p>
50,458,523
5
1
null
2018-05-22 01:20:11.64 UTC
1
2021-06-02 20:14:46.007 UTC
2018-05-23 01:54:26.597 UTC
null
183,680
null
183,680
null
1
11
c#|asp.net-web-api|asp.net-core|advanced-rest-client
59,803
<p>Why are you generating you own json?</p> <p>Use <code>JSONConvert</code> from JsonNewtonsoft.</p> <p>Your json object string values need <code>&quot; &quot;</code> quotes and <code>,</code></p> <p>I'd use http client for Posting, not webclient.</p> <pre><code>using (var client = new HttpClient()) { var res = client.PostAsync(&quot;YOUR URL&quot;, new StringContent(JsonConvert.SerializeObject( new { OBJECT DEF HERE }, Encoding.UTF8, &quot;application/json&quot;) ); try { res.Result.EnsureSuccessStatusCode(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } </code></pre>
5,962,671
Prevent session expired in PHP Session for inactive user
<p>I have a problem with my application: my application has many forms and need about 1 hour to finish this form because the form is dynamic (can add other forms). The problem is: the session of my web server is 24 minutes. When user fill the form, they spent so much time and the session timed out because server recognize that the user is inactive. It's very annoying when form submitted, most data was lost and the user is returned to the login page. I have tried to make my session expired in 10 hours with this code:</p> <pre><code>ini_set('session.gc_maxlifetime', '36000'); </code></pre> <p>But it's not working in my server, is it possible my server preventing <code>ini_set()</code> function?</p> <p>So, what should I do for solving this problem? Can I prevent session timeout so that the session can be expanded to 10 hours? Or can I disable session expiration?</p> <p>Thanks</p>
5,964,295
6
4
null
2011-05-11 10:19:25.31 UTC
10
2022-04-08 01:40:32.99 UTC
2011-05-11 11:45:17.717 UTC
null
53,114
null
629,556
null
1
21
php|session|session-timeout
43,649
<p>Instead of setting the time in ini to a fixed length, remind that session timeout is reset on reload. So create some ajax code that does a request every 5 minutes or so to a file (image or smth). This way the timer is reset every 5 minutes and users can spend a day filling out your forms.</p>
5,834,191
SQL Server Management Studio missing
<p>i just installed sql server 2008 r2 and SQL Server Management Studio. After installation i found that the SQL Server Management Studio has not been installed.</p> <p>i wanted to install SQL Server Management Studio, but cannot find the installation for this. Any idea how to install it?</p>
5,834,374
6
2
null
2011-04-29 15:43:36.983 UTC
7
2020-05-31 16:46:47.823 UTC
null
null
null
null
637,493
null
1
31
ssms
121,199
<p>Did you include "Management Tools" as a chosen option during setup?</p> <p><img src="https://i.stack.imgur.com/XmuMO.png" alt="enter image description here"></p> <p>Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.</p>
5,608,980
How to ensure a timestamp is always unique?
<p>I'm using timestamps to temporally order concurrent changes in my program, and require that each timestamp of a change be unique. However, I've discovered that simply calling <code>DateTime.Now</code> is insufficient, as it will often return the same value if called in quick succession.</p> <p>I have some thoughts, but nothing strikes me as the "best" solution to this. Is there a method I can write that will guarantee each successive call produces a unique <code>DateTime</code>?</p> <p>Should I perhaps be using a different type for this, maybe a long int? <code>DateTime</code> has the obvious advantage of being easily interpretable as a real time, unlike, say, an incremental counter.</p> <p><strong>Update:</strong> Here's what I ended up coding as a simple compromise solution that still allows me to use <code>DateTime</code> as my temporal key, while ensuring uniqueness each time the method is called:</p> <pre><code>private static long _lastTime; // records the 64-bit tick value of the last time private static object _timeLock = new object(); internal static DateTime GetCurrentTime() { lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness DateTime result = DateTime.UtcNow; if ( result.Ticks &lt;= _lastTime ) result = new DateTime( _lastTime + 1 ); _lastTime = result.Ticks; return result; } } </code></pre> <p>Because each tick value is only one 10-millionth of a second, this method only introduces noticeable clock skew when called on the order of 10 million times per second (which, by the way, it is efficient enough to execute at), meaning it's perfectly acceptable for my purposes.</p> <p>Here is some test code:</p> <pre><code>DateTime start = DateTime.UtcNow; DateTime prev = Kernel.GetCurrentTime(); Debug.WriteLine( "Start time : " + start.TimeOfDay ); Debug.WriteLine( "Start value: " + prev.TimeOfDay ); for ( int i = 0; i &lt; 10000000; i++ ) { var now = Kernel.GetCurrentTime(); Debug.Assert( now &gt; prev ); // no failures here! prev = now; } DateTime end = DateTime.UtcNow; Debug.WriteLine( "End time: " + end.TimeOfDay ); Debug.WriteLine( "End value: " + prev.TimeOfDay ); Debug.WriteLine( "Skew: " + ( prev - end ) ); Debug.WriteLine( "GetCurrentTime test completed in: " + ( end - start ) ); </code></pre> <p>...and the results:</p> <pre><code>Start time: 15:44:07.3405024 Start value: 15:44:07.3405024 End time: 15:44:07.8355307 End value: 15:44:08.3417124 Skew: 00:00:00.5061817 GetCurrentTime test completed in: 00:00:00.4950283 </code></pre> <p>So in other words, in half a second it generated 10 million <em>unique</em> timestamps, and the final result was only pushed ahead by half a second. In real-world applications the skew would be unnoticeable.</p>
14,369,695
6
4
null
2011-04-10 00:44:05.933 UTC
20
2019-10-17 14:35:19.537 UTC
2013-04-04 18:58:43.71 UTC
null
238,948
null
238,948
null
1
35
c#|.net|datetime|concurrency
33,671
<p>One way to get a strictly ascending sequence of timestamps with no duplicates is the following code. </p> <p>Compared to the other answers here this one has the following benefits:</p> <ol> <li>The values track closely with actual real-time values (except in extreme circumstances with very high request rates when they would get slightly ahead of real-time).</li> <li>It's lock free and should perform better that the solutions using <code>lock</code> statements.</li> <li>It guarantees ascending order (simply appending a looping a counter does not).</li> </ol> <p></p> <pre><code>public class HiResDateTime { private static long lastTimeStamp = DateTime.UtcNow.Ticks; public static long UtcNowTicks { get { long original, newValue; do { original = lastTimeStamp; long now = DateTime.UtcNow.Ticks; newValue = Math.Max(now, original + 1); } while (Interlocked.CompareExchange (ref lastTimeStamp, newValue, original) != original); return newValue; } } } </code></pre>
6,303,490
What's the difference between HTML <head> and <body> tags?
<p>What's the difference between HEAD tags and BODY tags?</p> <p>most HTML books only 'briefly' mentions <code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> tags...but they just go away really fast.</p> <p>Do they affect how browsers render web pages?</p> <p>Also, do they affect the order in which javascripts are run?</p> <p>(I mean, if I have a javascript inside a <code>&lt;head&gt;</code> tag, would it run BEFORE another javascript inside <code>&lt;body&gt;</code> tag? Even when <code>&lt;body&gt;</code> came BEFORE <code>&lt;head&gt;</code>?)</p> <p>This is too confusing--I haven't ever used a head/body tags, but i never had any trouble with it. But while reading Jquery tutorial, I saw people recommending putting some codes inside <code>&lt;head&gt;</code> and the others inside <code>&lt;body&gt;</code> tags.</p> <p>Thank you!!!</p>
6,303,543
8
2
null
2011-06-10 07:52:31.9 UTC
12
2018-08-25 02:12:55.34 UTC
2011-06-10 07:53:53.487 UTC
null
52,162
null
531,820
null
1
27
javascript|html
70,744
<p>Generally javascript code will function in the head before code in the body. The head section is usually used to contain information about the page that you dont neccessarily see like the meta keywords meta description or title of a page. You would also link to any external files like .css .js files in the head section as they need to load before the page is displayed. </p> <p>Anything in the body section is what you would expect to be see on screen.</p>
44,120,314
Result of a delete mutation?
<p>What should be the result of a delete mutation in Graphql? I'm using the graphql-ruby gem. Here's an example of my mutation, but I'm just not sure what I should be returning as the response.</p> <pre><code>Mutations::Brands::Delete = GraphQL::Relay::Mutation.define do name "DeleteBrand" description "Delete a brand" input_field :id, types.ID # return_field ?? resolve -&gt;(object, inputs, ctx) { brand = Brand.find(inputs[:id]) brand.destroy } end </code></pre>
44,132,000
2
1
null
2017-05-22 19:02:32.79 UTC
4
2019-04-04 04:09:03.503 UTC
2019-04-04 04:09:03.503 UTC
null
214,759
null
214,759
null
1
29
graphql|graphql-ruby
16,952
<p>You can return deleted_id or message. If it is an associated object you can return updated object like below example.</p> <pre><code>Destroy = GraphQL::Relay::Mutation.define do name 'DestroyComment' description 'Delete a comment and return post and deleted comment ID' # Define input parameters input_field :id, !types.ID # Define return parameters return_field :deletedId, !types.ID return_field :article, ArticleType return_field :errors, types.String resolve -&gt;(_obj, inputs, ctx) { comment = Comment.find_by_id(inputs[:id]) return { errors: 'Comment not found' } if comment.nil? article = comment.article comment.destroy { article: article.reload, deletedId: inputs[:id] } } </code></pre> <p><a href="http://tech.eshaiju.in/blog/2017/05/15/graphql-mutation-query-implementation-ruby-on-rails/" rel="noreferrer">http://tech.eshaiju.in/blog/2017/05/15/graphql-mutation-query-implementation-ruby-on-rails/</a></p>
24,931,155
Cordova 3.5.0 Install Error- Please Install Android Target 19
<p>I try to get this working and it's driving me nuts:</p> <pre><code>$ cordova platform add android </code></pre> <p>The output is:</p> <pre><code>Creating android project... /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:126 throw e; ^ Error: Please install Android target 19 (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run "android" from your command-line to install/update any missing SDKs or tools. at /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/lib/check_reqs.js:80:29 at _fulfilled (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:798:54) at self.promiseDispatch.done (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:827:30) at Promise.promise.promiseDispatch (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:760:13) at /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:574:44 at flush (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:108:17) at process._tickCallback (node.js:419:13) Error: /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/create: Command failed with exit code 8 at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:135:23) at ChildProcess.emit (events.js:98:17) at maybeClose (child_process.js:755:16) at Process.ChildProcess._handle.onexit (child_process.js:822:5) </code></pre> <p>If did run the command <code>android</code> this are all the things I installed:</p> <p><img src="https://i.stack.imgur.com/5lhEv.png" alt="installed"></p> <p>I also did:</p> <p><code>open ~/.bash_profile</code> </p> <p>And added:</p> <p><code>export PATH=${PATH}:/Users/doekewartena/Documents/adt-bundle-mac-x86_64-20140702/sdk/platform-tools:/Users/doekewartena/Documents/adt-bundle-mac-x86_64-20140702/sdk/tools</code></p> <p>But it doesn't help :(</p> <p>Could someone help.</p>
24,934,188
6
1
null
2014-07-24 10:23:38.85 UTC
24
2021-05-01 16:47:43.03 UTC
null
null
null
null
1,022,707
null
1
98
android|macos|cordova
66,875
<p>Android SDK is not your target Android version. Target Android version 19 is the API level for android Kitkat.So in you SDK manager check if you have Android 4.4.2(API 19) installed. If you want your target API version to be different then change it in ANdroidManifest.xml </p> <pre><code>&lt;uses-sdk android:minSdkVersion="16" android:targetSdkVersion="18" /&gt; </code></pre> <p>Edit these lines. Here <code>android:targetSdkVersion</code> is your Android version that you are targeting.</p> <p><img src="https://i.stack.imgur.com/93vWk.png" alt="enter image description here"></p>
49,226,309
What are the proper typescript types for addEventListener mousemove and it's event argument?
<p><strong>Question:</strong> Without using <code>any</code>, What is the proper typing for my <code>onMouseMove</code> function?</p> <pre><code>export class Main { private dTimer: number; constructor() { this.init(); } private init() { this.mouseHandlers(); } private mouseHandlers() { document.addEventListener('mousemove', this.onMouseMove) } private onMouseMove: EventListener = (event: MouseEvent) =&gt; { clearTimeout(this.dTimer); this.dTimer = setTimeout(() =&gt; { console.log(event.pageX, event.pageY) }, 500); } } </code></pre> <p>Typescript is complaining about my types and I dunno how to make it happy w/o using any.</p> <pre><code>main.ts(38,3): error TS2322: Type '(event: MouseEvent) =&gt; void' is not assignable to type 'EventListener'. Types of parameters 'event' and 'evt' are incompatible. Type 'Event' is not assignable to type 'MouseEvent'. Property 'altKey' is missing in type 'Event'. </code></pre>
49,226,332
3
1
null
2018-03-11 23:41:49.353 UTC
2
2022-02-13 06:28:25.807 UTC
null
null
null
null
1,191,635
null
1
21
typescript|mouseevent|mousemove|tsc|static-typing
58,334
<blockquote> <p>What are the proper typescript types for addEventListener mousemove and it's event argument?</p> </blockquote> <p>Being explicit will set you free: </p> <pre><code>onMouseMove: { (event: MouseEvent): void } = (event: MouseEvent) =&gt; { } </code></pre> <p>Or, let TypeScript infer it from assignment : </p> <pre><code>onMouseMove = (event: MouseEvent) =&gt; { } </code></pre>
42,581,173
initializing a struct containing a slice of structs in golang
<p>I have a struct that I want to initialize with a slice of structs in golang, but I'm trying to figure out if there is a more efficient version of appending every newly generated struct to the slice:</p> <pre><code>package main import ( "fmt" "math/rand" ) type LuckyNumber struct { number int } type Person struct { lucky_numbers []LuckyNumber } func main() { count_of_lucky_nums := 10 // START OF SECTION I WANT TO OPTIMIZE var tmp []LuckyNumber for i := 0; i &lt; count_of_lucky_nums; i++ { tmp = append(tmp, LuckyNumber{rand.Intn(100)}) } a := Person{tmp} // END OF SECTION I WANT TO OPTIMIZE fmt.Println(a) } </code></pre>
42,581,219
2
1
null
2017-03-03 14:15:34.54 UTC
4
2017-03-03 17:29:26.547 UTC
2017-03-03 17:29:26.547 UTC
null
2,636,317
null
2,636,317
null
1
15
go|struct|slice
41,714
<p>You can use <a href="https://golang.org/pkg/builtin/#make" rel="noreferrer"><code>make()</code></a> to allocate the slice in "full-size", and then use a <a href="https://golang.org/ref/spec#For_statements" rel="noreferrer"><code>for range</code></a> to iterate over it and fill the numbers:</p> <pre><code>tmp := make([]LuckyNumber, 10) for i := range tmp { tmp[i].number = rand.Intn(100) } a := Person{tmp} fmt.Println(a) </code></pre> <p>Try it on the <a href="https://play.golang.org/p/34JCCo8mVe" rel="noreferrer">Go Playground</a>.</p> <p>Note that inside the <code>for</code> I did not create new "instances" of the <code>LuckyNumber</code> struct, because the slice already contains them; because the slice is not a slice of pointers. So inside the <code>for</code> loop all we need to do is just use the struct value designated by the <a href="https://golang.org/ref/spec#Index_expressions" rel="noreferrer">index expression</a> <code>tmp[i]</code>.</p>
32,833,896
Does Java 8's new Java Date Time API take care of DST?
<p>I am thinking of using the new <strong>java 8 Date Time API</strong>. I googled a bit and found jodaTime as good choice for java but still kind of interested to see how this new API works. </p> <p>I am storing all time in UTC values in my datastore and will be converting them to Local Time Zone specific value based on user's timezone. I can find many articles showing how to use new Java Date Time API. However I am not sure if the API will take care of DST changes ? Or do we have any better way of handling Date ?</p> <p>I am just learning the new Date API , so thought of hearing your thoughts on handling the DateTime and displaying it on the basis of Users TimeZone.</p>
32,834,133
3
2
null
2015-09-29 00:40:13.633 UTC
11
2020-05-21 23:59:19.107 UTC
null
null
null
null
1,946,741
null
1
29
java|datetime|datetimeoffset
22,395
<p>It depends on which class you use:</p> <ul> <li><code>Instant</code> is an instantaneous point on the global time-line (UTC), and is unrelated to time-zone.</li> <li><code>LocalDate</code> and <code>LocalDateTime</code> have no concept of time-zone, but calling <code>now()</code> will of course give you your correct time.</li> <li><code>OffsetDateTime</code> has a time-zone, but doesn't support Daylight Savings Time.</li> <li><code>ZonedDateTime</code> has full time-zone support.</li> </ul> <p>Converting between them usually requires a time-zone, so to answer your question:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;Yes, Java 8 Date/Time <strong>can</strong> take care of DST, <em>if</em> you use it right.</p>
9,500,285
How to count the number of sub string from a split in java
<p>I have this piece of code in my java class</p> <pre><code>mystring = mysuperstring.split("/"); </code></pre> <p>I want to know how many sub-string is created from the split.</p> <p>In normal situation, if i want to access the first sub-string i just write</p> <pre><code>mystring[0]; </code></pre> <p>Also, i want to know if <code>mystring[5]</code> exist or not.</p>
9,500,304
6
0
null
2012-02-29 13:46:32.537 UTC
1
2021-05-14 11:40:23.733 UTC
null
null
null
null
1,237,500
null
1
7
java|string|split
52,694
<blockquote> <p>I want to know how many sub-string is created from the split.</p> </blockquote> <p>Since <code>mystring</code> is an array, you can simply use <code>mystring.length</code> to get the number of substrings.</p> <blockquote> <p>Also, i want to know if <code>mystring[5]</code> exist or not.</p> </blockquote> <p>To do this:</p> <pre><code>if (mystring.length &gt;= 6) { ... } </code></pre>
9,159,757
Can I add comments to a pip requirements file?
<p>I'd like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this?</p> <p>I'm imagining something like</p> <pre><code>Babel==0.9.5 # translation CherryPy==3.2.0 # web server Creoleparser==0.7.1 # wiki formatting Genshi==0.5.1 # templating </code></pre>
9,160,112
1
0
null
2012-02-06 11:59:20.177 UTC
17
2022-06-25 11:35:05.8 UTC
null
null
null
null
236,081
null
1
317
python|comments|pip
73,906
<p>Sure, you can, just use <code>#</code></p> <p><a href="https://pip.pypa.io/en/latest/reference/requirements-file-format/" rel="noreferrer"><code>pip</code> docs</a>:</p> <blockquote> <p>A line that begins with # is treated as a comment and ignored. Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.</p> </blockquote>
9,370,518
Xcode 4.2 how include one project into another one?
<p>I keep searching, but cannot find <strong>a clear and simple explanation on how to include one XCode project, along with all of it's sub-classes into another project.</strong> I routinely see stuff like that in sample projects that I download off the web, but do not know how to do this myself.</p> <p>Within XCode, along with .h and .m files, and folders, there's a whole new project, starting with a blue xcode project icon, that is expandable to contain everything within the project. </p> <p>Please, can someone explain to me step by step what do I need to do to add one XCode project into another one? I've seen a ton of one liners like "header search paths", but that does not tell me much. </p> <p><strong>UPDATE: After re-reading the documentation, I realized that the project to include must be dragged ONTO the BLUE project icon of the parent project.</strong> Regular sources can be dragged anywhere, but a project must be dragged onto a project.</p> <p>Thank you!</p>
9,370,634
6
0
null
2012-02-21 00:35:30.153 UTC
43
2019-09-25 10:33:58.247 UTC
2012-03-05 15:10:05.973 UTC
null
967,484
null
967,484
null
1
77
ios|version-control|xcode4.2
51,514
<p>This makes a lot of sense when you are trying to add a static library to your xcode projects. There are a couple steps required for doing this. First, make sure that the static library project is <strong>not</strong> open in XCode. </p> <p>Then start by dragging and dropping the static library xcodeproj file (from the Finder) onto your app's xcode project. <img src="https://i.stack.imgur.com/XIoWL.png" alt="StaticLib"></p> <p>After this you need to add this library to your app's build phases. Click on the main project, and select the BuildPhases tab of the target.</p> <p><img src="https://i.stack.imgur.com/vDc3r.png" alt="Build Phases"></p> <p>You're going to want to add the other project to the Target Dependencies and to your Link Binary With Libraries Section.</p> <p>Finally, the app needs to be aware of your headers. Therefore, you need to add the path to your static libraries classes to your User Header Search Paths. Go to the Build Settings of the Main Target and search for Header Search Path.</p> <p><img src="https://i.stack.imgur.com/s8tm7.png" alt="Header Search Path"></p> <p>This will make your app aware of the new static library.</p> <p>Sometimes you need to add a few Other Linker Flags. In the Build Settings search for Other Linker Flags and add <code>-all_load</code> and <code>-ObjC</code></p> <p><img src="https://i.stack.imgur.com/vahHr.png" alt="Other Linker Flags"></p> <p>Hope this helps, I know the first time I tried to do this I was banging my head against the wall for a while.</p>
7,021,873
Check if JAVA_HOME is present in environment using batch script
<p>I want to check whether JAVA_HOME is present in environment or not So I wrote the below script <code>a.bat</code></p> <pre><code>if "%JAVA_HOME%" == "" ( echo Enter path to JAVA_HOME: set /p javahome= ) if not "%JAVA_HOME%" == "" ( echo %JAVA_HOME% ) </code></pre> <p>It shows "The syntax of the command is incorrect" where am i going wrong?</p>
7,021,916
2
0
null
2011-08-11 06:44:10.943 UTC
5
2011-08-27 07:13:49.57 UTC
null
null
null
null
707,414
null
1
13
windows|scripting|batch-file
87,708
<p>Try this:</p> <pre><code>@echo off IF "%JAVA_HOME%" == "" ( echo Enter path to JAVA_HOME: set /p JAVA_HOME= ) ELSE ( echo %JAVA_HOME% ) </code></pre>
7,025,186
How to remove or edit Exif from mp4 video?
<p>I recorded a Full HD video with Samsung Galaxy II, when I uploaded it to YouTube I found that it turned to 90 degrees like Portrait layout 1080x1920 NOT 1920x1080. I found the cause of the problem: </p> <blockquote> <p>YouTube is reading video metadata and rotate video acording Exif orientation before encoding</p> </blockquote> <p>This is ExifTool report (please see last tag "Rotation"): <code><pre> ExifTool Version Number : 8.61 File Name : video.mp4 Directory : . File Size : 217 MB File Modification Date/Time : 2011:08:11 00:47:23+04:00 File Permissions : rw-rw-rw- File Type : 3GP MIME Type : video/3gpp Major Brand : 3GPP Media (.3GP) Release 4 Minor Version : 0.3.0 Compatible Brands : 3gp4, 3gp6 Movie Data Size : 227471371 Movie Header Version : 0 Create Date : 1900:01:00 00:00:00 Modify Date : 1900:01:00 00:00:00 Time Scale : 1000 Duration : 0:01:46 Preferred Rate : 1 Preferred Volume : 100.00% Preview Time : 0 s Preview Duration : 0 s Poster Time : 0 s Selection Time : 0 s Selection Duration : 0 s Current Time : 0 s Next Track ID : 3 Track Header Version : 0 Track Create Date : 1900:01:00 00:00:00 Track Modify Date : 1900:01:00 00:00:00 Track ID : 1 Track Duration : 0:01:46 Track Layer : 0 Track Volume : 0.00% Image Width : 1920 Image Height : 1080 Graphics Mode : srcCopy Op Color : 0 0 0 Compressor ID : avc1 Source Image Width : 1920 Source Image Height : 1080 X Resolution : 72 Y Resolution : 72 Bit Depth : 24 Video Frame Rate : 30.023 Matrix Structure : 1 0 0 0 1 0 0 0 1 Media Header Version : 0 Media Create Date : 1900:01:00 00:00:00 Media Modify Date : 1900:01:00 00:00:00 Media Time Scale : 16000 Media Duration : 0:01:46 Handler Type : Audio Track Handler Description : SoundHandler Balance : 0 Audio Format : mp4a Audio Channels : 1 Audio Bits Per Sample : 16 Audio Sample Rate : 16000 Play Mode : SEQ_PLAY Avg Bitrate : 17.1 Mbps Image Size : 1920x1080 Rotation : 90 </pre></code></p> <p>How do I remove whole Exif data or just edit Rotation property?</p>
8,177,749
2
0
null
2011-08-11 11:39:47.653 UTC
13
2015-02-08 19:08:21.597 UTC
2011-08-11 12:21:53.763 UTC
null
889,796
null
889,796
null
1
24
youtube|orientation|quicktime|mp4|exif
33,636
<p>Mp4 files (and many others) use the <a href="http://en.wikipedia.org/wiki/MPEG-4" rel="noreferrer" title="MPEG-4">MPEG-4</a> standard, which arranges the data inside it in little boxes called atoms. You can find a great description of atoms in this <a href="http://atomicparsley.sourceforge.net/mpeg-4files.html" rel="noreferrer" title="page">Page</a>. In short, atoms are organized in a tree like structure, where an atom can be either the parent of other atoms or a container of data, but not both (although some people break this rule)</p> <p>In particular the atom you are looking for is called "tkhd" (Track Header). You can find a list of atoms <a href="http://www.mp4ra.org/atoms.html" rel="noreferrer">here</a>. </p> <p>Within this atom you will find metadata of the video. The structure of the "tkhd" atom is specified <a href="http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-SW1" rel="noreferrer">here</a></p> <p>Finally the chunk of metadata you need (which is not an atom), is called "Matrix Structure". From <a href="http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-18737" rel="noreferrer">developer.apple.com</a>: </p> <blockquote> <p>All values in the matrix are 32-bit fixed-point numbers divided as 16.16, except for the {u, v, w} column, which contains 32-bit fixed-point numbers divided as 2.30.</p> </blockquote> <p>This is shown in the following image:</p> <p><img src="https://i.stack.imgur.com/tW0De.gif" alt="&quot;Matrix Structure&quot; a transformation matrix"></p> <p>The 9 byte matrix starts in byte 48 of the "tkhd" atom. An example of a "matrix structure" for an orientation of 0° would be 1 0 0 0 1 0 0 0 1 (the identity matrix)</p> <p>SO!</p> <p>After all that, what you need is to modify this matrix. The next parragraph is taken from <a href="http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-18737" rel="noreferrer">developer.apple.com</a>: </p> <blockquote> <p>A transformation matrix defines how to map points from one coordinate space into another coordinate space. By modifying the contents of a transformation matrix, you can perform several standard graphics display operations, including translation, rotation, and scaling. The matrix used to accomplish two-dimensional transformations is described mathematically by a 3-by-3 matrix.</p> </blockquote> <p>This means that the transformation matrix defines a function, that maps each coordinate into a new one.</p> <p>Since you only need to rotate the image, simply modify the left most 2 x 3 matrix, which is defined by the bytes 0, 1, 3, 4, 6 and 7.</p> <p>Here are the 2 x 3 matrices I use to represent each orientation (values 0, 1, 3, 4, 6 and 7 of the 3x3 matrix):</p> <p><strong>0°:</strong> (x', y') = (x, y)<br> 1 0<br> 0 1<br> 0 0</p> <p><strong>90°:</strong> (x', y') = (height - y, x)<br> 0 1<br> -1 0<br> height 0</p> <p><strong>180°:</strong> (x', y') = (widht - x, height - y)<br> -1 0<br> 0 -1<br> width height</p> <p><strong>270°:</strong> (x', y') = (y, width - x)<br> 0 -1<br> 1 0<br> 0 width</p> <p>If you don't have them, the width and height can be obtained just after the matrix structure. They are also fixed point numbers of 4 bytes (16.16).</p> <p>It is quite probable your video metadata contains the 90° Matrix </p> <p>(Thanks to Phil Harvey, creator of <a href="http://www.sno.phy.queensu.ca/~phil/exiftool/" rel="noreferrer">Exiftool</a> for his help and a wonderful software)</p>
7,306,367
Is there alternative way to access session details in deferred custom action?
<p>I have a custom action and need to get below values for copying some parts from installation folder to VS2010 folder</p> <ol> <li>VS2010 directory path (<code>VS2010DEVENV</code> property)</li> <li>Installation path (<code>INSTALLLOCATION</code> property)</li> </ol> <p>To give enough privileges, I've set custom action as <code>Execute='deferred' Impersonate='no'</code>. But when running the installer, it logged the message: </p> <blockquote> <p>Cannot access session details from a non-immediate custom action</p> </blockquote> <p>It seems we cannot access a property in a "deferred" custom action (i.e <code>session["VS2010DEVENV"]</code>)</p> <p>Is there any other way so that I can retrieve those values as needed?</p>
7,306,809
2
0
null
2011-09-05 09:49:43.073 UTC
11
2017-06-15 20:40:59.293 UTC
2017-06-15 20:40:59.293 UTC
null
2,642,204
null
553,090
null
1
34
session|wix|windows-installer|custom-action
13,762
<p><a href="http://msdn.microsoft.com/en-us/library/aa370543.aspx" rel="noreferrer">This</a> must be helpful. Pay special attention to the bottom of the page, a guideline of 2 steps how to pass values via <a href="http://msdn.microsoft.com/en-us/library/2w2fhwzz(v=vs.80).aspx" rel="noreferrer">CustomActionData</a>.</p> <p>Here is the excerpt:</p> <blockquote> <p>To write the value of a property into the installation script for use during a deferred execution custom action:</p> <ol> <li>Insert a small custom action into the installation sequence that sets the property of interest to a property having the same name as the deferred execution custom action. For example, if the primary key for the deferred execution custom action is "MyAction" set a property named "MyAction" to the property X which you need to retrieve. You must set the "MyAction" property in the installation sequence before the "MyAction" custom action. Although any type of custom action can set the context data, the simplest method is to use a property assignment custom action (for example Custom Action Type 51).</li> <li>At the time when the installation sequence is processed, the installer will write the value of property X into the execution script as the value of the property CustomActionData.</li> </ol> </blockquote>
31,361,721
python dask DataFrame, support for (trivially parallelizable) row apply?
<p>I recently found <a href="http://dask.pydata.org/en/latest/index.html">dask</a> module that aims to be an easy-to-use python parallel processing module. Big selling point for me is that it works with pandas.</p> <p>After reading a bit on its manual page, I can't find a way to do this trivially parallelizable task: </p> <pre><code>ts.apply(func) # for pandas series df.apply(func, axis = 1) # for pandas DF row apply </code></pre> <p>At the moment, to achieve this in dask, AFAIK,</p> <pre><code>ddf.assign(A=lambda df: df.apply(func, axis=1)).compute() # dask DataFrame </code></pre> <p>which is ugly syntax and is actually slower than outright</p> <pre><code>df.apply(func, axis = 1) # for pandas DF row apply </code></pre> <p>Any suggestion?</p> <p>Edit: Thanks @MRocklin for the map function. It seems to be slower than plain pandas apply. Is this related to pandas GIL releasing issue or am I doing it wrong?</p> <pre><code>import dask.dataframe as dd s = pd.Series([10000]*120) ds = dd.from_pandas(s, npartitions = 3) def slow_func(k): A = np.random.normal(size = k) # k = 10000 s = 0 for a in A: if a &gt; 0: s += 1 else: s -= 1 return s s.apply(slow_func) # 0.43 sec ds.map(slow_func).compute() # 2.04 sec </code></pre>
31,364,127
2
3
null
2015-07-11 20:52:46.553 UTC
21
2019-03-16 19:07:32.487 UTC
2015-07-18 10:05:16.783 UTC
null
839,601
null
1,568,919
null
1
51
python|pandas|parallel-processing|dask
25,076
<h3><code>map_partitions</code></h3> <p>You can apply your function to all of the partitions of your dataframe with the <code>map_partitions</code> function.</p> <pre><code>df.map_partitions(func, columns=...) </code></pre> <p>Note that func will be given only part of the dataset at a time, not the entire dataset like with <code>pandas apply</code> (which presumably you wouldn't want if you want to do parallelism.)</p> <h3><code>map</code> / <code>apply</code></h3> <p>You can map a function row-wise across a series with <code>map</code></p> <pre><code>df.mycolumn.map(func) </code></pre> <p>You can map a function row-wise across a dataframe with <code>apply</code></p> <pre><code>df.apply(func, axis=1) </code></pre> <h3>Threads vs Processes</h3> <p>As of version 0.6.0 <code>dask.dataframes</code> parallelizes with threads. Custom Python functions will not receive much benefit from thread-based parallelism. You could try processes instead</p> <pre><code>df = dd.read_csv(...) df.map_partitions(func, columns=...).compute(scheduler='processes') </code></pre> <h3>But avoid <code>apply</code></h3> <p>However, you should really avoid <code>apply</code> with custom Python functions, both in Pandas and in Dask. This is often a source of poor performance. It could be that if you find a way to do your operation in a vectorized manner then it could be that your Pandas code will be 100x faster and you won't need dask.dataframe at all.</p> <h3>Consider <code>numba</code></h3> <p>For your particular problem you might consider <a href="http://numba.pydata.org/" rel="noreferrer"><code>numba</code></a>. This significantly improves your performance.</p> <pre><code>In [1]: import numpy as np In [2]: import pandas as pd In [3]: s = pd.Series([10000]*120) In [4]: %paste def slow_func(k): A = np.random.normal(size = k) # k = 10000 s = 0 for a in A: if a &gt; 0: s += 1 else: s -= 1 return s ## -- End pasted text -- In [5]: %time _ = s.apply(slow_func) CPU times: user 345 ms, sys: 3.28 ms, total: 348 ms Wall time: 347 ms In [6]: import numba In [7]: fast_func = numba.jit(slow_func) In [8]: %time _ = s.apply(fast_func) # First time incurs compilation overhead CPU times: user 179 ms, sys: 0 ns, total: 179 ms Wall time: 175 ms In [9]: %time _ = s.apply(fast_func) # Subsequent times are all gain CPU times: user 68.8 ms, sys: 27 µs, total: 68.8 ms Wall time: 68.7 ms </code></pre> <p>Disclaimer, I work for the company that makes both <code>numba</code> and <code>dask</code> and employs many of the <code>pandas</code> developers.</p>
37,834,955
How to use 'DISTINCT' in Codeigniter Active Records?
<p>I have a query using active records.</p> <pre><code>$this-&gt;db-&gt;select('reg.users_id,reg.registration_id,reg.device_type'); $this-&gt;db-&gt;join('users as usr','usr.users_id = reg.users_id','left'); $this-&gt;db-&gt;where('usr.users_status',1); $this-&gt;db-&gt;where('reg.users_id',91); $query = $this-&gt;db-&gt;get('users_gcm_registration as reg'); </code></pre> <p>I want to fetch <code>DISTINCT(registration_id)</code>.</p> <p>How can I do that?</p>
37,835,109
5
2
null
2016-06-15 12:04:34.493 UTC
null
2019-01-11 04:18:11.21 UTC
2016-06-20 15:36:44.003 UTC
null
472,495
null
1,170,507
null
1
10
php|activerecord|codeigniter-2
46,896
<p>You can use distinct as</p> <pre><code>$this-&gt;db-&gt;distinct('reg.registration_id'); $this-&gt;db-&gt;select('reg.users_id,reg.device_type'); .... </code></pre> <p>But better use <code>group_by</code></p> <pre><code>$this-&gt;db-&gt;select('reg.users_id,reg.registration_id,reg.device_type'); $this-&gt;db-&gt;join('users as usr','usr.users_id = reg.users_id','left'); $this-&gt;db-&gt;where('usr.users_status',1); $this-&gt;db-&gt;where('reg.users_id',91); $this-&gt;db-&gt;group_by('reg.registration_id');// add group_by $query = $this-&gt;db-&gt;get('users_gcm_registration as reg'); </code></pre>
36,869,443
Restart apache on Docker
<p>I am trying to update my .htaccess file on a Docker container. After updating the file I need to restart Apache. Whenever I try to restart Apache: with the command <code>service apache2 restart</code> I get the following error:</p> <blockquote> <p>(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Action 'start' failed. The Apache error log may have more information. ...fail!</p> </blockquote> <p>When I got to the error log it doesn't have any new errors. This is what my Dockerfile looks like:</p> <pre><code> FROM ubuntu:12.04 # Install dependencies RUN apt-get update -y RUN apt-get install -y git curl apache2 php5 libapache2-mod-php5 php5-mcrypt php5-mysql php5-curl vim # Install app RUN rm -rf /var/www/ * ADD src /var/www # Configure apache RUN a2enmod rewrite RUN chown -R www-data:www-data /var/www ENV APACHE_RUN_USER www-data ENV APACHE_RUN_GROUP www-data ENV APACHE_LOG_DIR /var/log/apache2 EXPOSE 80 CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"] </code></pre>
36,877,604
2
1
null
2016-04-26 15:31:17.507 UTC
1
2019-01-06 11:38:09.57 UTC
2016-04-26 15:36:11.767 UTC
null
2,844,319
null
2,417,339
null
1
5
php|apache|ubuntu|docker|dockerfile
51,708
<p>It's because you are (correctly) not starting apache as a service when you <code>docker run</code> the container. The line:</p> <pre><code>CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"] </code></pre> <p>Starts apache in the foreground. </p> <p>I'm guessing you are then using <code>docker exec</code> to execute a shell in the container to edit the file and restart apache? If so this would explain why the second time you start apache it complains about the existing process.</p> <p>I think if you are using containers in this way then you are really missing out on the benefit of containers which comes when you treat them as immutable and keep the data outside the container (either on your host or in volumes) so that you can easily replace the container. </p> <p>In your case if you need to modify the .htaccess file I think it would be more normal to mount that file into the container by using a command like:</p> <pre><code>docker run -d --name apache -v $(pwd)/.htaccess:/path/to/.htaccess -p 80:80 image:tag </code></pre> <p>Then if you have to change the file and need to restart apache you can use:</p> <pre><code>docker restart apache </code></pre> <p>Although it may be worth investigating the suggestion from Charlotte Dunois that you might not even need to restart apache.</p>
35,691,647
What's the difference between "deletemany" and "remove" in mongodb?
<p>What's the difference between the two commands here?<br> <code>db.collection.deleteMany({condition})</code><br> <code>db.collection.remove({condition})</code></p>
35,692,473
2
1
null
2016-02-29 03:47:58.803 UTC
2
2021-06-23 18:14:17.87 UTC
2016-02-29 04:45:09.89 UTC
null
4,660,897
null
5,960,979
null
1
58
mongodb
48,886
<p>As far as I can say, </p> <blockquote> <p>db.collection.deleteMany </p> </blockquote> <pre><code>Returns: A document containing: &gt; A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled &gt; deletedCount containing the number of deleted documents </code></pre> <p>REF: <a href="https://docs.mongodb.org/manual/reference/method/db.collection.deleteMany/" rel="noreferrer">db.collection.deleteMany</a></p> <p>Where as</p> <blockquote> <p>db.collection.remove</p> </blockquote> <p>return <a href="https://docs.mongodb.org/manual/reference/method/db.collection.remove/#writeresults-remove" rel="noreferrer">WriteResult</a></p> <p>And to remove a single document, there a similar command, <code>db.collection.removeOne</code> where as with <code>db.collection.remove</code> you need to set and option called <code>justOne</code> option to limit delete to 1 document.</p> <p>Otherwise I guess they are similar.</p> <blockquote> <p>node.js drivers</p> </blockquote> <p>When talking about <code>node.js drivers</code>, <code>remove</code> has been deprecated (and may be removed in future releases) and <code>deleteOne</code> or <code>deleteMany</code>.</p> <p>Hope this makes sense ....</p>
3,468,150
Using special auto start servlet to initialize on startup and share application data
<p>I need to get some configuration and connect to external resources/objects/systems somewhere and store it in application scope.</p> <p>I can see two ways to setup my application:</p> <ul> <li>Overriding the <code>init()</code> in the existing servlets and required code there and keeping all constructed objects inside that same servlet.</li> <li>Having some kind of an initialisation servlet and using its <code>init()</code> to do the work. Then storing created objects in <code>ServletContext</code> to share it with my other servlets.</li> </ul> <p>Which out of above is better approach? Is there any better way to share objects between servlets? Calling them directly from one another or so...?</p>
3,468,317
1
0
null
2010-08-12 13:30:23.773 UTC
23
2021-11-16 16:35:40.443 UTC
2015-10-07 09:09:41.413 UTC
null
157,882
null
383,802
null
1
34
servlets|initialization|data-sharing
17,080
<p>None of both is the better approach. Servlets are intended to listen on HTTP events (HTTP requests), not on deployment events (startup/shutdown).</p> <hr /> <h2>CDI/EJB unavailable? Use <a href="https://jakarta.ee/specifications/servlet/5.0/apidocs/jakarta/servlet/servletcontextlistener" rel="nofollow noreferrer"><code>ServletContextListener</code></a></h2> <pre><code>@WebListener public class Config implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { // Do stuff during webapp's startup. } public void contextDestroyed(ServletContextEvent event) { // Do stuff during webapp's shutdown. } } </code></pre> <p>If you're not on Servlet 3.0 yet and can't upgrade (it would be about time because Servlet 3.0 was introduced more than a decade ago), and thus can't use <code>@WebListener</code> annotation, then you need to manually register it in <code>/WEB-INF/web.xml</code> like below:</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt;com.example.Config&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>To store and obtain objects in the application scope (so that all servlets can access them), use <a href="https://jakarta.ee/specifications/servlet/5.0/apidocs/jakarta/servlet/servletcontext#setAttribute(java.lang.String,java.lang.Object)" rel="nofollow noreferrer"><code>ServletContext#setAttribute()</code></a> and <a href="https://jakarta.ee/specifications/servlet/5.0/apidocs/jakarta/servlet/servletcontext#getAttribute(java.lang.String)" rel="nofollow noreferrer"><code>#getAttribute()</code></a>.</p> <p>Here's an example which lets the listener store itself in the application scope:</p> <pre><code> public void contextInitialized(ServletContextEvent event) { event.getServletContext().setAttribute(&quot;config&quot;, this); // ... } </code></pre> <p>and then obtain it in a servlet:</p> <pre><code> protected void doGet(HttpServletRequest request, HttpServletResponse response) { Config config = (Config) getServletContext().getAttribute(&quot;config&quot;); // ... } </code></pre> <p>It's also available in JSP EL by <code>${config}</code>. So you could make it a simple bean as well.</p> <hr /> <h2>CDI available? Use <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/event/observes" rel="nofollow noreferrer"><code>@Observes</code></a> on <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/applicationscoped" rel="nofollow noreferrer"><code>ApplicationScoped.class</code></a></h2> <pre><code>import jakarta.enterprise.context.ApplicationScoped; // And thus NOT e.g. jakarta.faces.bean.ApplicationScoped @ApplicationScoped public class Config { public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext context) { // Do stuff during webapp's startup. } public void destroy(@Observes @Destroyed(ApplicationScoped.class) ServletContext context) { // Do stuff during webapp's shutdown. } } </code></pre> <p>This is available in a servlet via <code>@Inject</code>. Make it if necessary also <code>@Named</code> so it's available via <code>#{config}</code> in EL as well.</p> <p>Noted should be that this is new since CDI 1.1. If you're still on CDI 1.0 and can't upgrade, then pick another approach.</p> <p>In case you're curious how to install CDI on a non-JEE server such as Tomcat, head to: <a href="https://stackoverflow.com/questions/18995951/how-to-install-and-use-cdi-on-tomcat">How to install and use CDI on Tomcat?</a></p> <hr /> <h2>EJB available? Consider <a href="https://jakarta.ee/specifications/enterprise-beans/4.0/apidocs/jakarta/ejb/startup" rel="nofollow noreferrer"><code>@Startup</code></a><a href="https://jakarta.ee/specifications/enterprise-beans/4.0/apidocs/jakarta/ejb/singleton" rel="nofollow noreferrer"><code>@Singleton</code></a></h2> <pre><code>@Startup @Singleton public class Config { @PostConstruct public void init() { // Do stuff during webapp's startup. } @PreDestroy public void destroy() { // Do stuff during webapp's shutdown. } } </code></pre> <p>This is available in a servlet via <code>@EJB</code>. The difference with other approaches is that it's by default transactional and in case of <code>@Singleton</code> also read/write locked. So if you would ever need to inject a random EJB (e.g. <code>@Stateless</code>) into a <code>@WebListener</code> or an <code>@ApplicationScoped</code> then you could basically as good merge both into a single <code>@Startup @Singleton</code>.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/4691132/how-to-run-a-background-task-in-a-servlet-application/">How to run a background task in a servlet based web application?</a></li> <li><a href="https://stackoverflow.com/questions/10776599/servletcontainerinitializer-vs-servletcontextlistener/">ServletContainerInitializer vs ServletContextListener</a></li> <li><a href="https://stackoverflow.com/questions/3600534/how-do-i-force-an-application-scoped-bean-to-instantiate-at-application-startup/">How do I force an application-scoped bean to instantiate at application startup?</a></li> </ul>
21,005,643
Container is running beyond memory limits
<p>In Hadoop v1, I have assigned each 7 mapper and reducer slot with size of 1GB, my mappers &amp; reducers runs fine. My machine has 8G memory, 8 processor. Now with YARN, when run the same application on the same machine, I got container error. By default, I have this settings:</p> <pre><code> &lt;property&gt; &lt;name&gt;yarn.scheduler.minimum-allocation-mb&lt;/name&gt; &lt;value&gt;1024&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.maximum-allocation-mb&lt;/name&gt; &lt;value&gt;8192&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.resource.memory-mb&lt;/name&gt; &lt;value&gt;8192&lt;/value&gt; &lt;/property&gt; </code></pre> <p>It gave me error:</p> <pre><code>Container [pid=28920,containerID=container_1389136889967_0001_01_000121] is running beyond virtual memory limits. Current usage: 1.2 GB of 1 GB physical memory used; 2.2 GB of 2.1 GB virtual memory used. Killing container. </code></pre> <p>I then tried to set memory limit in mapred-site.xml:</p> <pre><code> &lt;property&gt; &lt;name&gt;mapreduce.map.memory.mb&lt;/name&gt; &lt;value&gt;4096&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;mapreduce.reduce.memory.mb&lt;/name&gt; &lt;value&gt;4096&lt;/value&gt; &lt;/property&gt; </code></pre> <p>But still getting error:</p> <pre><code>Container [pid=26783,containerID=container_1389136889967_0009_01_000002] is running beyond physical memory limits. Current usage: 4.2 GB of 4 GB physical memory used; 5.2 GB of 8.4 GB virtual memory used. Killing container. </code></pre> <p>I'm confused why the the map task need this much memory. In my understanding, 1GB of memory is enough for my map/reduce task. Why as I assign more memory to container, the task use more? Is it because each task gets more splits? I feel it's more efficient to decrease the size of container a little bit and create more containers, so that more tasks are running in parallel. The problem is how can I make sure each container won't be assigned more splits than it can handle? </p>
21,008,262
9
2
null
2014-01-08 20:18:01.757 UTC
58
2021-04-24 18:05:30.61 UTC
2014-01-09 16:24:27.097 UTC
null
2,367,983
null
2,367,983
null
1
91
hadoop|mapreduce|hadoop-yarn|mrv2
149,218
<p>You should also properly configure the maximum memory allocations for MapReduce. From <a href="https://web.archive.org/web/20170610145449/http://hortonworks.com/blog/how-to-plan-and-configure-yarn-in-hdp-2-0/" rel="noreferrer">this HortonWorks tutorial</a>:</p> <blockquote> <p>[...]</p> <p>Each machine in our cluster has 48 GB of RAM. Some of this RAM should be >reserved for Operating System usage. On each node, we’ll assign 40 GB RAM for >YARN to use and keep 8 GB for the Operating System</p> <p>For our example cluster, we have the minimum RAM for a Container (yarn.scheduler.minimum-allocation-mb) = 2 GB. We’ll thus assign 4 GB for Map task Containers, and 8 GB for Reduce tasks Containers.</p> <p>In mapred-site.xml:</p> <p><code>mapreduce.map.memory.mb</code>: 4096</p> <p><code>mapreduce.reduce.memory.mb</code>: 8192</p> <p>Each Container will run JVMs for the Map and Reduce tasks. The JVM heap size should be set to lower than the Map and Reduce memory defined above, so that they are within the bounds of the Container memory allocated by YARN.</p> <p>In mapred-site.xml:</p> <p><code>mapreduce.map.java.opts</code>: <code>-Xmx3072m</code></p> <p><code>mapreduce.reduce.java.opts</code>: <code>-Xmx6144m</code></p> <p>The above settings <strong>configure the upper limit of the physical RAM that Map and Reduce tasks will use</strong>. </p> </blockquote> <p>To sum it up:</p> <ol> <li>In YARN, you should use the <code>mapreduce</code> configs, not the <code>mapred</code> ones. <strong>EDIT:</strong> This comment is not applicable anymore now that you've edited your question.</li> <li>What you are configuring is actually how much you want to request, not what is the max to allocate.</li> <li>The max limits are configured with the <code>java.opts</code> settings listed above.</li> </ol> <p>Finally, you may want to check this other <a href="https://stackoverflow.com/questions/20803577/hadoop-yarn-container-does-not-allocate-enough-space/">SO question</a> that describes a similar problem (and solution).</p>
40,809,530
Single file of a multi-files gist on Medium.com
<p>Does anyone know a way to include a single file of a multi-file gist into a medium post? </p> <p>I've tried, without luck, the solutions proposed here:</p> <ul> <li><a href="https://stackoverflow.com/questions/14206307/how-do-i-embed-a-single-file-from-a-github-gist-with-the-new-gist-interface">How do I embed a single file from a GitHub gist with the new gist interface?</a></li> <li><a href="https://blog.medium.com/yes-we-get-the-gist-1c2a27cdfc22" rel="noreferrer">Yes, we get the gist</a></li> </ul> <p>Thanks, M.</p>
64,728,065
2
2
null
2016-11-25 16:52:28.013 UTC
14
2020-11-07 14:10:48.71 UTC
2017-09-26 22:33:20.307 UTC
null
8,048,497
null
1,871,890
null
1
50
gist|medium.com
3,220
<h1>2020 - It is possible! </h1> <p>There is a way for that <strong>without</strong> using <code>&lt;script&gt;</code>, but it's kind of tricky:</p> <blockquote> <p>⚠️ The order matters!</p> </blockquote> <ol> <li>Copy the (multi-file) gist path. e.g.:</li> </ol> <pre><code>https://gist.github.com/MojtabaHs/91e34fd0e987fe7ce801936dc6ece0e8 </code></pre> <hr /> <ol start="2"> <li>Paste it somewhere else than the Medium article. Like an online textbox:</li> </ol> <p><a href="https://i.stack.imgur.com/MPLKH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MPLKH.png" alt="Demo" /></a></p> <p><sub>⚠️ Do not hit search or return button</sub></p> <hr /> <ol start="3"> <li>Append the query param for the file to the URL. e.g:</li> </ol> <pre><code>https://gist.github.com/MojtabaHs/91e34fd0e987fe7ce801936dc6ece0e8?file=Interface.swift </code></pre> <p><sub>Note that <code>?file=Interface.swift</code> at the end of the URL, right?</sub></p> <hr /> <ol start="4"> <li>Copy and paste it in the article and see the magic </li> </ol> <h3>An article using this method:</h3> <p><strong><a href="https://mojtabahs.medium.com/implement-custom-activity-indicator-in-the-swiftui-9e0f3d4155e4" rel="noreferrer">Implement Custom Activity Indicator With The SwiftUI</a></strong></p> <hr /> <h1>The MOST Important note that MUST be considered:</h1> <p>⚠️ Note that you <strong>MUST</strong> copy an unformatted plain text in the medium and <strong>MUST NOT</strong> edit the URL after pasting it in the Medium! You can copy the link in an online textbox like google.com and after appending the query, copy it back and paste it in the Medium.</p>
41,163,506
Excel merge cell date and time
<p>I want merge cell in Excel 2013 column date (2016-01-01) and column time (16:00:00),</p> <p>How do I format cells to get <strong>2016-01-01 16:00:00</strong> ?</p> <p>Here is my example <a href="https://postimg.org/image/clxeqb66h/" rel="noreferrer">https://postimg.org/image/clxeqb66h/</a></p> <p>I get <code>42677 16:00:00</code></p>
41,163,618
3
2
null
2016-12-15 11:51:23.177 UTC
1
2020-01-12 23:11:10.13 UTC
2016-12-15 12:38:32.513 UTC
null
238,978
null
5,908,200
null
1
13
excel|datetime|ms-office
46,038
<p>You can achieve this by using TEXT function.</p> <p>As long as the date is on the A1 cell..</p> <pre><code>=TEXT(A1,"YYYY-MM-DD") =TEXT(A1,"HH:MM:SS") </code></pre>
1,878,640
Including rake tasks in gems
<p>1) Is there a 'best' place for rake tasks inside of gems? I've seen them in <code>/tasks</code>, <code>/lib/tasks</code>, and I've seen them written as <code>*.rb</code> and <code>*.rake</code> -- not sure which (if any) is 'correct'</p> <p>2) How do I make them available to the app once the gem is configured in the environment?</p>
5,444,867
3
2
null
2009-12-10 04:29:07.703 UTC
12
2018-07-22 15:16:05.267 UTC
2018-07-22 15:16:05.267 UTC
null
2,252,927
null
115,462
null
1
61
ruby-on-rails|ruby|rubygems|rake
17,582
<p>On Rails 3, you do this via Railties. Here's the code to do it for a gem I just made:</p> <pre><code>class BackupTask &lt; Rails::Railtie rake_tasks do Dir[File.join(File.dirname(__FILE__),'tasks/*.rake')].each { |f| load f } end end </code></pre> <p>So you basically create a class that inherits from <code>Rails::Railtie</code>, then within that class you have a <code>rake_tasks</code> block that loads the relevant files. You must load instead of require if you want to use a <code>.rake</code> extension.</p> <p>I found that I need to specify the full path to <code>Dir</code> (hence the <code>File.join</code> gymnastics). If I just wanted to list the file explicitly then I could get away with just saying <code>load 'tasks/foo.rake'</code> because the <code>/lib</code> dir of my gem was in the load path.</p>
1,432,485
Coding Katas for practicing the refactoring of legacy code
<p>I've gotten quite interested in coding katas in recent months. I believe they are a great way to hone my programming skills and improve the quality of the code I write on the job.</p> <p>There are numerous places where Katas can be found. like..</p> <p><a href="http://codekata.pragprog.com/" rel="noreferrer">http://codekata.pragprog.com/</a></p> <p><a href="http://schuchert.wikispaces.com/Katas" rel="noreferrer">http://schuchert.wikispaces.com/Katas</a></p> <p><a href="http://www.codingdojo.org/" rel="noreferrer">http://www.codingdojo.org/</a></p> <p>I've found these to be excellent repositories of Katas... my attempts at some of them have been been immensely rewarding.</p> <p>However, I feel that all the Kata's I've seen so far have one short coming. None of them seem to allow me to practice refactoring bad code. It's great learning how to write clean code the first time around...but in my current job, I don't have too many opportunities to write new code. Rather I'm often battling against legacy code and trying to figure out how to refactor modules, eliminate dependencies, and reduce coupling.</p> <p>As such, I'm on the look out for a couple Katas that I can use to hone my skills of refactoring legacy code and turning it into clean code.</p> <p>Does anyone know of any that already exist? I know I get a lot of practice at it while I'm at work...but I'd like to hone my skills to the point where I'm able to quickly see how to break apart dependencies and separate concerns in classes that do far too much.</p>
1,475,658
3
4
null
2009-09-16 11:50:17.077 UTC
71
2016-02-25 22:36:16.4 UTC
2015-05-16 08:06:09.147 UTC
null
1,559,201
null
39,532
null
1
128
refactoring|legacy-code
16,774
<p>I don't know of a site that catalogs them directly, but one strategy that I've used on occasion is this:</p> <ol> <li>Find an old, small, unmaintained open source project on sourceforge</li> <li>Download it, get it to compile/build/run</li> <li>Read the documentation, get a feel for the code</li> <li>Use the techniques in <em>Working Effectively with Legacy Code</em> to get a piece of it under test</li> <li>Refactor that piece, perhaps fixing bugs and adding features along the way</li> <li>Repeat steps 4 through 6</li> </ol> <p>When you find a part that was especially challenging, throw away your work and repeat it a couple times to reinforce your skills.</p> <p>This doesn't just practice refactoring, but other skills like code reading, testing, and dealing with build processes.</p> <p>The hardest problem is finding a project that you're interested enough in to keep working in. The last one I worked on was a python library for genetic programming, and the current one I'm working on is a IRC library for Java.</p>
27,139,366
Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?
<p>I understand why <code>componentDidMount</code> is appropriate for anything that requires DOM access, but an AJAX request doesn’t necessarily or usually need this.</p> <p>What gives?</p>
27,139,507
3
3
null
2014-11-26 00:32:06.807 UTC
34
2020-08-29 09:46:38.85 UTC
2020-08-29 09:46:38.85 UTC
null
472,495
null
211,327
null
1
102
reactjs
25,291
<p><code>componentDidMount</code> is for side effects. Adding event listeners, AJAX, mutating the DOM, etc. </p> <p><code>componentWillMount</code> is rarely useful; especially if you care about server side rendering (adding event listeners causes errors and leaks, and lots of other stuff that can go wrong).</p> <p>There is talk about removing <code>componentWillMount</code> from class components since it serves the same purpose as the constructor. It will remain on <code>createClass</code> components.</p>
961,238
jQuery - Append JavaScript to a Div
<p>I'm using <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a> to append some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> when an item is expanded.</p> <p>But the JavaScript code inside of the jQuery function is causing the rest of the jQuery code to explode.</p> <pre><code>$(this).parent('li').find('.moreInfo').append('&lt;script&gt;alert("hello");&lt;/script&gt;'); </code></pre> <p>What can I do to solve this problem?</p>
961,306
4
4
null
2009-06-07 05:15:00.15 UTC
1
2017-12-30 01:23:18.297 UTC
2010-02-03 20:54:32.35 UTC
null
63,550
null
105,008
null
1
13
javascript|jquery
39,727
<p>For the appending JavaScript problem use this:</p> <pre><code>var str="&lt;script&gt;alert('hello');"; str+="&lt;"; str+="/script&gt;"; $(this).parent('li').find('.moreInfo').append(str); </code></pre> <p>Otherwise a better option will be to wire-up <strong>li's</strong> click event:</p> <pre><code> $("ul#myList li").click(function(){ $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "url to your content page", data: "{}",//any data that you want to send to your page/service dataType: "json", success: function(msg) { $(this).find('.moreInfo').append(msg); } }); }); </code></pre> <p>Actually I don't know what language are you using. If you are using <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> please read this <a href="http://encosia.com/category/aspnet/" rel="noreferrer">blog</a> by Dave.</p>
488,194
Deploy jQuery using a SharePoint Feature or physical files?
<p>We are about to undertake a rather large customization of SharePoint and I wanted to get some feedback prior to jumping in with both feet. One of the issues we are kicking the tires on is do we deploy the jQuery javascript library to the 12 hive directly (making it available in _layouts for each site etc.) or do we wrap it up in a feature and activate that feature for each site? I have also seen two projects on CodePlex that wrap it up in features and that could be a third option I guess.</p> <p>Thoughts?</p>
488,243
4
0
null
2009-01-28 16:03:42.577 UTC
9
2011-04-29 19:07:32.08 UTC
2009-07-04 09:40:40.643 UTC
null
6,651
Goyuix
243
null
1
15
jquery|sharepoint
14,880
<p>options and commentary on <a href="http://www.sharepointblogs.com/rohan/archive/2008/11/20/sharepoint-and-jquery.aspx" rel="noreferrer">www.sharepointblogs.com</a></p> <p>follow the link above or google it.</p> <p>Summary is that modifying the 12 hive directly is easy but unsupported (i.e. Microsoft reserves the right to destroy your environment at will)</p> <p>recommended option on above link is:</p> <blockquote> <p>Use the AdditionalPageHead Delegate Control (my favorite!)</p> <p>By providing the contents for the AdditionalPageHead Delegate Control that is used by all the out-of-the-box master pages, you can make sure the the jQuery library is loaded by all the SharePoint pages. The AdditionalPageHead Delegate Control allows multiple controls to provide contents, so it’s a great extensibility scenario. To accomplish this you need to build a web user control (ASCX file), that contains the script tag to load the jQuery library:</p> </blockquote> <pre><code>&lt;%@ Control Language=&quot;VB&quot; ClassName=&quot;jQueryControl&quot; %&gt; </code></pre>
612,805
Arrow keys with NSTableView
<p>Is it possible to navigate an NSTableView's editable cell around the NSTableView using arrow keys and enter/tab? For example, I want to make it feel more like a spreadsheet.</p> <p>The users of this application are expected to edit quite a lot of cells (but not all of them), and I think it would be easier to do so if they didn't have to double-click on each cell.</p>
617,221
4
0
null
2009-03-04 22:43:30.787 UTC
9
2011-02-06 02:33:23.95 UTC
null
null
null
dreamlax
10,320
null
1
15
objective-c|cocoa|macos
5,942
<p>Well it isn't easy but I managed to do it without having to use RRSpreadSheet or even another control. Here's what you have to do:</p> <ol> <li><p>Create a subclass of <code>NSTextView</code>, this will be the field editor. For this example the name <code>MyFieldEditorClass</code> will be used and <code>myFieldEditor</code> will refer to an instance of this class.</p></li> <li><p>Add a method to <code>MyFieldEditorClass</code> called "<code>- (void) setLastKnownColumn:(unsigned)aCol andRow:(unsigned) aRow</code>" or something similar, and have it save both the input parameter values somewhere.</p></li> <li><p>Add another method called "setTableView:" and have it save the NSTableView object somewhere, or unless there is another way to get the NSTableView object from the field editor, use that.</p></li> <li><p>Add another method called <code>- (void) keyDown:(NSEvent *) event</code>. This is actually overriding the <code>NSResponder</code>'s <code>keyDown:</code>. The source code should be (be aware that StackOverflow's MarkDown is changing <code>&lt;</code> and <code>&gt;</code> to <code>&amp;lt;</code> and <code>&amp;gt;</code>):</p> <pre><code>- (void) keyDown:(NSEvent *) event { unsigned newRow = row, newCol = column; switch ([event keyCode]) { case 126: // Up if (row) newRow = row - 1; break; case 125: // Down if (row &lt; [theTable numberOfRows] - 1) newRow = row + 1; break; case 123: // Left if (column &gt; 1) newCol = column - 1; break; case 124: // Right if (column &lt; [theTable numberOfColumns] - 1) newCol = column + 1; break; default: [super keyDown:event]; return; } [theTable selectRow:newRow byExtendingSelection:NO]; [theTable editColumn:newCol row:newRow withEvent:nil select:YES]; row = newRow; column = newCol; } </code></pre></li> <li><p>Give the NSTableView in your nib a delegate, and in the delegate add the method:</p> <pre><code>- (BOOL) tableView:(NSTableView *)aTableView shouldEditColumn:(NSTableColumn *) aCol row:aRow { if ([aTableView isEqual:TheTableViewYouWantToChangeBehaviour]) [myFieldEditor setLastKnownColumn:[[aTableView tableColumns] indexOfObject:aCol] andRow:aRow]; return YES; } </code></pre></li> <li><p>Finally, give the Table View's main window a delegate and add the method:</p> <pre><code>- (id) windowWillReturnFieldEditor:(NSWindow *) aWindow toObject:(id) anObject { if ([anObject isEqual:TheTableViewYouWantToChangeBehaviour]) { if (!myFieldEditor) { myFieldEditor = [[MyFieldEditorClass alloc] init]; [myFieldEditor setTableView:anObject]; } return myFieldEditor; } else { return nil; } } </code></pre></li> </ol> <p>Run the program and give it a go!</p>
475,758
How to determine the platform Qt is running on at runtime?
<p>Is there a (Qt) way to determine the platform a Qt application is running on at runtime?</p>
476,450
4
0
null
2009-01-24 08:54:53.827 UTC
7
2021-09-22 20:03:19.9 UTC
2013-03-07 08:13:43.29 UTC
null
24,587
andreas buykx
19,863
null
1
28
qt|qt4|cross-platform
27,672
<p>Note that the Q_WS_* macros are defined at compile time, but QSysInfo gives some run time details.</p> <p>To extend gs's function to get the specific windows version at runtime, you can do</p> <pre><code>#ifdef Q_WS_WIN switch(QSysInfo::windowsVersion()) { case QSysInfo::WV_2000: return &quot;Windows 2000&quot;; case QSysInfo::WV_XP: return &quot;Windows XP&quot;; case QSysInfo::WV_VISTA: return &quot;Windows Vista&quot;; default: return &quot;Windows&quot;; } #endif </code></pre> <p>and similar for Mac.</p> <p>If you are using a Qt version 5.9 or above, kindly use the below mentioned library function to retrieve correct OS details, more on this can be found <a href="https://doc.qt.io/qt-5/qoperatingsystemversion.html" rel="nofollow noreferrer">here</a>. There is also a <a href="https://doc.qt.io/qt-5/qsysinfo.html" rel="nofollow noreferrer">QSysInfo</a> class which can do some additional functionalities.</p> <pre><code>#ifdef Q_WS_WIN #include &lt;QOperatingSystemVersion&gt; switch(QOperatingSystemVersion::current()) { case QOperatingSystemVersion::Windows7: return &quot;Windows 7&quot;; case QOperatingSystemVersion::Windows8: return &quot;Windows 8&quot;; case QOperatingSystemVersion::Windows10: return &quot;Windows 10&quot;; default: return &quot;Windows&quot;; } #endif </code></pre>
897,743
How to find a DLL given a CLSID?
<p>I have a situation in which a managed DLL calls some unmanaged DLL. I know the CLSID of the unmanaged DLL, is there any way to find out what binary file houses that CLSID?</p>
897,766
4
1
null
2009-05-22 13:07:23.457 UTC
3
2021-04-19 09:59:49.863 UTC
null
null
null
null
84,720
null
1
30
dll|clsid
43,251
<p>Normaly, you can just go to:</p> <p>HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\"GUID"</p> <p>And find a key called "InProcServer32" for instance and there will be the default value that has the DLL. This is one simple way to do it.</p>
1,033,424
How to remove bad path characters in Python?
<p>What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?</p> <h3>Solution</h3> <p>Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:</p> <pre><code>def remove(value, deletechars): for c in deletechars: value = value.replace(c,'') return value; print remove(filename, '\/:*?"&lt;&gt;|') </code></pre>
1,033,669
4
2
null
2009-06-23 15:45:39.697 UTC
7
2021-10-12 00:37:45.747 UTC
2020-11-28 21:23:23.683 UTC
null
42,223
null
25,782
null
1
42
python|path|illegal-characters
32,953
<p>Unfortunately, the set of acceptable characters varies by OS <em>and</em> by filesystem.</p> <ul> <li><p><a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx" rel="noreferrer">Windows</a>:</p> <blockquote> <ul> <li>Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following: <ul> <li>The following reserved characters are not allowed:<br> &lt; &gt; : " / \ | ? *</li> <li>Characters whose integer representations are in the range from zero through 31 are not allowed.</li> <li>Any other character that the target file system does not allow.</li> </ul></li> </ul> </blockquote> <p>The list of accepted characters can vary depending on the OS and locale of the machine that first formatted the filesystem.</p> <p>.NET has <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx" rel="noreferrer">GetInvalidFileNameChars</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx" rel="noreferrer">GetInvalidPathChars</a>, but I don't know how to call those from Python.</p></li> <li>Mac OS: NUL is always excluded, "/" is excluded from POSIX layer, ":" excluded from Apple APIs <ul> <li>HFS+: any sequence of non-excluded characters that is representable by UTF-16 in the Unicode 2.0 spec</li> <li>HFS: any sequence of non-excluded characters representable in MacRoman (default) or other encodings, depending on the machine that created the filesystem</li> <li>UFS: same as HFS+</li> </ul></li> <li>Linux: <ul> <li>native (UNIX-like) filesystems: any byte sequence excluding NUL and "/"</li> <li>FAT, NTFS, other non-native filesystems: varies</li> </ul></li> </ul> <p>Your best bet is probably to either be overly-conservative on all platforms, or to just try creating the file name and handle errors.</p>
48,634,459
scrollIntoView block vs inline
<p>I noticed <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView" rel="noreferrer"><code>scrollIntoView</code></a> has some new options since last I looked.</p> <p>Namely, <code>block</code> and <code>inline</code>. What's the difference between these two? I'm <em>guessing</em> <code>{block: "start"}</code> will align the top of the element with the top of the page, but I'm not sure how that would be different from <code>inline</code>, or how you would use both these options simultaneously?</p>
48,635,751
1
0
null
2018-02-06 02:16:02.97 UTC
12
2020-03-03 13:46:22.617 UTC
2020-03-03 13:46:22.617 UTC
null
3,211,932
null
65,387
null
1
41
javascript|js-scrollintoview
28,553
<p>The <code>block</code> option decides where the element will be vertically aligned inside the visible area of its scrollable ancestor:</p> <ul> <li>Using <code>{block: "start"}</code>, the element is aligned at the top of its ancestor.</li> <li>Using <code>{block: "center"}</code>, the element is aligned at the middle of its ancestor.</li> <li>Using <code>{block: "end"}</code>, the element is aligned at the bottom of its ancestor.</li> <li>Using <code>{block: "nearest"}</code>, the element: <ul> <li>is aligned at the top of its ancestor if you're currently below it.</li> <li>is aligned at the bottom of its ancestor if you're currently above it.</li> <li>stays put, if it's already in view.</li> </ul></li> </ul> <p>The <code>inline</code> option decides where the element will be horizontally aligned inside the visible area of its scrollable ancestor:</p> <ul> <li>Using <code>{inline: "start"}</code>, the element is aligned at the left of its ancestor.</li> <li>Using <code>{inline: "center"}</code>, the element is aligned at the centre of its ancestor.</li> <li>Using <code>{inline: "end"}</code>, the element is aligned at the right of its ancestor.</li> <li>Using <code>{inline: "nearest"}</code>, the element: <ul> <li>is aligned at the left of its ancestor if you're currently on its right.</li> <li>is aligned at the right of its ancestor if you're currently on its left.</li> <li>stays put, if it's already in view.</li> </ul></li> </ul> <p>Both <code>block</code> and <code>inline</code> can be used at the same time to scroll to a specified point in one motion.</p> <p>Check out the following snippet to see how each works in action.</p> <p><strong>Snippet:</strong></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/* ----- JavaScript ----- */ var buttons = document.querySelectorAll(".btn"); [].forEach.call(buttons, function (button) { button.onclick = function () { var where = this.dataset.where.split("-"); document.querySelector("div#a1").scrollIntoView({ behavior: "smooth", block: where[0], inline: where[1] }); }; });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* ----- CSS ----- */ body { padding: 500px; width: 2000px; } header { position: fixed; top: 0; left: 0; width: 100; } div#a1 { width: 1000px; height: 300px; background: url(//www.w3schools.com/css/trolltunga.jpg); background-repeat: no-repeat; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!----- HTML -----&gt; &lt;header&gt; &lt;button class="btn" data-where="start-start"&gt;T-L&lt;/button&gt; &lt;button class="btn" data-where="start-center"&gt;T-C&lt;/button&gt; &lt;button class="btn" data-where="start-end"&gt;T-R&lt;/button&gt; &lt;button class="btn" data-where="center-start"&gt;C-L&lt;/button&gt; &lt;button class="btn" data-where="center-center"&gt;C-C&lt;/button&gt; &lt;button class="btn" data-where="center-end"&gt;C-R&lt;/button&gt; &lt;button class="btn" data-where="end-start"&gt;B-L&lt;/button&gt; &lt;button class="btn" data-where="end-center"&gt;B-C&lt;/button&gt; &lt;button class="btn" data-where="end-end"&gt;B-R&lt;/button&gt; &lt;/header&gt; &lt;div id = "a1"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
48,668,660
docker no space left on device macOS
<p>I am trying to build a docker image that requires copying some large files (~75GB) and I'm getting the following error when I run the following: </p> <pre><code>$ docker build -t my-project . </code></pre> <pre><code>Step 8/10 : COPY some-large-directory failed to copy files: failed to copy directory: Error processing tar file(exit status 1): write /directory: no space left on device </code></pre> <p>I think the error is caused by the container running out of space (I already increased the docker disk image size to 160GB using docker preferences). If so how can I increase the maximum container size on macOS (high sierra) (I read the default is 100GB)?</p>
56,797,529
3
0
null
2018-02-07 16:26:04.89 UTC
11
2020-10-09 10:48:04.513 UTC
2019-06-27 19:33:48.4 UTC
null
425,313
null
3,957,721
null
1
56
macos|docker|containers
46,488
<p>Docker objects accumulate over time, so with heavy usage you can eventually exhaust the available storage. You can confirm that this is the issue with <a href="https://docs.docker.com/engine/reference/commandline/system_df/" rel="noreferrer">docker system df</a>:</p> <pre><code>docker system df </code></pre> <p>You can start reclaiming some space by doing a prune of your unused objects, a couple examples:</p> <pre><code># Prune everything docker system prune # Only prune images docker image prune </code></pre> <p>Be sure to read the <a href="https://docs.docker.com/config/pruning/" rel="noreferrer">Prune unused Docker objects</a> documentation first to make sure you understand what you'll be discarding.</p> <p>If you really can't reclaim enough space by discarding objects, then you can always <a href="https://docs.docker.com/docker-for-mac/space/" rel="noreferrer">allocate more disk space</a>.</p>
42,438,587
'bash' is not recognized as an internal or external command
<p>i have an error in installing react-flux-starter-kit-windows. i have installed latest node.js and npm when i am using this command : npm install -g react-flux-starter-kit it gives me following error</p> <pre><code>[email protected] postinstall C:\Users\Hardik\AppData\Roaming\npm\node_modules\react-flux-starter-kit bash setup.sh 'bash' is not recognized as an internal or external command, operable program or batch file. npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\Hardik\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "install" "-g" "react-flux-starter-kit" npm ERR! node v6.9.5 npm ERR! npm v4.2.0 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] postinstall: bash setup.sh npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] postinstall script 'bash setup.sh'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the react-flux-starter-kit package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! bash setup.sh npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs react-flux-starter-kit npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls react-flux-starter-kit npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! C:\Users\Hardik\AppData\Roaming\npm-cache_logs\2017-02-22T10_01_48_356Z-debug.log </code></pre>
42,439,350
4
0
null
2017-02-24 12:24:20.69 UTC
0
2021-11-21 03:10:22.423 UTC
2019-11-22 06:47:28.077 UTC
null
5,743,249
null
5,743,249
null
1
14
node.js|reactjs|bash|npm
92,444
<p>It seems that it needs Bash installed. If you're using Windows then you may be able to install it using one of:</p> <ul> <li><a href="https://git-for-windows.github.io/" rel="noreferrer">https://git-for-windows.github.io/</a></li> <li><a href="https://www.cygwin.com/" rel="noreferrer">https://www.cygwin.com/</a></li> <li><a href="https://msdn.microsoft.com/en-us/commandline/wsl/about" rel="noreferrer">https://msdn.microsoft.com/en-us/commandline/wsl/about</a></li> <li><a href="http://win-bash.sourceforge.net/" rel="noreferrer">http://win-bash.sourceforge.net/</a></li> </ul>
60,368,017
'await' has no effect on the type of this expression
<p>I searched about this but I didn't find anything specific for what I need. If there is one, please, share here.</p> <p>I'm trying to create a generic service to be called in various components. Since it's a function that requests data from an external source, I need to treat it as an asynchronous function. Problem is, the editor returns the message "'await' has no effect on the type of this expression". And the app indeed crashes since there is no data yet.</p> <p><strong>People.js calls the service requests.js</strong></p> <pre><code>import React, { useEffect, useState } from "react"; import requests from "../services/requests"; export default () =&gt; { // State const [ people, setPeople ] = useState({ count: null, next: null, previous: null, results: [] }); // Tarefas iniciais useEffect(() =&gt; { carregarpeople(1); }, []); // Carregando os dados da API const carregarpeople = async (pageIndex) =&gt; { const peopleResponse = await requests("people", pageIndex); // This line below needs to be executed but it crashes the app since I need to populate it with the data from the function requests // setPeople(peopleResponse); } return ( &lt;div&gt; { people.results.length &gt; 0 ? ( &lt;ul&gt; { people.results.map(person =&gt; &lt;li key = { person.name }&gt;{ person.name }&lt;/li&gt;) } &lt;/ul&gt; ) : &lt;div&gt;Loading...&lt;/div&gt; } &lt;/div&gt; ) } </code></pre> <p><strong>And this is requests.js, where it returns the json from API</strong></p> <pre><code>export default (type, id) =&gt; { console.table([ type, id ]); fetch(`https://swapi.co/api/${type}/?page=${id}`) .then(response =&gt; response.json()) .then(json =&gt; { console.log(json); return json; })} </code></pre> <p><a href="https://i.stack.imgur.com/TMZTj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TMZTj.png" alt="enter image description here"></a></p>
60,368,041
5
0
null
2020-02-23 23:52:06.477 UTC
5
2022-09-05 07:49:23.94 UTC
2020-02-24 00:19:44.003 UTC
null
1,218,980
null
11,396,618
null
1
35
javascript|reactjs|async-await
64,313
<p><code>await</code> is only useful if you use it with a promise, but <code>requests</code> does not return a promise. It doesn't have a return statement at all, so it's implicitly returning <code>undefined</code>. </p> <p>Looks like you meant for it to return a promise, so here's your code with the return added in:</p> <pre><code>export default (type, id) =&gt; { console.table([ type, id ]); return fetch(`https://swapi.co/api/${type}/?page=${id}`) .then(response =&gt; response.json()) .then(json =&gt; { console.log(json); return json; }) } </code></pre> <p>p.s, if you prefer to do this using <code>async</code>/<code>await</code>, it would look like:</p> <pre><code>export default async (type, id) =&gt; { console.table([ type, id ]); const response = await fetch(`https://swapi.co/api/${type}/?page=${id}`); const json = await response.json(); console.log(json); return json; } </code></pre>
59,810,838
How to get the short sha for the github workflow?
<p>I am creating a workflow in GitHub which creates and uses a docker image. Therefore I have started my workflow file with a global environment variable for this docker image which is visible for all the jobs in my workflow:</p> <pre><code>name: continuous integration on: push: branches: - '**' env: IMAGE: docker.pkg.github.com/${{ github.repository }}/jactor-persistence:${{ github.sha }} </code></pre> <p>I want to replace <code>${{ github.sha }}</code> with the short sha of the head commit, the same as the result of the following command <code>git rev-parse --short HEAD</code></p> <p>Is this possible?</p>
59,819,441
4
0
null
2020-01-19 14:12:12.19 UTC
7
2022-09-01 17:44:33.357 UTC
2020-02-23 15:05:12.92 UTC
null
1,033,581
null
5,984,627
null
1
50
git|docker|github-actions
41,015
<p>As VonC mentioned, you can just compute the string yourself in a previous step.</p> <pre><code> - name: Set outputs id: vars run: echo "::set-output name=sha_short::$(git rev-parse --short HEAD)" - name: Check outputs run: echo ${{ steps.vars.outputs.sha_short }} </code></pre>
23,325,973
jQuery: replace() in html()
<p>How can I replace html parts with <code>replace()</code>?</p> <pre><code>&lt;div&gt; &lt;a href="http://www.google.com"&gt;google.com&lt;/a&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>var e = $("div"), fix = e.html().replace("google.com", "duckduckgo.com"); e.html(fix); </code></pre> <p>I guess html() is not working the same as <code>text()</code> ?</p> <p>Test: <a href="http://jsfiddle.net/Hmhrd/" rel="noreferrer">http://jsfiddle.net/Hmhrd/</a></p>
23,326,020
3
0
null
2014-04-27 16:33:17.65 UTC
2
2018-11-04 03:14:17.58 UTC
null
null
null
null
370,215
null
1
6
jquery|html|replace
78,850
<p>The problem is that <code>.replace</code> only replaces first occurence. If you want to replace all occurences, you must use a regular expression with a <code>g</code> (global) flag:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var e = $("div"), fix = e.html().replace(/google\.com/g, "duckduckgo.com"); e.html(fix);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt; &lt;a href="http://www.google.com"&gt;google.com&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/Hmhrd/3/" rel="noreferrer"><strong>Demo</strong></a></p> <p>Remember you must escape <a href="https://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions">special characters</a> such as <code>.</code>, though. If you prefer, you can use</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>String.prototype.replaceAll = function(s1, s2) { return this.replace( new RegExp( s1.replace(/[.^$*+?()[{\|]/g, '\\$&amp;'), 'g' ), s2 ); }; var e = $("div"), fix = e.html().replaceAll('google.com', "duckduckgo.com"); e.html(fix);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt; &lt;a href="http://www.google.com"&gt;google.com&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/Hmhrd/4/" rel="noreferrer"><strong>Demo</strong></a></p>
35,084,227
jQuery - Find href that contains a value and return the full value
<p>I'd like to search the body for an href that contains <code>/test/</code>. I then want to return the entire href value e.g. <code>/test/123/</code>.</p> <p>Below is what I've come up with so far. I know that it can find <code>/test/</code> but I'm struggling with returning the full href value. Any ideas?</p> <pre><code>function() { var htmlString = $('body').html().toString(); var index = htmlString.indexOf("/test/"); if (index != -1) return index.closest('div').find('a').attr('href'); } </code></pre> <p>HTML:</p> <pre><code>&lt;div&gt; &lt;a href="/test/123/"&gt;Test&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Thanks in advance.</p>
35,084,296
5
0
null
2016-01-29 12:08:15.163 UTC
2
2016-02-01 06:44:20.707 UTC
2016-01-29 12:16:59.103 UTC
null
2,755,131
null
660,498
null
1
10
javascript|jquery
50,869
<p>You can do it like following using jQuery <a href="https://api.jquery.com/attribute-contains-selector/" rel="noreferrer">contain attribute</a> selector.</p> <pre><code>$('a[href*="/test/"]').attr('href'); </code></pre>
18,090,037
Documenting `tuple` return type in a function docstring for PyCharm type hinting
<p>How can I document that a function returns a <code>tuple</code> in such a way that PyCharm will be able to use it for type hinting?</p> <p>Contrived example:</p> <pre><code>def fetch_abbrev_customer_info(customer_id): """Pulls abbreviated customer data from the database for the Customer with the specified PK value. :type customer_id:int The ID of the Customer record to fetch. :rtype:??? """ ... magic happens here ... return customer_obj.fullname, customer_obj.status #, etc. </code></pre>
18,138,687
1
3
null
2013-08-06 20:40:01.953 UTC
3
2014-10-17 15:28:06.187 UTC
2014-10-13 12:46:08.383 UTC
user212218
null
user212218
null
null
1
47
python|pycharm|docstring
23,862
<p>I contacted PyCharm support, and this is what they said:</p> <blockquote> <p>For tuple please use <code>(&lt;type_1&gt;, &lt;type_2&gt;, &lt;type_3&gt;, e t.c.)</code> syntax.</p> <p>E.g.:</p> <pre><code>&quot;&quot;&quot; :rtype: (string, int, int) &quot;&quot;&quot; </code></pre> </blockquote> <p>This is confirmed in <a href="http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html" rel="noreferrer">PyCharm's documentation</a>:</p> <blockquote> <h2>Type Syntax</h2> <p>Type syntax in Python docstrings is not defined by any standard. Thus, PyCharm suggests the following notation:</p> <p>...</p> <ul> <li>(Foo, Bar) # Tuple of Foo and Bar</li> </ul> </blockquote>
22,710,243
How to get a list of all tags while using the gem 'acts-as-taggable-on' in Rails (not the counts)
<p>I have set the <code>acts-as-taggable-on</code> gem in my model like this :</p> <pre><code> acts_as_taggable_on :deshanatags </code></pre> <p>It use the context <code>deshanatags</code>. Now I need to get a list of all the tags (not only the ones assigned for one item. I need everything) in this context in the following format :</p> <pre><code>[ {"id":"856","name":"House"}, {"id":"1035","name":"Desperate Housewives"} ] </code></pre> <p>How can I do this?</p> <p>I tried to follow many tutorials but hit dead ends because most of them are written for Rails 3. Rails for have some changes to the model like removal of attr_accessor which make it difficult for me to understand those tutorials. So please help.</p> <p>Simply im trying to add Jquery Token input (<a href="http://loopj.com/jquery-tokeninput/">http://loopj.com/jquery-tokeninput/</a>) to my app</p> <p><strong>PS :</strong> Through Tagging table, is there a way to get a list of tags like the output of Tag.all by filtering the context?</p>
22,710,616
4
0
null
2014-03-28 10:30:19.41 UTC
10
2020-01-07 23:28:11.66 UTC
2014-04-01 02:36:40.84 UTC
null
734,776
null
734,776
null
1
21
ruby-on-rails|ruby|ruby-on-rails-4|acts-as-taggable-on
9,861
<p>The tags are stored in the Tags table, which you access from your program with e.g.</p> <pre><code>ActsAsTaggableOn::Tag.all </code></pre> <p>If you need more info on tag usage, there is also the table</p> <pre><code>ActsAsTaggableOn::Tagging </code></pre> <p>which contains links to where each tag is being used, including its context</p> <p>To further apply this to your example, you can use</p> <pre><code>ActsAsTaggableOn::Tagging.includes(:tag).where(context: 'deshanatags').map { |tagging| { 'id' =&gt; tagging.tag_id.to_s, 'name' =&gt; tagging.tag.name } }.uniq </code></pre> <p>Let's explain the various parts in this statement:</p> <ul> <li>the 'includes' makes sure the different tags are "eager loaded", in other words, that instead of loading n+1 records, only 2 queries will be done on the database</li> <li>the 'where' limits the records to the ones with the given context</li> <li>the 'map' converts the resulting array of records into a new array, containing the hashes you asked for in your problem, with id mapped to the tag's id, and name mapped to the tag's name</li> <li>finally the 'uniq' makes sure that you don't have doubles in your list </li> </ul> <p>To also cope with your additional problem, being taggins without tag, you could extend the where clause to</p> <pre><code>where("(context = 'deshanatags') AND (tag_id IS NOT NULL)") </code></pre>
45,406,213
Unable to install TA-Lib on Ubuntu
<p>I'm trying to install Python Ta-Lib in Ubuntu,but when I run:</p> <pre><code>pip install TA-Lib </code></pre> <p>I get this error:</p> <pre><code>Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YfCSFn/TA-Lib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-swmI7D-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-YfCSFn/TA-Lib/ </code></pre> <p>I already installed:</p> <pre><code>sudo apt-get install python3-dev </code></pre> <p>and installed Ta-lib</p> <p>How can I fix this?</p>
45,406,275
3
1
null
2017-07-31 01:02:54.183 UTC
8
2022-09-06 23:15:58.95 UTC
null
null
null
null
1,934,510
null
1
9
python|ubuntu
15,054
<p>Seem like other people had <a href="https://stackoverflow.com/questions/31498495/error-when-installing-using-pip">this problem</a>.</p> <p>To quote the accepted answer:</p> <blockquote> <p>Seems that your PiP can't access Setuptools as per the "import setuptools" in the error. Try the below first then try running your pip install again.</p> </blockquote> <pre><code>&gt; sudo pip install -U setuptools </code></pre> <p>Or if it doesn't work to quote his comment:</p> <blockquote> <p>Try this 'sudo -H pip install TA-Lib'</p> </blockquote> <p>As Filipe Ferminiano said in comment if this still doesn't fix it then you can try what is said on <a href="https://stackoverflow.com/questions/11108461/python-importerror-cython-distutils">this link</a> .</p> <p>To quote the accepted answer once again:</p> <pre><code>Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this question for more info. You need to make sure that sudo calls the right python, either by using the full path: sudo /usr/local/epd/bin/python setup.py install </code></pre> <blockquote> <p>or by doing the following (in bash):</p> </blockquote> <pre><code>alias sudo='sudo env PATH=$PATH' sudo python setup.py install </code></pre> <p>Here is the question <a href="https://stackoverflow.com/questions/257616/sudo-changes-path-why">he's talking about</a></p> <p>Please give credit to the one of the accepted answer if it fix your problem.</p>
22,244,738
How can I use Guzzle to send a POST request in JSON?
<p>Does anybody know the correct way to <code>post</code> JSON using <code>Guzzle</code>?</p> <pre><code>$request = $this-&gt;client-&gt;post(self::URL_REGISTER,array( 'content-type' =&gt; 'application/json' ),array(json_encode($_POST))); </code></pre> <p>I get an <code>internal server error</code> response from the server. It works using Chrome <code>Postman</code>.</p>
22,245,541
15
2
null
2014-03-07 08:06:37.22 UTC
46
2022-02-21 13:16:30.467 UTC
2016-09-06 12:17:19.547 UTC
null
2,856,839
null
3,379,466
null
1
225
php|postman|guzzle
330,767
<p>For <strong>Guzzle &lt;= 4</strong>:</p> <p>It's a raw post request so putting the JSON in the body solved the problem</p> <pre><code>$request = $this-&gt;client-&gt;post( $url, [ 'content-type' =&gt; 'application/json' ], ); $request-&gt;setBody($data); #set body! $response = $request-&gt;send(); </code></pre>
25,840,720
xcode 6 pch.file not found
<p>I load my project from xcode 5 to xcode 6 and see error myProject-prefix.pch is not found in myProjectTests, I add this file and see new error</p> <pre><code>Ld /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/Мобильный\ Extreme\ FitnessTests.xctest/Мобильный\ Extreme\ FitnessTests normal x86_64 cd /Users/willrock/Desktop/ExtremeFitness export IPHONEOS_DEPLOYMENT_TARGET=7.1 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -bundle -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk -L/Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator -F/Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/Developer/Library/Frameworks -filelist /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Intermediates/Мобильный\ Extreme\ Fitness.build/Debug-iphonesimulator/Мобильный\ Extreme\ FitnessTests.build/Objects-normal/x86_64/Мобильный\ Extreme\ FitnessTests.LinkFileList -bundle_loader /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/extreme_fitness.app/extreme_fitness -Xlinker -objc_abi_version -Xlinker 2 -framework XCTest -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.1 -framework XCTest -framework UIKit -framework Foundation -Xlinker -dependency_info -Xlinker /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Intermediates/Мобильный\ Extreme\ Fitness.build/Debug-iphonesimulator/Мобильный\ Extreme\ FitnessTests.build/Objects-normal/x86_64/Мобильный\ Extreme\ FitnessTests_dependency_info.dat -o /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/Мобильный\ Extreme\ FitnessTests.xctest/Мобильный\ Extreme\ FitnessTests </code></pre> <p>l<code>d: file not found: /Users/willrock/Library/Developer/Xcode/DerivedData/Мобильный_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/extreme_fitness.app/extreme_fitness clang: error: linker command failed with exit code 1 (use -v to see invocation)</code></p> <p>if i load project see in xctest</p> <p><code>clang: error: no such file or directory: '/Users/willrock/Desktop/ExtremeFitness/extreme_fitness/extreme_fitness-Prefix.pch' clang: error: no input files Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1</code></p> <p>but in xcode 5 is work fine</p>
26,394,796
9
1
null
2014-09-15 04:13:16.287 UTC
23
2016-07-15 23:21:43.393 UTC
2014-09-15 04:36:41.853 UTC
null
3,814,966
null
3,814,966
null
1
33
objective-c|xcode|xcode6
37,730
<p>i solved it - in targets delete xctest target and it compiled</p>