title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Front Loaded and Back Loaded | Normal Distribution Column Chart and S Curves in Excel
|
<p>Most of us may be aware of normal distribution curves however those who are new to front-loaded and back-loaded normal distribution, I would like to provide the background and then would proceed on stating my problem.</p>
<hr>
<p><strong>Front-Loaded Distribution</strong>: As demonstrated below, it have a rapid start. For e.g. in a project when more resources assumed to be consumed early in the project, cost/hours is distributed aggressively at the start of project.
<a href="https://i.stack.imgur.com/2yAEU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2yAEU.png" alt="Front-Loaded Distribution / S Curve"></a></p>
<hr>
<p><strong>Back-Loaded Distribution</strong>: Contrary to Front-Loaded distribution, it start out with a lower slope and increasingly steep towards the end of the project. For e.g. when most resources assumed to be consumed late in the project.
<a href="https://i.stack.imgur.com/0PkLr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0PkLr.png" alt="Rear Load Distribution S Curve"></a></p>
<p>In the above charts, <strong>green line is S-Curve</strong> which represents cumulative distribution (utilization of resources over the proposed time) and the blue Columns represents the isolated distribution of resources (Cost/Hours) in that period.</p>
<hr>
<p>For reference, I am providing the Bell Curve / standard normal distribution (when Mean=Median) chart (below) and the associated formula to begin with.
<a href="https://i.stack.imgur.com/UaP3J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UaP3J.png" alt="Normal Distribution S Curve"></a></p>
<hr>
<p><strong>Problem Statement</strong>: I was able to generate the normal distribution curve (See below with formulae) however I am unable to find a solution for Front loaded or Back Loaded curves. </p>
<p><em>How to bring the skewness to the right (front-loaded / positively skewed distribution which means mean is greater than median) and left skewed (back-loaded / negatively skewed distribution which means mean is less than median) in a normal distribution?</em> </p>
<p><a href="https://i.stack.imgur.com/fesb9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fesb9.png" alt="Gaussian Bell Curve with Excel Formula"></a></p>
<p><strong>Formula Explaned</strong>:</p>
<p><em>Cell B8</em> denotes arbitrarily chosen standard deviation. It affects the kurtosis of normal distribution. In the above screenshot, I am choosing the range of the normal distribution to be from -3SD to 3SD.</p>
<p><em>Cell B9 to B18</em> denotes the even distribution of Z-Score using the formula:</p>
<pre><code>=B8-((2*$B$8)/Period)
</code></pre>
<p><em>Cell C9 to C18</em> denotes the normal distribution on the basis of Z Score and the Amount using the formula:</p>
<pre><code>=(NORMSDIST(B9)-NORMSDIST(B8))*Amount/(1-2*NORMSDIST($B$8))
</code></pre>
<hr>
<p><strong>Update:</strong> Following one of the link in comment, I closest got to the below situation. The issue is highlighted in Yellow pattern as due to the usage of volatile Rand() function the charts are not smooth as they should be. As my given formula above do not create ZigZag pattern, I am sure we can have skewed normal distribution and smooth too !
<a href="https://i.stack.imgur.com/WV2XM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WV2XM.png" alt="ZigZag Columns Issue in Normal Distribution"></a></p>
<p>Note: </p>
<ol>
<li><p>I am using Excel 2016, so I welcome if any newly introduced formula can solve my problem. Also, I am not hesitant to use UDFs.</p></li>
<li><p>The numbers of front-load and back-load distribution are notional. They could vary. I am only interested in shape of resulting chart.</p></li>
</ol>
<p>Kindly help !</p>
| 1 | 1,136 |
Scikit-learn's GridSearchCV with linear kernel svm takes too long
|
<p>I took sample code from sklearn website, which is</p>
<pre><code>tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
scores = [('f1', f1_score)]
for score_name, score_func in scores:
print "# Tuning hyper-parameters for %s" % score_name
print
clf = GridSearchCV( SVC(), tuned_parameters, score_func=score_func, n_jobs=-1, verbose=2 )
clf.fit(X_train, Y_train)
print "Best parameters set found on development set:"
print
print clf.best_estimator_
print
print "Grid scores on development set:"
print
for params, mean_score, scores in clf.grid_scores_:
print "%0.3f (+/-%0.03f) for %r" % (
mean_score, scores.std() / 2, params)
print
print "Detailed classification report:"
print
print "The model is trained on the full development set."
print "The scores are computed on the full evaluation set."
print
y_true, y_pred = Y_test, clf.predict(X_test)
print cross_validation.classification_report(y_true, y_pred)
print
</code></pre>
<p>X_train is a pandas DataFrame with approx 70 rows.</p>
<p>The output is </p>
<pre><code>[GridSearchCV] kernel=rbf, C=1, gamma=0.001 ....................................
[GridSearchCV] kernel=rbf, C=1, gamma=0.001 ....................................
[GridSearchCV] kernel=rbf, C=1, gamma=0.001 ....................................
[GridSearchCV] kernel=rbf, C=1, gamma=0.0001 ...................................
[Parallel(n_jobs=-1)]: Done 1 jobs | elapsed: 0.0s
[GridSearchCV] ........................... kernel=rbf, C=1, gamma=0.001 - 0.0s
[GridSearchCV] ........................... kernel=rbf, C=1, gamma=0.001 - 0.0s
[GridSearchCV] ........................... kernel=rbf, C=1, gamma=0.001 - 0.0s
[GridSearchCV] .......................... kernel=rbf, C=1, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=rbf, C=1, gamma=0.0001 ...................................
[GridSearchCV] kernel=rbf, C=1, gamma=0.0001 ...................................
[GridSearchCV] kernel=rbf, C=10, gamma=0.001 ...................................
[GridSearchCV] kernel=rbf, C=10, gamma=0.001 ...................................
[GridSearchCV] .......................... kernel=rbf, C=1, gamma=0.0001 - 0.0s
[GridSearchCV] .......................... kernel=rbf, C=1, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=rbf, C=10, gamma=0.001 ...................................
[GridSearchCV] .......................... kernel=rbf, C=10, gamma=0.001 - 0.0s
[GridSearchCV] .......................... kernel=rbf, C=10, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=10, gamma=0.0001 ..................................
[GridSearchCV] .......................... kernel=rbf, C=10, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=10, gamma=0.0001 ..................................
[GridSearchCV] kernel=rbf, C=10, gamma=0.0001 ..................................
[GridSearchCV] ......................... kernel=rbf, C=10, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=rbf, C=100, gamma=0.001 ..................................
[GridSearchCV] ......................... kernel=rbf, C=10, gamma=0.0001 - 0.0s
[GridSearchCV] ......................... kernel=rbf, C=10, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=rbf, C=100, gamma=0.001 ..................................
[GridSearchCV] ......................... kernel=rbf, C=100, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=100, gamma=0.001 ..................................
[GridSearchCV] kernel=rbf, C=100, gamma=0.0001 .................................
[GridSearchCV] ......................... kernel=rbf, C=100, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=100, gamma=0.0001 .................................
[GridSearchCV] ......................... kernel=rbf, C=100, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=100, gamma=0.0001 .................................
[GridSearchCV] kernel=rbf, C=1000, gamma=0.001 .................................
[GridSearchCV] ........................ kernel=rbf, C=100, gamma=0.0001 - 0.0s
[GridSearchCV] ........................ kernel=rbf, C=100, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=rbf, C=1000, gamma=0.001 .................................
[GridSearchCV] ........................ kernel=rbf, C=100, gamma=0.0001 - 0.0s
[GridSearchCV] ........................ kernel=rbf, C=1000, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=1000, gamma=0.001 .................................
[GridSearchCV] kernel=rbf, C=1000, gamma=0.0001 ................................
[GridSearchCV] kernel=rbf, C=1000, gamma=0.0001 ................................
[GridSearchCV] ........................ kernel=rbf, C=1000, gamma=0.001 - 0.0s
[GridSearchCV] kernel=rbf, C=1000, gamma=0.0001 ................................
[GridSearchCV] ........................ kernel=rbf, C=1000, gamma=0.001 - 0.0s
[GridSearchCV] ....................... kernel=rbf, C=1000, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=linear, C=1 ..............................................
[GridSearchCV] ....................... kernel=rbf, C=1000, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=linear, C=1 ..............................................
[GridSearchCV] kernel=linear, C=1 ..............................................
[GridSearchCV] ....................... kernel=rbf, C=1000, gamma=0.0001 - 0.0s
[GridSearchCV] kernel=linear, C=10 .............................................
</code></pre>
<p>And then it never finishes. I run it on Mac Book Pro with Lion. What do I do wrong?</p>
| 1 | 1,896 |
Netty channelRead never called
|
<p>I've played a bit with netty and followed a video(<a href="https://www.youtube.com/watch?v=tsz-assb1X8" rel="nofollow">https://www.youtube.com/watch?v=tsz-assb1X8</a>) to build a chat server and client the server works properly(I tested with telnet and here it works) but the client does not recives data. The channelRead method in ChatClinetHandler.java were never called but the channelReadComplete were called.</p>
<p>ChatClient.java</p>
<pre><code>import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ChatClient {
public static void main(String args[]) {
try {
new ChatClient(new InetSocketAddress("localhost", 8000)).run();
} catch (Exception ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private final InetSocketAddress server;
public ChatClient(InetSocketAddress server) {
this.server = server;
}
public void run() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChatClientInitializer());
Channel channel = bootstrap.connect(server).sync().channel();
System.out.println("Connected to Server: " + server.toString());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (channel.isActive()) {
String userMessage = in.readLine();
channel.writeAndFlush(userMessage + "\r\n");
if (userMessage.equalsIgnoreCase("bye")) {
group.shutdownGracefully();
break;
}
}
} finally {
group.shutdownGracefully();
}
}
}
</code></pre>
<p>ChatClientInitializer.java</p>
<pre><code>import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder;
public class ChatClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel c) throws Exception {
ChannelPipeline pipeline = c.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ChatClientHandler());
} }
</code></pre>
<p>ChatClinetHandler.java</p>
<pre><code>import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ChatClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg.toString());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
}
}
</code></pre>
| 1 | 1,401 |
How to convert Confluence Storage Format XML to HTML?
|
<p>I am pulling content from confluence using the REST API.</p>
<p><a href="https://docs.atlassian.com/atlassian-confluence/REST/3.2/" rel="nofollow noreferrer">https://docs.atlassian.com/atlassian-confluence/REST/3.2/</a></p>
<p>The API returns confluence pages with a content property. The content is a mix of XHTML and proprietary XML tags. The XML is Confluence Storage Format:</p>
<p><a href="https://confluence.atlassian.com/display/DOC/Confluence+Storage+Format" rel="nofollow noreferrer">https://confluence.atlassian.com/display/DOC/Confluence+Storage+Format</a></p>
<p>The custom XML tags are used for things like images, relative links, and attachments. If I render the content straight out the custom XML will not render.</p>
<p>I've found what looks like an endpoint that is supposed to convert the the format:
<a href="https://docs.atlassian.com/confluence/latest/com/atlassian/confluence/xhtml/api/XhtmlContent.html" rel="nofollow noreferrer">https://docs.atlassian.com/confluence/latest/com/atlassian/confluence/xhtml/api/XhtmlContent.html</a></p>
<p>I don't think it is longer supported.</p>
<p>I've also found this project:</p>
<p><a href="http://www.amnet.net.au/~ghannington/confluence/readme.html#wikifier" rel="nofollow noreferrer">http://www.amnet.net.au/~ghannington/confluence/readme.html#wikifier</a></p>
<p>Which converts confluence XML into confluence wiki markup. The project comes with two <code>.xsl</code> sheets One sheet is <code>confluence2wiki.xsl</code> which handles the markup conversion, and the other is <code>confluence2xhtml.xsl</code>which sounds like it would do the job but unfortunately the implementation is poor. It literally converts the confluence XML into XHTML that looks like the XML. So an image tag from the confluence XML unfortunately becomes:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="extension-element">
<p class="extension-element-markup">
<span class="element-name">ac:image</span>
<span class="attribute-name">ac:alt</span>
<span class="markup">="</span>
<span class="attribute-value">Example1.png</span>
<span class="markup">"</span>
</p>
<div class="extension-element-contents">
<div class="extension-element">
<p class="extension-element-markup">
<span class="element-name">ri:url</span>
<span class="attribute-name">ri:value</span>
<span class="markup">="</span>
<span class="attribute-value">https://example.com/attachments/token/2ujwb0dm4jsorgk/?name=Omniata_Docs_Projects_Example1.png</span>
<span class="markup">"</span>
</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Which is not very helpful. Currently it looks like I will have to write my own <code>xsl</code> sheet based on the <code>wkik xsl sheet</code>. I'm hoping there is a less manual solution out there or someone has done this before.</p>
| 1 | 1,188 |
How to get id back, after posting data to mongoDb?
|
<p>I am using node.js, angularjs, & mongoDb. <br/>
I am creating a product upload page.<br/><br/>
It is divided into 2 parts:<br/></p>
<ol>
<li><strong>Data page</strong>: This part will contain, textfields & dropdowns.</li>
<li><strong>Image Upload page</strong>: This part will have image upload control.
<br/></li>
</ol>
<p>So I thought to create 2 forms in same page, from first page i will post text data to mongoDb, return <strong>product_id</strong> of the newly created product, and then upload images with returned <strong>product_id</strong>.
<br/><br/>
I have developed restFul API to post product <code>api/products/create-product</code>.
<br/>
<strong>Product model</strong> :</p>
<pre><code>{
productName:{type: String},
productPrice:{type: Number}
}
</code></pre>
<p><br/>
<strong>Image model</strong>:</p>
<pre><code>{
productId:{type: String},
imagePaths:[{type: Array}]
}
</code></pre>
<p><br/>
<strong>Product Controller(Angular):</strong></p>
<pre><code>$scope.newProduct = function(){
var formData = new FormData;
for(key in $scope.product){
formData.append(key, $scope.product[key]);
}
//getting the files
var file = $('#file')[0].files[0];
formData.append('image', file);
//Post data
$http.post('http://localhost:3000/products/api/new-product',formData,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(res){
$scope.item = res.data;
});
}
</code></pre>
<p><br/>
<strong>Angular front-end</strong></p>
<pre><code><input type="text" class="form-control" ng-model="product.productName" placeholder="Enter Product Name">
<input type="file" multiple="multiple" id="file" >
<button type="submit" ng-click="newProduct()" class="btn btn-primary">Add Product</button>
</code></pre>
<p><br/>
<strong>POST API</strong></p>
<pre><code>router.post('/api/new-product',upload.any(),function(req, res, next){
var pro = req.body;
if(req.files){
req.files.forEach(function(file){
var filename = (new Date()).valueOf() + '-' + file.originalname;
fs.rename(file.path,'public/images/'+ filename, function(err){
if (err) throw err;
//Save to mongoose
var product = new Products({
productName: req.body.productName
});
product.save(function(err, result){
if(err){ throw err}
res.json(result);
});
});
});
}
});
</code></pre>
<p><strong>Questions</strong>:</p>
<ol>
<li>Am I doing this correct way, or there is another better way for doing this?</li>
<li>If this is correct way, then how can I post get posted <strong>product_id</strong>, in order to post images?
<br/>
Thanks.</li>
</ol>
| 1 | 1,046 |
Function pointer in swift
|
<p>I'm following this <a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW3" rel="nofollow noreferrer">tutorial</a>, especially I have problems to convert this function in Swift language:</p>
<pre><code>- (id)init
{
CFRunLoopSourceContext context = {0, self, NULL, NULL, NULL, NULL, NULL,
&RunLoopSourceScheduleRoutine,
RunLoopSourceCancelRoutine,
RunLoopSourcePerformRoutine};
runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context);
commands = [[NSMutableArray alloc] init];
return self;
}
</code></pre>
<p>of this, in the init function is <code>context</code> variable to give me problems.</p>
<p>In the code above, context is a variable of type : <code>CFRunLoopSourceContext</code> and the initialization of this object in the apple documentation is <a href="https://developer.apple.com/reference/corefoundation/cfrunloopsourcecontext" rel="nofollow noreferrer">like this</a></p>
<p>so, I in my initialization, used the following code, concentrating on the <code>schedule</code> parameter :</p>
<pre><code>var context = CFRunLoopSourceContext(version: 0, info: bridge(obj: self) ,
retain: nil,
release: nil,
copyDescription: nil,
equal: nil,
hash: nil,
schedule: RunLoopSourceScheduleRoutine,
cancel: nil,
perform: nil)
</code></pre>
<p>The function <code>RunLoopSourceScheduleRoutine</code> is like so :</p>
<pre><code> func RunLoopSourceScheduleRoutine(info:UnsafeMutableRawPointer? ,rl:CFRunLoop? , mode:CFRunLoopMode?) {
let obj : RunLoopSource = Unmanaged<RunLoopSource>.fromOpaque(info!).takeUnretainedValue()
let theContext = RunLoopContext(withSource: obj, andLoop: rl!)
performSelector(onMainThread: #selector(myMethod), with: theContext, waitUntilDone: false)
}
</code></pre>
<p>but the compiler gives me the following error message : <code>a c function pointer can only be formed from a reference to a 'func' or a literal closure</code></p>
<p>even if I make the following closure :</p>
<pre><code>let runLoopSourceScheduleRoutine = { (info:UnsafeMutableRawPointer? ,rl:CFRunLoop? , mode:CFRunLoopMode?)-> Void in return
let obj : RunLoopSource = Unmanaged<RunLoopSource>.fromOpaque(info!).takeUnretainedValue()
let theContext = RunLoopContext(withSource: obj, andLoop: rl!)
performSelector(onMainThread: #selector(myMethod), with: theContext, waitUntilDone: false)
}
</code></pre>
<p>and i put it like this :</p>
<pre><code>var context = CFRunLoopSourceContext(version: 0, info: bridge(obj: self) ,
retain: nil,
release: nil,
copyDescription: nil,
equal: nil,
hash: nil,
schedule: runLoopSourceScheduleRoutine,
cancel: nil,
perform: nil)
</code></pre>
<p>gives me the same error.
What is the problem ?
any tips</p>
| 1 | 1,732 |
How to format the list items of QCompleter's popup list properly?
|
<p>I want to investigate how to make a small user interface in which a user can type some letters and gets some suggestions based on a given data source (list here) which makes searches easier. For this purpose i am using Qt's <code>QCompleter</code> class.</p>
<p>In the matching elements the typed letters shall be highlighted with HTML like the example in the code below: <code>Au<b>st</b>ria</code>.
Finally i merged some SO answers (see <a href="https://stackoverflow.com/q/1956542/1504082">How to make item view render rich (html) text in Qt</a>) and tutorials to a small standalone module:</p>
<pre class="lang-python prettyprint-override"><code>from PySide import QtCore, QtGui
class HTMLDelegate(QtGui.QStyledItemDelegate):
""" From: https://stackoverflow.com/a/5443112/1504082 """
def paint(self, painter, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
if options.widget is None:
style = QtGui.QApplication.style()
else:
style = options.widget.style()
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(option.rect.width())
options.text = ""
style.drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
# Highlighting text if item is selected
# if options.state & QtGui.QStyle.State_Selected:
# ctx.palette.setColor(QtGui.QPalette.Text,
# options.palette.color(QtGui.QPalette.Active,
# QtGui.QPalette.HighlightedText))
textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText,
options)
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(options.rect.width())
return QtCore.QSize(doc.size().width(), doc.size().height())
class CustomQCompleter(QtGui.QCompleter):
""" Implement "contains" filter mode as the filter mode "contains" is not
available in Qt < 5.2
From: https://stackoverflow.com/a/7767999/1504082 """
def __init__(self, parent=None):
super(CustomQCompleter, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
self.delegate = HTMLDelegate()
def setModel(self, model):
self.source_model = model
super(CustomQCompleter, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
# see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
class InnerProxyModel(QtGui.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
# model index mapping by row, 1d model => column is always 0
index = self.sourceModel().index(sourceRow, 0, sourceParent)
source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
# performs case insensitive matching
# return True if item shall stay in th returned filtered data
# return False to reject an item
return local_completion_prefix.lower() in source_data.lower()
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter, self).setModel(proxy_model)
# @todo: Why to be set here again?
self.popup().setItemDelegate(self.delegate)
def splitPath(self, path):
self.local_completion_prefix = path
self.updateModel()
return ""
class AutoCompleteEdit(QtGui.QLineEdit):
""" Basically from:
http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
"""
def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
super(AutoCompleteEdit, self).__init__()
# settings
self._separator = separator
self._addSpaceAfterCompleting = addSpaceAfterCompleting
# completer
self._completer = CustomQCompleter(self)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.model = QtGui.QStringListModel(list_data)
self._completer.setModel(self.model)
# connect the completer to the line edit
self._completer.setWidget(self)
# trigger insertion of the selected completion when its activated
self.connect(self._completer,
QtCore.SIGNAL('activated(QString)'),
self._insertCompletion)
self._ignored_keys = [QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Tab]
def _insertCompletion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
It will remove the already typed string with the one of the completion.
"""
stripped_text = self.text()[:-len(self._completer.completionPrefix())]
extra_text = completion # [-extra:]
if self._addSpaceAfterCompleting:
extra_text += ' '
self.setText(stripped_text + extra_text)
def textUnderCursor(self):
text = self.text()
textUnderCursor = ''
i = self.cursorPosition() - 1
while i >= 0 and text[i] != self._separator:
textUnderCursor = text[i] + textUnderCursor
i -= 1
return textUnderCursor
def keyPressEvent(self, event):
if self._completer.popup().isVisible():
if event.key() in self._ignored_keys:
event.ignore()
return
super(AutoCompleteEdit, self).keyPressEvent(event)
completionPrefix = self.textUnderCursor()
if completionPrefix != self._completer.completionPrefix():
self._updateCompleterPopupItems(completionPrefix)
if len(event.text()) > 0 and len(completionPrefix) > 0:
self._completer.complete()
if len(completionPrefix) == 0:
self._completer.popup().hide()
def _updateCompleterPopupItems(self, completionPrefix):
"""
Filters the completer's popup items to only show items
with the given prefix.
"""
self._completer.setCompletionPrefix(completionPrefix)
# self._completer.popup().setCurrentIndex(
# self._completer.completionModel().index(0, 0))
if __name__ == '__main__':
def demo():
import sys
app = QtGui.QApplication(sys.argv)
values = ['Germany',
'Au<b>st</b>ria',
'Switzerland',
'Hungary',
'The United Kingdom of Great Britain and Northern Ireland']
editor = AutoCompleteEdit(values)
window = QtGui.QWidget()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(editor)
window.setLayout(hbox)
window.show()
sys.exit(app.exec_())
demo()
</code></pre>
<p>My problem is the suggestion of user Timo in the answer <a href="https://stackoverflow.com/a/5443112/1504082">https://stackoverflow.com/a/5443112/1504082</a>: </p>
<blockquote>
<p>After line: 'doc.setHtml(options.text)', you need to set also doc.setTextWidth(option.rect.width()), otherwise the delegate wont render longer content correctly in respect to target drawing area. For example does not wrap words in QListView.</p>
</blockquote>
<p>So i did this to avoid cropping of long text in the completer's popup. But i get the following output:
<a href="https://i.stack.imgur.com/MFnj8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MFnj8.png" alt="Where does this vertical margin come from?"></a></p>
<p>Where does this additional vertical margin come from?</p>
<p>I investigated this a bit and i see that the <code>sizeHint</code> method of <code>HTMLDelegate</code> is sometimes called with an <code>options</code> parameter which contains a rectangle with attributes <code>(0, 0, 0, 0)</code>. And the display behaviour finally changes after the call of <code>doc.setTextWidth(options.rect.width())</code>. But i couldnt finally find out who calls it with this parameter and how i could properly fix this.</p>
<p>Can somebody explain where this comes from and how i can fix this porperly? </p>
| 1 | 3,776 |
terminate called after throwing an instance of 'std::bad_alloc'
|
<p>This is my setup (boiled down). I have a "layout function":</p>
<pre><code> struct LayoutFunc {
LayoutFunc( int limit , int value ) { lim.push_back(limit); val.push_back(value); }
//LayoutFunc(LayoutFunc&& func) : lim(func.lim),val(func.val) {}
LayoutFunc(const LayoutFunc& func) : lim(func.lim),val(func.val) {} // error: std::bad_alloc
LayoutFunc(const std::vector<int>& lim_,
const std::vector<int>& val_ ) : lim(lim_),val(val_) {}
LayoutFunc curry( int limit , int value ) const {
std::vector<int> rlim(lim);
std::vector<int> rval(val);
rlim.push_back(limit);
rval.push_back(value);
LayoutFunc ret(rlim,rval);
return ret;
};
std::vector<int> lim;
std::vector<int> val;
};
</code></pre>
<p>Then I have a class that uses <code>LayoutFunc</code>:</p>
<pre><code>template<class T> class A
{
public:
A( const LayoutFunc& lf_ ) : lf(lf_), member( lf.curry(1,0) ) {}
A(const A& a): lf(lf), member(a.function) {} // corresponds to line 183 in real code
private:
LayoutFunc lf;
T member;
};
</code></pre>
<p>The order of data members is correct. There are more types like <code>class A</code> which use slightly different numbers to "curry" the layout function. I don't print them here to save space (they have the same structure, only different numbers). At the end I use something like:</p>
<pre><code>A< B< C<int> > > a( LayoutFunc(1,0) );
</code></pre>
<p>which would build the "curried" layout function according to the template type order.</p>
<p>Now, probably this simple (boiled down) example works. However, in my real application at runtime I get a <code>terminate called after throwing an instance of 'std::bad_alloc'</code> in the copy constructor of <code>LayoutFunc</code>.</p>
<p>I think there is a flaw in the setup that has to do with taking a reference to a temporary and this temporary is destroyed before the consumer (in this case the copy constructor of <code>LayoutFunc</code>) uses it. This would explain <code>lim(func.lim),val(func.val)</code> to fail. But I can't see where the flaw is especially because <code>curry</code> returns a true <code>lvalue</code>. Also I tried it with the move constructor and compiled in c++11 mode. Same behaviour.</p>
<p>Here the backtrace:</p>
<pre><code>#0 0x00007ffff6437445 in __GI_raise (sig=<optimised out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#1 0x00007ffff643abab in __GI_abort () at abort.c:91
#2 0x00007ffff6caa69d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff6ca8846 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff6ca8873 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff6ca896e in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x00007ffff6c556a2 in std::__throw_bad_alloc() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7 0x00000000004089f6 in allocate (__n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/ext/new_allocator.h:90
#8 _M_allocate (__n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:150
#9 _Vector_base (__a=..., __n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:123
#10 vector (__x=..., this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:279
#11 LayoutFunc (func=..., this=0x7fffffffdae0) at layoutfunc.h:17
#12 A (a=..., this=0x7fffffffdad0) at A.h:183
</code></pre>
<p>A.h:183 is the copy constructor of <code>A</code>:</p>
<pre><code> A(const A& a): lf(lf), member(a.function) {}
</code></pre>
| 1 | 1,524 |
Bad magic number for Bundle in Android
|
<p>I'm passing data from one activity to other activity with this code:</p>
<pre><code> @Override
public void execute(List<Report> reports, Questions question) {
Intent replyIntent = new Intent(listener, ReplyActivity.class);
replyIntent.putExtra("id", 0L);
replyIntent.putExtra("questions", question);
listener.openReportOk(question);
listener.startActivity(replyIntent);
}
</code></pre>
<p>Listener its a Activity reference for callbacks.</p>
<p>Questions is this class:</p>
<pre><code>@Table(name = "Questions")
public class Questions extends Entity implements Parcelable {
public static final Creator<Questions> CREATOR = new Creator<Questions>() {
public Questions createFromParcel(Parcel source) {
return new Questions(source);
}
public Questions[] newArray(int size) {
return new Questions[size];
}
};
@TableField(name = "idReport", datatype = DATATYPE_INTEGER)
private int idReport;
@TableField(name = "nameReport", datatype = DATATYPE_STRING)
private String nameReport;
@TableField(name = "replyGroups", datatype = DATATYPE_STRING)
private String replyGroups;
@TableField(name = "questionGroups", datatype = DATATYPE_ENTITY)
private List<QuestionsGroup> questionsGroup;
private Boolean canCreateNew;
public Questions(int idReport, String nameReport, String replyGroups, List<QuestionsGroup> questionsGroup) {
this.idReport = idReport;
this.nameReport = nameReport;
this.replyGroups = replyGroups;
this.questionsGroup = questionsGroup;
this.canCreateNew = false;
}
public Questions() {
questionsGroup = new ArrayList<QuestionsGroup>();
}
private Questions(Parcel in) {
this();
this.idReport = in.readInt();
this.nameReport = in.readString();
this.replyGroups = in.readString();
Bundle b = in.readBundle(QuestionsGroup.class.getClassLoader());
this.questionsGroup = b.getParcelableArrayList("questionGroups");
this.canCreateNew = (Boolean) in.readValue(Boolean.class.getClassLoader());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.idReport);
dest.writeString(this.nameReport);
dest.writeString(this.replyGroups);
Bundle b = new Bundle();
b.putParcelableArrayList("questionGroups", (ArrayList<QuestionsGroup>) this.questionsGroup);
dest.writeBundle(b);
dest.writeValue(this.canCreateNew);
}
}
</code></pre>
<p>And when i receive the parcels in onCreate method:</p>
<pre><code> private void getData(Intent data) {
ID = data.getExtras().getLong("id");
questions = data.getExtras().getParcelable("questions");
}
</code></pre>
<p>Im getting this error:</p>
<pre><code>10-05 13:19:15.508 3499-3499/com.firext.android E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.firext.android, PID: 3499
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.firext.android/com.firext.android.activities.reply.ReplyActivity}: java.lang.IllegalStateException: Bad magic number for Bundle: 0x28
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.access$800(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5070)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
Caused by: java.lang.IllegalStateException: Bad magic number for Bundle: 0x28
at android.os.BaseBundle.readFromParcelInner(BaseBundle.java:1342)
at android.os.BaseBundle.<init>(BaseBundle.java:90)
at android.os.Bundle.<init>(Bundle.java:66)
at android.os.Parcel.readBundle(Parcel.java:1645)
at com.firext.android.domain.QuestionsGroup.<init>(QuestionsGroup.java:53)
at com.firext.android.domain.QuestionsGroup$1.createFromParcel(QuestionsGroup.java:25)
at com.firext.android.domain.QuestionsGroup$1.createFromParcel(QuestionsGroup.java:23)
at android.os.Parcel.readParcelable(Parcel.java:2160)
at android.os.Parcel.readValue(Parcel.java:2066)
at android.os.Parcel.readListInternal(Parcel.java:2422)
at android.os.Parcel.readArrayList(Parcel.java:1756)
at android.os.Parcel.readValue(Parcel.java:2087)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2393)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getParcelableArrayList(Bundle.java:782)
at com.firext.android.domain.Questions.<init>(Questions.java:58)
at com.firext.android.domain.Questions.<init>(Questions.java:18)
at com.firext.android.domain.Questions$1.createFromParcel(Questions.java:22)
at com.firext.android.domain.Questions$1.createFromParcel(Questions.java:20)
at android.os.Parcel.readParcelable(Parcel.java:2160)
at android.os.Parcel.readValue(Parcel.java:2066)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2393)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getParcelable(Bundle.java:738)
at com.firext.android.activities.reply.ReplyActivity.getData(ReplyActivity.java:72)
at com.firext.android.activities.reply.ReplyActivity.onCreate(ReplyActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1102)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2208)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.access$800(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5070)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
</code></pre>
<p>Whats wrong?</p>
| 1 | 2,922 |
Docker: not found when running cmds in jenkinsfile
|
<p>I am new to docker and CI. I am trying to create a jenkinsfile that would build and test my application, then build a docker image with the Dockerfile i've composed and then push it into AWS ECR. The steps I am stuck on is building an image with docker, i receive and error message <code>docker: not found</code>. I downloaded docker plug-in and configured it in the global tool configuration tab. Am i not adding it into tools correctly?</p>
<p>There was another post wear you could use kubernetes to do that however kubernetes no longer supports docker.</p>
<p>image of how i configured docker in global tools config:
<a href="https://i.stack.imgur.com/xmOl3.png" rel="nofollow noreferrer">global tool config</a></p>
<p>error</p>
<pre><code>/var/jenkins_home/workspace/client-pipeline_feature-jenkins@tmp/durable-41220eb0/script.sh: 1: /var/jenkins_home/workspace/client-pipeline_feature-jenkins@tmp/durable-41220eb0/script.sh: docker: not found
</code></pre>
<p><a href="https://i.stack.imgur.com/IcJLW.png" rel="nofollow noreferrer">error with permission to sock</a></p>
<pre><code>def gv
containerVersion = "1.0"
appName = "foodcore"
imageName = appName + ":" + version
pipeline {
agent any
environment {
CI = 'true'
}
tools {
nodejs "node"
docker "docker"
}
stages {
stage("init") {
steps {
script {
gv = load "script.groovy"
CODE_CHANGES = gv.getGitChanges()
}
}
}
stage("build frontend") {
steps {
dir("client") {
sh 'npm install'
}
}
}
stage("build backend") {
steps {
dir("server") {
sh 'npm install'
}
}
}
stage("test") {
when {
expression {
script {
CODE_CHANGES == false
}
}
}
steps {
dir("client") {
sh 'npm test'
}
}
}
stage("build docker image") {
when {
expression {
script {
env.BRANCH_NAME.toString().equals('Main') && CODE_CHANGES == false
}
}
}
steps {
sh "docker build -t ${imageName} ."
}
}
stage("push docker image") {
when {
expression {
env.BRANCH_NAME.toString().equals('Main')
}
}
steps {
sh 'aws ecr get-login-password --region us-east-2 | docker login --username AWS --password-stdin repoURI'
sh 'docker tag foodcore:latest ...repoURI
sh 'docker push repoURI'
}
}
}
}
</code></pre>
| 1 | 1,688 |
Spring security 403 forbidden error keeps happening even with csrf disable
|
<p>I've been following a tutorial from <a href="https://programmingtechie.com/2019/11/08/build-a-full-stack-reddit-clone-with-spring-boot-and-angular-part-3/" rel="nofollow noreferrer">https://programmingtechie.com/2019/11/08/build-a-full-stack-reddit-clone-with-spring-boot-and-angular-part-3/</a>.</p>
<p>And for some reason, <code>/auth/api/login</code> REST-API keeps throwing 403 forbidden error (Access denied) even when I disabled csrf.</p>
<pre class="lang-java prettyprint-override"><code> @Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
httpSecurity.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}
</code></pre>
<p>This is on the <code>SecurityConfig</code> class extending <code>WebSecurityConfigurerAdapter</code>.</p>
<p>Below is the <code>AuthController</code>.</p>
<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping("/api/auth")
@AllArgsConstructor
public class AuthController {
private final AuthService authService;
private final RefreshTokenService refreshTokenService;
@PostMapping("/signup")
public ResponseEntity<String> signup (@RequestBody RegisterRequest registerRequest) {
authService.signup(registerRequest);
return new ResponseEntity<>("User Registration Successful", HttpStatus.OK);
}
@PostMapping("/login")
public AuthenticationResponse login(@RequestBody LoginRequest loginRequest) {
return authService.login(loginRequest);
}
@GetMapping("accountVerification/{token}")
public ResponseEntity<String> verifyAccount(@PathVariable String token) {
authService.verifyAccount(token);
return new ResponseEntity<>("Account Activated Successfully", OK);
}
</code></pre>
<p>When I try requesting <code>http://localhost:8080/api/auth/signup</code>, it works just fine but <code>http://localhost:8080/api/auth/login</code> keeps returning 403 forbidden error.</p>
<p>To be clear, below is the <code>JwtAuthenticationFilter</code> class.</p>
<pre class="lang-java prettyprint-override"><code> @Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && jwtProvider.validateToken(jwt)){
String username = jwtProvider.getUsernameFromJwt(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request){
String bearerToken = request.getHeader("Authorization");
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
return bearerToken.substring(7);
}
return bearerToken;
}
</code></pre>
<p>Can somebody point out the mistakes or is there more configuration that I need to do?</p>
| 1 | 1,401 |
Renderbox was not laid out when added to a row
|
<p>I have looked at quite a few answers about this error, and I'm not quite sure which widgets width is the problem. I would ideally like a vertical form that can scroll, and is fairly manageable. I have the form working like I want, but as I add more fields, I will need to scroll. In preparing for this, I've also thought ahead and decided to make my label and field, a horizontal form element. Prior to adding the "field" method, I had a label widget and a textbox widget, that I put directly into the form, but I decided to wrap the two widgets into a row, to save some screen real estate. I've tried wrapping them in a sized box, as the error indicates it's an uncertainty in the size of a widget. </p>
<p>Can someone help me with this? Additionally, are there any resources out there that explain how to better troubleshoot widget issues like this? And are there any resources out there discussing the issue I'm facing?</p>
<p>Thanks in advance</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:wedding_app/models/constants/colors.dart';
import 'package:wedding_app/models/constants/styles.dart';
import 'package:wedding_app/models/constants/utility.dart';
import 'package:intl/intl.dart';
class BudgetWidget extends StatefulWidget {
@override
_BudgetWidgetState createState() => _BudgetWidgetState();
}
// limo, flowers, wedding invites, save the dates, center pieces,
class _BudgetWidgetState extends State<BudgetWidget> {
_BudgetWidgetState({this.totalBudget});
var currencyFormat = NumberFormat.simpleCurrency();
double totalBudget = 0;
double currentExpenses = 0;
Map<String, double> expenses =
new Map.from({"venue": 0.0, "limo": 0.0, "flowers": 0.0});
@override
Widget build(BuildContext context) {
final colors = ApplicationColors();
var form = <Widget>[
Padding(
padding: EdgeInsets.only(top: BudgetingStyles.topPadding(context)),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(
totalBudget == null || totalBudget == 0
? "Your Budget"
: currencyFormat.format(
totalBudget - expenses.values.reduce((a, b) => a + b)),
style: TextStyle(
fontFamily: "acme",
fontSize: BudgetingStyles.headerFontSize(context),
color: colors.black),
),
),
],
),
),
textBox(
"Enter your budget",
BudgetingStyles.textBoxMargins(context),
BudgetingStyles.topPadding(context),
(String value) {
if (Utility.isNumeric(value)) {
setState(() {
totalBudget = double.parse(value);
});
} else if (totalBudget > 0 && value.length == 0) {
setState(() {
totalBudget = 0;
});
}
},
),
Padding(
padding: EdgeInsets.only(top: BudgetingStyles.topPadding(context) * 2),
child: Text(
"Expenses",
style: TextStyle(
fontFamily: "acme",
fontSize: BudgetingStyles.headerFontSize(context)),
),
),
Padding(
padding: EdgeInsets.only(top: 3),
child: Divider(
color: colors.black,
),
),
field("Venue Cost", "Venue", "venue"),
field("Limo Cost", "Limo", "limo"),
field("Flowers Cost", "Flowers", "flowers")
];
var innerContainer = Container(
color: colors.ivory,
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: form,
),
);
return Scaffold(
body: innerContainer,
);
}
// Why did wrapping it the label and field in a row, give a paint error
Widget field(String hintText, String labelText, String expenseKey) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Text(
labelText,
style: TextStyle(
fontFamily: "acme",
fontSize: BudgetingStyles.subHeaderFontSize(context)),
),
),
),
textBox(
hintText,
BudgetingStyles.textBoxMargins(context),
BudgetingStyles.topPadding(context),
(String value) {
setState(
() {
expenses[expenseKey] =
Utility.isNumeric(value) ? double.parse(value) : 0;
},
);
},
)
],
);
}
Widget textBox(String hintText, double textboxPaddingWidth, double topPadding,
void onChangeHandler(String value)) {
return Container(
child: Padding(
padding: EdgeInsets.only(
left: textboxPaddingWidth,
right: textboxPaddingWidth,
top: topPadding),
child: TextField(
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: hintText,
),
onChanged: onChangeHandler),
),
);
}
}
</code></pre>
<p>Here is the closest thing to a stack trace I could find</p>
<pre><code>The following RenderObject was being processed when the exception was fired:
I/flutter (16757): RenderFlex#a932f relayoutBoundary=up3 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): creator: Row ← Column ← DecoratedBox ← Container ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ←
I/flutter (16757): CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ←
I/flutter (16757): _InkFeatures-[GlobalKey#bfdef ink renderer] ← NotificationListener<LayoutChangedNotification> ← ⋯
I/flutter (16757): parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
I/flutter (16757): constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
I/flutter (16757): size: MISSING
I/flutter (16757): direction: horizontal
I/flutter (16757): mainAxisAlignment: center
I/flutter (16757): mainAxisSize: max
I/flutter (16757): crossAxisAlignment: stretch
I/flutter (16757): textDirection: ltr
I/flutter (16757): verticalDirection: down
I/flutter (16757): This RenderObject had the following descendants (showing up to depth 5):
I/flutter (16757): RenderPadding#b1255 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): RenderParagraph#411ca NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): RenderPadding#45b3e NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): RenderSemanticsAnnotations#4c0e1 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): RenderIgnorePointer#2e796 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): RenderPointerListener#d6273 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): _RenderDecoration#df698 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (16757): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (16757): Another exception was thrown: RenderBox was not laid out: RenderFlex#a932f relayoutBoundary=up3 NEEDS-PAINT
I/flutter (16757): Another exception was thrown: RenderBox was not laid out: RenderFlex#edb16 relayoutBoundary=up2 NEEDS-PAINT
I/flutter (16757): Another exception was thrown: RenderBox was not laid out: RenderDecoratedBox#ca6a1 relayoutBoundary=up1 NEEDS-PAINT
I/flutter (16757): Another exception was thrown: RenderBox was not laid out: RenderDecoratedBox#ca6a1 relayoutBoundary=up1
</code></pre>
| 1 | 3,395 |
validate login & redirect to success page using jquery validate plugin
|
<p>I am new to advance level of jQuery scripting and here I am using jquery validation for my login page.</p>
<p>If my login page was success it has to redirect to success page the code was working fine with the below code when I click submit button . </p>
<pre><code><form id="form1" name="login" method="post" action="mainpage.html">
</form>
</code></pre>
<p>Here is my code</p>
<pre><code>$(function (){
$("#form1").validate({
// Specify the validation rules
rules: {
username: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify the validation error messages
messages: {
username: "Please enter a valid email address",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
submitHandler: function (form) { // for demo
$('#username').focus();
$('#submit').click(function () {
event.preventDefault(); // prevent PageReLoad
var ValEmail = $('#username').val() === 'admin@admin.com'; // Email Value
alert("Email" + ValEmail);
var ValPassword = $('#password').val() === 'admin1234'; // Password Value
if (ValEmail === true && ValPassword === true) { // if ValEmail & Val ValPass are as above
alert('valid!'); // alert valid!
window.location.href = "http://java67.blogspot.com";
// go to home.html
}
else {
alert('not valid!'); // alert not valid!
}
});
}
}
});
});
</code></pre>
<p>But I need to do validation example if emailid = admin@admin.com & passsword = admin1234 when I click the submit it needs to check whether my emailid was John@xyz.com and passsword was password if both was successful it has to redirect, else it has to show error message in the label.</p>
<p>Now I am getting the error as HTTP Error 405.0 - Method Not Allowed</p>
<p>Here is the Fiddle <a href="http://jsfiddle.net/karthic2914/ny9bt1ak/4/" rel="nofollow">Link</a></p>
<p>Thanks in advance</p>
<p>Regards
M</p>
| 1 | 1,250 |
matdialog 'mat-label' is not a known element
|
<p>I have an <code>angular 5.0.2</code> app. I'm trying to put a form in my <code>MatDialog</code> component. The dialog works but when I put from fields in there it breaks and gives the error.</p>
<blockquote>
<p>compiler.js:466 Uncaught Error: Template parse errors: 'mat-label' is
not a known element:<br />
1 . If 'mat-label' is an Angular component, then verify that it is part of this module.</p>
</blockquote>
<p>Here is the dialog component ts</p>
<pre class="lang-js prettyprint-override"><code>import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'email-dialog',
templateUrl: './email-dialog.component.html',
styleUrls: ['./email-dialog.component.css']
})
export class EmailDialogComponent {
constructor(
public dialogRef: MatDialogRef<EmailDialogComponent>) { }
onNoClick(): void {
this.dialogRef.close();
}
}
</code></pre>
<p>html</p>
<pre class="lang-html prettyprint-override"><code><div mat-dialog-content>
<mat-form-field>
<mat-label>Title</mat-label>
<mat-input placeholder="Title"></mat-input>
</mat-form-field>
</div>
<div mat-dialog-actions>
<button class="cfm-btn btn-n" mat-button (click)="onNoClick()">Cancel</button>
<button class="cfm-btn btn-y" mat-button [mat-dialog-close]="true">Send</button>
</div>
</code></pre>
<p>Here is my app.module. I've imported <code>MatFormFieldModule</code> and placed them under <code>imports</code> and <code>exports</code> I don't see what I'm missing.</p>
<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Http, HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { GlobalService } from './shared/global.service';
import { SharedModule } from './shared/shared.module';
import { LP_HTTP_PROVIDERS } from './shared/http.interceptor';
import { GenericService } from 'app/shared/generic.service';
import { RequestSelectComponent } from 'app/request/request-select.component';
import {MatTableModule} from '@angular/material/table';
import { MatProgressSpinnerModule, MatSliderModule, MatButtonToggleModule, MatChipsModule, MatFormFieldModule, MatButtonModule, MatSelectModule, MatCheckboxModule, MatInputModule, MatRadioModule, MatAutocompleteModule, MatTooltipModule, MatTabsModule, MatGridListModule, MatSnackBarModule, MatProgressBarModule, MatDialogModule, MatCardModule, MatExpansionModule, MatIconModule, MatDatepickerModule, MatNativeDateModule, MatPaginatorModule, MatSortModule } from '@angular/material';
import { DynamicFormComponent } from 'app/questionnaire/dynamic-form.component';
import { DynamicFormGroupComponent } from 'app/questionnaire/dynamic-form-group.component';
import { DynamicFormQuestionComponent } from 'app/questionnaire/dynamic-form-question.component';
import { LoadingComponent } from 'app/loading/loading.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { VaultComponent } from 'app/components/vault.component';
import { CookieService } from 'ngx-cookie-service';
import { FlexLayoutModule } from '@angular/flex-layout';
import { ProjectOrderCodeComponent } from 'app/questionnaire/project-order-code.component';
import { ProjectOrderCodeKitsComponent } from 'app/questionnaire/project-order-code-kits.component';
import { OwlDateTimeModule } from 'ng-pick-datetime';
import { DateTimePickComponent } from 'app/questionnaire/datetime-picker.component';
import { DraftSearchComponent } from 'app/modals/draft-search.component';
import { ZupSearchComponent } from 'app/questionnaire/zup-search.component';
import { ProjectConversionComponent } from 'app/project-conversion/project-conversion.component';
import { ProjectConversionRowComponent } from 'app/project-conversion/project-conversion-row.component';
import { ProjectConversionRowFilterComponent } from 'app/project-conversion/project-conversion-row-filter.component';
import { ProjectConversionRowFiltersComponent } from 'app/project-conversion/project-conversion-row-filters.component';
import { WorkfrontParameterComponent } from 'app/project-conversion/workfront-parameter.component';
import { RadioControlComponent } from 'app/workfront-controls/radio-control.component';
import { MultiSelectControlComponent } from 'app/workfront-controls/multi-select-control.component';
import { SelectControlComponent } from 'app/workfront-controls/select-control.component';
import { TextControlComponent } from 'app/workfront-controls/text-control.component';
import { DateControlComponent } from 'app/workfront-controls/date-control.component';
import { CheckboxControlComponent } from 'app/workfront-controls/checkbox-control.component';
import { SelfServicingComponent } from 'app/self-servicing/self-servicing.component';
import { OwlNativeDateTimeModule } from 'ng-pick-datetime';
import { OWL_DATE_TIME_LOCALE } from 'ng-pick-datetime';
import { OWL_DATE_TIME_FORMATS } from 'ng-pick-datetime';
import { ZupAdvancedSearchComponent } from 'app/zup-advanced-search/zup-advanced-search.component';
import { ZupAdvancedSearchResultsComponent } from 'app/zup-advanced-search/zup-advanced-search-results.component';
import { CopyRequestComponent } from './modals/copy-request.component';
import { CsatEmailComponent } from 'app/csat/csat-email.component';
import {ConfirmationDialogComponent} from 'app/components/confimation-dialog/confirmation-dialog.component';
import {EmailDialogComponent} from 'app/components/email-component/email-dialog.component';
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
RouterModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
MatButtonModule,
MatSelectModule,
MatCheckboxModule,
MatInputModule,
MatRadioModule,
MatAutocompleteModule,
MatTooltipModule,
MatTabsModule,
MatSnackBarModule,
MatGridListModule,
MatProgressBarModule,
MatCardModule,
MatExpansionModule,
MatIconModule,
MatDatepickerModule,
MatNativeDateModule,
MatTableModule,
MatPaginatorModule,
FlexLayoutModule,
OwlDateTimeModule,
OwlNativeDateTimeModule,
MatDialogModule,
MatSortModule,
MatFormFieldModule,
MatChipsModule,
MatButtonToggleModule,
MatSliderModule,
MatProgressSpinnerModule
],
providers: [
GlobalService,
GenericService,
LP_HTTP_PROVIDERS,
CookieService,
{provide: OWL_DATE_TIME_LOCALE, useValue: 'en-US'}
],
entryComponents: [ConfirmationDialogComponent, EmailDialogComponent],
exports: [ SharedModule, MatTableModule, MatFormFieldModule ],
declarations: [ AppComponent, RequestSelectComponent, DynamicFormComponent, DynamicFormGroupComponent, DynamicFormQuestionComponent, LoadingComponent, VaultComponent, ProjectOrderCodeComponent, DateTimePickComponent, DraftSearchComponent, ZupSearchComponent, ProjectConversionComponent, ProjectConversionRowComponent, ProjectConversionRowFiltersComponent, ProjectConversionRowFilterComponent, WorkfrontParameterComponent, RadioControlComponent, MultiSelectControlComponent, SelectControlComponent, TextControlComponent, DateControlComponent, CheckboxControlComponent, SelfServicingComponent, ZupAdvancedSearchComponent, ZupAdvancedSearchResultsComponent, ProjectOrderCodeKitsComponent, CopyRequestComponent, CsatEmailComponent,
ConfirmationDialogComponent, EmailDialogComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
</code></pre>
| 1 | 2,616 |
Overwriting CSS from CSS library (Bootstrap)
|
<p>My main issue with using CSS libraries is that they often overwrite custom CSS styles that I specifically set. For example, here I have a list that exists within a Bootstrap expand/collapse menu:</p>
<pre><code><ul class="nav navbar-nav">
<li>
<a href="#" style=""><img src="images/arrow.gif" style="width: 20px;">Link A</a>
</li>
</ul>
</code></pre>
<p>I want to set my own font color, so I use the following CSS:</p>
<pre><code>nav li {
font-size: 16px;
color: #004687;
}
</code></pre>
<p>But when I view in Firefox's Inspector, I see the color I have chosen is being overridden by Bootstrap.</p>
<p>My custom CSS occurs <strong>after</strong> the Bootstrap files have been loaded in the of the HTML document.</p>
<p>How do I prevent this happening without setting <code>style="color: #004687"</code> to every element?</p>
<p><strong>EDIT:</strong> Thanks for the suggestions thus far, but none have been successful. I'm pasting the full original code to give you greater detail:</p>
<pre><code><div class="container">
<header class="navbar navbar-static-top bs-docs-nav">
<div class="col-md-4 visible-xs" id="mobile-nav-outer">
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="../" class="navbar-brand">Menu</a>
</div>
<nav class="collapse navbar-collapse bs-navbar-collapse" id="mobile-nav-inner" role="navigation">
<ul class="nav navbar-nav">
<li>
<a href="#" class="nav-mobile-link"><img src="images/arrow.gif" style="width: 20px;">Link A</a>
</li>
</ul>
</nav>
</div>
</header>
</div>
</code></pre>
<p>My CSS is included like this:</p>
<pre><code> <head>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="bootstrap/css/docs.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<style type="text/css">
#mobile-nav-outer {
border: 1px solid #CCC;
background-color: #FFF;
}
#mobile-nav-inner {
border: 1px solid #CCC;
background-color: #FFF;
margin: 3px;
}
nav li {
font-size: 16px;
color: #004687;
}
.nav-mobile-link {
font-size: 16px;
color: #004687;
}
</style>
</head>
</code></pre>
<p><strong>EDIT 3:</strong> I have found a cheap workaround by using ID's rather than classes which works due to CSS specificity (ID's override classes). This isn't a very clean solution and I'd still like to know why I cannot override the Bootstrap classes with my own.</p>
| 1 | 1,525 |
pymongo.errors.CursorNotFound: cursor id '…' not found at server
|
<p>I am trying to read about 1M documents from mongodb to csv file using pymongo. My code looks like:</p>
<pre><code>import csv
from pymongo import MongoClient
from datetime import datetime
from bson import json_util
from tempfile import NamedTemporaryFile
client = MongoClient('mongodb://login:pass@server:port')
db = client.some_mongo_database
collection = db.some_mongo_collection
fromDate = datetime.strptime("2018-05-15 21:00", '%Y-%m-%d %H:%M')
tillDate = datetime.strptime("2018-05-16 21:00", '%Y-%m-%d %H:%M')
query = {
"$or": [
{"LastUpdated": {"$gte": fromDate
, "$lt": tillDate}
},
{"$and": [
{"Created": {"$gte": fromDate
, "$lt": tillDate}
},
{"LastUpdated": None}
]
}
]
}
cursor = collection.find(query, no_cursor_timeout=True)
</code></pre>
<p>after that if I'l do:</p>
<pre><code>for row in cursor:
print(row)
cursor.close()
</code></pre>
<p>everything works fine, and I could get all the documents.
But if I do something like that:</p>
<pre><code>with NamedTemporaryFile("w", delete=False) as temp:
csv_writer = csv.writer(temp, delimiter='\t', quotechar='\b', quoting=csv.QUOTE_MINIMAL)
for row in cursor:
csv_row = [ [[row['_id']], str(json.dumps(row,default=json_util.default))] ]
csv_writer.writerows(csv_row)
cursor.close()
</code></pre>
<p>After about 2 minutes and 200k documents I'm receive:</p>
<pre><code>Traceback (most recent call last):
File "mongo_data_loader.py", line 25, in <module>
for row in cursor:
File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 1169, in next
if len(self.__data) or self._refresh():
File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 1106, in _refresh
self.__send_message(g)
File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 975, in __send_message
helpers._check_command_response(first)
File "/Library/Python/2.7/site-packages/pymongo/helpers.py", line 142, in _check_command_response
raise CursorNotFound(errmsg, code, response)
pymongo.errors.CursorNotFound: cursor id 184972541202 not found
</code></pre>
<p>What am I doing wrong?</p>
<pre><code>Python 2.7.10
pymongo 3.6.1
mongo db.version() 3.6.5
</code></pre>
| 1 | 1,134 |
angular2 failing lodash import
|
<p>I started simple Angular 2 app, all working. But when I add import of lodash and try to use it, I get errors and the app stops working, and can't figure out what is the problem.</p>
<p><strong>I am getting these 2 errors in console:</strong></p>
<blockquote>
<p>Uncaught SyntaxError: Unexpected token <__exec @ system.src.js:1374entry.execute @ system.src.js:3300linkDynamicModule @ system.src.js:2921link @ system.src.js:2764execute @ system.src.js:3096doDynamicExecute @ system.src.js:715link @ system.src.js:908doLink @ system.src.js:569updateLinkSetOnLoad @ system.src.js:617(anonymous function) @ system.src.js:430run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2-polyfills.js:138 </p>
<p>Uncaught SyntaxError: Unexpected token <
Evaluating <a href="http://localhost:3000/lodash" rel="nofollow">http://localhost:3000/lodash</a>
Error loading <a href="http://localhost:3000/app/app.jsrun" rel="nofollow">http://localhost:3000/app/app.jsrun</a> @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:1444(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305</p>
</blockquote>
<p><strong>FILES</strong></p>
<p><strong>index.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/app')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>tsconfig.json</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}</code></pre>
</div>
</div>
</p>
<p><strong>package.json</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.2",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"lodash": "^4.1.0",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"systemjs": "0.19.6",
"zone.js": "0.5.10"
},
"devDependencies": {
"concurrently": "^1.0.0",
"lite-server": "^1.3.4",
"typescript": "^1.7.5"
}
}</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {bootstrap} from 'angular2/platform/browser'
import {Component} from 'angular2/core';
import * as _ from 'lodash';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App with lodash</h1>'
})
export class AppComponent {
constructor(){
console.log(_.last([1, 2, 3]));
console.log('hello');
}
}
bootstrap(AppComponent);</code></pre>
</div>
</div>
</p>
| 1 | 2,219 |
expression pattern of type 'CountableClosedRange<Int>' cannot match values of type 'Int'?
|
<p>At one point before Swift 3 this code would work without any compile errors however after converting to Swift 3 this code isn't compiling and I don't completely understand how the value types are different.</p>
<p>The error given is <code>expression pattern of type 'CountableClosedRange<Int>' cannot match values of type 'Int'</code> for the switch cases where I'm attempting to use different ranges of values in the switch statement:</p>
<pre><code>switch hour {
case 0 ... 11:
greetingStatement.text = "Good Morning"
case 12 ... 24:
greetingStatement.text = "Good Evening"
default:
greetingStatement.text = "Hello"
}
</code></pre>
<p>Here is the full code:</p>
<pre><code>import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userInput: UITextField!
@IBOutlet weak var usertOutput: UILabel!
@IBOutlet weak var tapMeAfterEnteringYourName: UIButton!
@IBOutlet weak var greetingStatement: UILabel!
@IBOutlet weak var letsGetStartedLabel: UILabel!
@IBOutlet weak var ballonsImageView: UIImageView!
@IBOutlet weak var teacherPointingToBoardImage: UIImageView!
@IBAction func setOutput(_ sender: AnyObject){
greetingStatement.isHidden = false
usertOutput.text=userInput.text
tapMeAfterEnteringYourName.isHidden = true
userInput.isHidden = true
letsGetStartedLabel.isHidden = false
ballonsImageView.isHidden = false
let date = Date()
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.hour], from: date)
let hour = components.hour
switch hour {
case 0 ... 11:
greetingStatement.text = "Good Morning"
case 12 ... 24:
greetingStatement.text = "Good Evening"
default:
greetingStatement.text = "Hello"
}
view.backgroundColor = UIColor.magenta
teacherPointingToBoardImage.isHidden=true
var timer = Timer.scheduledTimer(timeInterval: 1.4, target: self, selector: #selector(ViewController.updateViewController), userInfo: nil, repeats: false)
let hover = CABasicAnimation(keyPath: "position")
hover.isAdditive = true
hover.fromValue = NSValue(cgPoint: CGPoint.zero)
hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: -100.0))
hover.autoreverses = true
hover.duration = 5
hover.repeatCount = Float.infinity
ballonsImageView.layer.add(hover, forKey: "myHoverAnimation")
}
func updateViewController() {
print("Timer just fired")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let resultViewController = storyBoard.instantiateViewController(withIdentifier: "MadLibOneViewController") as! MadLibOneViewController
self.present(resultViewController, animated:true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor=UIColor.purple
usertOutput.textColor=UIColor.white
userInput.textColor = UIColor.purple
greetingStatement.isHidden = true
letsGetStartedLabel.isHidden = true
ballonsImageView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
</code></pre>
<p>Can someone clarify that is simply a generic where any type of Int is allowable or expected?</p>
| 1 | 1,335 |
Notice: Trying to get property of non-object - nor is foreach looping properly
|
<p>For some reason I cannot for the life of me figure out/understand why this is not working properly...All I am trying to do is display comments on a photo page. The photo I am testing this on has 2 comments but all I get is the following:</p>
<pre><code>Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/photo_gallery/public/photo.php on line 47
NULL @ ::
</code></pre>
<p>photo.php page is simply calling for the comments by the photo id and then displaying them in a foreach loop:</p>
<pre><code><?php
$photo = Photograph::findByID($_GET['id']);
$comments = $photo->comments();
printr($comments);
?>
<div class="comments">
<?php if ($comments): ?>
<?php foreach ($comments as $comment): ?>
<p style="margin-bottom: 15px;">
<?php echo htmlentities($comment->author); ?> @ <?php echo strip_tags($comment->created, '<strong><em><p>'); ?> :: <?php echo $comment->body; ?>
</p>
<?php endforeach; ?>
<?php else: ?>
<p>No comments found.</p>
<?php endif; ?>
</div>
</code></pre>
<p>When I print_r on the $comments results, only the first comment shows up in the object array..</p>
<p><strong>Part of the Photograph class:</strong></p>
<pre><code>class Photograph extends DatabaseObject {
public $id;
function comments() {
return Comment::findCommentsOn($this->id);
}
}
</code></pre>
<p><strong>Part of the MySQLiDatabase class:</strong></p>
<pre><code>public static function findByPrepare($sql = "", $params) {
global $db;
$result = $db->query($sql, $params);
foreach ($result as $row) {
printr($result);
return self::instantiate($row);
}
}
private static function instantiate($record) {
$className = get_called_class();
$obj = new $className;
foreach ($record as $attribute => $val) {
if ($obj->hasAttribute($attribute)) {
$obj->$attribute = $val;
}
}
return $obj;
}
private function hasAttribute($key) {
// get_object_vars returns an assoc array with all attributes as keys and their current values as the value
$objVars = $this->attributes();
return array_key_exists($key, $objVars);
}
protected function attributes() {
// return an array of attribute keys and their values
$attributes = array();
foreach(static::$dbFields as $field) {
if (property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
</code></pre>
<p>Seems like it is stemming from the foreach in the findByPrepare() function...</p>
<p>When I printr($result) it shows both comments in an array fine, however when I printr($row) it displays just the first comment in an array...so somehow I need to get $row to loop through each result. I have tried looping the self::instantiate($row) in an array but then that throws another error: <strong>Fatal error: Call to a member function comments() on a non-object</strong></p>
<p>*<strong>print_r on $comments (this is only coming up with 1 result when there's actually 2 comments)*</strong></p>
<pre><code>Comment Object
(
[id] => 1
[photo_id] => 1
[created] => 2013-12-20 16:37:02
[author] => Nate
[body] => This is a cool pic!
)
</code></pre>
<p>*<strong>var_dump($comment->author) displays*</strong></p>
<pre><code>NULL @ ::
</code></pre>
<p>*<strong>var_dump($comments) displays*</strong></p>
<pre><code>object(Comment)#4 (5) { ["id"]=> int(1) ["photo_id"]=> int(1) ["created"]=> string(19) "2013-12-20 16:37:02" ["author"]=> string(4) "Nate" ["body"]=> string(19) "This is a cool pic!" }
</code></pre>
<p><em>The rest of the code that was requested:</em></p>
<p><strong>Comments class:</strong></p>
<pre><code>class Comment extends DatabaseObject {
protected static $tableName = "comments";
protected static $dbFields = array('id', 'photo_id', 'created', 'author', 'body');
public $id;
public $photo_id;
public $created;
public $author;
public $body;
public static function findCommentsOn($photo_id = 0) {
$params = func_get_args();
$sql = "SELECT * FROM ". self::$tableName ." WHERE photo_id = ? ORDER BY created ASC";
$results = parent::findByPrepare($sql, $params);
return $results;
}
}
</code></pre>
<p><strong>MySQLiDatabase class:</strong></p>
<pre><code>class MySQLiDatabase {
public $conn;
public $lastQuery;
public $stmt;
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private $params;
public function __construct() {
$this->connection();
}
public function connection() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($this->conn->connect_errno) {
return "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
public function query($sql, $params) {
$this->lastQuery = $sql;
$result = $this->prepareQuery($sql, $params);
if ($params) { $this->bindParams($params, $this->stmt); }
$this->stmt->execute();
$results = $this->bindResults($this->stmt);
return $results;
}
private function prepareQuery($sql, $params) {
$this->stmt = $this->conn->prepare($sql);
$this->confirmQuery($this->stmt);
return $this->stmt;
}
public function bindParams($params, $stmt) {
$types = "";
for($i = 0; $i < sizeof($params); $i++) {
$types .= "s";
}
$array = array_merge(array($types), $params);
return call_user_func_array(array($this->stmt, 'bind_param'), $this->refValues($array));
}
public function bindResults($stmt) {
if ($stmt->affected_rows === -1) { // SELECT
$meta = $this->stmt->result_metadata();
$params = array();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($this->stmt, 'bind_result'), $params);
$results = array();
while ($stmt->fetch()) {
$x = array();
foreach ($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
} else { // INSERT UPDATE DELETE
$results = $stmt->affected_rows;
}
return $results;
}
</code></pre>
| 1 | 3,091 |
How can I display value of input type date when edit data on vue component?
|
<p>My vue component like this :</p>
<pre><code><template>
<section>
...
<form-input id="total-sold" name="total-sold" :value="products.total_sold">Total Sold</form-input>
<form-input id="created-at" type="date" name="created-at" :value="products.created_at">Created At</form-input>
</section>
</template>
<script>
export default {
props: ['products'],
mounted() {
console.log(this.products.total_sold) // The result : 46
console.log(this.products.created_at) // The result : 2018-02-26 09:03:03
},
}
</script>
</code></pre>
<p>My form-input component vue like this :</p>
<pre><code><template>
<div class="form-group">
<label :for="id" class="control-label" :class="classLabel"><slot></slot></label>
<input :type="type" :name="name" :id="id" class="form-control" :placeholder="dataPlaceholder" :disabled="disabled" :value="value">
</div>
</template>
<script>
export default {
name: "form-input",
props: {
'id': String,
'name': String,
'type': {
type: String,
default: 'text'
},
'disabled': String,
'dataPlaceholder': {
type: String,
default() {
return this.$slots.default ? this.$slots.default[0].text : ''
}
},
'value': {
type: [String, Number]
}
},
data(){
return {
classLabel: {'sr-only': !this.$slots.default}
}
}
}
</script>
</code></pre>
<p>So on the my first component vue, it will call form-input component vue. I make the component like that. So later that component can be used repeatedly</p>
<p>If the component executed, the input text from total sold display data. The result is 46. But the input text from created at is not display data. Seems it because the type is date</p>
<p>How can I solve this problem? </p>
| 1 | 1,059 |
Selenium is not running with Firefox 12.0
|
<p>Selenium is not working after Firefox upgraded to latest version 12.0. It is failing with below message. Please advise, it is still working fine if i use older version of firefox. </p>
<pre><code>org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
*** LOG addons.xpi: startup
*** LOG addons.xpi: Skipping unavailable install location app-system-local
*** LOG addons.xpi: Skipping unavailable install location app-system-share
*** LOG addons.xpi: Ignoring file entry whose name is not a valid add-on ID: C:\Users\Abdul\AppData\Local\Temp\anonymous869859993705622974webdriver-profile\extensions\webdriver-staging
*** LOG addons.xpi: checkForChanges
*** LOG addons.xpi: No changes found
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:95)
at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:157)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:93)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:136)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:78)
at Google.Open_Google_Firefox.Test_Google_FireFox(Open_Google_Firefox.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:702)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:894)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1219)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:768)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:87)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
at org.testng.TestNG.run(TestNG.java:1022)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:109)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
FAILED CONFIGURATION: @AfterMethod tearDown
</code></pre>
<p>..
..
..
..</p>
| 1 | 1,084 |
Ruby Kafka Uncaught exception: Failed to find group coordinator
|
<p>I use Apache Kafka as Docker container <a href="https://hub.docker.com/r/wurstmeister/kafka/" rel="nofollow noreferrer">https://hub.docker.com/r/wurstmeister/kafka/</a></p>
<p>I'm able to successfully connect to Kafka from my Java application with Spring Kafka.</p>
<p>But when I try to connect to Kafka from the Ruby application via Ruby Kafka I receive the following error:</p>
<pre><code>Uncaught exception: Failed to find group coordinator
</code></pre>
<p>The only difference between the Java and Ruby applications - is that Ruby application is located on another machine in my local network but I can see the Kafka machine from Ruby machine and all of the ports there. </p>
<p>How to find the issue and solve it?</p>
<p><strong>UPDATED</strong></p>
<pre><code>I, [2018-06-25T10:06:49.513848 #62261] INFO -- : New topics added to target list: post.sent
I, [2018-06-25T10:06:49.514036 #62261] INFO -- : Fetching cluster metadata from kafka://10.0.0.102:9093
D, [2018-06-25T10:06:49.514262 #62261] DEBUG -- : Opening connection to 10.0.0.102:9093 with client id test...
D, [2018-06-25T10:06:49.518350 #62261] DEBUG -- : Sending topic_metadata API request 1 to 10.0.0.102:9093
D, [2018-06-25T10:06:49.519336 #62261] DEBUG -- : Waiting for response 1 from 10.0.0.102:9093
D, [2018-06-25T10:06:49.530220 #62261] DEBUG -- : Received response 1 from 10.0.0.102:9093
I, [2018-06-25T10:06:49.530351 #62261] INFO -- : Discovered cluster metadata; nodes: 10.0.75.1:9093 (node_id=1001)
D, [2018-06-25T10:06:49.530439 #62261] DEBUG -- : Closing socket to 10.0.0.102:9093
I, [2018-06-25T10:06:49.530682 #62261] INFO -- : Joining group `my_group`
D, [2018-06-25T10:06:49.530812 #62261] DEBUG -- : Getting group coordinator for `my_group`
D, [2018-06-25T10:06:49.531019 #62261] DEBUG -- : Opening connection to 10.0.75.1:9093 with client id test...
D, [2018-06-25T10:06:49.616368 #62261] DEBUG -- : Handling fetcher command: subscribe
I, [2018-06-25T10:06:49.616797 #62261] INFO -- : Will fetch at most 1048576 bytes at a time per partition from post.sent
D, [2018-06-25T10:06:49.617262 #62261] DEBUG -- : Handling fetcher command: configure
D, [2018-06-25T10:06:49.617462 #62261] DEBUG -- : Handling fetcher command: start
D, [2018-06-25T10:06:49.617599 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:49.618108 #62261] INFO -- : Fetching cluster metadata from kafka://10.0.0.102:9093
D, [2018-06-25T10:06:49.619053 #62261] DEBUG -- : Opening connection to 10.0.0.102:9093 with client id test...
D, [2018-06-25T10:06:49.624053 #62261] DEBUG -- : Sending topic_metadata API request 1 to 10.0.0.102:9093
D, [2018-06-25T10:06:49.625459 #62261] DEBUG -- : Waiting for response 1 from 10.0.0.102:9093
D, [2018-06-25T10:06:49.635283 #62261] DEBUG -- : Received response 1 from 10.0.0.102:9093
I, [2018-06-25T10:06:49.635468 #62261] INFO -- : Discovered cluster metadata; nodes: 10.0.75.1:9093 (node_id=1001)
D, [2018-06-25T10:06:49.635596 #62261] DEBUG -- : Closing socket to 10.0.0.102:9093
I, [2018-06-25T10:06:49.635853 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:50.637187 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:50.637804 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:51.642172 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:51.642471 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:52.645354 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:52.645640 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:53.647833 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:53.648259 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:54.650357 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:54.650647 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:55.652582 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:55.653477 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:56.657937 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:56.659627 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:57.664130 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:57.664861 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
D, [2018-06-25T10:06:58.666290 #62261] DEBUG -- : Fetching batches
I, [2018-06-25T10:06:58.666620 #62261] INFO -- : There are no partitions to fetch from, sleeping for 1s
E, [2018-06-25T10:06:59.534809 #62261] ERROR -- : Timed out while trying to connect to 10.0.75.1:9093: Operation timed out
D, [2018-06-25T10:06:59.535083 #62261] DEBUG -- : Closing socket to 10.0.75.1:9093
E, [2018-06-25T10:06:59.535342 #62261] ERROR -- : Failed to get group coordinator info from 10.0.75.1:9093 (node_id=1001): Operation timed out
I, [2018-06-25T10:06:59.535567 #62261] INFO -- : Leaving group `my_group`
D, [2018-06-25T10:06:59.535709 #62261] DEBUG -- : Getting group coordinator for `my_group`
D, [2018-06-25T10:06:59.535875 #62261] DEBUG -- : Opening connection to 10.0.75.1:9093 with client id test...
D, [2018-06-25T10:06:59.666983 #62261] DEBUG -- : Handling fetcher command: stop
E, [2018-06-25T10:07:09.540409 #62261] ERROR -- : Timed out while trying to connect to 10.0.75.1:9093: Operation timed out
D, [2018-06-25T10:07:09.540833 #62261] DEBUG -- : Closing socket to 10.0.75.1:9093
E, [2018-06-25T10:07:09.541172 #62261] ERROR -- : Failed to get group coordinator info from 10.0.75.1:9093 (node_id=1001): Operation timed out
Exiting
Uncaught exception: Failed to find group coordinator
</code></pre>
| 1 | 2,307 |
Adding custom list adapter to a TableLayout
|
<p>I have a custom list adapter inside of a TableLayout. This TableLayout is nested inside a of a LinearLayout.</p>
<p>The list adapter expands if new childviews are added to the list. I want the size of the TableRow to increase dynamically when the size of the list adapter increases. And the buttons pushed down when the list grows.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent" android:layout_width="match_parent"
>
<LinearLayout">
<!-- Draw header + sub title -->
<LinearLayout android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent" >
<TextView ></TextView>
<TextView ></TextView>
</LinearLayout>
<LinearLayout android:orientation="horizontal">
<ImageView />
<LinearLayout android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent"
android:layout_weight="1">
<TableLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1">
<TableRow android:id="@+id/tr1">
<CustomList android:id="@+id/mainview"
ndroid:layout_height="wrap_content" android:layout_width="wrap_content" />
</TableRow>
<TableRow android:layout_height="wrap_content"
android:layout_width="match_parent">
<Button android:layout_width="wrap_content" android:id="@+id/button1"
android:text="@string/buttonPrevious" android:layout_height="wrap_content">
</Button>
<Button android:layout_width="wrap_content" android:id="@+id/button2"
android:text="@string/buttonNext" android:layout_height="wrap_content"></Button>
</TableRow>
</TableLayout>
</LinearLayout>
<ImageView />
</LinearLayout>
</ScrollView>
</code></pre>
<p>Do I have to do change something like change the way layouts are inflated in my custom list adapter or anything else?</p>
| 1 | 1,251 |
how to call qweb report in another model in odoo?
|
<p>I have created a wizard in the that using many2one field of another model. where the qweb-report has been mentioned. Now I want to select 1record(from many2one field) and print the respective report.[previously i've done invoice printing in that menu's form view.] . sometimes here empty report is getting prints.Can anybody please explain it clearly?here is my code.</p>
<pre><code>class invoice_wizard(osv.TransientModel):
_name = 'invoice.wizard'
_columns = {
'name':fields.many2one('hotel.booking',string="CustomerName"),
}
def invoice_print(self,cr,uid,ids,vals,context=None):
bookz=self.browse(cr,uid,ids,context=context)
ids2=self.pool.get['book.room'].search([('name','=',bookz.name.name)])
data = {
'ids': ids2,
'model': 'book.room',
'form': self.env['book.room'].read(['name'])[0]
}
return self.env['report'].get_action(self, 'hotels.Booking_Details',
data=data)
invoice_wizard()
</code></pre>
<p>I'm getting this error:</p>
<pre><code>Traceback (most recent call last):
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 537, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 574, in dispatch
result = self._call_function(**self.params)
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 310, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/service/model.py", line 113, in wrapper
return f(dbname, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 307, in checked_call
return self.endpoint(*a, **kw)
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 803, in __call__
return self.method(*args, **kw)
File "/home/anipr/Desktop/odoo-8.0/openerp/http.py", line 403, in response_wrap
response = f(*args, **kw)
File "/home/anipr/Desktop/odoo-8.0/openerp/addons/web/controllers/main.py", line 952, in call_button
action = self._call_kw(model, method, args, {})
File "/home/anipr/Desktop/odoo-8.0/openerp/addons/web/controllers/main.py", line 940, in _call_kw
return checked_call(request.db, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/service/model.py", line 113, in wrapper
return f(dbname, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/addons/web/controllers/main.py", line 939, in checked_call
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/anipr/Desktop/odoo-8.0/openerp/addons/hotels/wizard/hotel_wizard.py", line 50, in invoice_print
ids2=self.pool.get['book.room'].search([('name','=',bookz.name.name)])
TypeError: 'instancemethod' object has no attribute '__getitem__'
</code></pre>
<p>thanks in advance..!! </p>
| 1 | 1,167 |
Read huge table with LINQ to SQL: Running out of memory vs slow paging
|
<p>I have a huge table which I need to read through on a certain order and compute some aggregate statistics. The table already has a clustered index for the correct order so getting the records themselves is pretty fast. I'm trying to use LINQ to SQL to simplify the code that I need to write. The problem is that I don't want to load all the objects into memory, since the DataContext seems to keep them around -- yet trying to page them results in horrible performance problems.</p>
<p>Here's the breakdown. Original attempt was this:</p>
<pre><code>var logs =
(from record in dataContext.someTable
where [index is appropriate]
select record);
foreach( linqEntity l in logs )
{
// Do stuff with data from l
}
</code></pre>
<p>This is pretty fast, and streams at a good rate, but the problem is that the memory use of the application keeps going up never stops. My guess is that the LINQ to SQL entities are being kept around in memory and not being disposed properly. So after reading <a href="https://stackoverflow.com/questions/2727591/out-of-memory-when-creating-a-lot-of-objects-c-sharp">Out of memory when creating a lot of objects C#</a> , I tried the following approach. This seems to be the common <code>Skip</code>/<code>Take</code> paradigm that many people use, with the added feature of saving memory.</p>
<p>Note that <code>_conn</code> is created beforehand, and a temporary data context is created for each query, resulting in the associated entities being garbage collected.</p>
<pre><code>int skipAmount = 0;
bool finished = false;
while (!finished)
{
// Trick to allow for automatic garbage collection while iterating through the DB
using (var tempDataContext = new MyDataContext(_conn) {CommandTimeout = 600})
{
var query =
(from record in tempDataContext.someTable
where [index is appropriate]
select record);
List<workerLog> logs = query.Skip(skipAmount).Take(BatchSize).ToList();
if (logs.Count == 0)
{
finished = true;
continue;
}
foreach( linqEntity l in logs )
{
// Do stuff with data from l
}
skipAmount += logs.Count;
}
}
</code></pre>
<p>Now I have the desired behavior that memory usage doesn't increase at all as I am streaming through the data. Yet, I have a far worse problem: each <code>Skip</code> is causing the data to load more and more slowly as the underlying query seems to actually cause the server to go through all the data for all previous pages. While running the query each page takes longer and longer to load, and I can tell that this is turning into a quadratic operation. This problem has appeared in the following posts:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/5261717/linq-skip-problem">LINQ Skip() Problem</a></li>
<li><a href="https://stackoverflow.com/questions/8202907/linq2sql-select-orders-and-skip-take">LINQ2SQL select orders and skip/take</a></li>
</ul>
<p>I can't seem to find a way to do this with LINQ that allows me to have limited memory use by paging data, and yet still have each page load in constant time. Is there a way to do this properly? <strong>My hunch is that there might be some way to tell the DataContext to explicitly forget about the object in the first approach above, but I can't find out how to do that.</strong></p>
| 1 | 1,066 |
What am i doing wrong? : Context Cannot be used while the model is being Created
|
<p>I'm stucked with this problem and i've spent more than 3 hours scouring the web and SO for a solution to no avail. My Code keeps throwing this error </p>
<blockquote>
<p>The context cannot be used while the model is being created. This
exception may be thrown if the context is used inside the
OnModelCreating method or if the same context instance is accessed by
multiple threads concurrently. Note that instance members of DbContext
and related classes are not guaranteed to be thread safe.</p>
</blockquote>
<p>This is my Context</p>
<pre><code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<ApprovalStatus> ApprovalStatuses { get; set; }
public DbSet<Bank> Banks { get; set; }
public DbSet<Documents> Documents { get; set; }
public DbSet<EducationLevel> EducationLevel { get; set; }
public DbSet<EmploymentDetail> EmploymentDetails { get; set; }
public DbSet<EmploymentStatus> EmploymentStatus { get; set; }
public DbSet<Gender> Genders { get; set; }
public DbSet<GuestPersonalDetail> GuestPersonalDetails { get; set; }
public DbSet<LGA> LocalGovts { get; set; }
public DbSet<LoanDetail> LoanDetails { get; set; }
public DbSet<MaritalStatus> MaritalStatuses { get; set; }
public DbSet<NameTitle> NameTitles { get; set; }
public DbSet<NextOfKin> NextOfKins { get; set; }
public DbSet<RejectionReasons> RejectionReasons { get; set; }
public DbSet<RepaymentMode> RepaymentModes { get; set; }
}
</code></pre>
<p>in my controller i have this where i try to populate a dropdownlist in my view</p>
<pre><code>[HttpGet]
public ActionResult Apply()
{
var db = new ApplicationDbContext();
ApplicationVM model = new ApplicationVM();
model.BankList = new SelectList(db.Banks, "Bankid", "BankName");
model.EducationLevellist = new SelectList(db.EducationLevel, "EducationLevelid", "Level");
model.EmploymentStatuslist = new SelectList(db.EmploymentStatus, "EmploymentStatusid", "EmpStatus");
model.GenderList = new SelectList(db.Genders, "Genderid", "GenderVal");
model.LGAlist = new SelectList(db.LocalGovts, "LGAid", "LgName");
model.MaritalStatusList = new SelectList(db.MaritalStatuses, "MaritalStatusid", "Status");
model.NameTitleList = new SelectList(db.NameTitles, "NameTitleid", "Title");
model.RepaymentModeList = new SelectList(db.RepaymentModes, "RepaymentModeid", "ModeOfRepayment");
return View(model);
}
</code></pre>
<p>i used this in view like this</p>
<pre><code><div class="form-group">
@Html.LabelFor(model => model.ApplicantTitleid, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.ApplicantTitleid, Model.NameTitleList, null, String.Empty)
@Html.ValidationMessageFor(model => model.ApplicantTitleid)
</div>
</div>
</code></pre>
<p>The error is being thrown at the Dropdownlistfor point. This is the stack trace</p>
<pre><code>[InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.]
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +115
System.Data.Entity.Internal.InternalContext.Initialize() +31
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +138
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +38
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +108
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +157
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +133
System.Web.Mvc.MultiSelectList.GetListItemsWithValueField() +461
System.Web.Mvc.MultiSelectList.GetListItems() +89
System.Web.Mvc.MultiSelectList.GetEnumerator() +39
System.Web.Mvc.Html.SelectExtensions.GetSelectListWithDefaultValue(IEnumerable`1 selectList, Object defaultValue, Boolean allowMultiple) +557
System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +574
System.Web.Mvc.Html.SelectExtensions.DropDownListHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +56
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +233
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, Object htmlAttributes) +142
ASP._Page_Views_Loan_Apply_cshtml.Execute() in c:\Users\RIDWAN\Documents\visual studio 2013\projects\ApplicationPortal\ApplicationPortal\Views\Loan\Apply.cshtml:37
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +120
System.Web.WebPages.StartPage.RunPage() +63
System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass28.<BeginInvokeAction>b__19() +321
System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +932
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +188
</code></pre>
<p>What am i doing wrong exactly?</p>
| 1 | 3,183 |
ChartJS changing displayed data based on date?
|
<p>I have a simple section in which I am displaying data from the database
, in my database I have two tables which shares 'sid` (session id); my tables
looks like this.</p>
<pre><code>Events table
id sid targetbuttonid
1 1377Qqng1hn4866h7oh0t3uruu27dm5 Yes
2 9021391Q86nog1028jnoqol8bqcrt182o7 No
3 541Qqta8cs8s6kv60fei8i6jbesg36 Yes
</code></pre>
<p>And </p>
<pre><code>Sessions table
id sid datetime
1 1377Qqng1hn4866h7oh0t3uruu27dm5 2019-08-07 07:00:03
2 9021391Q86nog1028jnoqol8bqcrt182o7 2019-08-07 07:00:11
3 541Qqta8cs8s6kv60fei8i6jbesg36 2019-08-13 09:56:51
</code></pre>
<p>I am displaying these data using charts js on pie chart like this</p>
<p>HTML </p>
<pre><code><body>
data from <input type="text" id = "firstdatepicker" name = "firstdatepicker">
to <input type="text" id = "lastdatepicker" name = "lastdatepicker">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
<canvas id="myPieChart" width="400" height="400"></canvas>
</body>
</code></pre>
<blockquote>
<p>UPDATE.</p>
</blockquote>
<p>JS</p>
<pre><code> $(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#firstdatepicker").datepicker();
$("#lastdatepicker").datepicker();
});
$('#filter').click(function(){
var from_date = $('#firstdatepicker').val();
var to_date = $('#lastdatepicker').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"https://meed.audiencevideo.com/admin/chats/stats.php",
type:"GET",
data:{from_date:from_date, to_date:to_date},
success:function(data){
var session= data[0].sessions;
var yes = data[0].num_yes;
var no =data[0].num_no;
var ctx = document.getElementById("myPieChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["sessions","yes", "no"],
datasets: [{
label: 'Genders',
data: [session,yes, no],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 0.2)',
],
borderWidth: 1
}]
},
});
}
});
}
else
{
alert("Please Select Date");
}
});
});
</code></pre>
<p>Here is php.</p>
<pre><code><?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'vvvv');
define('DB_PASSWORD', 'vvvvv');
define('DB_NAME', 'vvvvv');
$firstdate = $_POST['firstdatepicker'];
$lastdate = $_POST['lastdatepicker'];
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
if (isset($_POST['firstdatepicker'])) {
$firstDate= $_POST['firstdatepicker'];
$lastDate= $_POST['lastdatepicker'];
$sql = sprintf("SELECT count(*) as num_rows, datetime, count(distinct sid) as sessions, sum( targetbuttonname = 'yes' ) as num_yes, sum( targetbuttonname = 'no' ) as num_no from events AND time BETWEEN '$firstdate' AND '$lastdate' ORDER BY datetime DESC");
}
//$query =sprintf("SELECT SUM( sid ) as session , COUNT( targetbuttonname ) as yes FROM events WHERE targetbuttonname LIKE 'Yes'");
$query = sprintf("SELECT count(*) as num_rows, count(distinct sid) as sessions, sum( targetbuttonname = 'yes' ) as num_yes, sum( targetbuttonname = 'no' ) as num_no from events;");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$mysqli->close();
print json_encode($data);
</code></pre>
<p>Now I want when user select date between certain dates, in pie chart it should display data based on those dates selected by user.</p>
<p>Unfortunately now when I select the dates data still the same <a href="https://meed.audiencevideo.com/admin/dashboard.php" rel="nofollow noreferrer">live demo</a></p>
<p>What am I doing wrong in my codes?.</p>
| 1 | 2,800 |
Getting objectManager / serviceLocator in fieldset in ZF2
|
<p>In order to get my object manager inside my fieldset's init() function I followed the <a href="http://framework.zend.com/manual/2.1/en/modules/zend.form.advanced-use-of-forms.html#the-specific-case-of-initializers" rel="nofollow">docs</a>
At first I found out that I had to change</p>
<pre><code>public function setServiceLocator(ServiceLocator $sl)
</code></pre>
<p>to</p>
<pre><code>public function setServiceLocator(ServiceLocatorInterface $sl)
</code></pre>
<p>otherwise I got an error:</p>
<pre><code>setServiceLocator() must be compatible with that of Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
</code></pre>
<p>When calling <code>$this->getServiceLocator()</code> I get an instance of the FormManager.
Additionally calling <code>$this->getServiceLocator()->getServiceLocator()</code> returns <code>NULL</code>.</p>
<p>Since I am still new to DI I wonder if I am missing a place to inject?</p>
<p>Testing I switched from</p>
<pre><code>$form = new MyForm();
</code></pre>
<p>to</p>
<pre><code>$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Application\Form\MyForm');
</code></pre>
<p>Since then I get this error:</p>
<pre><code>exception 'Zend\Di\Exception\RuntimeException' with message 'Invalid instantiator of type "NULL" for "Zend\ServiceManager\ServiceLocatorInterface".'
An abstract factory could not create an instance of applicationformmyform(alias: Application\Form\MyForm).
</code></pre>
<p>Anyway reading some other threads using the <code>ServiceLocator</code> Awareness isn't recommended. Is using the <code>FormElementProviderInterface</code> the alternative?</p>
<p>I used the ServiceLocatorAwareInterface before in my classes like this:</p>
<pre><code>use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyClass implements ServiceLocatorAwareInterface
{
protected $services;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->services = $serviceLocator;
}
public function getServiceLocator()
{
return $this->services;
}
</code></pre>
<p>and simply calling it per service locator in my c</p>
<pre><code>$sm = $this->getServiceLocator();
$myClass = $sm->get('Application\Service\MyClass');
</code></pre>
<p>without having to set an DI. Is this necessary for Fieldsets / Form and where / how exactely?</p>
<p>I tried to inject my Form and Fieldset this way:</p>
<pre><code> 'service_manager' => array(
'factories' => array(
'Application\Form\CreateCostcenter' => function (\Zend\ServiceManager\ServiceLocatorInterface $sl) {
$form = new \Application\Form\CreateCostcenter();
$form->setServiceLocator($sl);
return $form;
},
'Application\Form\CostcenterFieldset' => function (\Zend\ServiceManager\ServiceLocatorInterface $sl) {
$fieldset = new \Application\Form\CostcenterFieldset();
$fieldset->setServiceLocator($sl);
return $fieldset;
},
),
),
</code></pre>
<p>The injection works for my form when calling it in my controller:</p>
<pre><code>$form = $this->getServiceLocator()->get('Application\Form\CreateCostcenter');
</code></pre>
<p>But of course it won't pass the serviceManager to the Fieldset.</p>
<p>Anyway I don't understand why there has to be a config for the serviceManagerAwareness since it works with other class by just implementing it.
There also is no hint in the docs for advanced usage since <strong>ZF 2.1</strong>:</p>
<p><a href="http://framework.zend.com/manual/2.1/en/modules/zend.form.advanced-use-of-forms.html#the-specific-case-of-initializers" rel="nofollow">use an initializer (like Zend\ServiceManager\ServiceLocatorAwareInterface) to inject a specific object to all your forms/fieldsets/elements</a></p>
| 1 | 1,384 |
Returning an image into imageView from Google Places Photo JSON
|
<p>I'm looking to get the photos from the Google places API, and have them store into a URL or Image to be displayed to the user in a seperate view controller.</p>
<p>It appears the photo json returns this for each location:</p>
<pre><code> photos = (
{
height = 466;
"html_attributions" = ();
"photo_reference" = "CnRnAAAAgBUy_mqt9WglYJvS2v8XBfw5ER1U8Wn7DWvfoWI4P78w8_ZAsLQeFSYescNYE1NVgkV50jJE7SYBxdZuOmGP4jWGyCLobCd2nyEDbeB9lg1JU7KYV0o57i-OQTROIwj9ZwzWG03aUOypMjA_7fXD8BIQqbC5J0daROt_LqztWmz-xhoU20meJb50VyAE-zqkp9Jzu1Fegfs";
width = 695;
}
);
</code></pre>
<p>And according to Google Places Photo docs all it says:</p>
<p><a href="https://developers.google.com/places/documentation/photos" rel="nofollow">https://developers.google.com/places/documentation/photos</a></p>
<p>Cannot find an example to be able to take this from json, and store it like I am strings since the url isn't a direct link to an image or anything.</p>
<p>EDIT: Getting error </p>
<pre><code>[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x13258510
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x13258510'
</code></pre>
<p>Updated Code:</p>
<pre><code>-(void)plotPositions:(NSArray *)data {
for (id<MKAnnotation> annotation in _mapView.annotations) {
if ([annotation isKindOfClass:[MapPoint class]]) {
[_mapView removeAnnotation:annotation];
}
}
// Loop through the array of places returned from the Google API.
for (int i=0; i<[data count]; i++) {
NSDictionary* place = [data objectAtIndex:i];
NSDictionary *geo = [place objectForKey:@"geometry"];
NSDictionary *loc = [geo objectForKey:@"location"];
// Getting Photo Reference Details - ADDED NOW RECIEVING ERROR?
NSDictionary *photoDict = [place objectForKey:@"photos"];
NSString *photoRef = [photoDict objectForKey:@"photo_reference"];
NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/photo?photoreference=%@&key=%@&sensor=false&maxwidth=320", photoRef, kGOOGLE_API_KEY];
NSLog(@"TESTING: %@", url);
NSString *name=[place objectForKey:@"name"];
NSString *vicinity=[place objectForKey:@"vicinity"];
CLLocationCoordinate2D placeCoord;
placeCoord.latitude=[[loc objectForKey:@"lat"] doubleValue];
placeCoord.longitude=[[loc objectForKey:@"lng"] doubleValue];
MapPoint *placeObject = [[MapPoint alloc] initWithName:name address:vicinity rating:rating coordinate:placeCoord];
[_mapView addAnnotation:placeObject];
}
}
</code></pre>
| 1 | 1,221 |
Pod install fails on m1 macbook
|
<p>Error in running pod install.
I've been trying to run pod install but it keeps failing on all projects, I even created new projects from scratch to eliminate the suspicion that it might be an error in the configuration but it also failed .<br />
I've tried gem cocoapods and brew cocoapods, I've also tried with and without arch -x86_64 but nothing works I've also tried everything in these links:<br />
<a href="https://stackoverflow.com/questions/65917288/react-native-pod-install-failed-on-apple-silicon-m1">React Native pod install failed on Apple Silicon (M1)</a></p>
<pre><code>Analyzing dependencies
Fetching podspec for `DoubleConversion` from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`
Fetching podspec for `RCT-Folly` from `../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec`
Fetching podspec for `boost` from `../node_modules/react-native/third-party-podspecs/boost.podspec`
Fetching podspec for `glog` from `../node_modules/react-native/third-party-podspecs/glog.podspec`
Downloading dependencies
Installing CocoaAsyncSocket (7.6.5)
Installing DoubleConversion (1.1.6)
Installing FBLazyVector (0.67.4)
Installing FBReactNativeSpec (0.67.4)
Installing Flipper (0.99.0)
Installing Flipper-Boost-iOSX (1.76.0.1.11)
Installing Flipper-DoubleConversion (3.1.7)
Installing Flipper-Fmt (7.1.7)
Installing Flipper-Folly (2.6.7)
Installing Flipper-Glog (0.3.6)
[!] /bin/bash -c
set -e
#!/bin/bash
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
set -e
PLATFORM_NAME="${PLATFORM_NAME:-iphoneos}"
CURRENT_ARCH="${CURRENT_ARCH}"
if [ -z "$CURRENT_ARCH" ] || [ "$CURRENT_ARCH" == "undefined_arch" ]; then
# Xcode 10 beta sets CURRENT_ARCH to "undefined_arch", this leads to incorrect linker arg.
# it's better to rely on platform name as fallback because architecture differs between simulator and device
if [[ "$PLATFORM_NAME" == *"simulator"* ]]; then
CURRENT_ARCH="x86_64"
else
CURRENT_ARCH="armv7"
fi
fi
export CC="$(xcrun -find -sdk $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME --show-sdk-path)"
export CXX="$CC"
# Remove automake symlink if it exists
if [ -h "test-driver" ]; then
rm test-driver
fi
./configure --host arm-apple-darwin
# Fix build for tvOS
cat << EOF >> src/config.h
/* Add in so we have Apple Target Conditionals */
#ifdef __APPLE__
#include <TargetConditionals.h>
#include <Availability.h>
#endif
/* Special configuration for AppleTVOS */
#if TARGET_OS_TV
#undef HAVE_SYSCALL_H
#undef HAVE_SYS_SYSCALL_H
#undef OS_MACOSX
#endif
/* Special configuration for ucontext */
#undef HAVE_UCONTEXT_H
#undef PC_FROM_UCONTEXT
#if defined(__x86_64__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__rip
#elif defined(__i386__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__eip
#endif
EOF
# Prepare exported header include
EXPORTED_INCLUDE_DIR="exported/glog"
mkdir -p exported/glog
cp -f src/glog/log_severity.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/raw_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/stl_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/vlog_is_on.h "$EXPORTED_INCLUDE_DIR/"
checking for a BSD-compatible install... /opt/homebrew/bin/ginstall -c
checking whether build environment is sane... yes
checking for arm-apple-darwin-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /opt/homebrew/bin/gmkdir -p
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for arm-apple-darwin-gcc... /Applications/Developer Tools/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -arch armv7 -isysroot /Applications/Developer Tools/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.2.sdk
checking whether the C compiler works... no
/Users/samimishal/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6/missing: Unknown `--is-lightweight' option
Try `/Users/samimishal/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6/missing --help' for more information
configure: WARNING: 'missing' script is too old or missing
configure: error: in `/Users/samimishal/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6':
configure: error: C compiler cannot create executables
See `config.log' for more details
</code></pre>
| 1 | 1,812 |
Accessing ServiceStack Authenticated Service using Ajax
|
<p>I've been working through a simple API example, a modified version of the ServiceStack Hello World example with authentication. The goal of the proof of concept is to create an a RESTful API that contains services requiring authentication accessible entirely through Ajax from several different web projects.</p>
<p>I've read the wiki for, and implemented, Authentication and authorization and implementing CORS (many, results [sorry, not enough cred to point to the relevant link]). At this point, my Hello service can authenticate using a custom authentication mechanism which is over-riding CredentialsAuthProvider and a custom user session object. I've created, or borrowed, rather, a simple test application (an entirely separate project to simulate our needs) and can authenticate and then call into the Hello service, passing a name, and receive a 'Hello Fred' response through a single browser session. That is, I can call the /auth/credentials path in the url, passing the username and id, and receive a proper response. I can then update the url to /hello/fred and receive a valid response. </p>
<p>My breakdown in understanding is how to implement the authentication for all ajax calls. My initial login, below, works fine. No matter what I do, my attempt to call the authenticated service via ajax, I either receive a OPTIONS 404 error or Not Found error, or Origin http // localhost:12345 (pseudo-link) is not allowed by Access-Control-Allow-Origin, etc.</p>
<p>Do I need to go <a href="https://stackoverflow.com/questions/17669389/how-can-i-authenticate-with-servicestack-using-jquery-ajax">this route</a>?</p>
<p>Sorry if this is confusing. I can provide greater details if required, but think this might be sufficient help the knowledgeable to help my lack of understanding.</p>
<pre><code> function InvokeLogin() {
var Basic = new Object();
Basic.UserName = "MyUser";
Basic.password = "MyPass";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(Basic),
url: "http://localhost:58795/auth/credentials",
success: function (data, textStatus, jqXHR) {
alert('Authenticated! Now you can run Hello Service.');
},
error: function(xhr, textStatus, errorThrown) {
var data = $.parseJSON(xhr.responseText);
if (data === null)
alert(textStatus + " HttpCode:" + xhr.status);
else
alert("ERROR: " + data.ResponseStatus.Message + (data.ResponseStatus.StackTrace ? " \r\n Stack:" + data.ResponseStatus.StackTrace : ""));
}
});
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Based on the responses and the link provided by Stefan, I've made a couple of changes:</p>
<p><strong>My Config</strong> (Note: I'm using custom authentication and session object and that is all working correctly.)</p>
<pre><code>public override void Configure(Funq.Container container)
{
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CustomCredentialsAuthProvider(),
}));
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders = {
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
{ "Access-Control-Allow-Headers", "Content-Type, Authorization" },
},
DefaultContentType = "application/json"
});
Plugins.Add(new CorsFeature());
this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.HttpMethod == "OPTIONS")
httpRes.EndRequest(); // extension method
});
Routes
.Add<Hello>("/Hello", "GET, OPTIONS");
container.Register<ICacheClient>(new MemoryCacheClient());
var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);
}
</code></pre>
<p><strong>My Simple Hello Service</strong></p>
<pre><code>[EnableCors]
public class HelloService : IService
{
[Authenticate]
public object GET(Hello request)
{
Looks strange when the name is null so we replace with a generic name.
var name = request.Name ?? "John Doe";
return new HelloResponse { Result = "Hello, " + name };
}
}
</code></pre>
<p>After making the login call, above, my subsequent call the Hello service is now yielding a 401 error, which is progress, though not where I need to be. (The Jquery.support.cors= true is set in my script file.)</p>
<pre><code>function helloService() {
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "json",
url: "http://localhost:58795/hello",
success: function (data, textStatus, jqXHR) {
alert(data.Result);
},
error: function (xhr, textStatus, errorThrown) {
var data = $.parseJSON(xhr.responseText);
if (data === null)
alert(textStatus + " HttpCode:" + xhr.status);
else
alert("ERROR: " + data.ResponseStatus.Message +
(data.ResponseStatus.StackTrace ? " \r\n Stack:" + data.ResponseStatus.StackTrace : ""));
}
});
}
</code></pre>
<p>Again, this works in the RESTConsole if I first make the call to /auth/credentials properly and then follow that up with a call to /hello.</p>
<p><strong>FINAL EDIT</strong>
Following Stefan's advise, below, including many other links, I was finally able to get this working. In addition to Stefan's code, I had to make one additional modification:</p>
<pre><code>Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));
</code></pre>
<p>On to the next challenge: Updating Jonas Eriksson's CustomAuthenticateAttibute code (which appears to be using an older version of ServiceStack as a couple of functions are no longer available.</p>
<p>THANKS AGAIN STEFAN!!</p>
| 1 | 2,159 |
Using JSON.net to deserialize a list of nested objects
|
<p>Thanks in advance for your help. </p>
<p>I have a JSON file that contains a list of nested objects. Using the code below - I get an exception on the call to DeserializeObject. We are using JSON.net</p>
<p>Any help is appreciated</p>
<p>JSON: </p>
<pre><code>[
{
"Email": "james@example.com",
"Active": true,
"CreatedDate": "2013-01-20T00:00:00Z",
"Input": {
"User": "Jim",
"Admin": "John"
},
"Output": {
"Version": "12345",
"Nylon": "None"
}
},
{
"Email": "bob@example.com",
"Active": true,
"CreatedDate": "2013-01-21T00:00:00Z",
"Input": {
"User": "Bob",
"Admin": "John"
},
"Output": {
"Version": "12399",
"Nylon": "134"
}
}
]
</code></pre>
<p>To support the deserialization I have created the following class structure. </p>
<pre><code>public class Test002
{
public class Input
{
public string User { get; set; }
public string Admin { get; set; }
}
public class Output
{
public string Version { get; set; }
public string Nylon { get; set; }
}
public class RootObject
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public Input input { get; set; }
public Output output { get; set; }
}
public class TestCases
{
public List<RootObject> rootObjects { get; set; }
}
}
</code></pre>
<p>And finally here is the call to JSON.net JsonConvert.DeserializeObject - throws the following exception. </p>
<pre><code>Test002.TestCases tTestCases = JsonConvert.DeserializeObject<Test002.TestCases>(File.ReadAllText(@"C:\test\Automation\API\Test002.json"));
</code></pre>
<p>I think I need something like this - to deseralize the list of objects - The code below fails</p>
<pre><code> Test002.TestCases tTestCases = JsonConvert.DeserializeObject<IList<Test002.TestCases>>(File.ReadAllText(@"C:\test\Automation\API\Test002.json"));
</code></pre>
<p>Exception: </p>
<p>An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code</p>
<p>Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'APISolution.Test002+TestCases' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.</p>
<p>To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.</p>
<p>Path '', line 1, position 1.</p>
| 1 | 1,313 |
Python: Replacing backslashes to avoid escape sequences in string
|
<p>I´m trying to replace the single backslashes i get within a string with double backslashes, because sometimes the the "backslash+character" combination creates an escape sequence. I have tried various ways (mostly from other stackoverflow questions), but nothing gets me the correct results so far.</p>
<p>Example <code>s = "\aa, \bb, \cc, \dd"</code></p>
<hr>
<pre><code>string.replace(s,"\\","\\\\")
</code></pre>
<p>replaces the first a and b with special characters (can´t get pasting the exact result here to work?):</p>
<pre><code>@a,@b,\\cc,\\dd
</code></pre>
<hr>
<pre><code>print s.encode("string_escape")
</code></pre>
<p>produces</p>
<pre><code>\x07a,\x08b,\\cc,\\dd
</code></pre>
<p>(same for "unicode-escape")</p>
<hr>
<p>using this <a href="https://stackoverflow.com/a/2428144">function</a></p>
<pre><code>escape_dict={'\a':r'\a',
'\b':r'\b',
'\c':r'\c',
'\f':r'\f',
'\n':r'\n',
'\r':r'\r',
'\t':r'\t',
'\v':r'\v',
'\'':r'\'',
'\"':r'\"',
'\0':r'\0',
'\1':r'\1',
'\2':r'\2',
'\3':r'\3',
'\4':r'\4',
'\5':r'\5',
'\6':r'\6',
'\7':r'\7',
'\8':r'\8',
'\9':r'\9'}
def raw(text):
"""Returns a raw string representation of text"""
new_string=''
for char in text:
try: new_string+=escape_dict[char]
except KeyError: new_string+=char
return new_string
</code></pre>
<p>produces</p>
<pre><code>\7a,\bb,\cc,\dd
</code></pre>
<hr>
<p>and using this <a href="https://stackoverflow.com/a/24519338">function</a></p>
<pre><code>import re
import codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U........ # 8-digit hex escapes
| \\u.... # 4-digit hex escapes
| \\x.. # 2-digit hex escapes
| \\[0-7]{1,3} # Octal escapes
| \\N\{[^}]+\} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
</code></pre>
<p>returns the string with special characters again</p>
<pre><code> @a,@b,\\cc,\\dd
</code></pre>
<p>The actual strings i need to convert would be something like <code>"GroupA\Group2\Layer1"</code></p>
| 1 | 1,210 |
When using a custom X509KeyManager Java is not able to determine a matching cipher suite for the SSL handshake
|
<p>I'm working with Java7 and JAX-WS 2.2.</p>
<p>For a SOAP web service I need to create a custom <code>X509KeyManager</code> in order to find the correct certificate for each connecting client in a JKS keystore.</p>
<p>However, I'm already struggling to get the my custom key manager running. So far I'm using the default one (retrieved from the initialized <code>KeyManagerFactory</code>) and it basically works - but of course it doesn't select the correct certificate. So the first idea was to create a custom <code>X509KeyManager</code> which holds the original key manager, only writes out some log messages but generally uses the default behaviour. </p>
<p>For some reason that doesn't work at all. The SSL handshake cannot be established. After the <em>ClientHello</em> the log shows the following error:</p>
<pre><code>Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Thread-3, READ: TLSv1 Handshake, length = 149
*** ClientHello, TLSv1
RandomCookie: GMT: 1476877930 bytes = { 207, 226, 8, 128, 40, 207, 47, 180, 146, 211, 157, 64, 239, 13, 201, 92, 158, 111, 108, 44, 223, 136, 193, 251, 33, 202, 7, 90 }
Session ID: {}
Cipher Suites: [TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods: { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
***
%% Initialized: [Session-3, SSL_NULL_WITH_NULL_NULL]
Thread-3, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated: [Session-3, SSL_NULL_WITH_NULL_NULL]
Thread-3, SEND TLSv1 ALERT: fatal, description = handshake_failure
Thread-3, WRITE: TLSv1 Alert, length = 2
Thread-3, fatal: engine already closed. Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
</code></pre>
<p>I didn't remove any cipher suites at all to my knowledge! And the SSL handshake <em>can</em> be made with the same certificates.</p>
<p>This is my key manager:</p>
<pre><code>public class CustomX509KeyManager extends X509ExtendedKeyManager
{
private static final Logger LOG = Logger.getLogger( CustomX509KeyManager.class );
private final X509KeyManager originalKeyManager;
public CustomX509KeyManager(final X509KeyManager keyManager)
{
super();
this.originalKeyManager = keyManager;
}
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers,
final Socket socket)
{
final String serverAliases=
this.originalKeyManager.chooseServerAlias( keyType, issuers, socket );
CustomX509KeyManager.LOG.info( "chooseServerAlias() " + serverAliases );
return serverAliases;
}
...
}
</code></pre>
<p>The other methods (not shown here) are just calling the corresponding methods in the <code>originalKeyManager</code> as well. During testing I never see the log message from the <code>chooseServerAlias()</code> method.</p>
<p>And it's initialized from another class in the <code>getSslContext()</code>method:</p>
<pre><code>private KeyManager[] getKeyManagers(final KeyManagerFactory keyManagerFactory)
{
final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
// replace any X509KeyManager with our own implementation
for ( int i = 0; i < keyManagers.length; i++ )
{
if ( keyManagers[i] instanceof X509KeyManager )
{
keyManagers[i] =
new CustomX509KeyManager( ( X509KeyManager ) keyManagers[i] );
}
}
return keyManagers;
}
public SSLContext getSslContext()
{
// create the KeyStore and load the JKS file
final KeyStore keyStore = createKeyStore();
// initialize key and trust manager factory
final KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
keyManagerFactory.init( keyStore, "changeit".toCharArray() );
final TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
trustManagerFactory.init( keyStore );
// initialize the SSL context
final SSLContext sslContext = SSLContext.getInstance( "TLS" );
// sslContext.init( keyManagerFactory.getKeyManagers(),
// trustManagerFactory.getTrustManagers(), new SecureRandom() );
sslContext.init( getKeyManagers( keyManagerFactory ),
trustManagerFactory.getTrustManagers(), new SecureRandom() );
return sslContext;
}
</code></pre>
<p>The commented lines show the original usage of the default key manager.</p>
<p>Any idea what's wrong? Why is the behaviour of using my <code>CustomX509KeyManager</code> so different than the default key manager that the handshake cannot be done? With the default key manager the encryption is negotiated for the TLS_DHE_RSA_WITH_AES_128_CBC_SHA algorithm which is available with the custom key manager as well but for some reason not chosen.</p>
<h3>Update 1</h3>
<p>I'm trying to connect with openssl in client mode to the server now but the server encounters the same problem using SSL. When I use the TLS protocol then the additional error message</p>
<blockquote>
<p>Unsupported extension type_35, data:</p>
</blockquote>
<p>appears.</p>
<h3>Update 2</h3>
<p>I can confirm that the above notice about unsupported extensions also appears upon successful handshakes so this is a false trace.</p>
| 1 | 2,199 |
Switching data models in AngularJS for dynamic select menus
|
<p>What I am trying to do is have three different <em><select></em> menus which will be all be tied into the same data. Changing the first select menu, will change menus 2 and 3's data.</p>
<p>This is the inside of my Controller:</p>
<pre><code>$scope.data = [
{
"id" : "0",
"site" : "Brands Hatch",
"buildings" : [
{ "building" : "Building #1" },
{ "building" : "Building #2" },
{ "building" : "Building #3" }
],
"floors" : [
{ "floor" : "Floor #1" },
{ "floor" : "Floor #2" },
{ "floor" : "Floor #3" }
]
},{
"id" : "1",
"site" : "Silverstone",
"buildings" : [
{ "building" : "Building #4" },
{ "building" : "Building #5" },
{ "building" : "Building #6" }
],
"floors" : [
{ "floor" : "Floor #4" },
{ "floor" : "Floor #5" },
{ "floor" : "Floor #6" }
]
}
];
</code></pre>
<p>Here's what I have tried from a reference so far, which uses the same idea I need: <a href="http://codepen.io/adnan-i/pen/gLtap" rel="noreferrer">http://codepen.io/adnan-i/pen/gLtap</a></p>
<p>When I select either 'Brands Hatch' or 'Silverstone' from the <em>first</em> select menu, the other two menus will have their data change/update to correspond with the correct data. I am using <em>$watch</em> to listen for changes, which I've taken from the above CodePen link.</p>
<p>Here's the watching script (unmodified and obviously not working):</p>
<pre><code>$scope.$watch('selected.id', function(id){
delete $scope.selected.value;
angular.forEach($scope.data, function(attr){
if(attr.id === id){
$scope.selectedAttr = attr;
}
});
});
</code></pre>
<p>As far as I know, this deletes the current data on change, then loops through <em>$scope.data</em> and if the attr.id matches the id passed into the function, it pushes the data back to the scope which updates the views. I am just really stuck on structuring this and would appreciate some guidance and help as I am really new to AngularJS. Thank you! :)</p>
<p>jsFiddle for the full workings if anyone can help out:
<a href="http://jsfiddle.net/sgdea/" rel="noreferrer">http://jsfiddle.net/sgdea/</a></p>
| 1 | 1,132 |
Bootstrap modal appearing under background in AngulaJS application
|
<p>This question might be flagged as duplicate but my issue isn't solved by the things mentioned in the relevant SO thread, here is the <a href="https://stackoverflow.com/questions/10636667/bootstrap-modal-appearing-under-background?page=1&tab=votes#tab-top">link</a> to that </p>
<p>I have to make a modal with an Image into it and stack it into an existing AngularJS application. So, by far what I have done is this. When I do data-backdrop="false", the whole black tint gets removed and that's pretty obvious. But I don't want that. I want the black tint to remain there but behind the modal not stacking on top of it.</p>
<p>How can I do that, without using jQuery.</p>
<p>Here is my code:</p>
<pre><code><li ui-sref-active="active">
<a href="javascript:;" data-toggle="modal" data-target="#myModal">
<i class="fa fa-bullhorn" style="color: #fff200"></i>
<span id="glow" style="color: #fff200">What's New</span>
</a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 class="modal-title" style="color: #000"><strong>New Features</strong></h3>
</div>
<div class="modal-body">
<center>
<img ng-src="{{'images/'+ 'Screen.png'}}" alt="New Features Screenshots" class="img-thumbnail img-responsive">
</center>
</div>
</div>
<!-- <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div> -->
</div>
</div>
</div>
</li>
</code></pre>
| 1 | 1,120 |
Docker - Can't share data between containers within a volume (docker-compose 3)
|
<p>I have some containers for a web app for now (nginx, gunicorn, postgres and node to build static files from source and a React server side rendering). In a Dockerfile for the node container I have two steps: build and run (<a href="https://www.dropbox.com/s/f2l4f1rzhuxat7d/Dockerfile.node?dl=0" rel="noreferrer">Dockerfile.node</a>). It ends up with two directories inside a container: <code>bundle_client</code> - is a static for an nginx and <code>bundle_server</code> - it used in the node container itself to start an express server.</p>
<p>Then I need to share a built static folder (<code>bundle_client</code>) with the nginx container. To do so according to docker-compose reference in my <code>docker-compose.yml</code> I have the following services (See full <a href="https://www.dropbox.com/s/aq8n8bug9jbhhwq/docker-compose.yml?dl=0" rel="noreferrer">docker-compose.yml</a>):</p>
<pre><code>node:
volumes:
- vnode:/usr/src
nginx:
volumes:
- vnode:/var/www/tg/static
depends_on:
- node
</code></pre>
<p>and volumes:</p>
<pre><code>volumes:
vnode:
</code></pre>
<p>Running <code>docker-compose build</code> completes with no errors. Running <code>docker-compose up</code> runs everyting ok and I can open <code>localhost:80</code> and there is nginx, gunicorn and node express SSR all working great and I can see a web page but all static files return 404 not found error.</p>
<p>If I check volumes with <code>docker volume ls</code> I can see two newly created volumes named <code>tg_vnode</code> (that we consider here) and <code>tg_vdata</code> (see full docker-compose.yml)</p>
<p>If I go into an nginx container with <code>docker run -ti -v /tmp:/tmp tg_node /bin/bash</code> I can't see my <code>www/tg/static</code> folder which should map my static files from the node volume. Also I tried to create an empty <code>/var/www/tg/static</code> folder with nginx container <code>Dockerfile.nginx</code> but it stays empty.</p>
<p>If I map a <code>bundle_client</code> folder from the host machine in the <code>docker-compose.yml</code> in a <code>nginx.volumes</code> section as <code>- ./client/bundle_client:/var/www/tg/static</code> it works ok and I can see all the static files served with nginx in the browser.</p>
<p>What I'm doing wrong and how to make my container to share built static content with the nginx container?</p>
<p><strong>PS:</strong> I read all the docs, all the github issues and stackoverflow Q&As and as I understood it has to work and there is no info what to do when is does not.</p>
<p><strong>UPD:</strong> Result of <code>docker volume inspect vnode</code>:</p>
<pre><code>[
{
"CreatedAt": "2018-05-18T12:24:38Z",
"Driver": "local",
"Labels": {
"com.docker.compose.project": "tg",
"com.docker.compose.version": "1.21.1",
"com.docker.compose.volume": "vnode"
},
"Mountpoint": "/var/lib/docker/volumes/tg_vnode/_data",
"Name": "tg_vnode",
"Options": null,
"Scope": "local"
}
]
</code></pre>
<p>Files:
<a href="https://www.dropbox.com/s/f2l4f1rzhuxat7d/Dockerfile.node?dl=0" rel="noreferrer">Dockerfile.node</a>,
<a href="https://www.dropbox.com/s/aq8n8bug9jbhhwq/docker-compose.yml?dl=0" rel="noreferrer">docker-compose.yml</a></p>
<p>Nginx dockerfile: <a href="https://www.dropbox.com/s/i5da41f4ejm0fya/Dockerfile.nginx?dl=0" rel="noreferrer">Dockerfile.nginx</a></p>
<hr>
<p><strong>UPD:</strong> I have created a simplified repo to reproduce a question: <a href="https://bitbucket.org/vashchukmaksim/docker-share-volume-test/src/master/" rel="noreferrer">repo</a>
(there are some warnings on <code>npm install</code> nevermind it installs and builds ok). Eventually when we open <code>localhost:80</code> we see an empty page and 404 messages for static files (<code>vendor.js</code> and <code>app.js</code>) in Chrome dev tools but there should be a message <code>React app: static loaded</code> generated by react script.</p>
| 1 | 1,424 |
How to get the text of an anchor tag selected by xPath() using selenium and Mocha
|
<p>I have successfully selected an <code><a></code> tag. I want to display the text of the anchor tag and I am unable to do so.</p>
<p>I am using selenium, mocha, javascript and phantomJS</p>
<p>Here's my script(full in detail):</p>
<pre><code>var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var equals = webdriver.equals;
/*-------login details--------*/
var userAdmin = 'saswat@matrixnmedia.com';
var passAdmin = 'DarkPrince2012';
var userTradeshow = 'joni@mailinator.com';
var passTradeshow = 'Mithun@';
/*-----login details ends-----*/
/*---setting up credentials---*/
var passArgument = process.env.KEY; /*fetch value from the environment value;*/
console.log("You chose to enter as '"+passArgument+"'");
if(passArgument.toLowerCase().indexOf("admin")>-1)
{
var username = userAdmin,
password = passAdmin;
}
else if(passArgument.toLowerCase().indexOf("trade")>-1)
{
var username = userTradeshow,
password = passTradeshow;
}
else
{
var username = "",
password = "";
}
/*-setting up credentials ends-*/
test.describe('TrackRevenue Test', function()
{
test.it('should work', function()
{
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.phantomjs())
.build();
var loginFlag = 0;
var baseUrl = 'http://saswatr3.ouh.co/login';
var expectedTitle = "Track Revenue";
var successMessage = "Welcome to the admin page!";
driver.get(baseUrl);
driver.getTitle().then(function(title)
{
if(expectedTitle === title)
{
console.log("Verification Successful - The correct title is displayed on the web page.");
}
else
{
console.log("Verification Failed - An incorrect title is displayed on the web page.");
}
});
driver.findElement(By.id('username')).sendKeys(username);
driver.findElement(By.id('password')).sendKeys(password);
driver.findElement(By.id('_submit')).click();
driver.findElements(By.xpath("//a[contains(text(), 'Log out')]")).then(function(elements_arr)
{
if(elements_arr.length > 0)
{
loginFlag = 1;
driver.findElements(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).then(function(e){
if(e.length > 0)
{
console.log("No. of elements :"+e.length);
console.log("Found The USerName : ");
console.log("Username : "+e[0].text);//this is the line with the issue. It prints undefined
}
});
}
else
{
driver.findElements(By.xpath("//div[contains(text(), 'Invalid credentials.')]")).then(function(elements_arr2)
{
if(elements_arr2.length > 0)
console.log("Login Unsuccessful, div invalid credentials found");
else
console.log("Login Unsuccessful, div invalid credentials not found");
});
}
if(loginFlag == 1)
console.log("Login Successful");
else
console.log("Login Unsuccessful");
});
driver.quit();
});
});
</code></pre>
<h3>1. Case 1: With e[0].text</h3>
<p>My problem lies within this script.</p>
<pre><code>driver.findElements(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).then(function(e){
if(e.length > 0)
{
console.log("No. of elements :"+e.length);
console.log("Found The USerName : ");
console.log("Username : "+e[0].text);//this is the line with the issue. It prints undefined
}
});
</code></pre>
<p>As you can see, <code>console.log("Username : "+e[0].text);</code> is causing problem.</p>
<p>For convenience, this is the full message I am getting.</p>
<pre><code> C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>env KEY=trade moch
a -t 120000 testMocha/login-as-administrator-mocha.js
You chose to enter as 'trade'
TrackRevenue Test
Verification Successful - The correct title is displayed on the web page.
Login Successful
No. of elements :1
Found The USerName :
Username : undefined
√ should work (71593ms)
1 passing (1m)
</code></pre>
<h3>2. Case 2: With e.text</h3>
<p>Now, when I made the changes like:</p>
<pre><code>driver.findElements(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).then(function(e){
if(e.length > 0)
{
console.log("No. of elements :"+e.length);
console.log("Found The USerName : ");
console.log("Username : "+e.text);//this is the line with the issue. It prints undefined
}
});
</code></pre>
<p>This is the message I get.</p>
<pre><code>C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>env KEY=trade moch
a -t 120000 testMocha/login-as-administrator-mocha.js
You chose to enter as 'trade'
TrackRevenue Test
Verification Successful - The correct title is displayed on the web page.
Login Successful
No. of elements :1
Found The USerName :
Username : undefined
√ should work (87006ms)
1 passing (1m)
</code></pre>
<h3>3. Case 3: With e[0].getText()</h3>
<p>I made the following changes:</p>
<pre><code>driver.findElements(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).then(function(e){
if(e.length > 0)
{
console.log("No. of elements :"+e.length);
console.log("Found The USerName : ");
console.log("Username : "+e[0].getText());
}
});
</code></pre>
<p>Here's the message:</p>
<pre><code>C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>env KEY=trade moch
a -t 120000 testMocha/login-as-administrator-mocha.js
You chose to enter as 'trade'
TrackRevenue Test
Verification Successful - The correct title is displayed on the web page.
Login Successful
No. of elements :1
Found The USerName :
Username : Promise::456 {[[PromiseStatus]]: "pending"}
√ should work (37212ms)
1 passing (37s)
</code></pre>
<p>Here's the HTML:</p>
<pre><code><ul class="nav navbar-top-links navbar-right">
<li>
<a class="user-name m-r-sm text-muted welcome-message" href="/profile/">saswat@matrixnmedia.com</a>
</li>
<li>
<a href="http://saswatr3.ouh.co/main/account/help.php">
<i class="fa fa-life-ring"></i>
</a>
</li>
<li>
<a class="log-out" href="/logout">
<i class="fa fa-sign-out"></i>
Log out
</a>
</li>
</ul>
</code></pre>
| 1 | 3,500 |
Fatal Error, ArrayObject::offsetGet() must be compatible with that ArrayAccess:offsetGet() with Zend framework 2.3 on Linux Debian 2.6.32-46
|
<p>Hi i have problem with ZF2, </p>
<p>when trying to access at public/index from the browser i got this Fatal Error from Server:</p>
<pre><code>PHP Fatal error: Declaration of Zend\\Stdlib\\ArrayObject::offsetGet() must be compatible with that of ArrayAccess::offsetGet() in /var/www/somevirtualhost/vendor/zendframework/zendframework/library/Zend/Stdlib/ArrayObject.php on line 23
</code></pre>
<p>I already update the composer.json from:</p>
<pre><code>{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for ZF2",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"zf2"
],
"homepage": "http://framework.zend.com/",
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": "2.3.*"
}
}
</code></pre>
<p>to:</p>
<pre><code>{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for ZF2",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"zf2"
],
"homepage": "http://framework.zend.com/",
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": "2.2.*"
}
}
</code></pre>
<p>Also on init_autoloader.php i added this lines:</p>
<pre><code> require $zf2Path . '/Zend/Stdlib/compatibility/autoload.php';
require $zf2Path . '/Zend/Session/compatibility/autoload.php';
</code></pre>
<p>and this how init_autoloader looks like:</p>
<pre><code>if ($zf2Path) {
if (isset($loader)) {
$loader->add('Zend', $zf2Path);
$loader->add('ZendXml', $zf2Path);
} else {
include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true
)
));
//Fix for PHP 5.3.3
require $zf2Path . '/Zend/Stdlib/compatibility/autoload.php';
require $zf2Path . '/Zend/Session/compatibility/autoload.php';
}
}
</code></pre>
<p>Besides all the changes mentioned above, i still receive the getting the same error.
By the way this is my PHP Versión:</p>
<pre><code>PHP 5.3.3-7+squeeze19 with Suhosin-Patch (cli) (built: Feb 18 2014 13:59:15)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
with Suhosin v0.9.32.1, Copyright (c) 2007-2010, by SektionEins GmbH
</code></pre>
| 1 | 1,117 |
metrics-server with CrashLoopBackOff
|
<p>I´m not able to run the metrics-server pod, it gets to crashloopbackoff error. Running "kubectl get pods -n kube-system" I see the following output:</p>
<pre><code>NAME READY STATUS RESTARTS AGE
calico-kube-controllers-6b9d4c8765-mht4w 1/1 Running 0 17m
calico-node-2rmzg 1/1 Running 0 17m
coredns-6955765f44-87kbn 1/1 Running 0 57m
coredns-6955765f44-wzrrt 1/1 Running 0 57m
etcd-master-node 1/1 Running 0 56m
kube-apiserver-master-node 1/1 Running 0 56m
kube-controller-manager-master-node 1/1 Running 0 56m
kube-flannel-ds-amd64-6htmh 1/1 Running 0 28m
kube-proxy-xvksz 1/1 Running 0 57m
kube-scheduler-master-node 1/1 Running 0 56m
metrics-server-7d9ffcffbd-r4gf9 0/1 CrashLoopBackOff 7 16m
</code></pre>
<p>Then, running "kubectl describe pods metrics-server -n kube-system" I see the following:</p>
<pre><code>Name: metrics-server-7d9ffcffbd-r4gf9
Namespace: kube-system
Priority: 0
Node: master-node/10.221.194.166
Start Time: Thu, 30 Jan 2020 17:07:37 -0300
Labels: k8s-app=metrics-server
pod-template-hash=7d9ffcffbd
Annotations: cni.projectcalico.org/podIP: 192.168.77.133/32
Status: Running
IP: 192.168.77.133
IPs:
IP: 192.168.77.133
Controlled By: ReplicaSet/metrics-server-7d9ffcffbd
Containers:
metrics-server:
Container ID: docker://90ccb84ccf10b130ac93620d105d80c244208b8753c48bb498d646cd3e0c5c17
Image: k8s.gcr.io/metrics-server-amd64:v0.3.6
Image ID: docker-pullable://k8s.gcr.io/metrics-server-amd64@sha256:c9c4e95068b51d6b33a9dccc61875df07dc650abbf4ac1a19d58b4628f89288b
Port: 4443/TCP
Host Port: 0/TCP
Command:
/metrics-server
--kubelet-insecure-tls
--kubelet-preferred-address-types=InternalIP
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 2
Started: Thu, 30 Jan 2020 17:24:10 -0300
Finished: Thu, 30 Jan 2020 17:24:11 -0300
Ready: False
Restart Count: 8
Environment:
Mounts:
/tmp from tmp-dir (rw)
/var/run/secrets/kubernetes.io/serviceaccount from metrics-server-token-rxfq2 (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
tmp-dir:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium:
SizeLimit:
metrics-server-token-rxfq2:
Type: Secret (a volume populated by a Secret)
SecretName: metrics-server-token-rxfq2
Optional: false
QoS Class: BestEffort
Node-Selectors: beta.kubernetes.io/os=linux
kubernetes.io/arch=amd64
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
Normal Scheduled 19m default-scheduler Successfully assigned kube-system/metrics-server-7d9ffcffbd-r4gf9 to master-node
Normal Pulling 18m (x4 over 19m) kubelet, master-node Pulling image "k8s.gcr.io/metrics-server-amd64:v0.3.6"
Normal Pulled 18m (x4 over 19m) kubelet, master-node Successfully pulled image "k8s.gcr.io/metrics-server-amd64:v0.3.6"
Normal Created 18m (x4 over 19m) kubelet, master-node Created container metrics-server
Normal Started 18m (x4 over 19m) kubelet, master-node Started container metrics-server
Warning BackOff 4m5s (x72 over 19m) kubelet, master-node Back-off restarting failed container
</code></pre>
<p>Can someone help me figuring out what is wrong? I´ve seen a lot of similar cases, but none of them worked. Furthermore, I´m running all inside a master node.</p>
<p>EDIT 1: Posting the output of log:</p>
<pre><code>Error: error creating self-signed certificates: mkdir apiserver.local.config: read-only file system
Usage:
[flags]
Flags:
--alsologtostderr log to standard error as well as files
--authentication-kubeconfig string kubeconfig file pointing at the 'core' kubernetes server with enough rights to create tokenaccessreviews.authentication.k8s.io.
--authentication-skip-lookup If false, the authentication-kubeconfig will be used to lookup missing authentication configuration from the cluster.
--authentication-token-webhook-cache-ttl duration The duration to cache responses from the webhook token authenticator. (default 10s)
--authentication-tolerate-lookup-failure If true, failures to look up missing authentication configuration from the cluster are not considered fatal. Note that this can result in authentication that treats all requests as anonymous.
--authorization-always-allow-paths strings A list of HTTP paths to skip during authorization, i.e. these are authorized without contacting the 'core' kubernetes server.
--authorization-kubeconfig string kubeconfig file pointing at the 'core' kubernetes server with enough rights to create subjectaccessreviews.authorization.k8s.io.
--authorization-webhook-cache-authorized-ttl duration The duration to cache 'authorized' responses from the webhook authorizer. (default 10s)
--authorization-webhook-cache-unauthorized-ttl duration The duration to cache 'unauthorized' responses from the webhook authorizer. (default 10s)
--bind-address ip The IP address on which to listen for the --secure-port port. The associated interface(s) must be reachable by the rest of the cluster, and by CLI/web clients. If blank, all interfaces will be used (0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces). (default 0.0.0.0)
--cert-dir string The directory where the TLS certs are located. If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored. (default "apiserver.local.config/certificates")
--client-ca-file string If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate.
--contention-profiling Enable lock contention profiling, if profiling is enabled
-h, --help help for this command
--http2-max-streams-per-connection int The limit that the server gives to clients for the maximum number of streams in an HTTP/2 connection. Zero means to use golang's default.
--kubeconfig string The path to the kubeconfig used to connect to the Kubernetes API server and the Kubelets (defaults to in-cluster config)
--kubelet-certificate-authority string Path to the CA to use to validate the Kubelet's serving certificates.
--kubelet-insecure-tls Do not verify CA of serving certificates presented by Kubelets. For testing purposes only.
--kubelet-port int The port to use to connect to Kubelets. (default 10250)
--kubelet-preferred-address-types strings The priority of node address types to use when determining which address to use to connect to a particular node (default [Hostname,InternalDNS,InternalIP,ExternalDNS,ExternalIP])
--log-flush-frequency duration Maximum number of seconds between log flushes (default 5s)
--log_backtrace_at traceLocation when logging hits line file:N, emit a stack trace (default :0)
--log_dir string If non-empty, write log files in this directory
--log_file string If non-empty, use this log file
--logtostderr log to standard error instead of files (default true)
--metric-resolution duration The resolution at which metrics-server will retain metrics. (default 1m0s)
--profiling Enable profiling via web interface host:port/debug/pprof/ (default true)
--requestheader-allowed-names strings List of client certificate common names to allow to provide usernames in headers specified by --requestheader-username-headers. If empty, any client certificate validated by the authorities in --requestheader-client-ca-file is allowed.
--requestheader-client-ca-file string Root certificate bundle to use to verify client certificates on incoming requests before trusting usernames in headers specified by --requestheader-username-headers. WARNING: generally do not depend on authorization being already done for incoming requests.
--requestheader-extra-headers-prefix strings List of request header prefixes to inspect. X-Remote-Extra- is suggested. (default [x-remote-extra-])
--requestheader-group-headers strings List of request headers to inspect for groups. X-Remote-Group is suggested. (default [x-remote-group])
--requestheader-username-headers strings List of request headers to inspect for usernames. X-Remote-User is common. (default [x-remote-user])
--secure-port int The port on which to serve HTTPS with authentication and authorization.If 0, don't serve HTTPS at all. (default 443)
--skip_headers If true, avoid header prefixes in the log messages
--stderrthreshold severity logs at or above this threshold go to stderr
--tls-cert-file string File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key are generated for the public address and saved to the directory specified by --cert-dir.
--tls-cipher-suites strings Comma-separated list of cipher suites for the server. If omitted, the default Go cipher suites will be use. Possible values: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_3DES_EDE_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_RC4_128_SHA
--tls-min-version string Minimum TLS version supported. Possible values: VersionTLS10, VersionTLS11, VersionTLS12
--tls-private-key-file string File containing the default x509 private key matching --tls-cert-file.
--tls-sni-cert-key namedCertKey A pair of x509 certificate and private key file paths, optionally suffixed with a list of domain patterns which are fully qualified domain names, possibly with prefixed wildcard segments. If no domain patterns are provided, the names of the certificate are extracted. Non-wildcard matches trump over wildcard matches, explicit domain patterns trump over extracted names. For multiple key/certificate pairs, use the --tls-sni-cert-key multiple times. Examples: "example.crt,example.key" or "foo.crt,foo.key:*.foo.com,foo.com". (default [])
-v, --v Level number for the log level verbosity
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
panic: error creating self-signed certificates: mkdir apiserver.local.config: read-only file system
goroutine 1 [running]:
main.main()
/go/src/github.com/kubernetes-incubator/metrics-server/cmd/metrics-server/metrics-server.go:39 +0x13b
</code></pre>
<p>Thanks in advance :)</p>
| 1 | 4,899 |
Trying to start GrizzlyServer - failed to start listener - adress already in use
|
<pre><code>static HttpServer server;
static Datenbank db = new Datenbank();
public static void main (String[] args) throws InterruptedException, IOException{
startServer();
db.dbinfo();
Thread.sleep(10*60*1000);
System.out.println("Server wurde beendet");
}
public static void startServer() throws IOException, InterruptedException {
URI baseUri = UriBuilder.fromUri("http://localhost/").port(4434).build();
ResourceConfig config = new ResourceConfig().register(BetroffenePersonenService.class);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
try{
server.start();
NetworkListener listener = new NetworkListener("grizzly2","localhost", 4434);
server.addListener(listener);
}
catch (Exception e){
System.err.println(e);
}
}
}
</code></pre>
<p>I am trying to start this server but i keep getting this </p>
<pre><code>16.01.2014 22:04:31 org.lightcouch.CouchDbClientBase process
INFO: >> HEAD /betroffene HTTP/1.1
16.01.2014 22:04:31 org.lightcouch.CouchDbClientBase process
INFO: << Status: 200
16.01.2014 22:04:31 org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.5 2013-12-18 14:27:29...
16.01.2014 22:04:32 org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:4434]
16.01.2014 22:04:32 org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
16.01.2014 22:04:32 org.glassfish.grizzly.http.server.HttpServer addListener
SCHWERWIEGEND: Failed to start listener [NetworkListener{name='grizzly2', host='localhost', port=4434, secure=false, state=STOPPED}] : java.net.BindException: Address already in use
16.01.2014 22:04:32 org.glassfish.grizzly.http.server.HttpServer addListener
SCHWERWIEGEND: java.net.BindException: Address already in use
java.net.BindException: Address already in use
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:124)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59)
at org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler.bindToChannelAndAddress(TCPNIOBindingHandler.java:132)
at org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler.bind(TCPNIOBindingHandler.java:88)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:233)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:213)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:204)
at org.glassfish.grizzly.http.server.NetworkListener.start(NetworkListener.java:680)
at org.glassfish.grizzly.http.server.HttpServer.addListener(HttpServer.java:171)
at server.AbleServer.startServer(AbleServer.java:39)
at server.AbleServer.main(AbleServer.java:23)
</code></pre>
<p>i have tried to find solutions online but i can not find any that work for me.
I have restarted everything, but it still says, that the address is in use.
it probably is a really small mistake that is causing all of this but it is really getting me frustrated.
your help would be appreciated! </p>
| 1 | 1,143 |
How do you remove NA's in geom_bar when plotting data subsets?
|
<p>this is related to the question <a href="https://stackoverflow.com/questions/11403104/remove-unused-factor-levels-from-a-ggplot-bar-plot?lq=1">here</a>, but the proposed solutions don't work in my case. </p>
<p>I've already posted a question regarding my large <code>data.frame</code> <a href="https://stackoverflow.com/questions/22855197/how-do-you-get-geom-map-to-show-all-parts-of-a-map/22875922?noredirect=1#comment34951335_22875922">here</a>, but if you just want to download it (>2000 rows) please do so via <a href="https://www.dropbox.com/s/87tnryu9zzf541t/ARCTP53_SOExample.txt?n=9895686" rel="nofollow noreferrer">this link</a>.</p>
<p>So the <strong>following code</strong> is used to create a simple <code>geom_bar</code>barplot in <code>ggplot2</code></p>
<pre><code>gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SoExample$Structural_motif=="NDBL/beta-sheets",],
aes(x=p53_IHC))
gghist+geom_bar()
</code></pre>
<p>This produces <strong>this plot</strong>:
<img src="https://i.stack.imgur.com/t9oGq.png" alt="A barplot with lots of "NA's""></p>
<p>As you can see, the NA's are plotted as well. I've tried various options to remove the NA's including the <strong><em>following</em></strong>: </p>
<pre><code>gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets",], aes(x=p53_IHC), drop=TRUE)
gghist+geom_bar()
gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets",], aes(x=p53_IHC), na.rm=TRUE)
gghist+geom_bar()
gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets",], aes(x=p53_IHC, na.rm=TRUE))
gghist+geom_bar()
gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets",], aes(x=factor(p53_IHC), na.rm=TRUE))
gghist+geom_bar()
gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets",], aes(x=factor(p53_IHC))
gghist+geom_bar(na.rm=TRUE)
</code></pre>
<p>And then I tried <strong>this</strong>: </p>
<pre><code>gghist_2<-ggplot(na.omit(ARCTP53_SOExample[ARCTP53_EsoMutClean$Structural_motif=="NDBL/beta-sheets",]), aes(x=p53_IHC))
gghist_2+geom_bar()
</code></pre>
<p>Which gives me <strong><em>this error</em></strong>: </p>
<pre><code>Error in as.environment(where) : 'where' is missing
</code></pre>
<p>Further, I tried <strong><em>this</em></strong>, which gives me the following <strong>errors</strong></p>
<pre><code>datasub<-ARCTP53_SOExample[!is.na(ARCTP53_SOExample)]
gghist_3<-ggplot(datasub[datasub$Structural_motif=="NDBL/beta-sheets",])
Error in datasub$Structural_motif :
$ operator is invalid for atomic vectors
</code></pre>
<p>And this code doesn't work either: </p>
<pre><code>gghist_3<-ggplot(datasub, aes(x=p53_IHC))
Error: ggplot2 doesn't know how to deal with data of class character
</code></pre>
<p>So, does anyone know an easy solution to this? The <code>data.frame</code> is big and inherently has a lot of missing data depending on which column I'm looking at, but not all missing data is missing across all rows, so deleting any row that has a single "NA" in it, would be defeating the point. </p>
<p>Help is much appreciated. </p>
<p>Kind regards, </p>
<p>Oliver</p>
<p><strong>EDIT</strong> Following Daniel's comments below, this what I get following the code <em>below</em>. As you can see the problem is still not solved. Sorry.</p>
<pre><code>gghist<-ggplot(ARCTP53_SOExample[ARCTP53_SOExample$Structural_motif=="NDBL/beta-sheets" & is.na(ARCTP53_SOExample$p53_IHC) == F,], aes(x=p53_IHC))
gghist+geom_bar()
</code></pre>
<p>UPDATE: Re-Ran the code and for some reason it works now. Got the plot below: </p>
<p><img src="https://i.stack.imgur.com/4zVDA.png" alt="It works"></p>
<p><img src="https://i.stack.imgur.com/o5q8y.png" alt="NAs reduced but still there"></p>
| 1 | 1,571 |
PODS_ROOT and other pods env variables not set when compiling Ionic app
|
<p>I have built an Ionic 2 app which uses Intercom (a third-party extension). Intercom is installed using cocoapods.</p>
<p>When compiling my app I am given the errors:</p>
<pre><code>diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
</code></pre>
<p>This is being generated by the Build Phase <code>[CP] Check Pods Manifest.lock</code>:</p>
<pre><code>diff "${PODS_PODFILE_DIR_PATH}/Podfile.lock" "${PODS_ROOT}/Manifest.lock" > /dev/null
if [ $? != 0 ] ; then
# print error to STDERR
echo "error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation." >&2
exit 1
fi
# This output is used by Xcode 'outputs' to avoid re-running this script phase.
echo "SUCCESS" > "${SCRIPT_OUTPUT_FILE_0}"
</code></pre>
<p>I have tried outputting the environment variables <code>PODS_PODFILE_DIR_PATH</code> and <code>PODS_ROOT</code> in the <code>STDERROR</code> <code>echo</code> from the script above and both are blank. I can probably get around this specific error by amending those paths myself, but clearly something else more fundamental is broken, so I need to fix the actual issue itself.</p>
<p>Why are these variables blank?</p>
<p>I have additional build phases for <code>[CP] Copy Pods Resources</code> and <code>[CP] Embed Pods Frameworks</code> which run some shell scripts. I have tried changing the order of these with no luck.</p>
<p>My Podfile.lock and Podfile (which was auto-generated anyway) both seem good:</p>
<p>Podfile:</p>
<pre><code># DO NOT MODIFY -- auto-generated by Apache Cordova
platform :ios, '8.0'
target 'niix' do
project 'niix.xcodeproj'
pod 'Intercom', '~> 3.2.2'
end
</code></pre>
<p>Podfile.lock:</p>
<pre><code>PODS:
- Intercom (3.2.12)
DEPENDENCIES:
- Intercom (~> 3.2.2)
SPEC CHECKSUMS:
Intercom: 3119e8ebf76d3da425bab717a08067398fcabfe6
PODFILE CHECKSUM: f99283bb8a4e56cb037a02390d2fbc4e76c97db9
COCOAPODS: 1.3.1
</code></pre>
<p>There are no errors when running <code>pod install</code>, and all files I expect are present.</p>
<p>Things I have tried already:</p>
<ul>
<li>Running <code>pod install</code> (of course)</li>
<li>Running <code>pod deintegrate</code>, running Product > Clean in XCode, re-running <code>pod install</code></li>
<li>Manually deleting the <code>Podfile.lock</code> and <code>Pods</code> directory, running a Clean in XCode and then re-running <code>pod install</code></li>
<li>A good nights sleep and another attempt the next morning!</li>
</ul>
<p>Things to note:</p>
<ul>
<li>I am running from <code>project.xcworkspace</code> not <code>project.xcodeproj</code></li>
<li>I am running the latest stable version of XCode 8.3.3</li>
<li>I am running the latest version of Cocoapods 1.3.1</li>
</ul>
| 1 | 1,067 |
Serving static files with Ngnix, Django and Docker
|
<p>I am fairly new to Nginx and Docker and am currently facing an issue regarding a docker container setup. The setup consists of three containers: Nginx, Django and Postgres. It works as expected for the most part, however, I am not able to access static files through Nginx.</p>
<p>Here is the nginx.conf:</p>
<pre><code>user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local]'
'"$request" $status $body_bytes_sent'
'"$http_referer" "$http_user_agent"'
'"$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
upstream server {
server server:8000;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name localhost;
charset utf-8;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ @rewrites;
}
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
location ^~ /static/ {
autoindex on;
alias /usr/share/nginx/html/static/;
}
location ~ ^/api {
proxy_pass http://server;
}
location ~ ^/admin {
proxy_pass http://server;
}
}
}
</code></pre>
<p>I would expect Nginx to serve <em>/usr/share/nginx/html/static/</em> when I access the address <em>localhost:8000/static</em>. I did check the container fs at <em>/usr/share/nginx/html/static/</em>, and the static files are present.</p>
<p>Here is the docker-compose.yml:</p>
<pre><code>version: "3"
services:
nginx:
container_name: nginx
build:
context: .
dockerfile: ./nginx/Dockerfile
image: nginx
restart: always
volumes:
- ./server/static:/usr/share/nginx/html/static
ports:
- 80:80
depends_on:
- server
command: nginx -g 'daemon off';
server:
container_name: server
build:
context: ./server
dockerfile: Dockerfile
hostname: server
ports:
- 8000:8000
volumes:
- ./server:/src/project
depends_on:
- "db"
restart: on-failure
env_file: .env
command: >
bash -c '
python manage.py makemigrations &&
python manage.py migrate &&
gunicorn project.wsgi -b 0.0.0.0:8000'
db:
container_name: postgres
image: postgres:latest
hostname: postgres
ports:
- 5432:5432
volumes:
- /var/lib/postgresql/data
</code></pre>
<p>The folder <em>./server/static</em> contains all static files assembled trough <code>python manage.py collectstatic</code> and adds them to the volume <em>/usr/share/nginx/html/static</em>. However, when I try to access the static files, f.e. at <em>localhost:8000/admin</em>, I receive warnings for missing css files (base.css, login.css, ..).</p>
| 1 | 1,222 |
Scroll event isn't propagated to parent
|
<p>I am having a grid-div with <code>overflow-y: scroll;</code> and this grid-div is some time 10000pixels long. On mouserhover of a specific items of a grid-div I am firing mouserhover event, and user shows tooltip over the element. Now user add this popup under the body element. and user has written scroll event on window that if scroll event is fired, hide the tooltip. but when user is still over my grid-div, scroll event is fired only on grid-div, and event is not propagate to any parent elements(html,body,window) so user can't hide that element.</p>
<p>So here why scroll event is not propagated like click events? what is the possible solution to propagate the event?</p>
<p>Here is an example <a href="https://jsfiddle.net/wrnanpmL/1/" rel="noreferrer">fiddle</a> of what issue I am facing, Here I haven't added tooltip but only sample code to reproduce that scrolling issue. Here I am expecting that for every "Scrolled On div" there should be "Scrolled On Window" written in log.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(window).on("scroll", function() {
// While scrolling on div why this event is not fired?
$('#eventData').append('<div>Scrolled On Window</div>');
});
$('#grid-div').on("scroll", function() {
$('#eventData').append('<div>Scrolled On div</div>');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#grid-div {
height: 200px;
overflow-y: scroll;
border: 1px solid gray;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="grid-div">
<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A<br/>A
</div>
<div id="eventData">
</div></code></pre>
</div>
</div>
</p>
| 1 | 1,355 |
Matplotlib error message: "TypeError: 'Ellipse' object is not iterable"
|
<p>I tried to run an animation within matplotlib (Python) animate and I got the error</p>
<pre><code>TypeError: 'Ellipse' object is not iterable
</code></pre>
<p>Ellipse is an object of type "patches" ... </p>
<p>the result being:</p>
<p><a href="https://i.stack.imgur.com/skEBk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skEBk.png" alt="this is the interim result from the code sample"></a></p>
<p>The program runs and produces the first subplot - it should move the ellipse along the read "line" .. however produced the above error message . </p>
<p>Now what does the error-message mean.</p>
<pre><code># -*- coding: utf-8 -*-
#############################################################################
# first try to compute the program for demonstrating the dependency of
# total annual insolation of a planet (here Earth) on the ellipticity of
# the orbit
#
#############################################################################
# created 2015-06-01 by Jörg Kampmann - IBK-consult - D-31228 Peine
#
#############################################################################
# the insolation
# N_EGA = (2*pi**2*R**2*N0)/(n*a**2*sqrt(1 - e**2))
# is dependent on "e" under the assumption that "a" and "N0" are constant
#
# this module
# computes and shows presently the dependency of TOI over e
#
# Todo: animation of size of ellipse when eccentricity grows from zero to
# ECCmax
#
#############################################################################
#Path to the workbook datasets
#datapath = '/home/kampmann/rtpSW/WorkbookDatasets/'
#Path to the hitran by-molecule database
#hitranPath = datapath+'Chapter4Data/hitran/ByMolecule/'
"""
Excentricity is ECC = sqrt(a**2 - b**2) or
ECC**2 = a**2 - b**2
b**2 = a**2 - ECC**2
b = sqrt(a**2 - ECC**2)
a = height/2.0
->
b = sqrt(height**2/4.0 - ECC**2)
"""
import math
from ClimateUtilities import *
import phys
import numpy as nm
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from matplotlib import patches
#from matplotlib import animation
#------------Constants and file data------------
# eccentricity
printswitch = True
printswitch = False
printswitch2 = True
#printswitch2 = False
ECCabsoluteMax = 0.9
ECCmax = 0.067 # maximum value for this run - should not be greater than
# ECCabsoluteMax
#ECCmax = 0.9 # maximum value for this run - should not be greater than
# ECCabsoluteMax
if ECCmax >= ECCabsoluteMax:
ECCmax = ECCabsoluteMax
ECCdelta = 0.001 # interval for graph
eccentricity = nm.arange(0., ECCmax, ECCdelta, dtype=float)
semimajorA = 1.0 # astronomical unit =~ 150.000.000 km mean distance Sun Earth
totalRadN0 = 1370. # radiation of Sun at TOA in Watt/m**2
albedoEarth = 0.3 # presently albedo of Earth, geographically constant
T = 365.25 # duration of one orbit around central celestial body in days
# here: duration of one orbit of Earth around Sun
R = 6378100.0 # radius of Earth in meters
TOIdim = ECCmax/ECCdelta
TOI =nm.arange(0., TOIdim, dtype=float )
# total insolation at location of Earth summed over 1 year
"""
now define various "functions" like:
"""
def computeTOI( ee, semimajorAxis, radiationAtStar, alpha ):
aa = semimajorAxis # semimajor axis of orbital ellipse
N0 = radiationAtStar# radiation of start at position of star (r = 0)
resultTOI = 2.*nm.pi*T*R**2*N0*alpha/(aa**2*math.sqrt(1 - ee**2))
return resultTOI
def init_TOI():
line1.set_data([], [])
return line1
def init_Ellipse():
line2.set_data([], [])
return line2
def animateTOI():
return True
#
#####################################################################
#
print "start of ellipticity and absorbed insolation"
#
#
# Start of programme here
#
#####################################################################
# compute the various TOIs dependant on eccentricity "ecc"
#
ii = 0
for ecc in eccentricity:
if printswitch: print 'TOI = ', computeTOI( ecc, semimajorA, totalRadN0, albedoEarth ), '\n'
TOI[ii] = computeTOI( ecc, semimajorA, totalRadN0, 1. - albedoEarth )/10.0**19
ii = ii + 1
# TOI is an array consisting of TOIs depending on eccemtricity "ecc"
x = eccentricity
if printswitch: print 'TOI = ', TOI
#print 'ECC = ', x
# almost the whole screen is filled with this plot ... :)
Main = plt.figure(figsize=(15.0,15.0))
Main.subplots_adjust(top=0.95, left=0.09, right=0.95, hspace=0.20)
axFigTOI = Main.add_subplot(211)
# Plot ... TOI over ECC:
if ECCmax < 0.07:
plt.axis([0,0.07,8.9,9.0])
plt.title( 'Absorbed Irradiation and Orbital Eccentricity for Planet Earth\n' )
plt.ylabel( 'Absorbed total \nsolar irradiation \n[Watt] *10**19' )
plt.xlabel( 'Eccentricity "e"' )
plt.plot( x, TOI, 'r-' ) # this works fine! 'x' and 'TOI' are center of mini-ellipse
# Now enter an ellipse here on Subplot 211:
xcenter, ycenter = x[1],TOI[1] # center of ellipse to start with
width = 0.0025
height = 0.01
e1 = patches.Ellipse((xcenter, ycenter), width, height,\
angle=0.0, linewidth=2, fill=True, zorder=2)
e1.set_visible(True)
axFigTOI.add_patch( e1 )
def init():
axFigTOI.add_patch(e1)
return e1
def animateEllipse(i):
xcenter = x[i]
ycenter = TOI[i]
e1 = patches.Ellipse((xcenter, ycenter), width, height,\
angle=0.0, linewidth=2, fill=True, zorder=2)
if i == 1:
e1.set_visible(True)
axFigTOI.add_patch(e1)
return e1
anim = animation.FuncAnimation(Main, animateEllipse,
init_func=init,
frames=360,
interval=20,
blit=True)
plt.show()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.pyc in resizeEvent(self=<matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object>, event=<0xbf9f7b48 >)
336 self.figure.set_size_inches(winch, hinch)
337 FigureCanvasBase.resize_event(self)
--> 338 self.draw()
self.draw = <bound method FigureCanvasQTAgg.draw of <matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object at 0xb0eef26c>>
339 self.update()
340 QtWidgets.QWidget.resizeEvent(self, event)
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.pyc in draw(self=<matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object>)
146 # causes problems with code that uses the result of the
147 # draw() to update plot elements.
--> 148 FigureCanvasAgg.draw(self)
global FigureCanvasAgg.draw = <unbound method FigureCanvasAgg.draw>
self = <matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object at 0xb0eef26c>
149 self._priv_update()
150
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self=<matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object>)
467
468 try:
--> 469 self.figure.draw(self.renderer)
self.figure.draw = <bound method Figure.draw of <matplotlib.figure.Figure object at 0xb100896c>>
self.renderer = <matplotlib.backends.backend_agg.RendererAgg object at 0xb117bbec>
470 finally:
471 RendererAgg.lock.release()
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist=<matplotlib.figure.Figure object>, renderer=<matplotlib.backends.backend_agg.RendererAgg object>, *args=(), **kwargs={})
57 def draw_wrapper(artist, renderer, *args, **kwargs):
58 before(artist, renderer)
---> 59 draw(artist, renderer, *args, **kwargs)
global draw = undefined
artist = <matplotlib.figure.Figure object at 0xb100896c>
renderer = <matplotlib.backends.backend_agg.RendererAgg object at 0xb117bbec>
args = ()
kwargs = {}
60 after(artist, renderer)
61
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self=<matplotlib.figure.Figure object>, renderer=<matplotlib.backends.backend_agg.RendererAgg object>)
1089 self._cachedRenderer = renderer
1090
-> 1091 self.canvas.draw_event(renderer)
self.canvas.draw_event = <bound method FigureCanvasQTAgg.draw_event of <matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object at 0xb0eef26c>>
renderer = <matplotlib.backends.backend_agg.RendererAgg object at 0xb117bbec>
1092
1093 def draw_artist(self, a):
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in draw_event(self=<matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg object>, renderer=<matplotlib.backends.backend_agg.RendererAgg object>)
1793 s = 'draw_event'
1794 event = DrawEvent(s, self, renderer)
-> 1795 self.callbacks.process(s, event)
self.callbacks.process = <bound method CallbackRegistry.process of <matplotlib.cbook.CallbackRegistry instance at 0xb0e3814c>>
s = u'draw_event'
event = <matplotlib.backend_bases.DrawEvent instance at 0xb0ebebac>
1796
1797 def resize_event(self):
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/cbook.pyc in process(self=<matplotlib.cbook.CallbackRegistry instance>, s=u'draw_event', *args=(<matplotlib.backend_bases.DrawEvent instance>,), **kwargs={})
538 del self.callbacks[s][cid]
539 else:
--> 540 proxy(*args, **kwargs)
proxy = <matplotlib.cbook._BoundMethodProxy object at 0xb0fdfb2c>
args = (<matplotlib.backend_bases.DrawEvent instance at 0xb0ebebac>,)
kwargs = {}
541
542
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/cbook.pyc in __call__(self=<matplotlib.cbook._BoundMethodProxy object>, *args=(<matplotlib.backend_bases.DrawEvent instance>,), **kwargs={})
413 mtd = self.func
414 # invoke the callable and return the result
--> 415 return mtd(*args, **kwargs)
mtd = <bound method ?._end_redraw of <matplotlib.animation.FuncAnimation object at 0xb0fdf44c>>
args = (<matplotlib.backend_bases.DrawEvent instance at 0xb0ebebac>,)
kwargs = {}
416
417 def __eq__(self, other):
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in _end_redraw(self=<matplotlib.animation.FuncAnimation object>, evt=<matplotlib.backend_bases.DrawEvent instance>)
879 # Now that the redraw has happened, do the post draw flushing and
880 # blit handling. Then re-enable all of the original events.
--> 881 self._post_draw(None, self._blit)
self._post_draw = <bound method FuncAnimation._post_draw of <matplotlib.animation.FuncAnimation object at 0xb0fdf44c>>
global None = undefined
self._blit = True
882 self.event_source.start()
883 self._fig.canvas.mpl_disconnect(self._resize_id)
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in _post_draw(self=<matplotlib.animation.FuncAnimation object>, framedata=None, blit=True)
825 # blitting.
826 if blit and self._drawn_artists:
--> 827 self._blit_draw(self._drawn_artists, self._blit_cache)
self._blit_draw = <bound method FuncAnimation._blit_draw of <matplotlib.animation.FuncAnimation object at 0xb0fdf44c>>
self._drawn_artists = <matplotlib.patches.Ellipse object at 0xb0fdf80c>
self._blit_cache = {}
828 else:
829 self._fig.canvas.draw_idle()
/home/kampmann/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in _blit_draw(self=<matplotlib.animation.FuncAnimation object>, artists=<matplotlib.patches.Ellipse object>, bg_cache={})
834 # of the entire figure.
835 updated_ax = []
--> 836 for a in artists:
a = undefined
artists = <matplotlib.patches.Ellipse object at 0xb0fdf80c>
837 # If we haven't cached the background for this axes object, do
838 # so now. This might not always be reliable, but it's an attempt
TypeError: 'Ellipse' object is not iterable
</code></pre>
| 1 | 5,513 |
HTML Strict & CSS: How do I close the gap?
|
<p>In the following web page, there is a gap of a few pixels between the image and the div. (I've tested in Firefox 3 and Safari 4.)</p>
<p>How can I close the gap?</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-css lang-css prettyprint-override"><code>body {
background-color: black;
}
img {
width: 250px;
height: 70px;
border: 0;
margin: 0;
padding: 0;
}
div {
background-color: white;
border: 0;
margin: 0;
padding: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test Page</title>
</head>
<body>
<img alt="Stack Overflow Logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAccAAABvCAMAAACuGvu3AAAAw1BMVEX///8iJCb0gCS8u7sAAAAfISP19fURFBccHiDJyMi3trYJDRFOUFEZGx30fRwWGBuVlpft7e3++vfX2Nimp6j2mluJiov0hinAwMAAAQnk5OQmKCljZGZzc3Q0NjcABwzzdwD0exMtLzHR0dJaW1xrbG3c3Nw6PD6trq5/gIH+9e45Ozz+8eednZ5FRkdSU1T3q3f5w5/1ijn71L395NH6yav1kET828j96Nj4tIf5wJr3qXH2lU/2n2b4soP1iTXzbwCyXU06AAAQuklEQVR4nO1caXuiOhQWBRJERKq1ilVE3Fttp/s2M/f//6qb5CQh4FLbOrXtk/dLJSThkDc5W0ILBQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ2Nn4SbQwugsQccPf93f2gZND6Mm79xsTg/tBQaH8SvarVYjH8fHVoOjQ/hT79I0X86tCAaH8I18FisahP5vfEIRFZPtIn83nipApG/Dy2IxofwAIq12L89tCQaH8ItN5GxTgd8bwgTeadN5LfDXOFszk1krE3kd8P85UUh8iHmmlWbyG+G5zj++5BeChPZf9jcROPr4Q9ZgFV19V3G2kR+P/DlFz/KEmkiLw8olsbbcNMXIeOlTI/fVLWJ/G6YHwsi45dzUShMZPV8W1ONL4VH7qAWq0WZH3/mJvLkkIJpvA23Ra5Hq1WhSI+uuIn8c1DJNN6Em5OqMJJP3EjeiILrw4qm8Rac/xW6tf/MifzFTeSJNpHfCZfS2xHECRN5p095fCc85b2d+d/PjSLHSb1uf86jXsHYKU8JiDD1Bv0xbR1aorfguprzdm7izzSR9sQ0zfpnPOkVtIaeGbluZIWFQsN0CczhoWV6E26K0tsBL1UGJJ9hIu0KtowvwOPM9CyDwBpQHl360zs9tFBbcfmSW2hqSoClVn9zE/nyCSbyi/A4igzAt+FxHlfju+sMQ0ePksgreh7g/C1RpNNoND7Aw9fgsdw2vhuPT2yb4+X2KFsojOQJXaz3Md9T3mFBzkzXXLxfnK/B4xJzFj2/8z14POJ89f/+UklKvZ34F7l86tMqv3bpsIkM97vzGJpAIxqMRt3gW/Ao4nxCU/ykODIPV5mUwEscn+y2n/wTeJwy3gx/yq+/Po/zK+GcUr1Z/JNydXQsiIyPzwvnJ8877ib/BB4XjDcs44yvz+PR7V2sMnlymTL5RxJ5d1M439VX/Qk81hBbjl1x/fV5JExeZ5nsP8sjq4rO3T101DweDPfHfYXJal8GlDecYeWwx6v4HB7DxGm10mp2AFCr8KI0xzdutVpOpkpBaWaTDh3e4648EilKrfE2KXLX6+TcJ26e41hhUgaU5y+0OH7e3NIOwjBQ86HreAzG9Xp9HK7vgN5JO1jl0abINBk3ewb2EcKD0xKUTN0OBVYeMUWsyORFSXdgIYR8Y1JLB77AmhkkREy6BunQx4MmrQ884goJhRcNewOP9e6ASWENRg6UNNgjjU4qfs2n3acPbHpMqGjtSOwFD5fFDJMvEIbMn2Pi52xycYJpt7LsTZaVUU3KTnhENUIuBVRqnE46GBuDs4tuK5cBDxujpeF1epVuid9Z4bG2rFSWU6XAnnWQBTkzy4uGCXuGb1FEygS68GiJt2QXySnyeRvsdppSCpPWwYNxDSPeIxqUBI8GdkV+dZXHoGtJKXw0YlQliEnhlmWtJRUiSqU/w7SC/08V9MOfqsokCSgZfY/9TVuPdrPT9jGRDGPfbQ+59IRHA5kMTXo97bU9+sJ0wHxzUlZ7WBiRT2ijd9o9WFp5HpsRxmZNaRNWIstI4XtslLo+G+k0kx1A6OCyuy3kK00styIUG6RtBkOlS8+0BY9b8jn1HspI4bMlObCy+rjOmPYupFDQr5sZhP1j/hQrLk81jh8pg7cbPtUJPdcyPBRFroswff8lG/4mHwO+OGYmNizkRqYZIY9McSAX3qrSJq/pkZuuR8gEtnI8ziLDyKSHwoFKCXtOgxS3WORuGVKFlV1gIWA3rWwbtOQrkqffcHoLo3rhdR6TCGc6JNJTImesnYVEtQWfTEFWqM56C7NHHP26U12eOL7cGPwHE8/A0XBRLk0Xs0rkE4UlecSIkEOHl9BIRs1qLsqJU66duuTtTTEZgyVhBPmntWmpMfLI7/askOeR0dhQH0ueykfOkkNIVavPLl1Zd8Tq+SPys+5CVcvzfT78iFMi06iSxg7tTPDIlO4aHsOeoDGVwiD1HGgn9914NVcoVpjjWK7Pf4h5LqAsbto+7iIDLx1h1cZdv+MIWfFwsaiBmnQsjLpy+jmU+wmfnaeIqiB+bzxCFqIkZHhsRmRyZ5wmGFFquowB4qPN9BYfoiWvZ0O9iG79nsIKRpPRrLvknHLVlqbDkYvILMMGewnOY6fX6w0ma3iccSk84ie5XD+gLp3bmdkk0nveiLfjtz/gzq/FfO1iO7p+UZjclFQddywDJUpBizttzM9Ji52MVkyIBTFhdpbIGLaVe00oV3mkqzFSbWOh0AEa/LPSeJzMOJEmYSuBderzeQEbFnhJ5ozDlduMzh+71MEK4YJHf9BMkunSjeAlgEdvFHBnLcdjCHbQQBet8djpQv8WJlKPGKnCQIpJZ0Qw3QPg1dt3eHz7X3z8eL2GTBJQcpenerXBVyU0pPZcBeWxqVzX83f5cEywgWbqLZgUCo+jvG2kswIGkE/wBewS+jPoT1Fh4PewB5x68idFCA4KYoc0OI/eEAZ6xufiK/HjNOIzAy756nTJjCuBmR5Ad0NhAyJY/ZC2xRf7PrbyGFNnplp8ebx/yNH1cAkBZbzpf6/UNoX7eR6zSEyyFOh7EEbwZE2FlMeRm7eNMrATqpnTxZYd+BTcYw1gxVBDFbIlbHVkH1OFJM4jCtY9ZiOPwA8+E7fP5BIPOvK5qVqVPc1gcm0enffh6FjuTcUnd7+f7s9VMh8uT+Itxx03pm228xi0DYuxQNs31lQQPNpUXaH8E8B7SftvMSIsGuON+RAGaTmukBnTcnODB0bMMujvtpEljOMVHg1Y0TJ6aICbakgBXWYMFkKtcrfZhl1NMynsF/OT1J8pVqtxv/py+esmzYc/PBb7GxNyREfsplezIBGU1Qs5XeM1FTiPdpfoLr+2epONhCMLQMOx+Q/601XCSTbRgBPXSXuBiibVCsBjVMo9ZzuP4EMpXjXYZgunHtEofQ5Dmz4hZMJavX2r1Yd+MQeyMPv9uz+3gsz548b8eII2xLOv8OgDjyHx6JfrXogTfErHw8rP3KAHa046wDZ4gG1q7MC1YUPI/Ua2NrkSbCQC9SFMBjqLgEfk5J6zncdQCU1BLFAFfiJcGfGK9MEL2heLf6AXf1bYM5761WqeSSAzjq8ub2+2bzgOyZR3T50wT8Z6Hm2O0IOXHJsbtg8ojx1nyO1g7mYA4ZqXmrMLxgnLfMFoWjgQuhTyKD3u4SIJKGDq7V081oHHM/nmNlhj1g1ojCjhjYjPS7Uwe2fQue384v8wbh5/31X78Toui1TLXh1vzgKQBUmzID7qLSsXw9GsloixXeExKM8uKksOslDYOxE3R0ZVGVDV2ZmQOeJ3jEwAw7oCBWakPA4VZQphCOWUe6tMXVi5XI4AU87v4jEBHpVJNkhdYLb82AhcUNHcEjDrtgoBN4//4pD1+cP15d1JdT2XxerWo8fJgM5sC2PseT4yJzUQMM9j44wmYQXE3GxtCluYCbSoq0AHz8xmsALGj9VZ4ZF5TBCU0NE2rLSa/494VJVFL+WR36yAn0zflTUmijXxUyXxQTgM+TB0fnP7fNInC3OFzSpbjzY0W3Gz7CYyXYQ8DIYgmjAiczyOTGx4rinBeSxF23gko1xjWS0ve4Sb87hhPcLSswYhpMf4roK1olcB/2g9CiECFizSJmO2S4B5J2ud9DfCLpcIynmpGY7uny7v8mTC56t2iWHd1w31aW02uphYJs2c+ixHkuVxFhlWNJzWQ47E22U9QtyYkKWUDSADI28fK6l9FMMflfhfeE+ee5nVcmi+28/Zah+5dkcJs9zMAWNzDTnMvbKsdU76GwE8ltbySHE0vyYmM5Yms3oMzVobeYT7dhA2aNK7TYczw6PjEvWmNhT+6jY/R2YgyZBYA/W9ub/aTv3Vs9RfJQMMrulwyfTDEtgGT8hanwv7iL/aW+evily5P/NkHXB4ugMm3LLwcbzGI8M8NZk8mfMaj/AuxKwz7zrDYzefLZBxB9qQ9qc8irgxJLShUe6mkYkfIdQWGwzgSYAmFULA+nDXS/8uHnn8mE6NBB4LpxECmFo47QF4h62PvSRzduKR4fyemkz+r+Z34pFaDbYEMjySgc3mvEQeIJhg9ndVRjVBMDWZx5cin88B18byeE8N8VWGwi3s+flrneP38chNbho9TzmxcKWG/+V8ibuPZM7uPDIc3UMEuRuPZPEwNaLySOJxa5Lxs0mcDPzNfNhUWpExs/9ITIulOuoivyqKYISECpUbEYaSja6DTW0rAxjI32/jkWfT+WxKHVZQq0JllpTNMFtpDnX2EXXkeDx6DaLZzjxOcjyGZ3kenTbnsdxebyCzPI7bRmZXhO93yI0h2LhKUyQjeVggVeegbHG6+usVueG2I49lnlHj02WabnBQNLOXYUdMJtFBkCbM95LMyfJ4/3L8Cn5DVm49j7kzbEyv0jWwcNORt1f0apPr1YLtWdxRF4B6+XMdZETbyjAbfOdvWB7b9S6PDU3ZT7oWTPlYvhq8s0ZAM0pBreNhvue9K491vl3WrbOje4Ipt1sKbWfE9x+lvRwJNSo1b0UcH2jv5ZPmLI/X/eor+LuNx2EubCAqjvFHIgq2zyAKMwETHQFuFwnfVqQouxZc5Hi0BzijjIQF9CISi/LFp0TkgVCsXiUtg20lw3LNXqUyMGn2AlswCDvyGIjtaxM+lhbnAXwiRZtLkR6Ck/sc0iIIxapGvh9Anse1SRwFV1t4HLroTHl9m57SYClLun8kN/HLxBxaaTa9ZWFD8FjoUdsntJ89MzGbvvnzciVCnKs4eZXcMSsjuxEkTnmpKXxHqjWLJZQY99BoRx6F6hTLzp6knovsWupteZwjPc/DH7s+ZH4z9shjzbQM7FVqSRiE4bg865E3j0CdkliDuASNKf2a1V4SsnClPCaoT4eeheV6LNQH5B5aLurkVmNCt0+oH7FyfpWYPAunTI17uSG0Mgs+gTFUU3dkgeTPy5Fnjdha2ZXHwEsPVlHhEnFgK5VCGR7+9aTiaYsS9Rzu+7FHHu0ZPeuIUTSYTAYoIobKck9BjYQDegrSddk5xoRpsYge0HUjz/IrPcljIaHkY5c0dmk6yD1lm615HsekB0+JnlmrFBhn95pBiebCjBrycqPeBVl35bFQwp7KY6HlZXr0jPJKc3ZikoMrVnMvavWtPFa36dVCi54vZkcDWfbETQ9EjSOX6hHwGBPGEa1mWL7ZDWh0It4vHJoii03vsaFd/S6gRsagraw5tZXXHuQCMjBOUY4ZZynbkEdFlniXnXksJBPTZ4fBuTtTX6qyVzLZNocZcdUdHxuQYirsBTke45NXcLeNRzJHRz7NkyPkts3JQv0apVahJ8qBWHtxZrJ/YGJ2uk4hIDe8dJ62ugjuoS7ng/3flSw32Mz9KxanOyCtiI+BTleEClk2/mwlTHNmZ/QsdNs0jW66dnjyPt9LE4qzcVGpu+zRjzMEZa0RBim8bj64h+ZqAuOClezpwONb40ceQG6OH+36tFarLRqtID9u6sc1duBMp9My/Hej/Ec3dlIm9xI703JNX9kyOyxPy6t72BtqixuhU24lGVHt9bXtbeXK5bg8LSVrpFhtvVGq9+CN+RzZbKc8gManQfP4M6B5/BnQPP4MaB5/BjSPPwOcx1L5jdh8PkfjEBA8vg+ax68CzePPgObxZ0Dz+DOgefwhcD6EQ0uvoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhofGd8T8UlHs1bs9urgAAAABJRU5ErkJggg==">
<div>text</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 1 | 5,021 |
File transfer using XMPP (Extension XEP-0065)
|
<p>Not sure why I am getting turn socket failed (turnSocketDidFail called). Anybody can help me in figure out this? Please point me what am I doing wrong here. I know there are lots of question like this and I have already checked all of these and from that I have taken little help already. One of client is Spark and other is simulator.</p>
<p><strong>Settings:</strong><br>
Server: testXyz<br>
Senderjid: user1@testXyz<br>
Receiverjid: user2@testXyz<br></p>
<pre><code>XMPPJID *jid = [XMPPJID jidWithString:Receiverjid];
[TURNSocket setProxyCandidates:[NSArray arrayWithObjects:Receiverjid, nil]];
TURNSocket *turnSocket = [[TURNSocket alloc] initWithStream:self.chatManager.xmppStream toJID:jid];
[turnSocket startWithDelegate:self delegateQueue:dispatch_get_main_queue()];
</code></pre>
<p><strong>Console logs</strong></p>
<pre><code>SEND:
<iq type="get" to="Receiverjid" id="C15C428D-6007-4B4E-96D5-65F7A307121A"><query xmlns="http://jabber.org/protocol/disco#items"/></iq>
RECV:
<iq xmlns="jabber:client" type="result" id="C15C428D-6007-4B4E-96D5-65F7A307121A" from="Receiverjid" to="Senderjid/4840c8ae">
<query xmlns="http://jabber.org/protocol/disco#items">
<item jid="Receiverjid" node="http://jabber.org/protocol/tune"/>
<item jid="Receiverjid/Spark 2.6.3"/>
</query>
</iq>
SEND:
<iq type="get" to="Receiverjid" id="A4D8B427-B323-4152-8B19-7B55164E9C4B">
<query xmlns="http://jabber.org/protocol/disco#info"/>
</iq>
RECV:
<iq xmlns="jabber:client" type="result" id="A4D8B427-B323-4152-8B19-7B55164E9C4B" from="Receiverjid" to="Senderjid/4840c8ae">
<query xmlns="http://jabber.org/protocol/disco#info">
<identity category="account" type="registered"/>
<identity category="pubsub" type="pep"/>
<feature var="http://jabber.org/protocol/disco#info"/>
</query>
</iq>
SEND:
<iq type="get" to="Receiverjid/Spark 2.6.3" id="2DE55487-9203-4266-A559-1B1D3DC5FBF4">
<query xmlns="http://jabber.org/protocol/disco#info"/>
</iq>
RECV:
<iq xmlns="jabber:client" id="2DE55487-9203-4266-A559-1B1D3DC5FBF4" to="Senderjid/4840c8ae" type="result" from="Receiverjid/Spark 2.6.3">
<query xmlns="http://jabber.org/protocol/disco#info">
<identity category="client" name="Smack" type="pc"/>
<feature var="http://www.xmpp.org/extensions/xep-0166.html#ns"/>
<feature var="urn:xmpp:tmp:jingle"/>
</query>
</iq>
RECV:
<iq xmlns="jabber:client" id="2DE55487-9203-4266-A559-1B1D3DC5FBF4" to="Senderjid/4840c8ae" type="result" from="Receiverjid/Spark 2.6.3">
<query xmlns="http://jabber.org/protocol/disco#info">
<identity category="client" name="Smack" type="pc"/>
<feature var="http://jabber.org/protocol/xhtml-im"/>
<feature var="http://jabber.org/protocol/muc"/>
<feature var="http://jabber.org/protocol/bytestreams"/>
<feature var="http://jabber.org/protocol/commands"/>\
<feature var="http://jabber.org/protocol/si/profile/file-transfer"/>
<feature var="http://jabber.org/protocol/si"/>
<feature var="http://jabber.org/protocol/ibb"/>
</query>
</iq>
</code></pre>
<p><strong>Update</strong></p>
<p>If I am changing:</p>
<p><code>[TURNSocket setProxyCandidates:[NSArray arrayWithObjects:Receiverjid, nil]];</code> </p>
<p>to:</p>
<p><code>[TURNSocket setProxyCandidates:[NSArray arrayWithObjects:Server, nil]];</code></p>
<p>It gives me:</p>
<p><code><error code="503" type="cancel"><service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></code>.</p>
<p>As suggested in one of question on stack to resolve this error I have replaced Receiverjid: 'user2@testXyz' by 'user2@testXyz/spark' but am still getting same error.</p>
| 1 | 1,695 |
Java Spring MVC Template Project Problems
|
<p>Brand new project that I just created using the Spring Template for MVC. I try to run on Server and get the following.</p>
<p>Any ideas?</p>
<pre><code>SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/src]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:650)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1582)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
at java.lang.Class.getDeclaredFields(Class.java:1743)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:87)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationListenerAnnotations(WebAnnotationSet.java:90)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContextException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
... 25 more
Jan 15, 2013 10:27:41 AM org.apache.catalina.startup.HostConfig deployDescriptor
SEVERE: Error deploying configuration descriptor /Users/maratlevit/springsource/vfabric-tc-server-developer-2.7.2.RELEASE/base-instance/conf/Catalina/localhost/src.xml
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/src]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:650)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1582)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
</code></pre>
<p><strong>EDIT:</strong> Looking at the Markers tab I see the following:</p>
<pre><code>Description Resource Path Location Type
Archive for required library: '/Users/maratlevit/.m2/repository/org/springframework/spring-aop/3.1.1.RELEASE/spring-aop-3.1.1.RELEASE.jar' in project 'FirstLesson' cannot be read or is not a valid ZIP file FirstLesson Build path Build Path Problem
</code></pre>
<p><strong>EDIT 2:</strong> Added list of dependencies as requested:</p>
<pre><code>/Users/maratlevit/.m2/repository/org/springframework/spring-context/3.1.1.RELEASE/spring-context-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-aop/3.1.1.RELEASE/spring-aop-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-beans/3.1.1.RELEASE/spring-beans-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-core/3.1.1.RELEASE/spring-core-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-expression/3.1.1.RELEASE/spring-expression-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-asm/3.1.1.RELEASE/spring-asm-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-webmvc/3.1.1.RELEASE/spring-webmvc-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-context-support/3.1.1.RELEASE/spring-context-support-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/springframework/spring-web/3.1.1.RELEASE/spring-web-3.1.1.RELEASE.jar
/Users/maratlevit/.m2/repository/org/aspectj/aspectjrt/1.6.10/aspectjrt-1.6.10.jar
/Users/maratlevit/.m2/repository/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar
/Users/maratlevit/.m2/repository/org/slf4j/jcl-over-slf4j/1.6.6/jcl-over-slf4j-1.6.6.jar
/Users/maratlevit/.m2/repository/org/slf4j/slf4j-log4j12/1.6.6/slf4j-log4j12-1.6.6.jar
/Users/maratlevit/.m2/repository/log4j/log4j/1.2.15/log4j-1.2.15.jar
/Users/maratlevit/.m2/repository/javax/inject/javax.inject/1/javax.inject-1.jar
/Users/maratlevit/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar
/Users/maratlevit/.m2/repository/javax/servlet/jsp/jsp-api/2.1/jsp-api-2.1.jar
/Users/maratlevit/.m2/repository/javax/servlet/jstl/1.2/jstl-1.2.jar
/Users/maratlevit/.m2/repository/junit/junit/4.7/junit-4.7.jar
</code></pre>
| 1 | 2,580 |
WPF Custom Buttons below ListBox Items
|
<p>WPF Experts - </p>
<p>I am trying to add buttons below my custom listbox and also have the scroll bar go to the bottom of the control. Only the items should move and not the buttons. I was hoping for some guidance on the best way to achieve this. I was thinking the ItemsPanelTemplate needed to be modified but was not certain.</p>
<p>Thanks</p>
<p><a href="https://i.stack.imgur.com/NlGWh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NlGWh.png" alt="alt text"></a>
</p>
<p>My code is below</p>
<pre><code> <!-- List Item Selected -->
<LinearGradientBrush x:Key="GotFocusStyle" EndPoint="0.5,1" StartPoint="0.5,0">
<LinearGradientBrush.GradientStops>
<GradientStop Color="Black" Offset="0.501"/>
<GradientStop Color="#FF091F34"/>
<GradientStop Color="#FF002F5C" Offset="0.5"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
<!-- List Item Hover -->
<LinearGradientBrush x:Key="MouseOverFocusStyle" StartPoint="0,0" EndPoint="0,1">
<LinearGradientBrush.GradientStops>
<GradientStop Color="#FF013B73" Offset="0.501"/>
<GradientStop Color="#FF091F34"/>
<GradientStop Color="#FF014A8F" Offset="0.5"/>
<GradientStop Color="#FF003363" Offset="1"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
<!-- List Item Selected -->
<LinearGradientBrush x:Key="LostFocusStyle" EndPoint="0.5,1" StartPoint="0.5,0">
<LinearGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterX="0.5" CenterY="0.5"/>
<SkewTransform CenterX="0.5" CenterY="0.5"/>
<RotateTransform CenterX="0.5" CenterY="0.5"/>
<TranslateTransform/>
</TransformGroup>
</LinearGradientBrush.RelativeTransform>
<GradientStop Color="#FF091F34" Offset="1"/>
<GradientStop Color="#FF002F5C" Offset="0.4"/>
</LinearGradientBrush>
<!-- List Item Highlight -->
<SolidColorBrush x:Key="ListItemHighlight" Color="#FFE38E27" />
<!-- List Item UnHighlight -->
<SolidColorBrush x:Key="ListItemUnHighlight" Color="#FF6FB8FD" />
<Style TargetType="ListBoxItem">
<EventSetter Event="GotFocus" Handler="ListItem_GotFocus"></EventSetter>
<EventSetter Event="LostFocus" Handler="ListItem_LostFocus"></EventSetter>
</Style>
<DataTemplate x:Key="CustomListData" DataType="{x:Type ListBoxItem}">
<Border BorderBrush="Black" BorderThickness="1" Margin="-2,0,0,-1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=ActualWidth}" />
</Grid.ColumnDefinitions>
<Label
VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent"
Foreground="{StaticResource ListItemUnHighlight}"
FontSize="24"
Tag="{Binding .}"
Grid.Column="0"
MinHeight="55"
Cursor="Hand"
FontFamily="Arial"
FocusVisualStyle="{x:Null}"
KeyboardNavigation.TabNavigation="None"
Background="{StaticResource LostFocusStyle}"
MouseMove="ListItem_MouseOver"
>
<Label.ContextMenu>
<ContextMenu Name="editMenu">
<MenuItem Header="Edit"/>
</ContextMenu>
</Label.ContextMenu>
<TextBlock Text="{Binding .}" Margin="15,0,40,0" TextWrapping="Wrap"></TextBlock>
</Label>
<Image
Tag="{Binding .}"
Source="{Binding}"
Margin="260,0,0,0"
Grid.Column="1"
Stretch="None"
Width="16"
Height="22"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<ObjectDataProvider ObjectType="{x:Type local:ImageLoader}" MethodName="LoadImages" />
</Window.DataContext>
<ListBox ItemsSource="{Binding}" Width="320" Background="#FF021422" BorderBrush="#FF1C4B79" >
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</SolidColorBrush>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="ItemTemplate" Value="{StaticResource CustomListData }" />
</Style>
</ListBox.Resources>
</ListBox>
</code></pre>
| 1 | 2,811 |
How to put a floating widget in flutter?
|
<p>What I want to do is make a TextField stay in the same position by scrolling down the screen. I want to know if there is a way to do this?</p>
<p>This is the TextField that I want to be floating:</p>
<p><a href="https://i.stack.imgur.com/WdYgn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WdYgn.png" alt="enter image description here"></a></p>
<p>This is the code, the <code>CardWidget</code> are just cards and searchInput is the textField:</p>
<pre><code>class RouteListPage extends StatefulWidget {
@override
_RouteListPageState createState() => _RouteListPageState();
}
class _RouteListPageState extends State<RouteListPage> {
TextEditingController searchController = new TextEditingController();
@override
Widget build(BuildContext context) {
final _screenSize = MediaQuery.of(context).size;
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
searchInput(),
CardWidget(),
CardWidget(),
CardWidget(),
CardWidget(),
SizedBox(height: 25.0)
],
),
),
);
}
Widget searchInput(){
return Container(
margin: EdgeInsets.symmetric(horizontal: 24, vertical: 25.0),
padding: EdgeInsets.symmetric(horizontal: 24),
decoration: BoxDecoration(
color: Color(0xfff6f6f6),
borderRadius: BorderRadius.circular(30),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black45,
offset: Offset(0.0, 2.0),
blurRadius: 10.0,
),
],
),
child: Row(
children: <Widget>[
Expanded(
child: TextField(
controller: searchController,
decoration: InputDecoration(
hintText: "Buscar rutas",
hintStyle: TextStyle(fontFamily: "WorkSansSemiBold", fontSize: 16.0),
border: InputBorder.none
),
)
),
InkWell(
onTap: () {},
child: Container(
child: Icon(Icons.search, color: Tema.Colors.loginGradientEnd, size: 28.0)
)
)
],
),
);
}
}
</code></pre>
| 1 | 1,078 |
Nextjs external css not updating on client side page transitions
|
<p>I am still new to nextjs so i don't know if this is a bug or if i just wrongly implemented it. </p>
<p>I successfully managed to extract all my scss files using this guide:
<a href="https://github.com/zeit/next-plugins/tree/master/packages/next-sass" rel="nofollow noreferrer">https://github.com/zeit/next-plugins/tree/master/packages/next-sass</a></p>
<p>Everything works just fine while using server side rendering. External css file gets properly updated and applied, but as soon as i do client side page transitions the new scss import doesnt get injected in the external css file. I also dont want to prefetch every scss file on the initial pageload it should dynamically fetch and update the external file on server side routing and client side routing.</p>
<p>My next.config.js </p>
<pre><code>const getRoutes = require('./routes');
const path = require('path');
const withSass = require('@zeit/next-sass');
module.exports = withSass({
exportPathMap: getRoutes,
// useFileSystemPublicRoutes: false,
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
})
</code></pre>
<p>Example Component</p>
<pre><code>import { Fragment } from 'react';
import Main from '../components/main';
import style from '../styles/pages/parkett.scss';
const Parkett = () =>
<Fragment>
<section className={`section ${style.sec_two_parkett}`}>
<div className={`sec_text ${style.sec_two_text}`}>
<h2 className="didonesque_headline">Detailiert</h2>
<p className="normal_text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</section>
<section className={`section ${style.sec_three_parkett}`}>
<div className={`sec_text ${style.sec_three_text}`}>
<h2 className="didonesque_headline">Erstaunlich</h2>
<p className="normal_text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.</p>
</div>
</section>
</Fragment>
export default () =>
<Main
title="parkett"
component={<Parkett />}
links={['Treppe', 'Moebel', 'Innenausbau']}
/>
</code></pre>
| 1 | 1,115 |
Efficient 8-Connected Flood Fill
|
<p>I've been using Paul Heckbert's excellent seed fill algorithm (available <a href="ftp://ftp-graphics.stanford.edu/pub/Graphics/GraphicsGems/Gems/GGems.tar.Z" rel="nofollow">here</a> and in the book <a href="http://www.graphicsgems.org" rel="nofollow">Graphic Gems (1990)</a>).</p>
<p>Convoluted as the algorithm may appear. It's well-conceived and it's fast! Unfortunately, it's only for 4-connected spaces.</p>
<p>I am looking for a well-designed, fast algorithm for 8-connected spaces (leaks along the diagonal). Any ideas?</p>
<p>Recursively visiting or repeatedly throwing every cell onto a stack will not be considered well-designed for the purposes of this question. Algorithms available in pseudocode are most appreciated (Heckbert's is available in both code and pseudocode).</p>
<p>Thanks!</p>
<p>Heckbert's algorithm is copied here for completeness:</p>
<pre><code>/*
* A Seed Fill Algorithm
* by Paul Heckbert
* from "Graphics Gems", Academic Press, 1990
*
* user provides pixelread() and pixelwrite() routines
*/
/*
* fill.c : simple seed fill program
* Calls pixelread() to read pixels, pixelwrite() to write pixels.
*
* Paul Heckbert 13 Sept 1982, 28 Jan 1987
*/
typedef struct { /* window: a discrete 2-D rectangle */
int x0, y0; /* xmin and ymin */
int x1, y1; /* xmax and ymax (inclusive) */
} Window;
typedef int Pixel; /* 1-channel frame buffer assumed */
Pixel pixelread();
typedef struct {short y, xl, xr, dy;} Segment;
/*
* Filled horizontal segment of scanline y for xl<=x<=xr.
* Parent segment was on line y-dy. dy=1 or -1
*/
#define MAX 10000 /* max depth of stack */
#define PUSH(Y, XL, XR, DY) /* push new segment on stack */ \
if (sp<stack+MAX && Y+(DY)>=win->y0 && Y+(DY)<=win->y1) \
{sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;}
#define POP(Y, XL, XR, DY) /* pop segment off stack */ \
{sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;}
/*
* fill: set the pixel at (x,y) and all of its 4-connected neighbors
* with the same pixel value to the new pixel value nv.
* A 4-connected neighbor is a pixel above, below, left, or right of a pixel.
*/
fill(x, y, win, nv)
int x, y; /* seed point */
Window *win; /* screen window */
Pixel nv; /* new pixel value */
{
int l, x1, x2, dy;
Pixel ov; /* old pixel value */
Segment stack[MAX], *sp = stack; /* stack of filled segments */
ov = pixelread(x, y); /* read pv at seed point */
if (ov==nv || x<win->x0 || x>win->x1 || y<win->y0 || y>win->y1) return;
PUSH(y, x, x, 1); /* needed in some cases */
PUSH(y+1, x, x, -1); /* seed segment (popped 1st) */
while (sp>stack) {
/* pop segment off stack and fill a neighboring scan line */
POP(y, x1, x2, dy);
/*
* segment of scan line y-dy for x1<=x<=x2 was previously filled,
* now explore adjacent pixels in scan line y
*/
for (x=x1; x>=win->x0 && pixelread(x, y)==ov; x--)
pixelwrite(x, y, nv);
if (x>=x1) goto skip;
l = x+1;
if (l<x1) PUSH(y, l, x1-1, -dy); /* leak on left? */
x = x1+1;
do {
for (; x<=win->x1 && pixelread(x, y)==ov; x++)
pixelwrite(x, y, nv);
PUSH(y, l, x-1, dy);
if (x>x2+1) PUSH(y, x2+1, x-1, -dy); /* leak on right? */
skip: for (x++; x<=x2 && pixelread(x, y)!=ov; x++);
l = x;
} while (x<=x2);
}
}
</code></pre>
| 1 | 1,538 |
XML Signature - Different signature value in PHP?
|
<p>I want to implement an XML digital signature in PHP. I'm testing the correctness of the signature at <a href="https://www.aleksey.com/xmlsec/xmldsig-verifier.html" rel="nofollow noreferrer">this verifier</a>.</p>
<p>I'm getting the wrong signature value, so I'm going to explain step by step what I'm doing and please correct what I'm doing wrong.</p>
<p>The XML I want to sign <em>(without new lines)</em>:</p>
<pre><code><root>
<node1>test</node1>
<node2 attr="value" />
</root>
</code></pre>
<p><strong>First</strong>, I canonicalize the XML and then hash it using sha256 which yields the correct digest value.</p>
<p><strong>Second</strong>, creation of SignedInfo XML element and canonicalizing it <em>(without new lines)</em>:</p>
<pre><code><SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></DigestMethod>
<DigestValue>EdtGJKqTvnmb0Z72M8ZxTO6Jv2jyXOohMgxVKe2Gkbo=</DigestValue>
</Reference>
</SignedInfo>
</code></pre>
<p><strong>Finally</strong>, signature of SignedInfo element using RSA-SHA256. This is the part that yields an incorrect result.</p>
<p>Signature is calculated using the following lines of code:</p>
<pre><code>openssl_sign($c14nSignedInfo,$signature,$privateKey,"sha256WithRSAEncryption");
$signature = base64_encode($signature);
</code></pre>
<p>But it yields an incorrect signature value, as stated by the <a href="https://www.aleksey.com/xmlsec/xmldsig-verifier.html" rel="nofollow noreferrer">verifier</a>. If I sign the same XML in C# using the same private key, I get the correct signature. So, what am I doing wrong? What am I missing? Clearly, I am signing the wrong thing, but what should I sign then? Should I hash the SignedInfo element before signing it?</p>
<p>This is my final result <em>(which is incorrect)</em>:</p>
<pre><code><root><node1>test</node1><node2 attr="value" /><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" /><DigestValue>EdtGJKqTvnmb0Z72M8ZxTO6Jv2jyXOohMgxVKe2Gkbo=</DigestValue></Reference></SignedInfo><SignatureValue>cqkvNxWf8Z03K01SQFk/J5Z7F/l8scSFpRECCknTH840rUm2L9lKHC8UF/SGKJ4LoVxOmYKJHyq0Dx8j6shTXTK1Abm0a3Ty3IP/V0Roj+3EApq4Hwr7VOpvZjcToQj1snuUtgPZFJ6pxPWdYJ5hZhxm0C+mDMlOCgcTuWP7UIDNQ3CSC1GMcKESEkxsfEAzIXNh9wHoIY2e2HnedceFzOsJLPaLnltd1qhewJvqYCq7M1gD8e+Hv5Lyo+wG7ipvxvhAQ4Ui+BAOD9mROzSQaiirrxg6nC/dMJyWketTjKwEprZDm5BOoMoJC+kb2PvShfXrdRgA/ezWZHIaT0mLGQ==</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>nENZ+u9FZ5DSDlFRZ+0f0tZ2Kvl6QY+cjUzSc89fhixKFuexGJQcEvCrs67x8QcgwxZCuoWHk/Cdh8qd3x0EZaC+ZoZ+AF7ofoxWPHioZ86CIuxhI4Zgk0bHWibSKx8Z7EIXVrQ1nM2OvX9CdM9iVjM0yfn1ohdd1o4EKmRBbJQf6kCZMTbCdOdr8UI0xGUMjjaZN6+vGj3VYoxlQXXi11NMHDlxsCyyyjBjyCvewnTerkXAomwf92xV77siOn1VZD2/YwWarv1Hk/0WtW1c6QGj0VNd4EbzUqvMtnkzY3301hz5MRqvPiPNez9tWMaawDzbMrGGkwbF2ivVAW3LHQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo></Signature></root>
</code></pre>
<p>And this is the correct result <em>(everything is the same, except signature value)</em>:</p>
<pre><code><root><node1>test</node1><node2 attr="value" /><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" /><DigestValue>EdtGJKqTvnmb0Z72M8ZxTO6Jv2jyXOohMgxVKe2Gkbo=</DigestValue></Reference></SignedInfo><SignatureValue>OzQtkphZ+eg8JnVHzf8BVZpUZ/xMFQJhkmw5j4h2+eu8PAJh8Z9mRZH5uN/hfPFgkByBTshS/VWDNyWyF6TclQRSc8m89L8sCBQhKqGxZKjCd7V8XUIXgRgh2+Zl1JZQ/hD36XESEPazFyQ26KWq+T+m1Tc541Rv3mklfOKv2qBOqZLd/n/nRnGhFJYMp6PtPMNk/BezosGaQFUu/IhSI5tiud5ia4qETk/1G1eXAXmE4RbnVMefkysarTjizJYkGRqW10f0cF0trGxbCPyohMMfb2msnYiQfZXZd0tW41mMpH0R0AHFeC7RPxK2GzxRMRJCkNeWe65brneUtUSHzA==</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>nENZ+u9FZ5DSDlFRZ+0f0tZ2Kvl6QY+cjUzSc89fhixKFuexGJQcEvCrs67x8QcgwxZCuoWHk/Cdh8qd3x0EZaC+ZoZ+AF7ofoxWPHioZ86CIuxhI4Zgk0bHWibSKx8Z7EIXVrQ1nM2OvX9CdM9iVjM0yfn1ohdd1o4EKmRBbJQf6kCZMTbCdOdr8UI0xGUMjjaZN6+vGj3VYoxlQXXi11NMHDlxsCyyyjBjyCvewnTerkXAomwf92xV77siOn1VZD2/YwWarv1Hk/0WtW1c6QGj0VNd4EbzUqvMtnkzY3301hz5MRqvPiPNez9tWMaawDzbMrGGkwbF2ivVAW3LHQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo></Signature></root>
</code></pre>
<p>To test both results or for more details, just copy them <a href="https://www.aleksey.com/xmlsec/xmldsig-verifier.html" rel="nofollow noreferrer">here</a> and click "Verify Signature".</p>
| 1 | 3,010 |
Adding Collapsible functions using Material-UI Drawer
|
<p>I was able to setup the Drawer working in my application. One feature I found missing in the default is the collapsible option, where sections are nested. an example is Mail which would have <code>inbox, sent, outbox,</code> etc.</p>
<p>I want it to look something like this:</p>
<p><code>Mail
Inbox
Sent
Outbox</code></p>
<p>How can I do this? This file is shared across the demos.</p>
<pre><code>import React from 'react';
import { ListItem, ListItemIcon, ListItemText } from 'material-ui/List';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import StarIcon from '@material-ui/icons/Star';
import SendIcon from '@material-ui/icons/Send';
import MailIcon from '@material-ui/icons/Mail';
import DeleteIcon from '@material-ui/icons/Delete';
import ReportIcon from '@material-ui/icons/Report';
export const mailFolderListItems = (
<div>
<ListItem button>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItem>
<ListItem button>
<ListItemIcon>
<StarIcon />
</ListItemIcon>
<ListItemText primary="Starred" />
</ListItem>
<ListItem button>
<ListItemIcon>
<SendIcon />
</ListItemIcon>
<ListItemText primary="Send mail" />
</ListItem>
<ListItem button>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItem>
</div>
);
export const otherMailFolderListItems = (
<div>
<ListItem button>
<ListItemIcon>
<MailIcon />
</ListItemIcon>
<ListItemText primary="All mail" />
</ListItem>
<ListItem button>
<ListItemIcon>
<DeleteIcon />
</ListItemIcon>
<ListItemText primary="Trash" />
</ListItem>
<ListItem button>
<ListItemIcon>
<ReportIcon />
</ListItemIcon>
<ListItemText primary="Spam" />
</ListItem>
</div>
);
//
</code></pre>
| 1 | 1,267 |
Invoking WebMethods with XmlHttpRequest and Pure JavaScript
|
<p>I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm punting, and asking you guys for help. </p>
<p>Here's the scenario:</p>
<ul>
<li>I have an ASPX page (Q2.aspx) that is decorated with the <code>WebService</code>,
<code>WebServiceBinding</code>, and <code>ScriptService</code> attributes. </li>
<li>That page contains a method, <code>GetAllContacts</code>, that is decorated with the <code>WebMethod</code>
attribute and returns a string containing JSON data. (For what it's worth, the page
itself contains no other controls or functionality.)</li>
<li>I have an HTML page that contains JavaScript which uses the <code>XmlHttpRequest</code>
object to invoke the <code>GetAllContacts</code> WebMethod on the ASPX page and transform
the JSON data into an HTML table. </li>
<li>I have verified that my <code>Web.Config</code> file contains the appropriate protocol handlers
for <code>HttpGet</code> and <code>HttpPut</code> in the <code>WebServices</code> section under <code>System.Web.webServices</code>.</li>
<li>I have verified that my <code>Web.Config</code> file contains the <code>ScriptModule</code> entry under the
<code>System.webServer.modules</code> section, and that it matches the appropriate documentation.</li>
</ul>
<p>However, when I view the HTML page in a browser, the following occur:</p>
<ul>
<li>The web request goes through, but the results are for the unprocessed HTML from the ASPX page.</li>
<li>The <code>GetAllContacts</code> method is never invoked, as evidenced by setting a breakpoint in its code.</li>
<li>The code to invoke the Web service, however, is invoked, and the JavaScript callback
function that is invoked upon request completion is properly invoked. </li>
</ul>
<p>It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the <code>WebMethod</code> on the ASPX page, and simply returns the page as though it were a plain HTML <code>GET</code> request. Clearly, an HTML document can't be evaluated by JavaScript's <code>eval</code> function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)</p>
<p>I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code <em>looks</em> like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.</p>
<p>Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.</p>
<p><strong>ASPX Code</strong></p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
<body>
<form runat="server" id="frmMain"/>
</body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Satuit
{
[WebService(Namespace="http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public partial class Q2 : Page
{
[WebMethod]
public static string GetAllContacts()
{
return LoadJsonData();
}
private static string LoadJsonData()
{
using (var stringWriter = new StringWriter())
{
string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");
using (var xmlTextReader = new XmlTextReader(xmlUri))
{
var xpathDocument = new XPathDocument(xmlTextReader);
var xslTransform = new XslCompiledTransform();
xslTransform.Load(xslUri);
xslTransform.Transform(xpathDocument, null, stringWriter);
return stringWriter.ToString();
}
}
}
}
}
</code></pre>
<p><strong>HTML Code</strong>
</p>
<pre><code> var objectData; // Receives the objectified results of the JSON request.
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
var jsonResultBuffer = xmlhttp.responseText;
objectData = eval(jsonResultBuffer);
DisplayTable();
}
}
};
xmlhttp.send(null);
function DisplayTable()
{
var sHtml = "";
sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";
for(i = 0; i < objectData.length; i++)
{
sHtml += "<tr>";
sHtml += "<td>" + objectData.ID;
sHtml += "<td>" + objectData.firstName + "</td>";
sHtml += "<td>" + objectData.lastName + "</td>";
sHtml += "<td>" + objectData.address + "</td>";
sHtml += "</tr>"
}
sHtml += "</table>"
document.getElementById("divTable").innerHTML = sHtml;
}
</script>
</code></pre>
<p>
</p>
<p><strong>Dev Environment Details</strong></p>
<ul>
<li>Vista Ultimate SP 2 </li>
<li>Visual Studio 2008 </li>
<li>.NET Framework 3.5 </li>
<li>Solution has not yet been deployed, so it's running in the "local Web server"
provided by Visual Studio. (Makes me wonder if I shouldn't just deploy IIS
under Vista.)</li>
<li>Note that the ASPX page containing the WebMethod and the HTML page reside within
the same solution.</li>
</ul>
| 1 | 2,504 |
dbContext An entity object cannot be referenced by multiple instances of IEntityChangeTracker
|
<p>So the problem I'm having is the following. When going into this if statement, then I want to delete all the entries with ClearDbInstallForGroupAndHeader() from table InstallationBOM. Then I want to add all the entries within NewInstallationBoms into my InstallationBOM table and while doing this calculating total cost, but when I want to add it with this line <strong>db.InstallationBOMs.Add(newInstallationBom);</strong>, I get the following error:<br>
<strong>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.</strong></p>
<pre><code> if (InstallationSelected)
{
bool newEntry = true;
if (SelectedQuoteDetails != null)
{
QuoteDetail theQuoteDetail = SelectedQuoteDetails.FirstOrDefault(X => X.GroupNr == groupID && X.LineType == "I");
if (theQuoteDetail != null)
{
this.ClearDbInstallForGroupAndHeader();
int position = SelectedQuoteDetails.IndexOf(theQuoteDetail);
newEntry = false;
theQuoteDetail.Quantity = InstallQty;
theQuoteDetail.UnitCost = InstallCost;
theQuoteDetail.UnitPrice = InstallPrice;
SelectedQuoteDetails[position] = theQuoteDetail;
db.QuoteDetails.Attach(theQuoteDetail);
db.Entry(theQuoteDetail).State = EntityState.Modified;
db.SaveChanges();
decimal totalInstallationCost = 0;
totalInstallationCost = AddInstallToDbCalcTotalCost(theQuoteDetail.Line.Value, groupID);
newLines.UnitCost = totalInstallationCost;
newLines.UnitPrice = newLines.UnitCost * (1 + (Settings.MarginPercentage / 100));
InstallCost = newLines.UnitCost ?? 0;
InstallPrice = newLines.UnitPrice ?? 0;
RaisePropertyChanged(() => SelectedQuoteDetails);
}
}
}
public void ClearDbInstallForGroupAndHeader()
{
try
{
using (QuoteConfiguratorEntities db = Utilities.GetContext())
{
List<InstallationBOM> dbList = db.InstallationBOMs.Where(x => x.QuoteHeaderId == this.SelectedQuoteHeader.ID && x.GroupNr == this.SelectedGroup.ID)
.ToList();
foreach (InstallationBOM existingInstallationBom in dbList)
{
db.InstallationBOMs.Remove(existingInstallationBom);
}
db.SaveChanges();
}
}
catch (Exception ex)
{
this.Message = ex.Message + "\n\n" + ex.StackTrace;
this.ShowErrorMessage();
}
}
public decimal AddInstallToDbCalcTotalCost(decimal pLine, long pGroupNr)
{
decimal totalInstallationCost = 0;
try
{
using (QuoteConfiguratorEntities db = Utilities.GetContext())
{
foreach (InstallationBOM newInstallationBom in this.NewInstallationBoms)
{
newInstallationBom.QuoteHeaderId = this.SelectedQuoteHeader.ID;
newInstallationBom.GroupNr = pGroupNr;
newInstallationBom.LineNumber = pLine;
totalInstallationCost += (newInstallationBom.Quantity.Value *
newInstallationBom.Cost.Value);
db.InstallationBOMs.Add(newInstallationBom);
db.SaveChanges();
}
}
}
catch (Exception ex)
{
this.Message = ex.Message + "\n\n" + ex.StackTrace;
this.ShowErrorMessage();
}
return totalInstallationCost;
}
public void OpenInstallationOptionsWindow(bool AsThread = false)
{
try
{
if (AsThread)
{
this.Busy = true;
this._Thread = new Thread(() => QuoteConfiguratorViewModel.OpenInstallationOptionsWindow(this));
this._Thread.IsBackground = true;
this._Thread.Start();
}
else
{
using (QuoteConfiguratorEntities db = Utilities.GetContext())
{
ObservableCollection<InstallationBOM> installBomListGroup = new ObservableCollection<InstallationBOM>(db.InstallationBOMs.Where(x => x.QuoteHeaderId == this.SelectedQuoteHeader.ID
&& x.GroupNr == this.SelectedGroup.ID).ToList());
if (installBomListGroup != null)
{
if (!installBomListGroup.Any())
{
ClearInstallationBomEntry();
NewInstallationBoms = new ObservableCollection<InstallationBOM>();
}
else if (installBomListGroup.Any())
{
NewInstallationBoms = installBomListGroup;
}
}
Messenger.Default.Send<OpenInstallationWindow>(new OpenInstallationWindow());
}
}
}
catch (Exception ex)
{
this.Message = Utilities.GetError(ex);
}
}
</code></pre>
| 1 | 2,740 |
Python switch function
|
<p>I've been trying to write a simple Port Scanner using a simple switch function built with if. I've already searched here for a proper solution on how to make the switch function as usable as in C++ or similliar. I found the problem already being discussed on here <a href="https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python">Replacements for switch statement in Python?</a> and i've tried a few of these approaches but haven't had any luck so far making it run properly. Whatever method i picked from the link i always get a syntax error on the second switch case like this : </p>
<pre><code> File "/home/h4v0kkx0008c/Desktop/Sources/setup/PortScannerV1.py", line 44
if case(2):
^
SyntaxError: invalid syntax
</code></pre>
<p>What might be the problem here?</p>
<p>This is the full code i wrote so far :</p>
<pre class="lang-py prettyprint-override"><code>from socket import *
import time, socket, os, sys, string, argparse, logging, math
n = raw_input("Choose Port range: \n(1)Standard Ports: 0 - 1025\n(2)Middle Range: 1025 - 5000\n(3)Higher Range: 5000 - 49151\n(4)Highest Range: 49151 - 65535\n(5)All Ports: 0 - 65535\n(6)Custom ")
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
while switch(n):
if case(1):
print"Your choice is: Standard Ports"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
for i in range(0, 1025):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
if case(2):
print"Your choice is: Middle Range"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
for i in range(1025, 5000):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
break
if case(3):
print"Your choice is: Higher Range"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
for i in range(500, 49151):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
break
if case(4):
print"Your choice is: Highest Range"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
for i in range(49151, 65535):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
break
if case(5):
print"Your choice is: All Ports"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
for i in range(0, 65535):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
break
if case(6):
print"Your choice is: Custom"
target= raw_input("Please specify Host or Ip to scan: ")
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
startPort= raw_input("Specify starting Port:")
endPort= raw_input("Specify end Port:")
for i in range(startPort, endPort):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i)
break
</code></pre>
| 1 | 1,486 |
jQuery Validate not working for Multi-select dropdown
|
<p>I am using Bootstrap with Bootstrap Multi-select plugin along with jQueryValidation for validating the fields.</p>
<p>Unfortunately, when I render the dropdown as a single select, validation is not triggered.</p>
<p>Any Ideas?</p>
<p><strong>Javascript</strong></p>
<pre><code> $( "#signupForm" ).validate( {
rules: {
firstname: "required",
lastname: "required",
food: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
food: "Fruit is required to enter",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
if ( element.prop( "type" ) === "checkbox" ) {
error.insertAfter( element.parent( "label" ) );
} else {
error.insertAfter( element );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
},
unhighlight: function (element, errorClass, validClass) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
}
} );
$('.multiselect').multiselect();
</code></pre>
<p><strong><a href="http://jsfiddle.net/skilledmonster/vg6oLvxo/82/" rel="nofollow">JSFIDDLE</a></strong></p>
| 1 | 1,545 |
pass data from popup to parent
|
<p>I have a parent w/ a popup child. When parent loads, I have to call a function within the popup without showing the popup (thus, I load "pupLove" but don't include it in layout)....I then pass this data to the parent. When the user manually clicks another button to open the popup, the same function is called & data passed to the parent. However, I am not able to pass dg.length to the parent. I believe the root problem is that I am loading "pupLove" & thus the parents are getting confused.....I'm guessing if I get rid of "pupLove" I can pass the data correctly but will need to call the child's function at creationComplete of the parent....how do I do that?</p>
<p>Here's my parent:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
backgroundColor="green" width="50%" height="100%"
xmlns:local="*"
>
<fx:Script>
<![CDATA[
import pup;
import mx.managers.PopUpManager;
public function showPup(evt:MouseEvent):void {
var ttlWndw:pup = PopUpManager.createPopUp(this, pup, true) as pup;
PopUpManager.centerPopUp(ttlWndw);
}
]]>
</fx:Script>
<mx:VBox>
<local:pup id="pupLove" visible="false" includeInLayout="false" />
<s:Button click="showPup(event);" label="launch Pup" />
<mx:Text id="Ptest" color="black" text="from Parent:{pupLove.dg.length}" />
</mx:VBox>
</s:Application>
</code></pre>
<p>And a popup child called 'pup.mxml':</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
<fx:Script>
<![CDATA[
public function init():void{
// send php call
}
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
private function removePup(evt:Event):void {
PopUpManager.removePopUp(this);
}
]]>
</fx:Script>
<fx:Declarations>
<s:ArrayCollection id="dg">
</s:ArrayCollection>
</fx:Declarations>
<s:TitleWindow width="100%" height="100%" close="removePup(event)">
<mx:VBox>
<mx:Text id="test" color="red" text="from Child:{dg.length}" />
<s:Button label="add Items" click="dg.addItem({id:'cat'})" />
</mx:VBox>
</s:TitleWindow>
</s:Group>
</code></pre>
<p>UPDATE: I guess my question can be more easily stated as: "is there a way to call a child's function from the parent without actually loading the child?"</p>
| 1 | 1,247 |
Is it possible to forward to Siteminder login.fcc from a JSF action?
|
<p>I have a "custom" (JSF) login page for my application. My company uses Siteminder for authentication. So, in order to login to Siteminder with a "custom" page, I have to have a form that posts to /login.fcc with the appropriate form fields (username/password and a couple of Siteminder specific hidden fields).</p>
<p>What I am trying to do is to continue to leverage the form validations and such of JSF and still post to login.fcc.</p>
<p>Here is a stripped down version of my custom form:</p>
<pre><code><rich:messages />
<h:form id="adminLogin" prependId="false">
<h:panelGrid columns="2" styleClass="center">
<h:outputLabel value="HUB USERNAME:" />
<h:inputText id="USER" label="Username" size="12" required="true" />
<h:outputLabel value="HUB PASSWORD:" />
<h:inputSecret id="PASSWORD" label="Password" size="12" required="true" />
<input type="hidden" name="target" value="#{loginController.smTarget}" />
<input type="hidden" name="smagentname" value="#{loginController.smAgentName}" />
</h:panelGrid>
<h:panelGroup layout="block" styleClass="max-width button-panel">
<a4j:commandButton id="adminLoginBtn" value="LOGIN"
styleClass="login-btn"
action="#{loginController.managerLogin}" />
</h:panelGroup>
</h:form>
</code></pre>
<p>Note that I have used standard hidden inputs for the target and smagentname fields. This is because I have no need to have both setters and getters in my controller for these fields. I simply want the controller to provide the values when the page renders.</p>
<p>My controller method looks like this: </p>
<pre><code>public void managerLogin()
{
LoginController.LOG.debug("manager is logging in...");
LoginController.LOG.debug("user: " + getRequestParameterValue("USER"));
LoginController.LOG.debug("smagent: " + getRequestParameterValue("smagentname"));
LoginController.LOG.debug("target: " + getRequestParameterValue("target"));
forwardTo(LoginController.SM_LOGIN_FCC);
}
</code></pre>
<p>You can see that I am logging the values from all fields except the password field and they all print correctly in my log...so I know I am getting the values. My "forwardTo()" method simply gets the ExternalContext and calls dispatch() on it...passing in the path to the login.fcc page (which is "/forms/login.fcc").</p>
<p>When I input values in the form and click the login button, I see my values in the console but I get a 404 message in my browser.</p>
<p>I can manually put the "/forms/login.fcc" page in the address line and I have no problems with the GET rendering the login.fcc page. But I, of course, don't want to render the login.fcc (GET) I want to peform the Siteminder login (via POST).</p>
<p>It is my understanding that all request parameters are made available through a forward process I was expecting this to work.</p>
<p>I can take this same form and un-JSF-ize it...and make the login button simply submit the form (whose action would be the /forms/login.fcc via POST and it works fine too, but then I loose the benefits of the form/field validations that JSF provides.</p>
<p>Any ideas?</p>
| 1 | 1,057 |
Traversing through CSV file in PHP
|
<p>I have this code :</p>
<pre><code><?php
$handle = fopen("GeneratePicklist.csv", "r");
$data = fgetcsv($handle, 5000, ",");
?>
</code></pre>
<p>Which opens up a php file and converts it into a php array. Then I will list out the array contents and display them into a formatted page. I have this code and it's working.</p>
<pre><code><?php
echo "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">
<tr>
<td class=\"dataHeader\" width=\"100\">Mat.Loc.</td>
<td class=\"dataHeader\" width=\"20\">Qty</td>
<td class=\"dataHeader\">Description</td>
<td class=\"dataHeader\" width=\"150\">Part Number</td>
<td class=\"dataHeader\" width=\"30\">Multiplier</td>
<td class=\"dataHeader\" width=\"80\">Total Qty</td>
</tr>
";
$locatePartNoString = array_search("Part Number",$data);
$arrayStart = $locatePartNoString-1;
end($data);
$lastField = key($data);
$counter = ($lastField - $arrayStart);
$arrayBegin = $locatePartNoString+6;
while($counter>0) {
echo "
<tr>
<td class=\"centered\"><span class=\"title\">*".$data[$arrayBegin+4]."*</span><br>".$data[$arrayBegin+4]."</td>
<td id=\"qty".$counter."\" class=\"centered\">".$data[$arrayBegin+1]."</td>
<td>".$data[$arrayBegin+2]."</td>
<td class=\"centered\">".$data[$arrayBegin]."</td>
<td class=\"centered\"><input type=\"text\" id=\"multiplier".$counter."\" name=\"multiplier".$counter."\" value=\"1\" size=\"3\" style=\"border:1px dotted #CCC;\"></td>
<td class=\"centered\"><input type=\"text\" id=\"total".$counter."\" name=\"total".$counter."\" value=\"1\" size=\"3\" style=\"border:1px dotted #CCC;\"></td>
</tr>
";
$counter--;
}
echo "</table>";
?>
</code></pre>
<p>What I am trying to do is the traverse through the CSV file and select certain data only within the coverage of <code>$arrayBegin</code> variable and the last part of my CSV data. I have done the first line and its working good but I do not know how to increment so my pointer moves to the next line of the CSV file and do the same formula as my first line of data.</p>
<p>Here's a sample of the CSV content, 7 fields:</p>
<pre><code>ÊÊ,Part Number,Qty,Description,BB Type,Material Location,Serial Number
ÊÊ,013224-001,1,"PCA,DDR2-800,MINIDIMM MOD256MBx 40",BOM,ASSY,ID121608ZS
ÊÊ,122657-00A,1,SOFTWARE TEST (US M3 CTO),BOM,ASSY,
ÊÊ,376383-002,8,"ASSY, BLANK,SFF",BOM,ASSY,
ÊÊ,458943-003,1,"CA ASSY, SFP BATTERY, 15 POS, 28AWG, 24",BOM,ASSY,
ÊÊ,460499-001,1,"ASSY, 4/V650HT BATTERY CHARGER MODULE",BOM,ASSY,
ÊÊ,499256-001,2,"ASSY, BLANK,MEDIA BAY,ML350G6",BOM,ASSY,
ÊÊ,500203-061,2,"DIMM,4GB PC3-10600R,256Mx4,RoHS",BOM,ASSY,RAKWF8DXV2Q100
</code></pre>
<p>I just need to select certain data from each line and then move on to the next line. How do i traverse to the next line using my while loop? Thank you for your future responses.</p>
| 1 | 1,400 |
Histogram of sum instead of count using numpy and matplotlib
|
<p>I have some data with two columns per row. In my case job submission time and area.</p>
<p>I have used matplotlib's hist function to produce a graph with time binned by day on the x axis, and count per day on the y axis:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime as dt
def timestamp_to_mpl(timestamp):
return mpl.dates.date2num(dt.datetime.fromtimestamp(timestamp))
nci_file_name = 'out/nci.csv'
jobs = np.genfromtxt(nci_file_name, dtype=int, delimiter=',', names=True, usecols(1,2,3,4,5))
fig, ax = plt.subplots(2, 1, sharex=True)
vect_timestamp_to_mpl = np.vectorize(timestamp_to_mpl)
qtime = vect_timestamp_to_mpl(jobs['queued_time'])
start_date = dt.datetime(2013, 1, 1)
end_date = dt.datetime(2013, 4, 1)
bins = mpl.dates.drange(start_date, end_date, dt.timedelta(days=1))
ax[0].hist(qtime[jobs['charge_rate']==1], bins=bins, label='Normal', color='b')
ax[1].hist(qtime[jobs['charge_rate']==3], bins=bins, label='Express', color='g')
ax[0].grid(True)
ax[1].grid(True)
fig.suptitle('NCI Workload Submission Daily Rate')
ax[0].set_title('Normal Queue')
ax[1].set_title('Express Queue')
ax[1].xaxis.set_major_locator(mpl.dates.AutoDateLocator())
ax[1].xaxis.set_major_formatter(mpl.dates.AutoDateFormatter(ax[1].xaxis.get_major_locator()))
ax[1].set_xlim(mpl.dates.date2num(start_date), mpl.dates.date2num(end_date))
plt.setp(ax[1].xaxis.get_majorticklabels(), rotation=25, ha='right')
ax[1].set_xlabel('Date')
ax[0].set_ylabel('Jobs per Day')
ax[1].set_ylabel('Jobs per Day')
fig.savefig('out/figs/nci_sub_rate_day_sub.png')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/EB9dB.png" alt="NCI Workload Submission Daily Rate"></p>
<p>I now want a graph with time binned by day on the x axis and the summed by bin area on the y axis.</p>
<p>So far I have come up with this using a list comprehension:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime as dt
def timestamp_to_mpl(timestamp):
return mpl.dates.date2num(dt.datetime.fromtimestamp(timestamp))
def binsum(bin_by, sum_by, bins):
bin_index = np.digitize(bin_by, bins)
sums = [np.sum(sum_by[bin_index==i]) for i in range(len(bins))]
return sums
fig, ax = plt.subplots(2, 1, sharex=True)
vect_timestamp_to_mpl = np.vectorize(timestamp_to_mpl)
qtime = vect_timestamp_to_mpl(jobs['queued_time'])
area = jobs['run_time'] * jobs['req_procs']
start_date = dt.datetime(2013, 1, 1)
end_date = dt.datetime(2013, 4, 1)
delta = dt.timedelta(days=1)
bins = mpl.dates.drange(start_date, end_date, delta)
sums_norm = binsum(qtime[jobs['charge_rate']==1], area[jobs['charge_rate']==1], bins)
sums_expr = binsum(qtime[jobs['charge_rate']==3], area[jobs['charge_rate']==3], bins)
ax[0].bar(bins, sums_norm, width=1.0, label='Normal', color='b')
ax[1].bar(bins, sums_expr, width=1.0, label='Express', color='g')
ax[0].grid(True)
ax[1].grid(True)
fig.suptitle('NCI Workload Area Daily Rate')
ax[0].set_title('Normal Queue')
ax[1].set_title('Express Queue')
ax[1].xaxis.set_major_locator(mpl.dates.AutoDateLocator())
ax[1].xaxis.set_major_formatter(mpl.dates.AutoDateFormatter(ax[1].xaxis.get_major_locator()))
ax[1].set_xlim(mpl.dates.date2num(start_date), mpl.dates.date2num(end_date))
plt.setp(ax[1].xaxis.get_majorticklabels(), rotation=25, ha='right')
ax[1].set_xlabel('Date')
ax[0].set_ylabel('Area per Day')
ax[1].set_ylabel('Area per Day')
fig.savefig('out/figs/nci_area_day_sub.png')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/M3NTn.png" alt="NCI Workload Area Daily Rate"></p>
<p>I am still new to NumPy and would like to know if I can improve:</p>
<pre><code>def binsum(bin_by, sum_by, bins):
bin_index = np.digitize(bin_by, bins)
sums = [np.sum(sum_by[bin_index==i]) for i in range(len(bins))]
return sums
</code></pre>
<p>So it doesn't use Python lists.</p>
<p>Is it possible to somehow explode out <code>sum_by[bin_index==i]</code> so I get an array of arrays, with length <code>len(bins)</code>? Then <code>np.sum()</code> would return a numpy array.</p>
| 1 | 1,702 |
Use superCSV to read a large text file of 80GB
|
<p>I want to read a huge csv file. We are using superCSV to parse through the files in general. In this particular scenario, the file is huge and there is always this problem of running out of memory for obvious reasons. </p>
<p>The initial idea is to read the file as chunks, but I am not sure if this would work with superCSV because when I chunk the file, only the first chunk has the header values and will be loaded into the CSV bean, while the other chunks do not have header values and I feel that it might throw an exception. So </p>
<p>a) I was wondering if my thought process is right<br>
b) Are there any other ways to approach this problem.</p>
<p>So my main question is </p>
<p>Does superCSV have the capability to handle large csv files and I see that superCSV reads the document through the BufferedReader. But I dont know what is the size of the buffer and can we change it as per our requirement ?</p>
<p>@Gilbert Le BlancI have tried splitting into smaller chunks as per your suggestion but it is taking a long time to break down the huge file into smaller chunks. Here is the code that I have written to do it.</p>
<pre><code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
public class TestFileSplit {
public static void main(String[] args) {
LineNumberReader lnr = null;
try {
//RandomAccessFile input = new RandomAccessFile("", "r");
File file = new File("C:\\Blah\\largetextfile.txt");
lnr = new LineNumberReader(new FileReader(file), 1024);
String line = "";
String header = null;
int noOfLines = 100000;
int i = 1;
boolean chunkedFiles = new File("C:\\Blah\\chunks").mkdir();
if(chunkedFiles){
while((line = lnr.readLine()) != null) {
if(lnr.getLineNumber() == 1) {
header = line;
continue;
}
else {
// a new chunk file is created for every 100000 records
if((lnr.getLineNumber()%noOfLines)==0){
i = i+1;
}
File chunkedFile = new File("C:\\Blah\\chunks\\" + file.getName().substring(0,file.getName().indexOf(".")) + "_" + i + ".txt");
// if the file does not exist create it and add the header as the first row
if (!chunkedFile.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(chunkedFile.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(header);
bw.newLine();
bw.close();
fw.close();
}
FileWriter fw = new FileWriter(chunkedFile.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
fw.close();
}
}
}
lnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
</code></pre>
| 1 | 1,538 |
How to start and stop timer display in ReactJS
|
<p>I am trying to create a Pomodoro timer in ReactJS. I am having trouble having the timer to stop it's countdown.</p>
<p><strong>PomView.js</strong></p>
<pre><code>const PomView = () => {
const [timer, setTimer] = useState(1500) // 25 minutes
const [start, setStart] = useState(false)
var firstStart = useRef(true)
var tick;
useEffect( () => {
if (firstStart.current) {
console.log("first render, don't run useEffect for timer")
firstStart.current = !firstStart.current
return
}
console.log("subsequent renders")
console.log(start)
if (start) {
tick = setInterval(() => {
setTimer(timer => {
timer = timer - 1
console.log(timer)
return timer
}
)
}, 1000)
} else {
console.log("clear interval")
clearInterval(tick);
}
}, [start])
const toggleStart = () => {
setStart(!start)
}
const dispSecondsAsMins = (seconds) => {
// 25:00
console.log("seconds " + seconds)
const mins = Math.floor(seconds / 60)
const seconds_ = seconds % 60
return mins.toString() + ":" + ((seconds_ == 0) ? "00" : seconds_.toString())
}
return (
<div className="pomView">
<ul>
<button className="pomBut">Pomodoro</button>
<button className="pomBut">Short Break</button>
<button className="pomBut">Long Break</button>
</ul>
<h1>{dispSecondsAsMins(timer)}</h1>
<div className="startDiv">
{/* event handler onClick is function not function call */}
<button className="startBut" onClick={toggleStart}>{!start ? "START" : "STOP"}</button>
{start && <AiFillFastForward className="ff" onClick="" />}
</div>
</div>
)
}
export default PomView
</code></pre>
<p>Although the <code>clearInterval</code> runs in the else portion of useEffect, the timer continues ticking. I am not sure if it is because of the asynchronous setTimer method in useEffect. I would like to know what the problem is with the code I have written.</p>
| 1 | 1,249 |
Detect clusters of circular objects by iterative adaptive thresholding and shape analysis
|
<p>I have been developing an application to count circular objects such as bacterial colonies from pictures. </p>
<p>What make it easy is the fact that the objects are generally well distinct from the background.</p>
<p>However, few difficulties make the analysis tricky:</p>
<ol>
<li>The background will present gradual as well as rapid intensity change.</li>
<li>In the edges of the container, the object will be elliptic rather than circular.</li>
<li>The edges of the objects are sometimes rather fuzzy.</li>
<li>The objects will cluster.</li>
<li>The object can be very small (6px of diameter)</li>
<li>Ultimately, the algorithms will be used (via GUI) by people that do not have deep understanding of image analysis, so the parameters must be intuitive and very few.</li>
</ol>
<p>The problem has been address many times in the scientific literature and "solved", for instance, using circular Hough transform or watershed approaches, but I have never been satisfied by the results.</p>
<p>One simple approach that was described is to get the foreground by adaptive thresholding and split (as I described in <a href="https://stackoverflow.com/questions/10313602/reshaping-noisy-coin-into-a-circle-form/10324759#10324759">this post</a>) the clustered objects using distance transform.</p>
<p>I have successfully implemented this method, but it could not always deal with sudden change in intensity. Also, I have been asked by peers to come out with a more "novel" approach.</p>
<p><strong>I therefore was looking for a new method to extract foreground.</strong></p>
<p>I therefore investigated other thresholding/blob detection methods.
I tried MSERs but found out that they were not very robust and quite slow in my case.</p>
<p>I eventually came out with an algorithm that, so far, gives me excellent results:</p>
<ol>
<li>I split the three channels of my image and reduce their noise (blur/median blur). For each channel:</li>
<li>I apply a manual implementation of the first step of adaptive thresholding by calculating the absolute difference between the original channel and a convolved (by a large kernel blur) one. Then, for all the relevant values of threshold:</li>
<li>I apply a threshold on the result of 2)</li>
<li>find contours</li>
<li>validate or invalidate contours on the grant of their shape (size, area, convexity...)</li>
<li>only the valid continuous regions (<em>i.e.</em> delimited by contours) are then redrawn in an accumulator (1 accumulator per channel).</li>
<li>After accumulating continuous regions over values of threshold, I end-up with a map of "scores of regions". The regions with the highest intensity being those that fulfilled the the morphology filter criteria the most often.</li>
<li>The three maps (one per channel) are then converted to grey-scale and thresholded (the threshold is controlled by the user)</li>
</ol>
<p>Just to show you the kind of image I have to work with:
<img src="https://i.stack.imgur.com/vXjUt.jpg" alt="enter image description here">
This picture represents part of 3 sample images in the top and the result of my algorithm (blue = foreground) of the respective parts in the bottom.</p>
<p>Here is my C++ implementation of : 3-7</p>
<pre><code>/*
* cv::Mat dst[3] is the result of the absolute difference between original and convolved channel.
* MCF(std::vector<cv::Point>, int, int) is a filter function that returns an positive int only if the input contour is valid.
*/
/* Allocate 3 matrices (1 per channel)*/
cv::Mat accu[3];
/* We define the maximal threshold to be tried as half of the absolute maximal value in each channel*/
int maxBGR[3];
for(unsigned int i=0; i<3;i++){
double min, max;
cv::minMaxLoc(dst[i],&min,&max);
maxBGR[i] = max/2;
/* In addition, we fill accumulators by zeros*/
accu[i]=cv::Mat(compos[0].rows,compos[0].cols,CV_8U,cv::Scalar(0));
}
/* This loops are intended to be multithreaded using
#pragma omp parallel for collapse(2) schedule(dynamic)
For each channel */
for(unsigned int i=0; i<3;i++){
/* For each value of threshold (m_step can be > 1 in order to save time)*/
for(int j=0;j<maxBGR[i] ;j += m_step ){
/* Temporary matrix*/
cv::Mat tmp;
std::vector<std::vector<cv::Point> > contours;
/* Thresholds dst by j*/
cv::threshold(dst[i],tmp, j, 255, cv::THRESH_BINARY);
/* Finds continous regions*/
cv::findContours(tmp, contours, CV_RETR_LIST, CV_CHAIN_APPROX_TC89_L1);
if(contours.size() > 0){
/* Tests each contours*/
for(unsigned int k=0;k<contours.size();k++){
int valid = MCF(contours[k],m_minRad,m_maxRad);
if(valid>0){
/* I found that redrawing was very much faster if the given contour was copied in a smaller container.
* I do not really understand why though. For instance,
cv::drawContours(miniTmp,contours,k,cv::Scalar(1),-1,8,cv::noArray(), INT_MAX, cv::Point(-rect.x,-rect.y));
is slower especially if contours is very long.
*/
std::vector<std::vector<cv::Point> > tpv(1);
std::copy(contours.begin()+k, contours.begin()+k+1, tpv.begin());
/* We make a Roi here*/
cv::Rect rect = cv::boundingRect(tpv[0]);
cv::Mat miniTmp(rect.height,rect.width,CV_8U,cv::Scalar(0));
cv::drawContours(miniTmp,tpv,0,cv::Scalar(1),-1,8,cv::noArray(), INT_MAX, cv::Point(-rect.x,-rect.y));
accu[i](rect) = miniTmp + accu[i](rect);
}
}
}
}
}
/* Make the global scoreMap*/
cv::merge(accu,3,scoreMap);
/* Conditional noise removal*/
if(m_minRad>2)
cv::medianBlur(scoreMap,scoreMap,3);
cvtColor(scoreMap,scoreMap,CV_BGR2GRAY);
</code></pre>
<p>I have two questions:</p>
<ol>
<li><p>What is the name of such foreground extraction approach and do you see any reason for which it could be improper to use it in this case ?</p></li>
<li><p>Since recursively finding and drawing contours is quite intensive, I would like to make my algorithm faster. Can you indicate me any way to achieve this goal ?</p></li>
</ol>
<p>Thank you very much for you help,</p>
| 1 | 2,402 |
`apt-get install librdkafka1` fails on Debian 9.x due to libssl dependency
|
<p>Basic <code>apt-get install librdkafka1</code> works on Debian 8.x but fails on Debian 9.x. This looks like a dependency version issue regarding libssl. Debian 8.x had libssl1.0.0 and Debian 9.x has libssl1.0.2 and libssl1.1, but no libssl1.0.0 and this version bump just causes the librdkafka1 install to break.</p>
<p>This is easily reproducible on the latest official Docker Debian 9 image:</p>
<pre><code>docker pull debian:9
docker run --rm -it debian:9
</code></pre>
<p>Then within the VM</p>
<pre><code>cat /etc/debian_version
# 9.4
apt-get update
# Get basics to setup Confluent repository
apt-get install -y wget gnupg2 software-properties-common libssl1.0.2
wget -qO - http://packages.confluent.io/deb/4.1/archive.key | apt-key add -
add-apt-repository "deb [arch=amd64] http://packages.confluent.io/deb/4.1 stable main"
apt-get update
</code></pre>
<p><code>apt-cache policy libssl1.0.2</code> results in:</p>
<pre><code>libssl1.0.2:
Installed: 1.0.2l-2+deb9u3
Candidate: 1.0.2l-2+deb9u3
Version table:
*** 1.0.2l-2+deb9u3 500
500 http://security.debian.org/debian-security stretch/updates/main amd64 Packages
100 /var/lib/dpkg/status
1.0.2l-2+deb9u2 500
500 http://deb.debian.org/debian stretch/main amd64 Packages
</code></pre>
<p><code>apt-cache policy librdkafka1</code> results in:</p>
<pre><code>librdkafka1:
Installed: (none)
Candidate: 0.11.4~1confluent4.1.0-1
Version table:
0.11.4~1confluent4.1.0-1 500
500 http://packages.confluent.io/deb/4.1 stable/main amd64 Packages
0.9.3-1 500
500 http://deb.debian.org/debian stretch/main amd64 Packages
</code></pre>
<p>And <code>apt-get install librdkafka1</code> results in:</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
librdkafka1 : Depends: libssl1.0.0 (>= 1.0.0) but it is not installable
E: Unable to correct problems, you have held broken packages.
</code></pre>
<p><code>apt-cache search libssl</code> produces the following. Note that there is a <code>libssl1.0.2</code> and <code>libssl1.1</code> but no <code>libssl1.0.0</code></p>
<pre><code>libssl-ocaml - OCaml bindings for OpenSSL (runtime)
libssl-ocaml-dev - OCaml bindings for OpenSSL
libssl-dev - Secure Sockets Layer toolkit - development files
libssl-doc - Secure Sockets Layer toolkit - development documentation
libssl1.1 - Secure Sockets Layer toolkit - shared libraries
libssl1.0-dev - Secure Sockets Layer toolkit - development files
libssl1.0.2 - Secure Sockets Layer toolkit - shared libraries
</code></pre>
<p><strong>UPDATE</strong>: This issue is still present with Confluent 4.1, librdkafka 0.11.4 and Debian 9.4.</p>
| 1 | 1,105 |
Android AutoCompleteTextView crashes when remove text fast
|
<p>I have a list of key words (about 1000 words) and i set this to an ArrayAdapter to be handled by AutoCompleteTextView. The basic process works fine. The problem arise when i selected a long word (10 character above), then use the keyboard backspace button to remove the word (press and hold on the button), after removing like 5 characters the app crashes with the following error. </p>
<p><i></p>
<pre><code>01-16 13:27:23.082: ERROR/AndroidRuntime(2874): FATAL EXCEPTION: main
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(-1, class android.widget.AutoCompleteTextView$DropDownListView) with Adapter(class com.hdm_i.dm.corp.android.muenchen.adapters.PoiAutoCompleteAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1527)
at android.widget.AbsListView.onLayout(AbsListView.java:1430)
at android.view.View.layout(View.java:7228)
at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
at android.view.View.layout(View.java:7228)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1145)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p></i></p>
<p>Below is my code, did i do anything wrong ? Thanks in advance for your suggestions :-)</p>
<p><i></p>
<pre><code>public class PoiAutoCompleteAdapter extends ArrayAdapter<SearchTextAutoSuggest> implements Filterable {
private List<SearchTextAutoSuggest> searchTextAutoSuggestList = new ArrayList<SearchTextAutoSuggest>();
private SearchTextAutoSuggest defaultSuggestion = new SearchTextAutoSuggest();
private Handler uiThreadHandler;
public PoiAutoCompleteAdapter(Context context, int viewResourceId, Handler uiThreadHandler) {
super(context, viewResourceId);
this.uiThreadHandler = uiThreadHandler;
defaultSuggestion.setName(AppConstants.DEFAULT_SEARCH_STRING_NAME);
}
@Override
public int getCount() {
return searchTextAutoSuggestList.size();
}
@Override
public SearchTextAutoSuggest getItem(int position) {
return searchTextAutoSuggestList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
synchronized (filterResults) {
if (constraint != null) {
// Clear and Retrieve the autocomplete results.
searchTextAutoSuggestList.clear();
searchTextAutoSuggestList = getFilteredResults(constraint);
// Assign the data to the FilterResults
filterResults.values = searchTextAutoSuggestList;
filterResults.count = searchTextAutoSuggestList.size();
}
return filterResults;
}
}
@Override
protected void publishResults(CharSequence constraint, final FilterResults filterResults) {
uiThreadHandler.post(new Runnable() {
public void run() {
synchronized (filterResults) {
if (filterResults != null && filterResults.count > 0) {
notifyDataSetChanged();
} else {
Logs.e("Tried to invalidate");
notifyDataSetInvalidated();
}
}
}
});
}
};
return filter;
}
private List<SearchTextAutoSuggest> getFilteredResults(CharSequence constraint) {
List<SearchTextAutoSuggest> searchTextAutoSuggestList = AppContext.searchTextAutoSuggestList;
List<SearchTextAutoSuggest> filteredSearchTextAutoSuggestList = new ArrayList<SearchTextAutoSuggest>();
// Assign constraint as a default option into the list
defaultSuggestion.setLabel(getContext().getString(R.string.general_default_search_str) + " \'" + constraint + "\'");
filteredSearchTextAutoSuggestList.add(defaultSuggestion);
for (int i = 0; i < searchTextAutoSuggestList.size(); i++) {
if (searchTextAutoSuggestList.get(i).getLabel().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
filteredSearchTextAutoSuggestList.add(searchTextAutoSuggestList.get(i));
}
}
return filteredSearchTextAutoSuggestList;
}
}
</code></pre>
<p></i></p>
| 1 | 2,266 |
EditableGrid+mysql with add/delete
|
<p>Soo.. i got an example of EditableGrid (<a href="http://www.editablegrid.net/" rel="nofollow">http://www.editablegrid.net/</a>) a pretty cool grid that lets me load data from mysql table to a html grid with sorting, inline editing + mysql database updates. I added filtering functionality from another example but am struggling with adding delete row and add row functionality.</p>
<p>I found an example of how to delete by adding a new column and i could call an update function from there.. but i'm struggling with syntax and where to place it .. javascript has me bretty boggled so far.. <a href="http://www.editablegrid.net/editablegrid/examples/simple/index.html" rel="nofollow">http://www.editablegrid.net/editablegrid/examples/simple/index.html</a></p>
<p>The output is loaded on to a div in a simple html file and works very well.. nice and fast and updated great. I just want to add 'new' and 'delete' functions to the table.</p>
<p>Any assistance appreciated.</p>
<pre><code>function DatabaseGrid()
{
this.editableGrid = new EditableGrid("plan_customerid", {
enableSort: true,
editmode: "absolute",
editorzoneid: "edition",
tableLoaded: function() {
datagrid.initializeGrid(this);
},
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row); },
});
this.fetchGrid();
}
DatabaseGrid.prototype.fetchGrid = function() {
// call a PHP script to get the data
this.editableGrid.loadXML("loaddata.php");
};
DatabaseGrid.prototype.initializeGrid = function(grid) {
grid.renderGrid("tablecontent", "testgrid", "tableid");
tableRendered = function() { this.updatePaginator(); };
_$('filter').onkeyup = function() { grid.filter(_$('filter').value); };
};
</code></pre>
<p>the output from loaddata.php is such:</p>
<pre><code><table>
<metadata>
<column name="customer_id" label="UID" datatype="string" editable="true"></column>
<column name="customer" label="Customer" datatype="string" editable="true"></column>
<column name="lastchange_by" label="Editor" datatype="string" editable="true"></column>
<column name="ts" label="Timestamp" datatype="date" editable="true"></column>
</metadata>
<data>
<row id="1">
<column name="customer_id">
<![CDATA[ 5000 ]]>
</column>
<column name="customer">
<![CDATA[ Foo ]]>
</column>
<column name="lastchange_by">
<![CDATA[ Bar ]]>
</column>
<column name="ts">
<![CDATA[ 2013-10-17 00:00:00 ]]>
</column>
</row>
</data>
</table>
</code></pre>
| 1 | 1,055 |
How to test if a string contains gibberish in PHP?
|
<p>I am making a registering form for a website and because I'm sure everyone
is going to enter some gibberish in the Secret Answer's input (I do that myself),
I would like to programmatically test that value to see if it's more likely
to be a good answer.</p>
<p>I have taken a look at a function that generates Markov Chains (see at bottom) in PHP but I
don't know how to test a string against that chains' Array to actually detect
the % accuracy of the given answer.</p>
<p>Has anyone here did something similar ? How you solved it or have you given
up ?</p>
<p>Thank you</p>
<pre><code>function generateCaptchaTextMarkov($length) {
$transitionMatrix = array(
0.0001, 0.0218, 0.0528, 0.1184, 0.1189, 0.1277, 0.1450, 0.1458, 0.1914, 0.1915, 0.2028, 0.2792, 0.3131, 0.5293, 0.5304, 0.5448, 0.5448, 0.6397, 0.7581, 0.9047, 0.9185, 0.9502, 0.9600, 0.9601, 0.9982, 1.0000,
0.0893, 0.0950, 0.0950, 0.0950, 0.4471, 0.4471, 0.4471, 0.4471, 0.4784, 0.4821, 0.4821, 0.6075, 0.6078, 0.6078, 0.7300, 0.7300, 0.7300, 0.7979, 0.8220, 0.8296, 0.9342, 0.9348, 0.9351, 0.9351, 1.0000, 1.0000,
0.1313, 0.1317, 0.1433, 0.1433, 0.3264, 0.3264, 0.3264, 0.4887, 0.5454, 0.5454, 0.5946, 0.6255, 0.6255, 0.6255, 0.8022, 0.8022, 0.8035, 0.8720, 0.8753, 0.9545, 0.9928, 0.9928, 0.9928, 0.9928, 1.0000, 1.0000,
0.0542, 0.0587, 0.0590, 0.0840, 0.3725, 0.3837, 0.3879, 0.3887, 0.5203, 0.5208, 0.5211, 0.5390, 0.5435, 0.5550, 0.8183, 0.8191, 0.8191, 0.8759, 0.9376, 0.9400, 0.9629, 0.9648, 0.9664, 0.9664, 1.0000, 1.0000,
0.0860, 0.0877, 0.1111, 0.2533, 0.3017, 0.3125, 0.3183, 0.3211, 0.3350, 0.3355, 0.3378, 0.4042, 0.4381, 0.5655, 0.5727, 0.5842, 0.5852, 0.7817, 0.8718, 0.9191, 0.9201, 0.9530, 0.9652, 0.9792, 0.9998, 1.0000,
0.1033, 0.1037, 0.1050, 0.1057, 0.2916, 0.3321, 0.3324, 0.3324, 0.4337, 0.4337, 0.4337, 0.4912, 0.4912, 0.4912, 0.7237, 0.7274, 0.7274, 0.8545, 0.8569, 0.9150, 0.9986, 0.9986, 0.9990, 0.9990, 1.0000, 1.0000,
0.1014, 0.1017, 0.1024, 0.1028, 0.2725, 0.2729, 0.2855, 0.4981, 0.5770, 0.5770, 0.5770, 0.6184, 0.6191, 0.6384, 0.7783, 0.7797, 0.7797, 0.9249, 0.9663, 0.9688, 0.9923, 0.9923, 0.9937, 0.9937, 1.0000, 1.0000,
0.2577, 0.2579, 0.2580, 0.2581, 0.6967, 0.6970, 0.6970, 0.6970, 0.8648, 0.8648, 0.8650, 0.8661, 0.8667, 0.8670, 0.9397, 0.9397, 0.9397, 0.9509, 0.9533, 0.9855, 0.9926, 0.9926, 0.9929, 0.9929, 1.0000, 1.0000,
0.0324, 0.0478, 0.0870, 0.1267, 0.1585, 0.1908, 0.2182, 0.2183, 0.2193, 0.2193, 0.2309, 0.2859, 0.3426, 0.6110, 0.6501, 0.6579, 0.6583, 0.6923, 0.8211, 0.9764, 0.9781, 0.9948, 0.9949, 0.9965, 0.9965, 1.0000,
0.1276, 0.1276, 0.1276, 0.1276, 0.4286, 0.4286, 0.4286, 0.4286, 0.4337, 0.4337, 0.4337, 0.4337, 0.4337, 0.4337, 0.6684, 0.6684, 0.6684, 0.6684, 0.6684, 0.6684, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
0.0033, 0.0059, 0.0100, 0.0109, 0.5401, 0.5443, 0.5477, 0.5485, 0.7149, 0.7149, 0.7149, 0.7316, 0.7333, 0.9247, 0.9264, 0.9273, 0.9273, 0.9289, 0.9791, 0.9816, 0.9824, 0.9824, 0.9833, 0.9833, 1.0000, 1.0000,
0.0850, 0.0865, 0.0874, 0.1753, 0.3439, 0.3725, 0.3744, 0.3746, 0.5083, 0.5083, 0.5192, 0.6784, 0.6840, 0.6848, 0.8088, 0.8128, 0.8128, 0.8147, 0.8326, 0.8511, 0.8743, 0.8817, 0.9054, 0.9054, 1.0000, 1.0000,
0.1562, 0.1760, 0.1774, 0.1776, 0.5513, 0.5517, 0.5517, 0.5520, 0.6352, 0.6352, 0.6352, 0.6369, 0.6486, 0.6499, 0.7717, 0.8230, 0.8230, 0.8337, 0.8697, 0.8703, 0.9376, 0.9376, 0.9378, 0.9378, 1.0000, 1.0000,
0.0255, 0.0265, 0.0682, 0.2986, 0.4139, 0.4204, 0.6002, 0.6009, 0.6351, 0.6360, 0.6507, 0.6672, 0.6679, 0.6786, 0.7718, 0.7723, 0.7732, 0.7873, 0.8364, 0.9715, 0.9753, 0.9797, 0.9803, 0.9804, 0.9997, 1.0000,
0.0050, 0.0089, 0.0183, 0.0379, 0.0410, 0.1451, 0.1494, 0.1514, 0.1654, 0.1656, 0.1866, 0.2171, 0.2821, 0.4272, 0.4761, 0.4926, 0.4927, 0.6434, 0.6722, 0.7195, 0.9126, 0.9332, 0.9913, 0.9925, 0.9999, 1.0000,
0.1596, 0.1688, 0.1688, 0.1688, 0.3799, 0.3799, 0.3799, 0.4011, 0.4827, 0.4827, 0.4833, 0.6081, 0.6087, 0.6090, 0.7353, 0.7953, 0.7953, 0.8804, 0.9181, 0.9584, 0.9952, 0.9952, 0.9952, 0.9952, 1.0000, 1.0000,
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
0.0902, 0.0938, 0.1003, 0.1555, 0.4505, 0.4606, 0.4705, 0.4740, 0.5928, 0.5928, 0.6018, 0.6201, 0.6402, 0.6605, 0.7619, 0.7666, 0.7671, 0.8125, 0.8645, 0.9029, 0.9226, 0.9298, 0.9319, 0.9319, 0.9996, 1.0000,
0.0584, 0.0598, 0.0903, 0.0912, 0.2850, 0.2870, 0.2883, 0.3902, 0.5057, 0.5058, 0.5165, 0.5271, 0.5400, 0.5447, 0.6525, 0.6762, 0.6792, 0.6792, 0.7512, 0.9370, 0.9843, 0.9851, 0.9953, 0.9953, 0.9999, 1.0000,
0.0416, 0.0419, 0.0466, 0.0467, 0.1673, 0.1696, 0.1697, 0.6314, 0.7003, 0.7003, 0.7003, 0.7142, 0.7150, 0.7160, 0.8626, 0.8626, 0.8627, 0.9023, 0.9255, 0.9498, 0.9746, 0.9746, 0.9812, 0.9812, 0.9998, 1.0000,
0.0141, 0.0308, 0.0668, 0.0877, 0.1241, 0.1282, 0.1874, 0.1874, 0.2191, 0.2192, 0.2210, 0.3626, 0.3794, 0.4618, 0.4632, 0.5097, 0.5097, 0.6957, 0.8373, 0.9949, 0.9949, 0.9961, 0.9963, 0.9982, 0.9984, 1.0000,
0.0740, 0.0740, 0.0740, 0.0740, 0.8423, 0.8423, 0.8423, 0.8423, 0.9486, 0.9486, 0.9486, 0.9486, 0.9486, 0.9491, 0.9836, 0.9836, 0.9836, 0.9849, 0.9849, 0.9849, 0.9907, 0.9907, 0.9907, 0.9907, 1.0000, 1.0000,
0.2785, 0.2789, 0.2795, 0.2823, 0.4088, 0.4118, 0.4118, 0.6070, 0.7774, 0.7774, 0.7782, 0.7840, 0.7840, 0.8334, 0.9704, 0.9704, 0.9704, 0.9861, 0.9996, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
0.0741, 0.0741, 0.1963, 0.1963, 0.2519, 0.2741, 0.2741, 0.3333, 0.4000, 0.4000, 0.4000, 0.4000, 0.4000, 0.4000, 0.4037, 0.6741, 0.7667, 0.7667, 0.7667, 0.9667, 0.9963, 0.9963, 0.9963, 0.9963, 1.0000, 1.0000,
0.0082, 0.0130, 0.0208, 0.0225, 0.1587, 0.1608, 0.1613, 0.1686, 0.2028, 0.2028, 0.2032, 0.2322, 0.2391, 0.2417, 0.8232, 0.8314, 0.8314, 0.8409, 0.9529, 0.9965, 0.9965, 0.9965, 0.9991, 0.9996, 1.0000, 1.0000,
0.0678, 0.0678, 0.0763, 0.0763, 0.7373, 0.7373, 0.7373, 0.7458, 0.8729, 0.8729, 0.8729, 0.8814, 0.8814, 0.8814, 0.9237, 0.9237, 0.9237, 0.9237, 0.9237, 0.9407, 0.9492, 0.9492, 0.9492, 0.9492, 0.9492, 1.0000
);
$chars = 'abcdefghijklmnopqrstuvwxyz';
$captchaText = '';
$char = rand(0, 25);
for ($i = 0; $i < $length; $i++) {
$captchaText .= chr($char + 65 + 32);
// Look up next char in transition matrix
$next = rand(0, 10000) / 10000;
for ($j = 0; $j < 26; $j++) {
if ($next < $transitionMatrix[$char * 26 + $j]) {
$char = $j;
break;
}
}
}
return $captchaText;
}
</code></pre>
<p><strong>Edit 2011-02-04:</strong></p>
<p>I've came up with a simple solution. I believe the letters in a gibberish string will most likely contains the same letters over and over again, I've came up with that little function:</p>
<pre><code>echo contains_gibberish( "heiahihaiaheiah" );
function contains_gibberish( $input )
{
$result = array();
for($i = 0; $i < strlen( $input ); $i++)
{
if ( isset( $result[ $input[ $i ] ] ) )
{
$result[ $input[ $i ] ]++;
} else {
$result[ $input[ $i ] ] = 1;
}
}
return ( max( $result ) / strlen( $input ) * 100 >= 33 ) ? true : false;
}
</code></pre>
<p>What do you guys think?</p>
| 1 | 4,198 |
Package-wide variable assignment in Golang's init() function
|
<p>I want to initialize a package-wide variable in some Go code to connect to a database, but I keep getting a nil pointer exception, so clearly the assignment isn't occurring properly. This throws an error:</p>
<pre><code>package main
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
)
var connection *sql.DB
func init() {
connectionString := "host=172.17.0.3 dbname=postgres user=postgres password=postgres port=5432 sslmode=disable"
connection, err := sql.Open(
"postgres",
connectionString,
)
check(err)
err = connection.Ping()
check(err)
}
func main() {
TestConnect()
}
func TestConnect() {
var pid int
err := connection.QueryRow("SELECT pg_backend_pid()").Scan(&pid)
check(err)
fmt.Printf("pid: %v", pid)
}
func check(err error) {
if err != nil {
panic(err)
}
}
</code></pre>
<p>Here's the error:</p>
<pre><code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4c1a1a]
goroutine 1 [running]:
database/sql.(*DB).conn(0x0, 0x70b7c0, 0xc4200102b8, 0x1, 0xc420055e08, 0x4c28df, 0xc4200b0000)
/usr/local/go/src/database/sql/sql.go:896 +0x3a
database/sql.(*DB).query(0x0, 0x70b7c0, 0xc4200102b8, 0x630335, 0x17, 0x0, 0x0, 0x0, 0x101, 0x741c80, ...)
/usr/local/go/src/database/sql/sql.go:1245 +0x5b
database/sql.(*DB).QueryContext(0x0, 0x70b7c0, 0xc4200102b8, 0x630335, 0x17, 0x0, 0x0, 0x0, 0x0, 0x8, ...)
/usr/local/go/src/database/sql/sql.go:1227 +0xb8
database/sql.(*DB).QueryRowContext(0x0, 0x70b7c0, 0xc4200102b8, 0x630335, 0x17, 0x0, 0x0, 0x0, 0xc420010cb0)
/usr/local/go/src/database/sql/sql.go:1317 +0x90
database/sql.(*DB).QueryRow(0x0, 0x630335, 0x17, 0x0, 0x0, 0x0, 0x0)
/usr/local/go/src/database/sql/sql.go:1325 +0x7c
main.TestConnect()
/home/tom/go/src/go-rest/ignore/connect.go:32 +0x82
main.main()
/home/tom/go/src/go-rest/ignore/connect.go:26 +0x20
exit status 2
</code></pre>
<p>However, if I switch it up so I can use the <code>=</code> operator on <code>connection</code> instead of <code>:=</code>...</p>
<pre><code>package main
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
)
var connection *sql.DB
func init() {
connectionString, err := GetConnectionString()
connection, err = sql.Open(
"postgres",
connectionString,
)
check(err)
err = connection.Ping()
check(err)
}
func main() {
TestConnect()
}
func TestConnect() {
var pid int
err := connection.QueryRow("SELECT pg_backend_pid()").Scan(&pid)
check(err)
fmt.Printf("pid: %v", pid)
}
func GetConnectionString() (string, error) {
return "host=172.17.0.3 dbname=postgres user=postgres password=postgres port=5432 sslmode=disable", nil
}
func check(err error) {
if err != nil {
panic(err)
}
}
</code></pre>
<p>Then everything works as expected, and the variable is properly assigned. Because the <code>err</code> variable is previously undefined, I have to use <code>:=</code> for assignment, but this seems to assume that I'm initializing a function-scoped <code>connection</code> variable, and not trying to assign to the package-scoped <code>connection</code> variable. Is there a way to force this assignment in Go? As it stands, I need to write useless, boilerplate code to get this to work the right way, and it seems like there should be a better way.</p>
<p>Of course, the possibility also stands that I'm trying to do something that I perhaps shouldn't be. Based on my research though, <a href="http://go-database-sql.org/accessing.html" rel="nofollow noreferrer">this guide</a> seems to suggest using a package-wide database connection is better then creating / closing connections as needed.</p>
| 1 | 1,505 |
Using dynamic enum as type in a parameter of a method
|
<p>What i am trying to achieve here is a bit tricky. Let me brief on a little background first before going ahead.</p>
<p>I am aware that we can use a enum as a type to a parameter of a method. For example I can do something like this (a very basic example)</p>
<pre>
namespace Test
{
class DefineEnums
{
public enum MyEnum
{
value1 = 0,
value2 = 1
}
}
class UseEnums
{
public void UseDefinedEnums(DefineEnums.MyEnum _enum)
{
//Any code here.
}
public void Test()
{
// "value1" comes here with the intellisense.
UseDefinedEnums(DefineEnums.MyEnum.value1);
}
}
}
</pre>
<p>What i need to do is create a dynamic Enum and use that as type in place of <code>DefineEnums.MyEnum</code> mentioned above.</p>
<p>I tried the following.
1. Used a method which i got from the net to create a dynamic enum from a list of strings. And created a static class which i can use.</p>
<pre>
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Test
{
public static class DynamicEnum
{
public static Enum finished;
static List<string> _lst = new List<string>();
static DynamicEnum()
{
_lst.Add("value1");
_lst.Add("value2");
finished = CreateDynamicEnum(_lst);
}
public static Enum CreateDynamicEnum(List<string> _list)
{
// Get the current application domain for the current thread.
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName aName = new AssemblyName("TempAssembly");
AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(
aName, AssemblyBuilderAccess.RunAndSave);
// Define a dynamic module in "TempAssembly" assembly. For a single-
// module assembly, the module has the same name as the assembly.
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
// Define a public enumeration with the name "Elevation" and an
// underlying type of Integer.
EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));
// Define two members, "High" and "Low".
//eb.DefineLiteral("Low", 0);
//eb.DefineLiteral("High", 1);
int i = 0;
foreach (string item in _list)
{
eb.DefineLiteral(item, i);
i++;
}
// Create the type and save the assembly.
return (Enum)Activator.CreateInstance(eb.CreateType());
//ab.Save(aName.Name + ".dll");
}
}
}
</pre>
<ol start="2">
<li>Tried using the class but i am unable to find the "finished" enum defined above. i.e. I am not able to do the following</li>
</ol>
<pre>
public static void TestDynEnum(Test.DynamicEnum.finished _finished)
{
// Do anything here with _finished.
}
</pre>
<p>I guess the post has become too long but i hope i have made it quite clear.</p>
| 1 | 1,446 |
Is the salt contained in a phpass hash or do you need to salt its input?
|
<p><a href="http://www.openwall.com/phpass/" rel="noreferrer"><em>phpass</em></a> is a widely used hashing 'framework'.<br>
Is it good practice to salt the plain password before giving it to PasswordHash (v0.2), like so?:</p>
<pre><code>$dynamicSalt = $record['salt'];
$staticSalt = 'i5ininsfj5lt4hbfduk54fjbhoxc80sdf';
$plainPassword = $_POST['password'];
$password = $plainPassword . $dynamicSalt . $staticSalt;
$passwordHash = new PasswordHash(8, false);
$storedPassword = $passwordHash->HashPassword($password);
</code></pre>
<hr>
<p>For reference the phpsalt class:</p>
<pre><code># Portable PHP password hashing framework.
#
# Version 0.2 / genuine.
#
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
# the public domain.
#
#
#
class PasswordHash {
var $itoa64;
var $iteration_count_log2;
var $portable_hashes;
var $random_state;
function PasswordHash($iteration_count_log2, $portable_hashes)
{
$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
$iteration_count_log2 = 8;
$this->iteration_count_log2 = $iteration_count_log2;
$this->portable_hashes = $portable_hashes;
$this->random_state = microtime() . getmypid();
}
function get_random_bytes($count)
{
$output = '';
if (is_readable('/dev/urandom') &&
($fh = @fopen('/dev/urandom', 'rb'))) {
$output = fread($fh, $count);
fclose($fh);
}
if (strlen($output) < $count) {
$output = '';
for ($i = 0; $i < $count; $i += 16) {
$this->random_state =
md5(microtime() . $this->random_state);
$output .=
pack('H*', md5($this->random_state));
}
$output = substr($output, 0, $count);
}
return $output;
}
function encode64($input, $count)
{
$output = '';
$i = 0;
do {
$value = ord($input[$i++]);
$output .= $this->itoa64[$value & 0x3f];
if ($i < $count)
$value |= ord($input[$i]) << 8;
$output .= $this->itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count)
break;
if ($i < $count)
$value |= ord($input[$i]) << 16;
$output .= $this->itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count)
break;
$output .= $this->itoa64[($value >> 18) & 0x3f];
} while ($i < $count);
return $output;
}
function gensalt_private($input)
{
$output = '$P$';
$output .= $this->itoa64[min($this->iteration_count_log2 +
((PHP_VERSION >= '5') ? 5 : 3), 30)];
$output .= $this->encode64($input, 6);
return $output;
}
function crypt_private($password, $setting)
{
$output = '*0';
if (substr($setting, 0, 2) == $output)
$output = '*1';
if (substr($setting, 0, 3) != '$P$')
return $output;
$count_log2 = strpos($this->itoa64, $setting[3]);
if ($count_log2 < 7 || $count_log2 > 30)
return $output;
$count = 1 << $count_log2;
$salt = substr($setting, 4, 8);
if (strlen($salt) != 8)
return $output;
# We're kind of forced to use MD5 here since it's the only
# cryptographic primitive available in all versions of PHP
# currently in use. To implement our own low-level crypto
# in PHP would result in much worse performance and
# consequently in lower iteration counts and hashes that are
# quicker to crack (by non-PHP code).
if (PHP_VERSION >= '5') {
$hash = md5($salt . $password, TRUE);
do {
$hash = md5($hash . $password, TRUE);
} while (--$count);
} else {
$hash = pack('H*', md5($salt . $password));
do {
$hash = pack('H*', md5($hash . $password));
} while (--$count);
}
$output = substr($setting, 0, 12);
$output .= $this->encode64($hash, 16);
return $output;
}
function gensalt_extended($input)
{
$count_log2 = min($this->iteration_count_log2 + 8, 24);
# This should be odd to not reveal weak DES keys, and the
# maximum valid value is (2**24 - 1) which is odd anyway.
$count = (1 << $count_log2) - 1;
$output = '_';
$output .= $this->itoa64[$count & 0x3f];
$output .= $this->itoa64[($count >> 6) & 0x3f];
$output .= $this->itoa64[($count >> 12) & 0x3f];
$output .= $this->itoa64[($count >> 18) & 0x3f];
$output .= $this->encode64($input, 3);
return $output;
}
function gensalt_blowfish($input)
{
# This one needs to use a different order of characters and a
# different encoding scheme from the one in encode64() above.
# We care because the last character in our encoded string will
# only represent 2 bits. While two known implementations of
# bcrypt will happily accept and correct a salt string which
# has the 4 unused bits set to non-zero, we do not want to take
# chances and we also do not want to waste an additional byte
# of entropy.
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '$2a$';
$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
$output .= '$';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);
return $output;
}
function HashPassword($password)
{
$random = '';
if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) {
$random = $this->get_random_bytes(16);
$hash =
crypt($password, $this->gensalt_blowfish($random));
if (strlen($hash) == 60)
return $hash;
}
if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) {
if (strlen($random) < 3)
$random = $this->get_random_bytes(3);
$hash =
crypt($password, $this->gensalt_extended($random));
if (strlen($hash) == 20)
return $hash;
}
if (strlen($random) < 6)
$random = $this->get_random_bytes(6);
$hash =
$this->crypt_private($password,
$this->gensalt_private($random));
if (strlen($hash) == 34)
return $hash;
# Returning '*' on error is safe here, but would _not_ be safe
# in a crypt(3)-like function used _both_ for generating new
# hashes and for validating passwords against existing hashes.
return '*';
}
function CheckPassword($password, $stored_hash)
{
$hash = $this->crypt_private($password, $stored_hash);
if ($hash[0] == '*')
$hash = crypt($password, $stored_hash);
return $hash == $stored_hash;
}
}
</code></pre>
| 1 | 4,139 |
Typescript error got undefined with useState hook
|
<p>Im new to graphql so I decided to follow this <a href="https://medium.com/make-it-heady/part-2-building-full-stack-web-app-with-postgraphile-and-react-client-side-1c5085c5a182" rel="nofollow noreferrer">guide</a>.</p>
<p>However I got an error when querying (step 7) :</p>
<pre><code>Argument of type '({ __typename?: "User"; } & Pick<User, "email" | "id" | "name" | "createdAt">)[]' is not assignable to parameter of type '(prevState: undefined) => undefined'.
Type '({ __typename?: "User"; } & Pick<User, "email" | "id" | "name" | "createdAt">)[]' provides no match for the signature '(prevState: undefined): undefined'. TS2345
37 | if (data && data.allUsers) {
38 | if (data && data.allUsers && data.allUsers.nodes) {
> 39 | setUsers(data.allUsers.nodes);
| ^
40 | }
41 | }
42 | }
</code></pre>
<p>Here is the component:</p>
<pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from 'react'
import { useGetUsers } from '../utils/services'
import { User } from '../generated/graphql'
const Users: React.FC = () => {
const [users, setUsers] = useState()
const { data, error, loading } = useGetUsers()
useEffect(() => {
if (data) {
if (data && data.allUsers && data.allUsers.nodes) {
setUsers(data.allUsers.nodes)
}
}
if (error) {
console.log(error)
}
if (loading) {
console.log(loading)
}
}, [data, error, loading])
return (
<>
<h2>Hello users,</h2>
{users &&
users.length > 0 &&
users.map((user: User, index: number) => (
<p key={`user_${index}`}>
{user.name}{' '}
</p>
))}
</>
)
}
export default Users
</code></pre>
<p>However it works when I use</p>
<pre class="lang-js prettyprint-override"><code>data.allUsers.nodes
</code></pre>
<p>Like this :</p>
<pre class="lang-js prettyprint-override"><code>{data && data.allUsers ? (
data.allUsers.nodes &&
data.allUsers.nodes.length > 0 &&
data.allUsers.nodes.map((user: User, index: number) => (
<p key={`user_${index}`}>{user.name}</p>
))
) : (
<React.Fragment />
)}
</code></pre>
<p>And of course I've removed <code>setUsers</code> in the <code>useEffect()</code> hooks.</p>
<p>I notice that I had to set strict to false in my <code>.tsconfig.json</code> file.</p>
<p>I would like to know why I m not able to use the setUsers hooks? Why I got that error and how to solve it?</p>
<p>Thank you!</p>
| 1 | 1,452 |
Does every stateful intermediate Stream API operation guarantee a new source collection?
|
<p>Is the following statement true?</p>
<blockquote>
<p>The <code>sorted()</code> operation is a “stateful intermediate operation”, which means that subsequent operations no longer operate on the backing collection, but on an internal state.</p>
</blockquote>
<p><sup>(<a href="https://www.toptal.com/java/top-10-most-common-java-development-mistakes" rel="nofollow noreferrer">Source</a> and <a href="https://dzone.com/articles/java-8-friday-10-subtle" rel="nofollow noreferrer">source</a> - they seem to copy from each other or come from the same source.)</sup></p>
<p><strong>Disclaimer:</strong> I am aware the following snippets are not legit usages of Java Stream API. Don't use in the production code.</p>
<p>I have tested <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> as a snippet from sources above:</p>
<pre><code>final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.sorted()
.forEach(list::remove);
System.out.println(list); // Prints [0, 1, 2, 3, 4, 5]
</code></pre>
<p>It works. I replaced <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> with <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--" rel="nofollow noreferrer"><code>Stream::distinct</code></a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#limit-long-" rel="nofollow noreferrer"><code>Stream::limit</code></a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-" rel="nofollow noreferrer"><code>Stream::skip</code></a>:</p>
<pre><code>final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.distinct()
.forEach(list::remove); // Throws NullPointerException
</code></pre>
<p>To my surprise, the <code>NullPointerException</code> is thrown.</p>
<p>All the tested methods follow the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps" rel="nofollow noreferrer">stateful intermediate operation</a> characteristics. Yet, this unique behavior of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> is not documented nor the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps" rel="nofollow noreferrer">Stream operations and pipelines</a> part explains whether the <em>stateful intermediate operations</em> really guarantee a new source collection.</p>
<p>Where my confusion comes from and what is the explanation of the behavior above?</p>
| 1 | 1,044 |
flock-ing a C++ ifstream on Linux (GCC 4.6)
|
<h3>context</h3>
<p>I'm slowly writing a specialized web server application in C++ (using the C <a href="https://github.com/davidmoreno/onion" rel="noreferrer">onion http server library</a> and the <a href="http://jsoncpp.sourceforge.net/" rel="noreferrer">JSONCPP library</a> for JSON serialization, if that matters)., for a Linux system with GCC 4.6 compiler (I don't care about portability to non Linux systems, or to GCC before 4.5 or to Clang before 3.0).</p>
<p>I decided to keep the user "database" (there will be very few users, probably one or two, so performance is not a concern, and O(n) access time is acceptable) in JSON format, probably as a small array of JSON objects like</p>
<pre><code> { "_user" : "basile" ;
"_crypasswd" : "XYZABC123" ;
"_email" : "basile@starynkevitch.net" ;
"firstname" : "Basile" ;
"lastname" : "Starynkevitch" ;
"privileges" : "all" ;
}
</code></pre>
<p>with the convention (à la <code>.htpasswd</code>) that the <code>_crypasswd</code> field is the <a href="http://linux.die.net/man/3/crypt" rel="noreferrer">crypt(3)</a> "encryption" of the user password, salted by the <code>_user</code> name;</p>
<p>The reason I want to describe users by Json objects is that my application might add (not replace) some JSON fields (like e.g. <code>privileges</code> above) in such Json objects describing users. I'm using <em>JsonCpp</em> as a Json parsing library for C++. This library wants an <code>ifstream</code> to be parsed.</p>
<p>So I am reading my password file with</p>
<pre><code>extern char* iaca_passwd_path; // the path of the password file
std::ifstream jsinpass(iaca_passwd_path);
Json::Value jpassarr;
Json::Reader reader;
reader.parse(jsinpass,jpassarr,true);
jsinpass.close();
assert (jpassarr.isArray());
for (int ix=0; ix<nbu; ix++) {
const Json::Value&jcuruser= jpassarr[ix];
assert(jcuruser.isObject());
if (jcuruser["_user"].compare(user) == 0) {
std::string crypasswd = jcuruser["_crypasswd"].asString();
if (crypasswd.compare(crypted_password(user,password)) == 0) {
// good user
}
}
}
</code></pre>
<hr>
<h2>question</h2>
<p>Obviously, I want to <a href="http://linux.die.net/man/2/flock" rel="noreferrer"><code>flock</code></a> or <a href="http://linux.die.net/man/3/lockf" rel="noreferrer"><code>lockf</code></a> the password file, to ensure that only one process is reading or writing it. To call these functions, I need to get the file descriptor (in Unix parlance) of the <code>ifstream jsinpass</code>. But Google gives me mostly <a href="http://www.ginac.de/~kreckel/fileno/" rel="noreferrer">Kreckel's fileno</a> (which I find complete, but a bit insane) to get the file descriptor of an <code>std::ifstream</code> and I am not sure that the constructor won't pre-read some of it. Hence my <strong>question</strong>:</p>
<h3>how can I lock a C++ <code>ifstream</code> (Linux, GCC 4.6) ?</h3>
<p>(Or do you find some other way to tackle that issue?)</p>
<p>Thanks</p>
| 1 | 1,078 |
How can I align the slides to the swiper slider?
|
<p>Good afternoon.
Please tell me how I can align the slides so that when you select the first or last slide on the left or right, there are the same number of next and previous slides.</p>
<p>In other words when selecting the first or last slide it should be like this:</p>
<p><a href="https://i.stack.imgur.com/S5Zmd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S5Zmd.png" alt="enter image description here" /></a></p>
<p>but at the moment it looks like this:
<a href="https://i.stack.imgur.com/8jWCE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jWCE.png" alt="enter image description here" /></a></p>
<p>In other words, if the first slide is active, then there is only the last slide to the left of it and the penultimate slide is missing.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sliderSelector = '.swiper-container',
options = {
init: true,
initialSlide: 1,
loop: true,
speed: 1200,
slidesPerView: 1.6848, // or 'auto'
spaceBetween: 0,
centeredSlides: true,
mousewheelControl: false,
lazyLoading: true,
slideToClickedSlide: true,
effect: 'coverflow', // 'cube', 'fade', 'coverflow',
autoplay: {
delay: 10000,
disableOnInteraction: false,
},
coverflowEffect: {
rotate: 0, // Slide rotate in degrees
stretch: 400, // Stretch space between slides (in px)
depth: 380, // Depth offset in px (slides translate in Z axis)
modifier: 1, // Effect multipler
slideShadows: false, // Enables slides shadows
},
grabCursor: true,
parallax: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function(index, className) {
return `<span class="dot swiper-pagination-bullet">${index +1}</span>`;
},
},
navigation: {
nextEl: 0,
prevEl: 0,
},
breakpoints: {
1023: {
slidesPerView: 5,
spaceBetween: 0
}
},
// Events
on: {
imagesReady: function() {
this.el.classList.remove('loading');
}
}
};
var mySwiper = new Swiper(sliderSelector, options);
// Initialize slider
mySwiper.init();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>[class^="swiper-button-"],
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet,
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet::before {
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
}
*,
*:before,
*:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.wrapper {
width: 100%;
display: flex;
justify-content: center;
background: #E5E5E5;
}
.container {
width: 1200px;
}
.swiper-slide-active img {
outline: 10px solid rgba(255, 255, 255, 0.5);
outline-offset: -10px;
}
.swiper-slide img {
outline: 10px solid rgba(255, 255, 255, 0.5);
outline-offset: -10px;
}
.swiper-slide img {
position: relative;
}
.swiper-container {
width: 100%;
min-height: 470px;
height: auto;
-webkit-transition: opacity 1s ease;
transition: opacity 1s ease;
}
.swiper-slide img {
display: block;
max-width: 100%;
height: auto;
}
.swiper-container.swiper-container-coverflow {
padding-top: 2%;
}
.swiper-container.loading {
opacity: 0;
visibility: hidden;
transition: all 0.5s ease-in;
}
.swiper-container:hover .swiper-button-prev,
.swiper-container:hover .swiper-button-next {
-webkit-transform: translateX(0);
transform: translateX(0);
opacity: 1;
visibility: visible;
}
.swiper-slide {
background-position: center;
background-size: cover;
}
.swiper-slide .entity-img {
display: none;
}
.swiper-slide .content {
position: absolute;
top: 40%;
left: 0;
width: 50%;
padding-left: 5%;
color: #fff;
}
.swiper-slide .content .title {
font-size: 2.6em;
font-weight: bold;
margin-bottom: 30px;
}
.swiper-slide img {
filter: brightness(20%);
transition: all 0.5s ease-in;
position: relative;
z-index: 2;
}
.swiper-slide-prev img {
filter: brightness(40%);
transition: all 0.5s ease-in;
}
.swiper-slide-next img {
filter: brightness(40%);
transition: all 0.5s ease-in;
}
.swiper-slide {
outline: 10px solid #ffffff;
outline-offset: -10px;
position: relative;
z-index: 5;
}
swiper-slide-next img {
filter: brightness(50%);
transition: all 0.5s ease-in;
}
.swiper-slide-active img {
filter: brightness(100%);
transition: all 0.5s ease-in;
}
.swiper-slide .content .caption {
display: block;
font-size: 13px;
line-height: 1.4;
}
[class^="swiper-button-"] {
width: 44px;
opacity: 0;
visibility: hidden;
}
.swiper-button-prev {
-webkit-transform: translateX(50px);
transform: translateX(50px);
}
.swiper-button-next {
-webkit-transform: translateX(-50px);
transform: translateX(-50px);
}
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet {
margin: 0 9px;
position: relative;
width: 12px;
height: 12px;
background-color: #fff;
opacity: 0.4;
}
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet::before {
content: "";
position: absolute;
top: 50%;
left: 50%;
width: 18px;
height: 18px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
border: 0px solid #fff;
border-radius: 50%;
}
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet:hover,
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet.swiper-pagination-bullet-active {
opacity: 1;
transition: all 5s ease-in;
}
.swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet.swiper-pagination-bullet-active::before {
border-width: 1px;
}
@media (max-width: 1180px) {
.swiper-slide .content .title {
font-size: 25px;
}
.swiper-slide .content .caption {
font-size: 12px;
}
}
@media (max-width: 1023px) {
.swiper-container {
height: 40vw;
}
.swiper-container.swiper-container-coverflow {
padding-top: 0;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.7/css/swiper.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.4.1/js/swiper.min.js"></script>
<div class="wrapper">
<div class="container">
<section class="swiper-container loading">
<div class="swiper-wrapper">
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
<div class="swiper-slide">
<img src="https://i.ytimg.com/vi/954FKvpQN2g/maxresdefault.jpg">
</div>
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev swiper-button-white"></div>
<div class="swiper-button-next swiper-button-white"></div>
</section>
</div>
</div></code></pre>
</div>
</div>
</p>
| 1 | 3,510 |
Upload text as file with POST (multipart/form-data) using php and wget
|
<p>I'm using PHP + wget to upload a file on an old cgi-bin control panel web-to-fax.</p>
<p>The cgi (dont know its language) checks the file format (doc txt pdf) and then returns me the error: "incorrect file format". If I do it manually everything works fine.</p>
<p>The form is 6 steps long, every step is quite similar (it asks you for destination, number of retries, etc) and my PHP + wget scripts work as expected (cookies handling, post, get, etc).</p>
<p>This is how the form looks like (lightened and translated from the original):</p>
<pre><code><FORM ACTION="xyz_httpfileupload" METHOD="post" ENCTYPE="multipart/form-data">
Write the file with full path:
<INPUT TYPE="FILE" NAME="sourcefile" size=40 maxlength=200>
<input type=hidden name=destfile value="N527yb">
<!-- this is a random generated filename -->
<input type=hidden name=urlredirect value="./xyz_upload?destfile=N527yb&filename=/tmp/VOTU9.txt">
<!-- this is another random generated filename -->
<input type=submit name="Upload" value="Upload">
</FORM>
</code></pre>
<p>The code (and some tests) shows that you can use both GET or POST.</p>
<p>This is my code, followed by explainations:</p>
<pre><code>$command = ' wget --debug -qSO- --cookies=on --keep-session-cookies '.
' --save-cookies='.$cookie.' --load-cookies='.$cookie.
' --header="Content-Type:text/plain" '.
' --post-file="'.$file.'" '.
// ' --post-data="sourcefile='.$rawfile.'" '.
' --post-data="'.
'destfile='.$randfile.
'&urlredirect=xyz_delivery?destfile='.$randfile.
'&filename=/tmp/'.$randname.'.txt" '.
'&pload=Upload "xyz_httpfileupload" ';
$data = shell_exec($command." && sleep 10 2>&1 | tee ".$dir."logfile.txt");
</code></pre>
<p>$cookie is the full server path to the cookie file. It works as expected.</p>
<p>$file is the full server path to my file. It's a simple file.txt</p>
<p>$randfile and $randname are retrieved using preg_match on the HTML output.</p>
<p>The commented line with $rawfile is a try to send the raw urlencoded content instead of the file: somebody say it's a working alternative but not for me, or at least I didn't code it right.</p>
<p>I also tried to post directly into the URL you see in urlredirect, but I get the same error file format incorrect, but I can't assure the right parsing from the cgi if I jump a step. </p>
<p>In any case logfile.txt was left empty.</p>
<p>I know curl would make my life easier, but the ubuntu platform the script resides on only supports wget and I feel I'm half the way on.</p>
<p>Advice me on methods to debug it. I can't via shell because I would lose the random names generated on every refresh. Perhaps TCPdump? Thanks for any advice you can give me, I think this is the ultimate discussion to definitely solve this matter.</p>
| 1 | 1,074 |
Handler to Handler VERSUS Messenger to Messenger communication in Android
|
<p><strong>The question:</strong></p>
<p>Is it "better" (= faster and less overhead) to use <a href="http://developer.android.com/reference/android/os/Handler.html" rel="nofollow">Handler</a> to Handler communication compared to using <a href="http://developer.android.com/reference/android/os/Messenger.html" rel="nofollow">Messenger</a> to Messenger communication in Android?</p>
<p><strong>The situation:</strong></p>
<p>Android App that has a bunch of activities and one service running (started service). Within the service a few threads are running next to the main thread of the service.
Application is started, first activity starts the service, service starts, first activity forwards to second activity, second activity binds to service,...</p>
<p><em>Handler to Handler:</em></p>
<p>...service hands out reference to <strong>service handler</strong>, second activity defines its own handler, second activity can now communicate to service directly using the service handler. To let the service handler know it has to reply to an activity handler, the <strong>msg.obj</strong> field within a <a href="http://developer.android.com/reference/android/os/Message.html" rel="nofollow">Message</a> object can be used to set the "reply-to" handler (= the handler within the activity). Now a two-way communication is sucessfully setup between activity and service.</p>
<p><em>Messenger to Messenger:</em></p>
<p>...service hands out reference to <strong>service messenger</strong>, second activity defines its own messenger, second activity can now communicate to service indirectly using the service messenger, which translates the message (Message object) into a Parcelable object, then re-translates the Parcelable object back into a new (but equal) Message object, which is handed over to the handler of the service. To let the service messenger know it has to reply to the activity messenger, the <strong>msg.replyTo</strong> field can be set with the messenger within the activity. Two-way communication sucessfully setup.</p>
<p><strong>The "problem":</strong></p>
<p>Why do I need Messenger to Messenger setup when I only need direct communication in my App that is within the boundaries of only one process? All threads within one process can easily communicate through the use of their Handlers (assuming these threads all have setup their own handlers correctly). I don't want messengers first flattening the Message objects shared between to two Handlers, that is just added overhead without any purpose besides "following the Android Service tutorial blindly".</p>
<p><strong>Possible solution:</strong></p>
<p>Start the service, bind once to it, let the service hand out a local binder object, set within the ServiceConnection implementation of onServiceConnected() the service handler within the activity, let the activity store it somewhere in a global memory space, switch to a third, forth, fifth activity and you never have to bind again in all the other activities, because all activities know their own handler (setup in each activity separate) and the can get the service handler from the global memory space. If the service needs to respond to the handler of the fourth activity, the fourth activity just adds its own handler (fourthHanlder) to the msg.obj field and the service knows whereto the reply message must be sent. That's it.</p>
<p>Besides that: the activity runs on the ui-thread/main-thread and the service runs also on the ui-thread/main-thread, so actually they are part of the same thread, only different handlers. Or is this incorrect thinking on my part?</p>
<p>This means the whole Messenger thing is only extra overhead for local (internal) communication between threads in the same process! It is not needed, unless the Android system figures out internally if the Messengers mutually communicate within the same process and bypass the flattening of the Messages and skip the translation into Parcelable objects, so that the Messengers actually communicate sortof directly between the Handlers themselves (without the user/programmer actually being aware of this. Well at least I am not aware of this if this is true what I am thinking right now).</p>
<p>I see that there are only three ways you can create asynchronous communication between activities and services by using:</p>
<ul>
<li><strong>Intents</strong> (can't send objects with an Intent!)</li>
<li><strong>Messengers</strong> (are limited in possibilities compared to using Handlers directly, for example: you can't queue a message to the front of the queue)</li>
<li><strong>Handlers</strong> (only possible when the threads to which the handlers belong are within the same process, otherwise you DO need Messengers)</li>
</ul>
<p>I believe the handlers are the fastest way to communicate between threads, followed up by the messengers and last are intents. Is this TRUE??? </p>
<p>Please share your insights and experiences on this matter, even when I am seeing this incorrectly :)
Thank you.</p>
| 1 | 1,189 |
Table inside div, but still higher than parent div
|
<p>Why does height="100%" attribute fail to work in the following snippet?</p>
<pre><code><table height="100%" width="100%">
</code></pre>
<p><strong>EDIT</strong>:
code as follows:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<div style="width:250px;height:90px;">
<table id="experiences-mirror" width="100%" border="1" cellpadding="0" height="100%">
<caption>Table Name</caption>
<tbody><tr><th>Company</th><th>Job Title</th><th>Industry</th><th>Job Function</th><th>Start Date</th><th>End Date</th></tr>
<tr title="hint">
<td><input name="company1" class="w100" type="text"></td><td><input name="jobTitle1" class="w100" value="" type="text"></td><td><input name="industry1" class="w100" value="" type="text"></td><td><input name="jobFunction1" class="w100" type="text"></td><td><input name="startDate1" class="w100" type="text"></td><td><input name="endDate1" class="w100" type="text"></td>
</tr>
<tr title="hint">
<td><input name="company2" class="w100" type="text"></td><td><input name="jobTitle2" class="w100" type="text"></td><td><input name="industry2" class="w100" type="text"></td><td><input name="jobFunction2" class="w100" type="text"></td><td><input name="startDate2" class="w100" type="text"></td><td><input name="endDate2" class="w100" type="text"></td>
</tr>
<tr title="hint">
<td><input name="company3" class="w100" type="text"></td><td><input name="jobTitle3" class="w100" type="text"></td><td><input name="industry3" class="w100" type="text"></td><td><input name="jobFunction3" class="w100" type="text"></td><td><input name="startDate3" class="w100" type="text"></td><td><input name="endDate3" class="w100" type="text"></td>
</tr>
<tr title="hint">
<td><input name="company4" class="w100" type="text"></td><td><input name="jobTitle4" class="w100" type="text"></td><td><input name="industry4" class="w100" type="text"></td><td><input name="jobFunction4" class="w100" type="text"></td><td><input name="startDate4" class="w100" type="text"></td><td><input name="endDate4" class="w100" type="text"></td>
</tr>
</tbody></table>
</div>
</code></pre>
| 1 | 1,421 |
Angular build - Unmatched selector: %
|
<p>When I run <code>npm run build</code> which executes <code>ng build -c production</code> build will be completed as expected. But command prompt will be filled with this warning:</p>
<pre><code>Warning: 303 rules skipped due to selector errors:
0% -> Unmatched selector: %
20% -> Unmatched selector: %
53% -> Unmatched selector: %
40% -> Unmatched selector: %
43% -> Unmatched selector: %
70% -> Unmatched selector: %
80% -> Unmatched selector: %
90% -> Unmatched selector: %
...
</code></pre>
<p>How to solve this warning?</p>
<p><code>package.json</code>:</p>
<pre><code>{
"name": "wepod-clients",
"version": "3.2.3",
"scripts": {
"ng": "ng",
"start": "node patch.js && ng serve",
"serve-auth": "ng run wepod-app:serve-auth-standalone:production",
"build": "node patch.js && node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng run wepod-app:app-shell:production && ng run wepod-app:auth-standalone:production",
"server": "npm run build && http-server -p 9090 -c-1 dist",
"test": "ng test",
"lint": "ng lint --fix",
"e2e": "ng e2e",
"postinstall": "node patch.js && ngcc",
"postbuild": "node post-build.js",
"prepare": "husky install",
"build-latest": "git pull origin production && npm run build"
},
"private": true,
"dependencies": {
"@angular/animations": "^13.0.0",
"@angular/cdk": "^13.0.0",
"@angular/cli": "^13.0.1",
"@angular/common": "^13.0.0",
"@angular/compiler": "^13.0.0",
"@angular/core": "^13.0.0",
"@angular/forms": "^13.0.0",
"@angular/localize": "^13.0.0",
"@angular/platform-browser": "^13.0.0",
"@angular/platform-browser-dynamic": "^13.0.0",
"@angular/platform-server": "^13.0.0",
"@angular/router": "^13.0.0",
"@angular/service-worker": "^13.0.0",
"@types/video.js": "^7.3.27",
"animate.css": "^4.1.1",
"assert": "^2.0.0",
"bowser": "^2.11.0",
"buffer": "^6.0.3",
"bundle-loader": "^0.5.6",
"compare-version": "^0.1.2",
"constants-browserify": "^1.0.0",
"crypto-browserify": "^3.12.0",
"crypto-js": "^4.1.1",
"d3": "^6.5.0",
"hammerjs": "^2.0.8",
"https-browserify": "^1.0.0",
"jalali-moment": "^3.3.10",
"lottie-web": "^5.7.13",
"lzutf8": "^0.6.0",
"net": "^1.0.2",
"ng-gallery": "^5.1.1",
"ng2-jalali-date-picker": "^2.4.2",
"ngx-device-detector": "^1.5.2",
"ngx-doughnut-chart": "0.0.4",
"ngx-infinite-scroll": "^8.0.2",
"ngx-lottie": "^7.0.4",
"ngx-owl-carousel-o": "^3.1.1",
"ngx-skeleton-loader": "^2.10.1",
"ngx-toastr": "^12.1.0",
"os-browserify": "^0.3.0",
"podchat-browser": "^10.14.13",
"rxjs": "^6.6.7",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"tls": "0.0.1",
"ts-ebml": "^2.0.2",
"tslib": "^2.0.0",
"uuid": "^8.3.2",
"video.js": "^7.15.4",
"videojs-record": "^4.5.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^13.0.1",
"@angular-devkit/core": "^13.0.1",
"@angular/compiler-cli": "^13.0.0",
"@angular/language-service": "^13.0.0",
"@egjs/hammerjs": "^2.0.17",
"@types/hammerjs": "^2.0.40",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "^2.0.10",
"@types/node": "^12.20.36",
"codelyzer": "^6.0.0",
"colors": "^1.4.0",
"git-tag-version": "^1.3.1",
"gulp": "^4.0.2",
"gulp-gzip": "^1.4.2",
"http-server": "^14.0.0",
"husky": "^7.0.4",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "^6.3.7",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "^2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "^7.0.0",
"ts-node": "^8.10.2",
"tslint": "^6.1.3",
"typescript": "4.4.4",
"zip-dir": "^2.0.0"
},
"browser": {
"fs": false,
"path": false,
"os": false
}
}
</code></pre>
| 1 | 3,432 |
Overlay raster plot using plot(...,add=T) leads to arbitrary misalignment of final plot
|
<p>I have found that when I try to overlay multiple rasters using plot(...,add=T) if I try to overlay more than 3 rasters together the subsequent plot does not align the rasters properly.</p>
<p>My original intent was to create a categorical map of modeled landcover where the darkness of the color representing a cover class varied wrt the certainty in our model projection. To do this, I created a simple script that would loop through each cover class and plot it (e.g., forest, green color on map) using a color gradient from grey (low certainty forest prediction) to full cover color (e.g., dark green for areas are strongly predicted).
What I have found is that using this approach, after the 3rd cover is added to the plot, all subsequent rasters that are overlayed on the plot are arbitrarily misaligned. I have reversed the order of plotting of the cover classes and the same behavior is exhibited meaning it is not an issue with the individual cover class rasters. Even more puzzling in Rstudio, when I use the zoom button to closely inspect the final plot, the misalignment worsens.</p>
<p>Do you have any ideas of why this behavior exists? Most importantly, do you have any suggested solutions or workarounds?</p>
<p>The code and data on the link below has all of the behaviors described captured.
<a href="https://dl.dropboxusercontent.com/u/332961/r%20plot%20raster%20add%20issue.zip" rel="noreferrer">https://dl.dropboxusercontent.com/u/332961/r%20plot%20raster%20add%20issue.zip</a>
Turn plot_gradient=F to see how if you just simply subset a same raster and add the subsets sequentially to the same plot you can replicate the issue. I have already tried setting the extent of the plot device plot(..., ext) but that did not work. I have also checked and the extent of each cover raster is the same.</p>
<p>Below is the figure of the misaligned cover classes. plotting to jpeg device will result in a similar image (i.e., this is not an issue of Rstudio rendering).
<img src="https://i.stack.imgur.com/FTsgv.png" alt="enter image description here">
Strangely enough, if I zoom into the image using Rstudio, the misalignment is different
<img src="https://i.stack.imgur.com/DfCOd.png" alt="enter image description here">
For comparison, this is how the covers should align correctly in the landscape
<img src="https://i.stack.imgur.com/wcMel.png" alt="enter image description here"></p>
<pre><code>library(raster)
library(colorRamps)
raster_of_classes=raster("C:/r plot raster add issue/raster_of_classes.tif")
raster_of_certainty_of_classes=raster("C:/r plot raster add issue/raster_of_certainty_of_classes.tif")
endCols=c("darkorchid4", "darkorange3", "red3", "green4", "dodgerblue4") #colors to be used in gradients for each class
classes=unique(raster_of_classes)
minVal=cellStats(raster_of_certainty_of_classes, min)
tmp_i=1
addPlot=F
plot_gradient=F #this is for debug only
#classes=rev(classes) #turn this off and on to see how last 2 classes are mis aligned, regardless of plotting order
for (class in classes){
raster_class=raster_of_classes==class #create mask for individual class
raster_class[raster_class==0]=NA #remove 0s from mask so they to do not get plotted
if (plot_gradient){
raster_of_certainty_of_class=raster_of_certainty_of_classes*raster_class #apply class mask to certainty map
}else{
raster_of_certainty_of_class=raster_class #apply class mask to certainty map
}
endCol=endCols[tmp_i] #pick color for gradient
col5 <- colorRampPalette(c('grey50', endCol))
if (plot_gradient){
plot(raster_of_certainty_of_class,
col=col5(n=49), breaks=seq(minVal,1,length.out=50), #as uncertainty values range from 0 to 1 plot them with fixed range
useRaster=T, axes=FALSE, box=FALSE, add=addPlot, legend=F)
}else{
plot(raster_of_certainty_of_class,
col=endCol,
useRaster=T, axes=FALSE, box=FALSE, add=addPlot, legend=F)
}
tmp_i=tmp_i+1
addPlot=T #after plotting first class, all other classes are added
}
</code></pre>
| 1 | 1,283 |
docker container fails to start after docker deamon has been restarted
|
<p>I am using Ubuntu 16.04 with docker 1.11.2. I have configured systemd to automatically restart docker daemon. When I kill the docker daemon, docker daemon restarts, but container will not even it has RestartPolicy set to always. From the logs I can read that it failed to create directory because it exists. I personally think that it related to stopping containerd. </p>
<p>Any help would be appreciated.</p>
<pre><code>Aug 25 19:20:19 api-31 systemd[1]: docker.service: Main process exited, code=killed, status=9/KILL
Aug 25 19:20:19 api-31 docker[17617]: time="2016-08-25T19:20:19Z" level=info msg="stopping containerd after receiving terminated"
Aug 25 19:21:49 api-31 systemd[1]: docker.service: State 'stop-sigterm' timed out. Killing.
Aug 25 19:21:49 api-31 systemd[1]: docker.service: Unit entered failed state.
Aug 25 19:21:49 api-31 systemd[1]: docker.service: Failed with result 'timeout'.
Aug 25 19:21:49 api-31 systemd[1]: docker.service: Service hold-off time over, scheduling restart.
Aug 25 19:21:49 api-31 systemd[1]: Stopped Docker Application Container Engine.
Aug 25 19:21:49 api-31 systemd[1]: Closed Docker Socket for the API.
Aug 25 19:21:49 api-31 systemd[1]: Stopping Docker Socket for the API.
Aug 25 19:21:49 api-31 systemd[1]: Starting Docker Socket for the API.
Aug 25 19:21:49 api-31 systemd[1]: Listening on Docker Socket for the API.
Aug 25 19:21:49 api-31 systemd[1]: Starting Docker Application Container Engine...
Aug 25 19:21:49 api-31 docker[19023]: time="2016-08-25T19:21:49.913162167Z" level=info msg="New containerd process, pid: 19029\n"
Aug 25 19:21:50 api-31 kernel: [87066.742831] audit: type=1400 audit(1472152910.946:23): apparmor="STATUS" operation="profile_replace" profile="unconfined" name="docker-default" pid=19043 comm="apparmor_parser"
Aug 25 19:21:50 api-31 docker[19023]: time="2016-08-25T19:21:50.952073973Z" level=info msg="[graphdriver] using prior storage driver \"overlay\""
Aug 25 19:21:50 api-31 docker[19023]: time="2016-08-25T19:21:50.956693893Z" level=info msg="Graph migration to content-addressability took 0.00 seconds"
Aug 25 19:21:50 api-31 docker[19023]: time="2016-08-25T19:21:50.961641996Z" level=info msg="Firewalld running: false"
Aug 25 19:21:51 api-31 docker[19023]: time="2016-08-25T19:21:51.016582850Z" level=info msg="Removing stale sandbox 66ef9e1af997a1090fac0c89bf96c2631bea32fbe3c238c4349472987957c596 (547bceaad5d121444ddc6effbac3f472d0c232d693d8cc076027e238cf253613)"
Aug 25 19:21:51 api-31 docker[19023]: time="2016-08-25T19:21:51.046227326Z" level=info msg="Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon option --bip can be used to set a preferred IP address"
Aug 25 19:21:51 api-31 docker[19023]: time="2016-08-25T19:21:51.081106790Z" level=warning msg="Your kernel does not support swap memory limit."
Aug 25 19:21:51 api-31 docker[19023]: time="2016-08-25T19:21:51.081650610Z" level=info msg="Loading containers: start."
Aug 25 19:22:01 api-31 kernel: [87076.922492] docker0: port 1(vethbbc1192) entered disabled state
Aug 25 19:22:01 api-31 kernel: [87076.927128] device vethbbc1192 left promiscuous mode
Aug 25 19:22:01 api-31 kernel: [87076.927131] docker0: port 1(vethbbc1192) entered disabled state
Aug 25 19:22:03 api-31 docker[19023]: .time="2016-08-25T19:22:03.085800458Z" level=warning msg="error locating sandbox id 66ef9e1af997a1090fac0c89bf96c2631bea32fbe3c238c4349472987957c596: sandbox 66ef9e1af997a1090fac0c89bf96c2631bea32fbe3c238c4349472987957c596 not found"
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.085907328Z" level=warning msg="failed to cleanup ipc mounts:\nfailed to umount /var/lib/docker/containers/547bceaad5d121444ddc6effbac3f472d0c232d693d8cc076027e238cf253613/shm: invalid argument"
Aug 25 19:22:03 api-31 kernel: [87078.882836] device veth5c6999c entered promiscuous mode
Aug 25 19:22:03 api-31 kernel: [87078.882984] IPv6: ADDRCONF(NETDEV_UP): veth5c6999c: link is not ready
Aug 25 19:22:03 api-31 systemd-udevd[19128]: Could not generate persistent MAC address for veth5c6999c: No such file or directory
Aug 25 19:22:03 api-31 systemd-udevd[19127]: Could not generate persistent MAC address for veth39fb4d3: No such file or directory
Aug 25 19:22:03 api-31 kernel: [87078.944218] docker0: port 1(veth5c6999c) entered disabled state
Aug 25 19:22:03 api-31 kernel: [87078.948636] device veth5c6999c left promiscuous mode
Aug 25 19:22:03 api-31 kernel: [87078.948640] docker0: port 1(veth5c6999c) entered disabled state
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.219677059Z" level=error msg="Failed to start container 547bceaad5d121444ddc6effbac3f472d0c232d693d8cc076027e238cf253613: rpc error: code = 6 desc = \"mkdir /run/containerd/547bceaad5d121444ddc6effbac3f472d0c232d693d8cc076027e238cf253613: file exists\""
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.219750430Z" level=info msg="Loading containers: done."
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.219776593Z" level=info msg="Daemon has completed initialization"
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.219847738Z" level=info msg="Docker daemon" commit=b9f10c9 graphdriver=overlay version=1.11.2
Aug 25 19:22:03 api-31 systemd[1]: Started Docker Application Container Engine.
Aug 25 19:22:03 api-31 docker[19023]: time="2016-08-25T19:22:03.226116336Z" level=info msg="API listen on /var/run/docker.sock"
</code></pre>
| 1 | 2,008 |
findViewById returns null for preference layout
|
<p>I have a preference screen (responder_generic.xml) as follows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference
android:defaultValue="false"
android:key="auto_responder_key"
android:layout="@layout/preference_header_switch_item_responder"
android:title="@string/auto_responder">
</Preference>
</PreferenceScreen>
</code></pre>
<p>which i am instantiating as follows : (in version 2.3.3)</p>
<pre><code>addPreferencesFromResource(R.xml.responder_generic);
</code></pre>
<p>and my layout = <code>preference_header_switch_item_responder</code> looks as follows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout of a header item in PreferenceActivity. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="33dp"
android:gravity="center_vertical"
android:minHeight="33dp"
android:id="@+id/preference_header_switch_item_responder"
style="?android:attr/listSeparatorTextViewStyle" >
<RelativeLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:singleLine="true"
android:text="@string/auto_responder"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
android:id="@+id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@android:id/title"
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
<include layout="@layout/compound_button" />
</LinearLayout>
</code></pre>
<p>Now, i have the compound button defined in <code>layout</code> folder and <code>layout/v-14</code> respectively as follows :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<CheckBox
android:id="@+id/switchWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:focusable="false"
android:padding="8dip"
android:layout_marginRight="14dip" />
</merge>
</code></pre>
<p>and</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Switch
android:id="@+id/switchWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:focusable="false"
android:padding="8dip"
android:layout_marginRight="14dip"/>
</merge>
</code></pre>
<p>In the <code>onPostCreate</code> method, i am trying to find the this checkbox/switch at run time using <code>findViewById(R.id.switchWidget)</code> but its always returning null. </p>
<p>Any idea what could be the reason ?</p>
| 1 | 1,562 |
Rails - Refresh view after submit from different controller
|
<p>I'm having trouble refreshing a view after a form submit creates an Item on a different controller than the current view.</p>
<p>I have 2 models, Users and Items. The Users have multiple Items.</p>
<p>The Users 'show' view lists all of its Items. In the view I have a partial for rendering all the items into separate table rows:</p>
<pre><code><table class="items">
<%= render @items%>
</table>
</code></pre>
<p>In the same view I have a div at the bottom that is used for creating new Items, this div contains a Items partial (which contains a form for creating new Items):</p>
<pre><code><div id="new_item_dialog">
<%= render :partial => '/items/new_items' %>
</div>
</code></pre>
<p>This 'new_item_dialog' div is popped up into a dialog via jquery, and has :remote => true to perform the Item 'create' async: </p>
<pre><code>$('#open-dialog').click(function(){
$item_dialog.dialog('open');
});
$('.item_submit').click(function(){
$item_dialog.dialog('close');
});
</code></pre>
<p><strong>The problem I'm running into is refreshing the User's 'show' page after the new Item has been submitted.</strong> </p>
<p>A simple redirect_to the User's show page from the Item's 'create' controller doesnt refresh the data</p>
<pre><code> def create
@user = cur_user
@item = @user.items.build(params[:item])
if @item.save
redirect_to @user
else
render 'new'
end
</code></pre>
<p>I've also tried to use jQuery to load the new data:</p>
<pre><code>$('.new_item').bind('ajax:success', function()
{
$.get('/items/new_item', function (html) {
$('.items').html(html);
});
});
</code></pre>
<p>But I get the error message:</p>
<pre><code>ActionView::MissingTemplate (Missing template items/show with
</code></pre>
<p>Any help would be greatly appreciated!</p>
<p>Note: I've also tried a 'render @user' after the Item gets saved in the Item's 'create' controller, to re-render the User's 'show' view, but I get the same "MissingTemplate" error as above.</p>
<p><strong>Updated:</strong>
Also tried:</p>
<pre><code>def create
@user = cur_user
@task = @user.item.build(params[:item])
if @item.save
render :partial => "items/item"
</code></pre>
<p>And (replacing the render in the above controller)</p>
<pre><code>render :partial => @item
</code></pre>
<p>And</p>
<pre><code>render :partial => 'views/items/item', :collection => @user.items
</code></pre>
<p>And</p>
<pre><code>render :partial => 'views/items/item', :locals => { :variable => @item}
</code></pre>
<p>And</p>
<pre><code>render :action => 'users/show', :layout => 'users'
</code></pre>
<p>Everyone of these returned the error:</p>
<pre><code>ActionView::MissingTemplate (Missing template ..... with {:locale=>[:en, :en], :formats=>[:js, :"*/*"], :handlers=>[:rhtml, :rxml, :builder, :erb, :rjs]} in view paths "test/app/views"):
app/controllers/items_controller.rb:11:in `create'
</code></pre>
<p>With Ajax like this: (doesnt ever get used though, everything fails on the rendering of the partial)</p>
<pre><code>$('.new_item').bind('ajax:success', function()
{
$.ajax({
success: function(html){
$(".items").html(html);
}
});
});
</code></pre>
| 1 | 1,304 |
Can't debug C++ in VS code with gdb
|
<p>I'm trying debugging C++ in Visual Studio Code, but here is something wrong.
The debug status keeps scrolling, but no console shows. If I stop debug (shift+ F5), I won't be able to debug again. Whether click the green triangle or F5, nothing happens. <a href="https://i.stack.imgur.com/lbWq1.png" rel="nofollow noreferrer">Debug screenshot</a> <br></p>
<p>Building is OK. It's just the debug problem.<br>
MinGW has been added to PATH. I can use g++ or gdb in CMD.<br></p>
<p>My environments:</p>
<ul>
<li>OS: Windows10 1803</li>
<li>Visual Studio Code: 1.24.0</li>
<li>C/C++ extension: 0.17.4</li>
<li>MinGW_w64: x86_64-8.1.0-release-posix-seh-rt_v6-rev0</li>
</ul>
<p>Here are my configs:</p>
<p>c_cpp_properties.json:</p>
<pre><code>{
"configurations": [
{
"name": "Win32",
"includePath": [
"C:/MinGW/include",
"C:/MinGW/x86_64-w64-mingw32/include",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/backward",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/tr1",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/x86_64-w64-mingw32",
"${workspaceFolder}"
],
"defines": [
"_DEBUG",
"UNICODE"
],
"compilerPath": "C:/MinGW/bin/gcc.exe",
"intelliSenseMode": "clang-x64",
"browse": {
"path": [
"C:/MinGW/include",
"C:/MinGW/x86_64-w64-mingw32/include",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/backward",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/tr1",
"C:/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/x86_64-w64-mingw32",
"${workspaceFolder}"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
},
"cStandard": "c11",
"cppStandard": "c++17"
}
],
"version": 4
}
</code></pre>
<p>launch.json:</p>
<pre><code>{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"preLaunchTask": "build",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:/MinGW/bin/gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}]
}
</code></pre>
<p>tasks.json</p>
<pre><code>{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
},
"windows": {
"command": "g++",
"args": [
"-g",
"\"${file}\"",
"--std=c++11",
"-o",
"\"${fileDirname}\\${fileBasenameNoExtension}.exe\""
]
}
}
]
}
</code></pre>
<p>settings.json</p>
<pre><code>{
"files.associations": {
"iostream": "cpp",
"ostream": "cpp",
"cmath": "cpp",
"array": "cpp",
"chrono": "cpp",
"functional": "cpp",
"ratio": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"future": "cpp",
"streambuf": "cpp",
"sstream": "cpp",
"initializer_list": "cpp",
"valarray": "cpp"
}
}
</code></pre>
| 1 | 2,689 |
Problems Adding to NSMutableArray: attempt to insert nil object at 10
|
<p>Hey guys, so I am getting these inconsistent errors when running my program, only about 50% of the time do these errors occur, and at seemingly different points of my program. Here is the console output:</p>
<pre><code>2011-05-11 14:22:03.926 Parking[20611:1903] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 10'
*** Call stack at first throw:
(
0 CoreFoundation 0x011afbe9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x013045c2 objc_exception_throw + 47
2 CoreFoundation 0x011a97f1 -[__NSArrayM insertObject:atIndex:] + 225
3 CoreFoundation 0x011a4c44 -[__NSArrayM addObject:] + 68
4 Parking 0x000182fd -[DataLoader loadOverlaysFromStore] + 1521
5 Parking 0x00017b76 -[DataLoader main] + 64
6 Foundation 0x00c5ebd2 -[__NSOperationInternal start] + 747
7 Foundation 0x00c5e826 ____startOperations_block_invoke_2 + 106
8 libSystem.B.dylib 0x9488c024 _dispatch_call_block_and_release + 16
9 libSystem.B.dylib 0x9487e2f2 _dispatch_worker_thread2 + 228
10 libSystem.B.dylib 0x9487dd81 _pthread_wqthread + 390
11 libSystem.B.dylib 0x9487dbc6 start_wqthread + 30
)
terminate called after throwing an instance of 'NSException'
</code></pre>
<p>And:</p>
<pre><code>2011-05-11 14:16:45.171 Parking[20500:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 2'
*** Call stack at first throw:
(
0 CoreFoundation 0x011afbe9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x013045c2 objc_exception_throw + 47
2 CoreFoundation 0x011a97f1 -[__NSArrayM insertObject:atIndex:] + 225
3 CoreFoundation 0x011a4c44 -[__NSArrayM addObject:] + 68
4 Parking 0x00012887 -[CoreDataSingleton getParkingLotTitlesForPermits:] + 1030
5 Parking 0x00004891 -[ParkingMapViewController sortLotsIntoSetsAccordingToPermitsAccepted] + 616
6 Parking 0x00006317 -[ParkingMapViewController viewDidLoad] + 1474
7 UIKit 0x000fc65e -[UIViewController view] + 179
8 UIKit 0x000faa57 -[UIViewController contentScrollView] + 42
9 UIKit 0x0010b201 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48
10 UIKit 0x00109831 -[UINavigationController _layoutViewController:] + 43
11 UIKit 0x0010ab4c -[UINavigationController _startTransition:fromViewController:toViewController:] + 524
12 UIKit 0x00105606 -[UINavigationController _startDeferredTransitionIfNeeded] + 266
13 UIKit 0x0021de01 -[UILayoutContainerView layoutSubviews] + 226
14 QuartzCore 0x01a15451 -[CALayer layoutSublayers] + 181
15 QuartzCore 0x01a1517c CALayerLayoutIfNeeded + 220
16 QuartzCore 0x01a15088 -[CALayer layoutIfNeeded] + 111
17 UIKit 0x000fdb5f -[UIViewController window:willAnimateRotationToInterfaceOrientation:duration:] + 587
18 UIKit 0x000768e9 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 4347
19 UIKit 0x002f5948 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 1053
20 UIKit 0x00100982 -[UIViewController presentModalViewController:withTransition:] + 3151
21 Parking 0x0000b104 -[SampleHomeScreen appButtonTapped:] + 124
22 UIKit 0x0004ea6e -[UIApplication sendAction:to:from:forEvent:] + 119
23 UIKit 0x000dd1b5 -[UIControl sendAction:to:forEvent:] + 67
24 UIKit 0x000df647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
25 UIKit 0x000de1f4 -[UIControl touchesEnded:withEvent:] + 458
26 UIKit 0x000730d1 -[UIWindow _sendTouchesForEvent:] + 567
27 UIKit 0x0005437a -[UIApplication sendEvent:] + 447
28 UIKit 0x00059732 _UIApplicationHandleEvent + 7576
29 GraphicsServices 0x01424a36 PurpleEventCallback + 1550
30 CoreFoundation 0x01191064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
31 CoreFoundation 0x010f16f7 __CFRunLoopDoSource1 + 215
32 CoreFoundation 0x010ee983 __CFRunLoopRun + 979
33 CoreFoundation 0x010ee240 CFRunLoopRunSpecific + 208
34 CoreFoundation 0x010ee161 CFRunLoopRunInMode + 97
35 GraphicsServices 0x01423268 GSEventRunModal + 217
36 GraphicsServices 0x0142332d GSEventRun + 115
37 UIKit 0x0005d42e UIApplicationMain + 1160
38 Parking 0x00002424 main + 102
39 Parking 0x000023b5 start + 53
)
terminate called after throwing an instance of 'NSException'
</code></pre>
<p>I have run through it with a debugger and have not been able to determine at which point of my program it fails at, however, I do have an inkling it may be within this new section of code I wrote (tossed in additional retains here and there to help this error-will deal with releasing later):</p>
<pre><code>-(id)initWithFunction:(LoaderFunc)func withDelegate:(id)delegate setRestricted:(NSSet *)restricted
setA:(NSSet *)A setC:(NSSet *)C setL:(NSSet *)L {
if (self = [super init]) {
self.addedOverlays = [[NSMutableArray alloc] init];
self.addedAnnotations = [[NSMutableArray alloc] init];
self.overlayRegions = [[NSMutableArray alloc] init];
self.loaderFunc = func;
self.DLDelegate = delegate;
return self;
}
return nil;
}
//...
-(void)loadOverlaysFromStore {
NSLog(@"DataLoader.m loadOverlaysFromStore");
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *permits;
permits = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"0",@"0",@"0",nil] forKeys:[NSArray arrayWithObjects:@"A",@"C",@"L",nil]];
NSSet *setOfRestrictedLots = [[NSSet setWithArray:[[CoreDataSingleton sharedManager] getParkingLotsForPermits:permits]] retain];
NSMutableArray *arrayOfRestrictedLotTitles = [[NSMutableArray alloc] init];
for (ParkingLot *l in [setOfRestrictedLots allObjects]) {
[arrayOfRestrictedLotTitles addObject:[[l lotName]retain]];
}
permits = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"0",nil] forKeys:[NSArray arrayWithObjects:@"A",@"C",@"L",nil]];
NSSet *setOfALots = [[NSSet setWithArray:[[CoreDataSingleton sharedManager] getParkingLotsForPermits:permits]] retain];
NSMutableArray *arrayOfALotTitles = [[NSMutableArray alloc] init];
for (ParkingLot *l in [setOfALots allObjects]) {
[arrayOfALotTitles addObject:[[l lotName]retain]];
}
permits = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"1",@"0",nil] forKeys:[NSArray arrayWithObjects:@"A",@"C",@"L",nil]];
NSSet *setOfCLots = [[NSSet setWithArray:[[CoreDataSingleton sharedManager] getParkingLotsForPermits:permits]] retain];
NSMutableArray *arrayOfCLotTitles = [[NSMutableArray alloc] init];
for (ParkingLot *l in [setOfCLots allObjects]) {
[arrayOfCLotTitles addObject:[[l lotName]retain]];
}
permits = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"1",@"1",nil] forKeys:[NSArray arrayWithObjects:@"A",@"C",@"L",nil]];
NSSet *setOfLLots = [[NSSet setWithArray:[[CoreDataSingleton sharedManager] getParkingLotsForPermits:permits]] retain];
NSMutableArray *arrayOfLLotTitles = [[NSMutableArray alloc] init];
for (ParkingLot *l in [setOfLLots allObjects]) {
[arrayOfLLotTitles addObject:[[l lotName]retain]];
}
[addedOverlays addObject:setOfRestrictedLots];
[addedOverlays addObject:setOfALots];
[addedOverlays addObject:setOfCLots];
[addedOverlays addObject:setOfLLots];
for (NSSet* set in addedOverlays) {
for (ParkingLot *lot in [set allObjects]) {
ParkingRegionOverlay *regionPolygon = [[ParkingRegionOverlay alloc] initWithPoints:[lot overlayCoordPoints]
andTitle:[lot lotName]
setRestricted:[NSSet setWithArray:arrayOfRestrictedLotTitles]
setA:[NSSet setWithArray:arrayOfALotTitles]
setC:[NSSet setWithArray:arrayOfCLotTitles]
setL:[NSSet setWithArray:arrayOfLLotTitles]];
[overlayRegions addObject:regionPolygon];
[regionPolygon release];
}
}
}//loadOverlays
</code></pre>
<p>Any help greatly appreciated. Thanks!</p>
| 1 | 4,900 |
Need to populate a Dropdown combo box in Gridview, (unbound column)
|
<p>I'm having difficulty populating a dropdown list in my gridview.
I have created the column with the code below:</p>
<pre><code> If Not Me.GridViewIsConstructed Then
gv.Columns.Add(createComboBoxWithDDL(Me.ddlGPField.Items, "Bank_GP_Field_Name", "GPField"))
gv.Columns.Add(createComboBoxWithDDL(Me.ddlBankField.Items, "Bank_Bank_Field_Name", "BankField"))
End IF
Private Function createComboBoxWithDDL(ByVal obj As Object, ByVal nDataFieldName As String, ByVal nColName As String) As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn
combo.DataSource = obj
combo.DataPropertyName = nDataFieldName
combo.Name = nColName
Return combo
End Function
</code></pre>
<p>The problem is that I cannot get the formatting handle to populate the combo box with the index that I need. here is my code attempts for the BankField DropDown List.</p>
<pre><code>If e.ColumnIndex = gv.Columns("BankField").Index Then
e.FormattingApplied = True
Dim _row = gv.Rows(e.RowIndex)
Dim _cell As New DataGridViewComboBoxColumn
fillGPFieldList(_cell)
_cell.DisplayIndex = 1
_cell.DisplayMember = "Credit"
_cell.ValueMember = "Credit"
_cell.DataSource = _cell.Items
e.Value = _cell
End If
If e.ColumnIndex = gv.Columns("TrxType").Index Then
e.FormattingApplied = True
e.Value = "BAL"
End If
</code></pre>
<p>The Gridview displays the dropdown object just fine, its just always set to index -1.</p>
<p>Please help</p>
<p>V*<strong><em>*</em>**<em>*</em>**<em>*</em>***<em></strong> Addendum Edit <strong></em>**<em>*</em>**<em>*</em>****</strong>*V</p>
<p>Unfortunately, no one answered my question. So I worked around the entire problem. Its ugly and I would greatly appreciate any feedback.</p>
<p>I was never able to get the ComboBox to bind to the data source. I tried everything until I turned blue. So I went to the basics and coded all the automatic stuff. I'm curious as to why the automatic binding didn't work. Perhaps its because my gridview datasource was LINQ.</p>
<p>Here is how I pulled it off. I hope someone down the road benefits from the last 48 hours of my delima:</p>
<p>First of all, know that I have two drop down lists on my form, one is the GPField and the other is the BankField. These are already populated DDLs that are static. So I used them to cheat on the values instead of using enums.</p>
<p>I don't think it matters, but here is how I fill the GPField and BankField:</p>
<pre><code> Sub fillGPFieldListDDL(ByVal obj As Object)
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the GP Field list
obj.Items.Clear()
For Each fld In db.getGPFieldList(Me.ddlImportID.SelectedItem, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
Sub fillBankFieldListDDL(ByVal obj As Object)
If String.IsNullOrEmpty(ddlImportID.Text) Then
Return
End If
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the Bank Field list
obj.Items.Clear()
For Each fld In db.getImportIDVirtualFields(Me.ddlImportID.Text, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
</code></pre>
<p>Next, based on a selection from the user, I populate my grid with the following function:</p>
<pre><code> Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
ColumnNameData.Bank_Bank_Field_Number.ToString, _
FieldNames.BankField.ToString)
gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
gv.Rows.Clear()
Dim ri As Integer = 0
For Each r In _query3
Dim _row As New DataGridViewRow
_row.CreateCells(gv)
_row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
_row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
gv.Rows.Add(_row)
ri += 1
Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
</code></pre>
<p>So, the unanswered questions are:
1). I couldn't use the _query or _query2 as datasources for the gridview, but _query3 did work for simple textboxes.
2). If using _query3 as the gv.datasource, why would my combobox throw "bank_gp_field_name" not found error when the gv.Columns.Add(_comboCol) was executed
3). I understand the reason I couldn't do a gv bind to _query3 because of the data in Bank_Bank_field_number is an integer and the DDL values don't have a translation between the integer and the string value. But I commented out that field expecting the GPField to operate on a standard bind. I still got the "Field called "Bank_GP_Field_Name" does not exist on gv.Columns.Add(_comboCol)</p>
<p>So, summed up, why doesn't the code below work whereas the one above does?</p>
<pre><code> Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
'_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
' ColumnNameData.Bank_Bank_Field_Number.ToString, _
' FieldNames.BankField.ToString)
'gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
'gv.Rows.Clear()
'Dim ri As Integer = 0
'For Each r In _query3
' Dim _row As New DataGridViewRow
' _row.CreateCells(gv)
' _row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
' _row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
' gv.Rows.Add(_row)
' ri += 1
'Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
Private Function CreateComboBoxColumn(ByVal obj As ComboBox.ObjectCollection, ByVal nDataFieldName As String, ByVal nColName As String) _
As DataGridViewComboBoxColumn
Dim column As New DataGridViewComboBoxColumn()
With (column)
.HeaderText = nColName
.DropDownWidth = 160
.Width = 90
.MaxDropDownItems = 3
.FlatStyle = FlatStyle.Flat
.DataSource = obj
.DataPropertyName = nDataFieldName
.Name = nColName
.ValueMember = nDataFieldName
.DisplayMember = .ValueMember
End With
Return column
End Function
</code></pre>
| 1 | 5,624 |
`require': cannot load such file -- HTTParty (LoadError)
|
<p>First off I'm a Newbie in regards to Ruby, and I'm following the simple tutorial on <a href="https://www.distilled.net/resources/web-scraping-with-ruby-and-nokogiri-for-beginners/" rel="nofollow noreferrer">https://www.distilled.net/resources/web-scraping-with-ruby-and-nokogiri-for-beginners/</a></p>
<p>I have a <code>test.rb</code> file that contains the following:</p>
<pre><code>require 'rubygems'
require 'Nokogiri'
require 'HTTParty'
require 'Pry'
require 'csv'
# this is how we request the page we're going to scrape
page = HTTParty.get('https://newyork.craigslist.org/search/pet?s=0')
Pry.start(binding)
</code></pre>
<p>When I try to run the ruby test script, I get the following error:</p>
<pre><code>pjw@ubuntu:~/ruby/test$ ruby test.rb
/home/pjw/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- HTTParty (LoadError)
from /home/pjw/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from test.rb:1:in `<main>'
</code></pre>
<p>I've verified HTTParty works properly by running:</p>
<pre><code>httparty "https://newyork.craigslist.org/search/pet?s=0"
</code></pre>
<p>The problem seems to be the <code>require</code> statement. If I mix the order or the required gems, the first one gives the same error as above. I've searched online and can't seem to find what I'm missing...</p>
<ul>
<li><a href="https://stackoverflow.com/questions/30584455/in-require-cannot-load-such-file-httparty-loaderror">in `require': cannot load such file -- httparty (LoadError)</a> - (No Answer)</li>
<li><a href="https://stackoverflow.com/questions/21831880/kernel-require-rb55in-require-cannot-load-such-file-error">kernel_require.rb:55:in `require': cannot load such file error</a> - (bundle exec ruby test.rb "Could not locate Gemfile or .bundle/ directory")</li>
<li><a href="https://stackoverflow.com/questions/33678945/unable-to-run-rb-files-on-mac-getting-rbenv-versions-2-2-3-lib-ruby-site-ru">Unable to run .rb files on mac - getting /.rbenv/versions/2.2.3/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'</a> - (GEMS already Installed)</li>
</ul>
<hr>
<pre><code>pjw@ubuntu:~/ruby/test$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.1 LTS
Release: 16.04
Codename: xenial
pjw@ubuntu:~/ruby/test$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
pjw@ubuntu:~/ruby/test$ gem list
*** LOCAL GEMS ***
actioncable (5.0.0.1)
actionmailer (5.0.0.1)
actionpack (5.0.0.1)
actionview (5.0.0.1)
activejob (5.0.0.1)
activemodel (5.0.0.1)
activerecord (5.0.0.1)
activesupport (5.0.0.1)
addressable (2.5.0)
arel (7.1.4)
autoprefixer-rails (6.5.3, 6.5.2, 6.5.1)
bcrypt (3.1.11)
bigdecimal (default: 1.2.8)
bootstrap (4.0.0.alpha5)
bootstrap-datepicker-rails (1.6.4.1)
bootstrap-sass (3.3.7)
builder (3.2.2)
bundler (1.13.6)
bundler-unload (1.0.2)
byebug (9.0.6)
cancancan (1.15.0)
coderay (1.1.1)
coffee-rails (4.2.1)
coffee-script (2.4.1)
coffee-script-source (1.10.0)
commonjs (0.2.7)
concurrent-ruby (1.0.2)
connection_pool (2.2.1, 2.2.0)
dashing-rails (2.5.0)
debug_inspector (0.0.2)
devise (4.2.0)
did_you_mean (1.0.2, 1.0.0)
erubis (2.7.0)
execjs (2.7.0)
executable-hooks (1.3.2)
ffi (1.9.14)
figaro (1.1.1)
gem-wrappers (1.2.7)
geocoder (1.4.0)
globalid (0.3.7)
gravatarify (3.1.1)
httparty (0.14.0)
i18n (0.7.0)
io-console (0.4.6, default: 0.4.5)
jbuilder (2.6.0)
jquery-rails (4.2.1)
json (2.0.2, default: 1.8.3)
less (2.6.0)
less-rails (2.8.0)
listen (3.1.5, 3.0.8)
loofah (2.0.3)
mail (2.6.4)
method_source (0.8.2)
mime-types (3.1)
mime-types-data (3.2016.0521)
mini_portile2 (2.1.0)
minitest (5.9.1, 5.8.3)
multi_json (1.12.1)
multi_xml (0.5.5)
net-telnet (0.1.1)
nio4r (1.2.1)
nokogiri (1.6.8.1)
orm_adapter (0.5.0)
power_assert (0.3.1, 0.2.6)
pry (0.10.4)
psych (2.1.1, default: 2.0.17)
public_activity (1.5.0)
public_suffix (2.0.4)
puma (3.6.0)
rack (2.0.1)
rack-test (0.6.3)
rails (5.0.0.1)
rails-dom-testing (2.0.1)
rails-html-sanitizer (1.0.3)
rails_serve_static_assets (0.0.5)
rails_stdout_logging (0.0.5)
railties (5.0.0.1)
rake (11.3.0, 10.4.2)
rb-fsevent (0.9.8)
rb-inotify (0.9.7)
rdoc (5.0.0, default: 4.2.1)
redis (3.3.1)
responders (2.3.0)
ruby_dep (1.5.0)
rubygems-bundler (1.4.4)
rubygems-update (2.6.8)
rufus-scheduler (3.2.2)
rvm (1.11.3.9)
sass (3.4.22)
sass-rails (5.0.6)
simple_calendar (2.2.0)
simple_form (3.3.1)
slop (4.4.1, 3.6.0)
spring (2.0.0)
spring-watcher-listen (2.0.1)
sprockets (3.7.0)
sprockets-rails (3.2.0)
sqlite3 (1.3.12)
table_print (1.5.6)
test-unit (3.2.2, 3.1.5)
thor (0.19.1)
thread_safe (0.3.5)
tilt (2.0.5)
turbolinks (5.0.1)
turbolinks-source (5.0.0)
twitter-bootstrap-rails (3.2.2)
tzinfo (1.2.2)
uglifier (3.0.3, 3.0.2)
warden (1.2.6)
web-console (3.4.0, 3.3.1)
websocket-driver (0.6.4)
websocket-extensions (0.1.2)
wunderground (1.2.0)
</code></pre>
| 1 | 2,448 |
Prevent Socket IO from ping timeout on inactive or not focused browser page on Chrome, firefox & Safari mobile browsers
|
<p>I have a simple <a href="https://socket.io/get-started/chat" rel="noreferrer">chat</a> app using socket io. Very similar to the socket io chat official demo. Socket io goes to ping timeout on all mobile browsers whenever the user minimizes the page or opens another app or page gets out of foucs.</p>
<p>In my web app whenever, the user clicks on file input upload from their chrome/firefox/safari browser on mobile, it opens up the phone dialog box to select the file from galley to select and upload. During this time (my chat page gets out of focus due to visibility), when user is searching for a file, and after exact 30 seconds, socket io client issues ping timeout, and the person chat is disconnected. </p>
<p>In my application level, i am doing a reconnect if socket io goes to ping timeout for whatever reason, but that doesn't fix my problem, because if the user clicks on 1 file after 31 seconds, then that image file is not sent in chat, because socket io was timed out during that time, and it takes few seconds to reconnect, when the user's focus is back on the browser tab. So the file upload action is lost, because file is uploaded but socket io connection was on ping timeout. so when it reconnects, the selected file upload is never sent to the other connected user.</p>
<p>I tried detecting whenever user's page focus is out, using this code, </p>
<pre><code>document.addEventListener("visibilitychange", onchange);
</code></pre>
<p>from <a href="https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active">Is there a way to detect if a browser window is not currently active?</a></p>
<p>and then once page is not in focus, i used setinterval to emit my custom heartbeat event to my server code. (just to keep socket io from talking to server to keep connection alive).. This works fine for desktop browsers, But on all mobile browsers, whenever user's page is not in focus, i.e if a user minimizes the browser, opens a new app, or goto select file upload screen, socket io times out after 30 seconds or sometimes even faster then this. </p>
<p>My client js code:</p>
<pre><code>var beating;
//function to detect if user gone out of page
//startSimulation and pauseSimulation defined elsewhere
function handleVisibilityChange() {
//socket = this.socket;
if (document.hidden) {
// console.log();
$('#logwrapper').prepend(" üser is outside \n ", socket.id);
//emit on server after every 10 seconds
beating = setInterval(function () {
$('#logwrapper').prepend(" inside interval emitting");
socket.emit('heartbeat', { data: "a" });
}, 15000)
} else {
//console.log("üser is in");
$('#logwrapper').prepend(" üser is in \n ", socket.id);
console.log("çlearing inteval beating from visiblity");
clearInterval(beating);
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);
</code></pre>
<p>And my server.js code</p>
<pre><code>
//socket events for heartbeat
socket.on("heartbeat", function (data) {
console.log("socket is outside ", data, socket.id);
});
//socket events for heartbeat , just log it so that my client remains active and keep communicating with server, to avoid socket io timeout
</code></pre>
<p>I also tried adjusting my socket io server & client timeout configs, but that is not making any difference, after user minimise the browser page on mobile, chorme, firefox & safari, socket io client emits ping timeout after 30 seconds or so, </p>
<p><strong>How can i increase this timeout, so socket io connection remains active (don't ping timeout) for longer time (as much as i want)?</strong></p>
<p>Here are my server.js configs for socket io:</p>
<pre><code>
var io = require("socket.io")(
231, {
transports: ["websocket", "polling"]
},
server, {
path: '/socket.io',
serveClient: true,
// below are engine.IO options
pingInterval: 25000, //was 10k, how many ms before sending a new ping packet, => how often to send a ping
pingTimeout: 30000, //should be above 30k to fix disconnection issue how many ms without a pong packet to consider the connection closed
upgradeTimeout: 20000, // default value is 10000ms, try changing it to 20k or more
agent: false,
cookie: false,
rejectUnauthorized: false,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
maxHttpBufferSize: 100000000 //100 mb
}
);
</code></pre>
<p>and my socket io client configs:</p>
<pre><code>
this.socket = io.connect('https://appurl.com', {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
//our site options
transports: ["polling", "websocket"],
secure: true,
rejectUnauthorized: false,
forceNew: false,
timeout: 60000
});
</code></pre>
<p>Basically on all mobile browsers, as long as page gets out of focus, my JS code stops executing, and whenever the page focused again, JS exection resumes, looks like its not a problem with setinterval or settimeout. How can i keep executing my client JS code to keep socket io from doing ping timeout?</p>
<p>I also tried a similar logic using settimeout, <a href="https://codepen.io/Suhoij/pen/jAxtn" rel="noreferrer">https://codepen.io/Suhoij/pen/jAxtn</a></p>
<p>this code works in codepen on all mobile browsers, even if i minimise this page on my mobile and come back again, the timer is still executing, but the same code when i run on my app, it doesn't work in my code. Why? Is socket io pausing my all client.js code when page is not in focus? OR is my logic not correct? I also tried emitting an event from my server.js after every 2 second to all clients, but the emits stop when page is not in foucs on mobile :/</p>
<p>Relevant socket io issues:
<a href="https://github.com/socketio/socket.io/issues/2769" rel="noreferrer">https://github.com/socketio/socket.io/issues/2769</a></p>
| 1 | 1,823 |
Cannot run a React app with WebStorm
|
<p>I am totally new to React and I am trying to follow the examples on <a href="https://reactjs.org/community/examples.html" rel="noreferrer">react official website</a>.</p>
<p>While running the calculator app(index.js) using WebStorm OR intellij idea ultimate </p>
<p><a href="https://i.stack.imgur.com/OxNsn.png" rel="noreferrer"><strong>output of npm run start or npm start</strong></a> </p>
<p>And i get this error:</p>
<pre><code>(function (exports, require, module, __filename, __dirname) { import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Process finished with exit code 1
</code></pre>
<p>My question is how to run such an app using intellij idea ultimate What i tried:</p>
<pre><code>npm install -g create-react-app
npm install -g eslint
npm install --save-dev babel-preset-es2015
npm install --save-dev babel-core babel-preset-es2015 babel-preset-react
npm install -g eslint babel-eslint eslint-plugin-react eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-flowtype
</code></pre>
<p>And adding the following to package.json:</p>
<pre><code>"babel": {
"presets": [ "es2015", "react" ]
}
</code></pre>
<p>Or to .babelrc </p>
<pre><code>{
"presets": [ "es2015", "react" ]
}
</code></pre>
<p>My question is how to run such an app using intellij idea ultimate package.json</p>
<pre><code>{
"name": "emoji-search",
"version": "0.1.0",
"private": true,
"homepage": "http://ahfarmer.github.io/emoji-search",
"devDependencies": {
"gh-pages": "^1.1.0",
"react-scripts": "^1.0.17"
},
"dependencies": {
"github-fork-ribbon-css": "^0.2.1",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"deploy": "gh-pages -d build"
},
"eslintConfig": {
"extends": "./node_modules/react-scripts/config/eslint.js"
},
"babel": {
"presets": [ "es2015", "react" ]
}
}
</code></pre>
<p>(My question is how to run such an app using intellij idea ultimate )</p>
| 1 | 1,122 |
specify .so files in build.gradle file android studio
|
<p>This is my Directory Structure</p>
<pre><code>src -main
-java
-jniLibs
-armeabi
-lib1.so
-lib2.so
</code></pre>
<p><strong><em>Need to understand what piece of code should be written in build gradle file for these files to be included in the build.
Right now, i am getting the error of not finding the .so file.</em></strong></p>
<pre><code> java.lang.UnsatisfiedLinkError: nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libFPEComponent.so"
</code></pre>
<p>Following <a href="https://stackoverflow.com/a/44932104/4075178">solution by H.Brooks</a></p>
<p>I have got to add here </p>
<p><a href="https://i.stack.imgur.com/obgcJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/obgcJ.png" alt="enter image description here"></a></p>
<p><a href="https://github.com/vikas0/BiometricRecordSample" rel="nofollow noreferrer">My Git repository:</a></p>
<p>My bUild.gradle file</p>
<pre><code> apply plugin: 'com.android.application'
android {
productFlavors {
arm {
ndk {
abiFilters "armeabi-v7a", "armeabi"
}
}
}
sourceSets
{
main
{
jniLibs.srcDirs = ['src/main/jnilibs']
}
//Another code
}
compileSdkVersion 26
buildToolsVersion '26.0.0'
defaultConfig {
applicationId "com.goambee.biometricziqitza"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
splits {
// Configures multiple APKs based on ABI.
abi {
// Enables building multiple APKs per ABI.
enable true
// By default all ABIs are included, so use reset() and include to specify that we only
// want APKs for x86, armeabi-v7a, and mips.
// Resets the list of ABIs that Gradle should create APKs for to none.
reset()
// Specifies a list of ABIs that Gradle should create APKs for.
include "armeabi-v7a"
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk false
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
// compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}
//task native-libstiveLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
// destinationDir file("$buildDir/native-libs")
// baseName 'native-libs'
// from fileTree(dir: 'src/main/jnilibs', include: '**/*.so')
// into 'lib/'
//}
//
//tasks.withType(JavaCompile)
// {
// compileTask -> compileTask.dependsOn(nativeLibsToJar)
// }
</code></pre>
<p><strong>Here i have included source set block, i also had tested without that block.</strong>
<strong>So still build isn't able to access .so files.</strong></p>
| 1 | 1,625 |
The Navigation Architecture Component animation
|
<p>I've been following the sample from <a href="https://github.com/googlesamples/android-architecture-components/tree/master/NavigationBasicSample" rel="noreferrer">NavigationBasicSample</a></p>
<p>but used newest library for navigation:</p>
<pre><code>implementation "android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha05"
implementation "android.arch.navigation:navigation-ui-ktx:1.0.0-alpha05"
</code></pre>
<p>and androidx library:</p>
<pre><code>implementation 'androidx.core:core-ktx:1.0.0-rc01'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
implementation 'com.google.android.material:material:1.0.0-rc01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0-rc01'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0-rc01'
</code></pre>
<p>and add to bundle.gradle</p>
<pre><code>androidExtensions {
experimental = true
}
</code></pre>
<p>all works except animation. It is bug maybe or ?</p>
<p>this is my nav_graph:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@+id/categoryFragment">
<fragment
android:id="@+id/categoryFragment"
android:name="com.sample.CategoriesFragment"
android:label="Categories"
tools:layout="@layout/fragment_categories">
<action
android:id="@+id/action_categoryFragment_to_itemsFragment"
app:destination="@id/itemsFragment"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left" />
</fragment>
<fragment
android:id="@+id/itemsFragment"
android:name="com.sample.ItemsFragment"
android:label="Items"
tools:layout="@layout/fragment_items" >
<argument android:name="cat_id" android:defaultValue="-1" />
</fragment>
</navigation>
</code></pre>
<p>and my navhost fragment:</p>
<pre><code><fragment
android:id="@+id/fragment_nav_host"
app:defaultNavHost="true"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_graph"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
</code></pre>
| 1 | 1,196 |
How to work correctly with Forms, FOS Rest Bundle and many to many relations in Symfony2
|
<p>I'm working with Symfony2 Forms and FOSRestBundle.</p>
<p>I'm trying to save in the database, an entity with a many to many relationship.</p>
<p>I create a Form with a collection field (<a href="http://symfony.com/doc/master/cookbook/form/form_collections.html" rel="noreferrer">http://symfony.com/doc/master/cookbook/form/form_collections.html</a>) like this:</p>
<pre><code>class MainType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('description');
$builder->add('others', 'collection', array(
'type' => new OtherType()
));
}
public function getName()
{
return '';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\SearchBundle\Entity\Main',
'csrf_protection' => false
));
}
}
class OtherType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id');
}
public function getName()
{
return '';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\SearchBundle\Entity\Other',
'csrf_protection' => false
));
}
}
</code></pre>
<p>The collection of objects of type "Other" is stored in the database. And I don't want to store more objects of that type, only read and relate them to the main object.</p>
<p>When I process the form I use this function:</p>
<pre><code>private function processForm(Main $main, $new = false)
{
$new = true;
$statusCode = $new ? 201 : 204;
$form = $this->createForm(new MainType(), $main);
$form->bind($this->getRequest());
if ($form->isValid()) {
$mainValidated = $form->getData();
// I should store the collection of objects of type other
// in the database
$em = $this->getDoctrine()->getEntityManager();
$em->persist($mainValidated);
$em->flush();
return $this->view($new ? $mainValidated : null, $statusCode);
}
return $this->view($form, 400);
}
</code></pre>
<p>The code json I send from a client Backbone.js is:</p>
<pre><code>{"others":[{"id":1}, {"id":2}]}
</code></pre>
<p>Entities:</p>
<ul>
<li>Main</li>
</ul>
<p>Xml:</p>
<pre><code> <entity name="Acme\SearchBundle\Entity\Main" table="main">
<id name="id type="integer" column="id">
<generator strategy="IDENTITY"/>
</id>
<field name="name" type="integer" column="name" nullable="true"/>
<field name="description" type="integer" column="description" nullable="true"/>
<many-to-many field="others" target-entity="Other" inversed-by="mains">
<cascade>
<cascade-persist/>
</cascade>
<join-table name="main_has_other">
<join-columns>
<join-column name="main" referenced-column-name="id"/>
</join-columns>
<inverse-join-columns>
<join-column name="other" referenced-column-name="id"/>
</inverse-join-columns>
</join-table>
</many-to-many>
</entity>
</code></pre>
<p>Entity:</p>
<pre><code><?php
namespace Acme\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\Expose;
class Main
{
/**
* @Type("integer")
* @Groups({"admin"})
*
* @var integer
*
*/
private $id;
/**
*
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $name;
/**
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $description;
/**
* @Type("ArrayCollection<Acme\SearchBundle\Entity\Other>")
* @Groups({"manage"})
*
* @var \Doctrine\Common\Collections\Collection
*/
private $others;
/**
* Constructor
*/
public function __construct()
{
$this->others = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set name
*
* @param string $name
* @return Main
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
* @return Main
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add others
*
* @param \Acme\SearchBundle\Entity\Other $other
* @return Main
*/
public function addOthers(\Acme\SearchBundle\Entity\Other $other)
{
$this->others[] = $other;
return $this;
}
/**
* Remove others
*
* @param \Acme\SearchBundle\Entity\Other $other
*/
public function removeOthers(\Acme\SearchBundle\Entity\Other $other)
{
$this->others->removeElement($other);
}
/**
* Get others
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getOthers()
{
return $this->others;
}
}
</code></pre>
<ul>
<li>Other</li>
</ul>
<p>Xml:</p>
<pre><code><entity name="Acme\SearchBundle\Entity\Other" table="other">
<id name="id" type="integer" column="id">
<generator strategy="IDENTITY"/>
</id>
<field name="name" type="string" column="name" length="255" nullable="true"/>
<field name="description" type="string" column="name" length="255" nullable="true"/>
<many-to-many field="mains" target-entity="Main" mapped-by="others">
<cascade>
<cascade-persist/>
</cascade>
</many-to-many>
</entity>
</code></pre>
<p>Entity:</p>
<pre><code><?php
namespace Acme\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Groups;
class Other
{
/**
* @Type("integer")
* @Groups({"manage"})
*
* @var integer
*/
private $id;
/**
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $name;
/**
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $description;
/**
* @Type("Acme\SearchBundle\Entity\Main")
* @Groups({"admin"})
*
* @var \Doctrine\Common\Collections\Collection
*/
private $mains;
/**
* Constructor
*/
public function __construct()
{
$this->mains = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set name
*
* @param string $name
* @return Other
*/
public function setName($name)
{
$this->name = $name
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
* @return Other
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* @param integer $id
* @return Other
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Add main
*
* @param \Acme\SearchBundle\Entity\Main $main
* @return Other
*/
public function addMains(\Acme\SearchBundle\Entity\Main $main)
{
$this->mains[] = $main;
return $this;
}
/**
* Remove main
*
* @param \Acme\SearchBundle\Entity\Main $main
*/
public function removeMains(\AcmeSearchBundle\Entity\Main $main)
{
$this->mains->removeElement($main);
}
/**
* Get mains
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMains()
{
return $this->mains;
}
}
</code></pre>
<p>When I persist the object of type "main" in the database, the collection is not persited in the table of many to many relationship. I have to save the collection manually when persist the "main" object. </p>
<p>I'm looking for a way to save the collection of objects automatically as easy as possible.</p>
| 1 | 4,278 |
how to implement Jquery datatable along with sortable()
|
<p>I am trying to implement data-table to create some schedule and the rows in the table are draggable. I used sortable to implement this functionality
this is my html Code.</p>
<pre><code><link href="~/NewFolder1/jquery.dataTables.min.css" rel="stylesheet" />
<link href="~/NewFolder1/dataTables.tableTools.css" rel="stylesheet" />
<link href="~/mycss/Sortable.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/NewFolder1/jquery-1.10.2.js"></script>
<script src="~/NewFolder1/jquery-ui.js"></script>
<script src="~/JScripts/jquery.dataTables.min.js"></script>
<script src="~/NewFolder1/dataTables.tableTools.js"></script>
<script src="~/JScripts/Sortable.js"></script>
<div id="Dataelements">
<div id="Left-Content" style="width:50%;float:left;">
</div>
<div id="Right-Content" style="width:49.5%;float:left;" >
<table id="example" class="display">
<caption>Create Your Template</caption>
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Duration</td>
</tr>
</thead>
<tbody id="sortable" >
</tbody>
</table>
</div>
</div>
<br /><br />
<hr />
<input type="submit" value="submit" id="button1"style="text-align:center;margin-top:50px;float:left;" />
</code></pre>
<p>Now some of code in my JS file are</p>
<pre><code> $("#sortable").sortable();
$('table#example').dataTable({
"aaSorting": [],
});
var table = $('table#example').dataTable().api();
$("#button1").click(function () {
var rows = $("#example").dataTable().fnGetNodes();
var cells = [];
for (var i = 0; i < rows.length; i++) {
cells.push($(rows[i]).find("td:eq(0)").html());
}
alert(cells);
});
</code></pre>
<p>Now after i click the button i am retrieving the 1st column of my table
Suppose at the start table=</p>
<blockquote>
<p>1 HTML 2</p>
<p>2 PHP 5</p>
<p>3 JS 4</p>
</blockquote>
<p>And after dragging and changing order</p>
<blockquote>
<p>2 PHP 5</p>
<p>3 JS 4</p>
<p>1 HTML 2</p>
</blockquote>
<p>but when i click on submit button i am getting output as 1,2,3 not as 2,3,1
Is there any way to save the state of rows after i drag and change the order.
The code was working fine with normal tables but not with Data Table</p>
| 1 | 1,587 |
How to add g729 codec in Android application?
|
<p>i am developing a SIP application for making and receiving a call and i want to add the G729 codec in my application.</p>
<p>currently i am doing analysis on open source project <a href="http://code.google.com/p/sipdroid/" rel="nofollow">SipDroid</a>. if i want to make that application to support G729 codec how to do that?</p>
<p>there is a different codecs configuration file in <a href="http://code.google.com/p/sipdroid/source/browse/#svn%2Ftrunk%2Fsrc%2Forg%2Fsipdroid%2Fcodecs" rel="nofollow">org.sipdroid.codecs</a> package.how do create the this kind of .java file for G729 codec?</p>
<p>Any suggestion and response will be appreciated.</p>
<p>Log message of asterisk</p>
<pre><code>Found RTP audio format 101
Found audio description format telephone-event for ID 101
Found RTP video format 103
Found video description format h263-1998 for ID 103
Capabilities: us - 0x100 (g729), peer - audio=0x0 (nothing)/video=0x100000 (h263p)/text=0x0 (nothing), combined - 0x0 (nothing)
Non-codec capabilities (dtmf): us - 0x1 (telephone-event|), peer - 0x1 (telephone-event|), combined - 0x1 (telephone-event|)
[Apr 9 18:00:25] NOTICE[3813]: chan_sip.c:9187 process_sdp: **No compatible codecs**, not accepting this offer!
</code></pre>
<p><strong>SDP</strong></p>
<pre><code>To: <sip:5003@192.168.1.17>
From: <sip:5004@192.168.1.17>;tag=z9hG4bK80811693
Call-ID: 082004294635@10.0.2.15
CSeq: 2 INVITE
Contact: <sip:5004@10.0.2.15:36252;transport=udp>
Expires: 3600
User-Agent: MySipdroid. !/2.4 beta/sdk
Authorization: Digest username="5004", realm="asterisk", nonce="6264308a", uri="sip:5003@192.168.1.17", algorithm=MD5, response="fb6dfb528d362657ef01458f96653adb"
Content-Length: 137
Content-Type: application/sdp
v=0
o=5004@192.168.1.17 0 0 IN IP4 10.0.2.15
s=Session SIP/SDP
c=IN IP4 10.0.2.15
t=0 0
m=audio 21000 RTP/AVP
a=fmtp:18 annexb=no
<------------->
--- (13 headers 7 lines) ---
Sending to 192.168.1.17:35370 (NAT)
Using INVITE request as basis request - 082004294635@10.0.2.15
Found peer '5004' for '5004' from 192.168.1.17:35370
== Using SIP RTP CoS mark 5
Capabilities: us - 0x100 (g729), peer - audio=0x0 (nothing)/video=0x0 (nothing)/text=0x0 (nothing), combined - 0x0 (nothing)
Non-codec capabilities (dtmf): us - 0x1 (telephone-event|), peer - 0x0 (nothing), combined - 0x0 (nothing)
[Apr 10 12:01:05] NOTICE[3524]: chan_sip.c:9187 process_sdp: No compatible codecs, not accepting this offer!
</code></pre>
<p><strong>Result of Show Translation</strong></p>
<pre><code>core show translation
Translation times between formats (in microseconds) for one second of data
Source Format (Rows) Destination Format (Columns)
g723 gsm ulaw alaw g726aal2 adpcm slin lpc10 g729 speex ilbc g726 g722 siren7 siren14 slin16 g719 speex16 testlaw
g723 - - - - - - - - - - - - - - - - - - -
gsm - - 1001 1001 3000 2000 1000 3000 3999 - 8999 3999 1001 - - 1002 - - 1001
ulaw - 2000 - 1 2001 1001 1 2001 3000 - 8000 3000 2 - - 3 - - 2
alaw - 2000 1 - 2001 1001 1 2001 3000 - 8000 3000 2 - - 3 - - 2
g726aal2 - 2999 1001 1001 - 2000 1000 3000 3999 - 8999 3999 1001 - - 1002 - - 1001
adpcm - 2000 2 2 2001 - 1 2001 3000 - 8000 3000 2 - - 3 - - 2
slin - 1999 1 1 2000 1000 - 2000 2999 - 7999 2999 1 - - 2 - - 1
lpc10 - 2999 1001 1001 3000 2000 1000 - 3999 - 8999 3999 1001 - - 1002 - - 1001
g729 - 2999 1001 1001 3000 2000 1000 3000 - - 8999 3999 1001 - - 1002 - - 1001
speex - - - - - - - - - - - - - - - - - - -
ilbc - 2998 1000 1000 2999 1999 999 2999 3998 - - 3998 1000 - - 1001 - - 1000
g726 - 2999 1001 1001 3000 2000 1000 3000 3999 - 8999 - 1001 - - 1002 - - 1001
g722 - 2000 2 2 2001 1001 1 2001 3000 - 8000 3000 - - - 1 - - 2
siren7 - - - - - - - - - - - - - - - - - - -
siren14 - - - - - - - - - - - - - - - - - - -
slin16 - 3000 1002 1002 3001 2001 1001 3001 4000 - 9000 4000 1000 - - - - - 1002
g719 - - - - - - - - - - - - - - - - - - -
speex16 - - - - - - - - - - - - - - - - - - -
testlaw - 2000 2 2 2001 1001 1 2001 3000 - 8000 3000 2 - - 3 - - -
</code></pre>
<p><strong>sip.conf</strong></p>
<pre><code>[5004]
type=friend
username=5004
secret=5004
host=dynamic
context=testcontext
nat=yes
disallow=all
allow=g729
qualify=yes
callerid="919999121312"<5004>
</code></pre>
| 1 | 3,047 |
Why triggers try to insert NULL value when using a field from 'inserted' table?
|
<p>I have to sync changes done in MSSQL with a remote MySQL database. The changes to be synced are adding invoices and users to the system. The remote server is not expected to be always reachable so I'm trying to set up a kind of log table for storing changes done in MSSQL.</p>
<p>Here is a fully working trigger for that:</p>
<pre><code>CREATE TRIGGER [dbo].[dokument_insert]
ON [dbo].[dokument]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [bcg_ekodu].[dbo].[sync_stack] (event,sql, table_name, import_priority)
SELECT
'INSERT',
'INSERT INTO bills SET
date = "'+CONVERT(VARCHAR(19),dok_kuup,120)+'",
total = "'+CAST(kokkusum AS nvarchar)+'",
number = "'+RTRIM(dok_nr)+'",
created = "'+CONVERT(VARCHAR(19),savetime,120)+'",
rounded = "'+CAST(ymardus AS nvarchar)+'",
currency = "'+CAST(valuuta AS nvarchar)+'",
due_date = "'+CONVERT(VARCHAR(19),tasupaev,120)+'",
pk_joosep = "'+CAST(dok_kood AS nvarchar)+'",
joosep_hankija = "'+CAST(hankija AS nvarchar)+'";
UPDATE
bills, users, companies
SET
bills.user_id = users.id,
bills.imported = NOW()
WHERE
bills.imported IS NULL
AND companies.id = users.company_id
AND companies.pk_joosep = 10
AND bills.user_id = users.pk_joosep',
'bills',
'200'
FROM inserted
END
</code></pre>
<p>It inserts a row into 'sync_stack' table every time a row is inserted to 'dokument' table. The 'sql' column will contain an SQL to create the same kind of row in another (MySQL) database.</p>
<p>But this trigger is not working:</p>
<pre><code>CREATE TRIGGER [dbo].[klient_insert]
ON [dbo].[klient]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [bcg_ekodu].[dbo].[sync_stack] (event,sql, table_name, import_priority)
SELECT
'INSERT',
'INSERT INTO users SET
username =10'+CAST(kl_kood as nvarchar)+',
password = NULL,
name ="'+LTRIM(RTRIM(kl_nimi))+'",
email ="'+CAST(LTRIM(RTRIM(kl_email)) as nvarchar)+'",
reference_no ="'+CAST(LTRIM(RTRIM(kl_viide)) as nvarchar)+'",
phone ="'+CAST(LTRIM(RTRIM(kl_tel1)) as nvarchar)+'",
logins ="'+CAST(0 as nvarchar)+'",
last_login = NULL,
created ="'+CONVERT(VARCHAR(19),savetime,120)+'",
updated = NULL,
deleted ="0",
address ="'+CAST(LTRIM(RTRIM(kl_aadr1)) as nvarchar)+'",
pk_joosep ="'+CAST(kl_kood as nvarchar)+'"',
'users',
'210'
FROM inserted
END
</code></pre>
<p>While the execution of the above SQL to create that trigger completes just fine, when I try to insert some rows to the 'triggered' table, I get the following error:</p>
<pre><code>No row was updated.
The data in row 175 was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message: Cannot insert the value NULL into column 'sql', table 'mydb.dbo.sync_stack'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Correct the errors and retry or press ESC to cancel the change(s).
</code></pre>
<ul>
<li>If I delete this trigger, this error does not occur.</li>
<li>If I insert just plain text for 'sql' column, it works as expected. </li>
<li>If I use any field from the inserted row, even just a text field, it fails again.</li>
<li>If I allow NULL values in 'sql' column, inserting rows succeeds but I get a NULL value in 'sql' column.</li>
</ul>
<p>How to make the second trigger work as expected, too?</p>
| 1 | 1,837 |
Bootstrap carousel Not functional
|
<p>I'm working in Laravel 5.5 which is bundled with Bootstrap and I have my main JS file running appropriately (i.e. laravel mix compiling with all the all the js files loaded with it appropriately). However, bootstrap 3.3.7's carousel is not working at all. The transitions (slide actions) don't work and the buttons dont work at all. here's my code below</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>/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
require('./animations');
window.Vue = require('vue');
// *
// * Next, we will create a fresh Vue application instance and attach it to
// * the page. Then, you may begin adding components to this application
// * or customize the JavaScript scaffolding to fit your unique needs.
Vue.component('example-component', require('./components/ExampleComponent.vue'));
const app = new Vue({
el: '.content'
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="{{ asset('js/jquery-3.2.1.min.js') }}"></script>
<!-- Styles -->
<link href="{{ asset('css/main.css') }}" rel="stylesheet"> . .. ...
<div class="container-fluid content">
<div class="carousel slide" id="features">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#features" data-slide-to="0" class="active"></li>
<li data-target="#features" data-slide-to="1"></li>
<li data-target="#features" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="/images/niceview.jpg">
<div class="carousel-caption">
<h4 class="carousel-header">Lorem Ipsum</h4>
<p class="carousel-text">Some Lorem ipsum.</p>
</div>
</div>
</div>
<div class="carousel-inner">
<div class="item">
<img src="/images/rear.jpg">
<div class="carousel-caption">
<h4 class="carousel-header">Dreams</h4>
<p class="carousel-text">Lorem ipsum</p>
</div>
</div>
</div>
<div class="carousel-inner">
<div class="item">
<img src="/images/view.jpg">
<div class="carousel-caption">
<h4 class="carousel-header">Dreams</h4>
<p class="carousel-text">Lorem ipsum</p>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#features" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#features" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>That's my js file which compiles successfully by mix and my html file. And right now I don't get any errors in the console so I have no clue as to what is wrong.</p>
<p>Please help :(</p>
| 1 | 1,518 |
Project image onto inside of sphere with Python Numpy
|
<h2>Problem:</h2>
<p>Let's say I have a large image, 5000x3000 pixels. I want to paste this image onto the inside of a sphere of some arbitrary radius.</p>
<p>To do this I will import the image as an array and I will determine the centre of the array. I will loop through each pixel, determining how far displaced it is from the centre, and using this x and y displacement I will use simple geometry to determine where it should be copied to on an output array. </p>
<p>Below are some examples of what my inputs and outputs are (but on a far smaller scale than I am trying to use).</p>
<p><strong>Example Input</strong></p>
<p><a href="https://i.stack.imgur.com/IpT2u.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IpT2u.jpg" alt="Example input image"></a></p>
<p><strong>Example Output</strong></p>
<p><a href="https://i.stack.imgur.com/KYyqO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KYyqO.jpg" alt="Example output image"></a></p>
<p>How can I speed up my method, which being pixel by pixel over a very large array, takes minutes, using python and numpy?</p>
<hr>
<h2>Code:</h2>
<pre><code>(x_d, y_d, z_d) = image.shape #get image dimensions
(x_c, y_c) = (x_d/2.0, y_d/2.0) #determine centre of image
new_image = np.zeros([x_m, y_m, d]) #create empty output image
for x in range(0, x_d): #iterate across pixels
for y in range(0, y_d): #iterate down pixels
(x_1, y_1) = (x-x_c, y-y_c) #determine pixel displacement from centre
(r_x, r_y) = (np.sqrt((rad**2.0)-(y_1**2.0)), np.sqrt((rad**2.0)-(x_1**2.0))) #determine relative radius (maths part 2)
#determine the relative radius
x_2 = int(np.round(r_x*np.sin(x_1/r_x), 0)) #determine new x-position (maths part 1)
y_2 = int(np.round(r_y*np.sin(y_1/r_y), 0)) #determine new y-position (maths part 1)
x_2 = int(np.round(x_2+x_c, 0)) #convert back to absolute pixel location
y_2 = int(np.round(y_2+y_c, 0)) #convert back to absolute pixel location
new_image[x_2, y_2, :] = image[x, y, :] #...place the pixel there
</code></pre>
<hr>
<h2>Attempts:</h2>
<p>I have searched for pre-built libraries to do this, but I struggle with some of the specific terminology and haven't found anything yet.</p>
<p>I have tried reading and writing array values using numpy's item and itemset functions, but that actually seems to slow down the processing.</p>
<p>Since I will be running this over multiple images I have tried generating the transformation array first, but this has only a very small impact on run times. ie:</p>
<pre><code>def generate_array(array, rad):
"""
Function takes image and returns array that can be used to warp it
"""
#array generated as code above but saved to 2 dimensional array for resultant x and y locations
return array
def spherize(image, array):
"""
Function takes image and warps it up as defined by the array
"""
#image processed as code above but maths is not performed, instead output x and y locations are read from previously generated array
return new_image
</code></pre>
<hr>
<h2>Maths:</h2>
<p><a href="https://i.stack.imgur.com/IpT2u.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXQKk.png" alt="Image explaining maths part 1 referred to in the code"></a>
<em>Image explaining "maths part 1" as referred to in the code.</em> This gets the resultant pixel location as if seen from the top of the sphere on which the image has been pasted. This works in one dimension should the radius remain the same in the other dimension, however for a sphere this effective radius changes since the circle drawn out on the inside of the sphere becomes smaller the further away you are from the centre. As such "maths part 2" finds the effective radius of the circle drawn out on the inside of the sphere in x given a displacement from the centre of the sphere in y.</p>
<p><a href="https://i.stack.imgur.com/KYyqO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yaP1B.png" alt="Image explaining maths part 2 referred to in the code"></a>
<em>Image explaining "maths part 2" as referred to in the code.</em> This finds the effective radius with which to calculate resultant x location based on the displacement from the centre of the sphere in y.</p>
| 1 | 1,456 |
java.lang.IllegalArgumentException: Unable to create converter for class com.dlv.dlv.UserResponseInfo for method UserApi.verifyUser
|
<p>i am using aurae/retrofit-logansquare to parse json in my android retrofit project.
i am getting following error</p>
<blockquote>
<p>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dlv.dlv, PID: 5922
java.lang.IllegalArgumentException: Unable to create converter for class com.dlv.dlv.UserResponseInfo
for method UserApi.verifyUser
at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720)
at retrofit2.ServiceMethod$Builder.createResponseConverter(ServiceMethod.java:706)
at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:167)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
at java.lang.reflect.Proxy.invoke(Proxy.java:813)
at $Proxy0.verifyUser(Unknown Source)
at com.dlv.dlv.RestApi.verifyUser(RestApi.java:156)
at com.dlv.dlv.DlvActivity$1.onClick(DlvActivity.java:52)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalArgumentException: Could not locate ResponseBody converter for class
com.dlv.dlv.UserResponseInfo.
Tried:
* retrofit2.BuiltInConverters
* com.github.aurae.retrofit2.LoganSquareConverterFactory
at retrofit2.Retrofit.nextResponseBodyConverter(Retrofit.java:346)
at retrofit2.Retrofit.responseBodyConverter(Retrofit.java:308)
at retrofit2.ServiceMethod$Builder.createResponseConverter(ServiceMethod.java:704)
... 16 more</p>
</blockquote>
<p>Application terminated.</p>
<p>build gradle (module:app)<br>
<code>compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.bluelinelabs:logansquare:1.3.6'
compile 'com.github.aurae.retrofit2:converter-logansquare:1.4.1'
</code></p>
| 1 | 1,456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.