title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
How to get the tables from AOT query in ax 2012
|
<p>I have drop down in one page, I am selecting AOT query in first page then i will click on next button, then it has to show tables related to that query</p>
| 2 |
JSESSIONID cookie not stored
|
<p>I have a frontend written in angular which runs on localhost:3002.
I have a backend written with Spring-boot which runs on localhost:8080.</p>
<p>I added a filter to handle CORS (which I found on SO and adapted to my need) : </p>
<pre><code>@Component
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3002");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request, response);
}
public void destroy() {}
}
</code></pre>
<p>When I authenticate, I can see that the server sends a cookie : </p>
<p><a href="https://i.stack.imgur.com/OPl0q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OPl0q.png" alt="enter image description here"></a></p>
<p>This cookie is not sent with the following requests. This results in 401 responses : </p>
<p><a href="https://i.stack.imgur.com/8KPHm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8KPHm.png" alt="enter image description here"></a></p>
<p>I looked at the "resources" panel of the chrome console and found out that no cookie were stored.</p>
<p>Any ideas?</p>
| 2 |
Python pandas: case statement in agg function
|
<p>I have sql statment like this:</p>
<pre><code>select id
, avg(case when rate=1 then rate end) as "P_Rate"
, stddev(case when rate=1 then rate end) as "std P_Rate",
, avg(case when f_rate = 1 then f_rate else 0 end) as "A_Rate"
, stddev(case when f_rate = 1 then f_rate else 0 end) as "std A_Rate"
from (
select id, connected_date,payment_type,acc_type,
max(case when is s_rate > 1 then 1 else 0 end) / count(open) as rate
sum(case when is hire_days <= 5 and paid>1000 then 1 else 0 end )/count(open) as f_rate
from analysis_table where alloc_date <= '2016-01-01' group by 1,2
) a group by id
</code></pre>
<p>I trying rewrite in using Pandas:
at first I will create dataframe for "inner" table:</p>
<pre><code>filtered_data = data.where(data['alloc_date'] <= analysis_date)
</code></pre>
<p>then I will group this data</p>
<pre><code>grouped = filtered_data.groupby(['id','connected_date'])
</code></pre>
<p>But what I have to use for filtering each column and use max/sum on it.</p>
<p>I tried something like this:</p>
<pre><code>`def my_agg_function(hire_days,paid,open):
r_arr = []
if hire_days <= 5 and paid > 1000:
r_arr.append(1)
else:
r.append(0)
return np.max(r_arr)/len(????)
inner_table['f_rate'] = grouped.agg(lambda row: my_agg_function(row['hire_days'],row['paid'],row['open'])`
</code></pre>
<p>and something similar for rate</p>
| 2 |
Auto delete tmp folder jboss-eap-6.2
|
<p>I am using jboss-eap-6.2 on windows with Spring Tool Suite.</p>
<p>After few server start - stop cycles, the size of tmp folder increases in GBs.</p>
<p>Is there any way to deal with this problem?
Like, tmp folder can be auto deleted?</p>
<p>I have tried below option by providing argument, but is not working:</p>
<p>-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache -Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440 </p>
<p>What can be done to get rid of tmp folder automatically?</p>
| 2 |
Django Reportlab using HTML
|
<p>Hello guys I'm trying to make a little PDF with python django using the reportlab library I've made some pdf with just some text but I have no idea how to do it with html, I wonder if you guys can give me an example using something like <code><h1>Hello</h1></code> or something with html, because if I use drawString it show me <code>'<h1>HELLO</h1>"</code> </p>
<p>Let me show you my source.</p>
<pre><code>from reportlab.pdfgen import canvas
from django.http import HttpResponse
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
import os
from io import BytesIO
import PIL.Image
def index(request):
return HttpResponse('Hola Marcos :D')
def reporte(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="informe.pdf"'
# Create the PDF object, using the response object as its "file."
buffer = BytesIO()
p = canvas.Canvas(response, pagesize=letter)
logo = ImageReader('http://django-unfriendly.readthedocs.io/en/latest/_static/img/python-logo-256.png')
numero =150
uno = 204 - numero
dos = uno
p.drawImage(logo, 250, 500,uno,dos, mask='auto')
p.setLineWidth(.1)
p.setFont('Helvetica',22)
p.drawString(30,750,'Company')
p.setFont('Helvetica',22)
p.drawString(30,725,'Report')
p.setFont('Helvetica-Bold', 12)
p.drawString(480,759,"7/01/1986")
p.line(460,747,560,747)
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
suma = (7*75675678567856785)*70+2*9090
suma = str(suma)
resta = 100-9
resta = str(resta)
p.drawString(100, 630, 'Este podria ser el primer informe de empresa con python Django')
p.drawString(100, 600, suma)
p.drawString(100, 590, resta)
p.drawString(100, 570, 'O2A5X1996A3B4B4A6')
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
# Create your views here.
</code></pre>
| 2 |
OpenIddict with two-factor authentication
|
<p>Well the title pretty much explains it all, but here is what I am trying to do:</p>
<p>I am working on an ASP.NET Core 1.0 application that needs to support authentication with JWT. This is very easily done with OpenIddict, but OpenIddict is one of those "magically works in the background" frameworks.</p>
<p>I would like to keep the simplicity of OpenIddict, but change it's default behaviour by using Identity and it's two-factor authentication features instead of just a username/password login.</p>
<p>I haven't found a way to provide a custom login manager to OpenIddict. Is there anyone who has experience with this?</p>
| 2 |
User Profile photo, with clickable icon in the corner to upload photo - html
|
<p>I want to implement a user profile photo in the navbar of my web app, to be more specific I wish to have a placeholder <a href="http://i.stack.imgur.com/dolAE.png" rel="nofollow">see placeholder</a></p>
<p>And then put a camera icon on the top right corner of the circle: <a href="http://i.stack.imgur.com/XMojX.png" rel="nofollow">see camera icon</a></p>
<p>When someone clicks on the camera icon they can upload a photo to change their profile picture, in any photo format. Here is what I have but the result gives me a messy output, with "choose file", the name of the file, and "submit". I don't want any of this - just the round placeholder icon where the photo file will be shown, and the small camera icon on the top right of the photo circle.</p>
<pre><code><div class="row">
<div class="col-sm-6 col-md-4">
<div class="img-circle usericon">
<img src="https://plus.google.com/photos/114809861514342788109/album/6306090224289882481/6306090221879682418?authkey=CJPV_OKHvczjSw" class="img-circle img-responsive" width="100" height="100">
<div>
<img src="https://plus.google.com/photos/114809861514342788109/album/6306090224289882481/6306090221856483314?authkey=CJPV_OKHvczjSw">
</div>
<div class="caption">
<form action="demo_form.asp">
<input type="file" name="pic" accept=".gif,.jpg,.png,.tif|image/*">
<input type="submit">
</form>
</div>
</div>
</div>
</div>
</code></pre>
<p>I uploaded the icons to google plus, so that is why the src is a google plus link. Many thanks in advance</p>
| 2 |
How to send apk file in chat Like HIKE?
|
<p>I am making Chat Application like WhatsApp and I want to add <strong>.apk</strong> file attachment in my Application. </p>
<p>So how to achieve that?</p>
| 2 |
how to hide the Vertical and horizontal Scrollbars with wxPython ?
|
<p>Am using this code to create a text window but i didn't figure out how to hide the Scrollbars
I saw some answers that wxpython doesn't support that , so any ideas ??
thanks!</p>
<p><strong>Note:Hiding the scrollbar not disabling the scrolling</strong><br>
Thanks :) </p>
<pre><code>import wx
import wx.lib.dialogs
import wx.stc as stc
faces = {'times':'Times New Roman','helv':"Arial","size":18}
class MainWindow(wx.Frame):
def __init__(self,parent,title):
self.filepath =''
self.leftMarginWidth = 25
wx.Frame.__init__(self,parent,title=title,size=(1350,720))
self.control=stc.StyledTextCtrl(self,style=wx.TE_MULTILINE | wx.TE_WORDWRAP|wx.TE_NO_VSCROLL)
self.control.CmdKeyAssign(ord("+"),stc.STC_SCMOD_CTRL,stc.STC_CMD_ZOOMIN) #Ctrl + + to zoom in
self.control.CmdKeyAssign(ord("-"),stc.STC_SCMOD_CTRL,stc.STC_CMD_ZOOMOUT) #Ctrl + - to zoom out
self.control.SetViewWhiteSpace(False)
self.control.SetMargins(5,0)
self.control.SetMarginType(1,stc.STC_MARGIN_NUMBER)
self.control.SetMarginWidth(1,self.leftMarginWidth)
self.control.Bind(wx.EVT_CHAR,self.OnCharEvent)
#don't forget the statusBar
#file men if you want it
self.Show()
def OnSave(self,e):
try:
f= open(self.filepath,"w")
f.write(self.control.GetText())
f.close()
except:
self.OnSaveAs(self)
def OnSaveAs(self,e):
try:
dlg=wx.FileDialog(self,'save file as',self.filepath,"untitled","*.*",wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
print dlg
if (dlg.ShowModal()== wx.ID_OK):
self.filepath = dlg.GetPath()
f=open(self.filepath,"w")
f.write(self.control.GetText())
f.close()
dlg.Destroy()
except:
pass
def OnOpen(self,e):
dlg=wx.FileDialog(self,"Choose a file",self.filepath,'',"*.*",wx.FD_OPEN)
if(dlg.ShowModal() == wx.ID_OK):
self.filepath = dlg.GetPath()
f=open(self.filepath,"r")
self.control.SetText(f.read())
f.close()
dlg.Destroy()
def OnCharEvent(self,e):
keycode=e.GetKeyCode()
print keycode
if (keycode == 15):
self.OnOpen(self)
elif keycode == 19:
self.OnSave(self)
else:
e.Skip()
app=wx.App()
frame = MainWindow(None,"my text Editor")
app.MainLoop()
</code></pre>
<p><a href="http://i.stack.imgur.com/tFf7n.png" rel="nofollow">image</a></p>
| 2 |
Build a C++ program in Clion: "Target not found"
|
<p>I have searched some solutions online and on Stackoverflow but could not found one that suits mine. The code below is the <code>CMakeList.txt</code> of <code>vector</code> file. <code>vector</code> file is a sub-file of the parent file <code>DSA</code>, in which there are also <code>main.cpp</code> and <code>CMakeList.txt</code>, but I do not believe they are relevant.</p>
<pre><code>cmake_minimum_required(VERSION 3.5)
project(vector)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES
copy_assignment.h
copy_constructor.h
main.cpp
traverse_funcs.h
vector.h
vector_bin_search_a.h
vector_bin_search_b.h
vector_bin_search_c.h
vector_bracket.h
vector_bubble.h
vector_bubblesort.h
vector_deduplicate.h
vector_disordered.h
vector_expand.h
vector_fib_search_a.h
vector_find.h
vector_insert.h
vector_merge.h
vector_mergesort.h
vector_permute.h
vector_remove.h
vector_removeinternal.h
vector_shrink.h
vector_traverse.h
vector_uniquify.h
vector_unsort.h)
add_executable(vector ${SOURCE_FILES})
</code></pre>
<p>main.cpp:</p>
<pre><code>#pragma once
#include <iostream>
#include "vector.h"
#include "vector_permute.h"
using namespace std;
int main()
{
Vector<int> foo = {1, 2, 3, 4};
cout << foo.size() << endl;
return 0;
}
</code></pre>
<p>This is the configuration window. I have added <code>add_executable(vector ${SOURCE_FILES})</code> into C makelist but it still does not work, what should I do?</p>
<p><a href="https://i.stack.imgur.com/SpQ6a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SpQ6a.png" alt=""></a></p>
| 2 |
org.springframework.beans.NotWritablePropertyException: Invalid property 'xxxx' of bean class :
|
<p>I am new to spring framework and was trying to create a bean using spring xml but I am now facing below exception</p>
<pre><code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feedServerLineRead' defined in class path resource [FeedServer.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'feedProcessor' of bean class [workflow.FeedServerLineRead]: Bean property 'feedProcessor' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at controller.FeedController.main(FeedController.java:76)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'feedProcessor' of bean class [workflow.FeedServerLineRead]: Bean property 'feedProcessor' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1024)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
</code></pre>
<hr/>
<pre><code>package workflow;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import org.springframework.jmx.export.annotation.ManagedResource;
import FeedData;
import FeedProcessor;
@ManagedResource(objectName="bean:name=FeedServerLineRead")
public class FeedServerLineRead implements Runnable {
private FeedProcessor feedProcessor;
BlockingQueue<String> queue;
@Override
public void run() {
while(true) {
String sb;
try {
sb = queue.take();
List <FeedData> beanList = new ArrayList<FeedData>();
FeedData dataPojo = new FeedData();
dataPojo.setSide(sb.charAt(60));
dataPojo.setProduct(sb.substring(145, 163));
beanList.add(dataPojo);
feedProcessor.insertBatch(beanList);
} catch (InterruptedException ex) {
break;
}
}
}
public FeedServerLineRead(){
this.queue=null;
}
public FeedServerLineRead(BlockingQueue<String> queue) {
this.queue = queue;
}
public FeedProcessor getFeedProcessor() {
return feedProcessor;
}
public void setFeedProcessor(FeedProcessor feedProcessor) {
this.feedProcessor = feedProcessor;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<bean id="feedProcessor" class="processor.FeedProcessor" />
<bean id="feedServerLineRead" class="workflow.FeedServerLineRead">
<property name="feedProcessor" ref="feedProcessor" />
</bean>
</beans>
</code></pre>
| 2 |
Include this.props.children as a component within the jsx
|
<p>I am very new to the react world and I am trying to include include <code>this.props.children</code> as a <code>component</code> via <code>React.cloneElement</code>. I am trying this so that I could refer that component using a <code>ref</code>.</p>
<p>For example, lets say I get the children to a <code>const</code> as follows,</p>
<p><code>const Child = React.cloneElement(this.props.children, this.props);</code></p>
<p>and try to render it like:</p>
<pre><code>return (
<div style={styles.container}>
<Child ref={"child"} />
</div>
);
</code></pre>
<p>But this is throwing this error: <code>warning.js?0260:45 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of 'OnlineOrderPane'.</code></p>
<p>It would be of great help if any of you experts would point me in the right direction to achieve this or if its actually feasible to do so.</p>
<p>Thanks alot.</p>
| 2 |
Scrapy Python loop to next unscraped link
|
<p>i'm trying to make my spider go over a list and scrape all the url's it can find following them scraping some data and returning to continue on the next unscraped link if i run the spider i can see that it returns back to the starting page but tries to scrape the same page again and just quits afterwards any code suggestions pretty new to python.</p>
<pre><code>import scrapy
import re
from production.items import ProductionItem, ListResidentialItem
class productionSpider(scrapy.Spider):
name = "production"
allowed_domains = ["domain.com"]
start_urls = [
"http://domain.com/list"
]
def parse(self, response):
for sel in response.xpath('//html/body'):
item = ProductionItem()
item['listurl'] = sel.xpath('//a[@id="link101"]/@href').extract()[0]
request = scrapy.Request(item['listurl'], callback=self.parseBasicListingInfo)
yield request
def parseBasicListingInfo(item, response):
item = ListResidentialItem()
item['title'] = response.xpath('//span[@class="detail"]/text()').extract()
return item
</code></pre>
<p>to clarify:
i'm passing [0] so it only takes the first link of the list
but i want it to continue using the next unscraped link </p>
<p>output after running the spider : </p>
<pre><code>2016-07-18 12:11:20 [scrapy] DEBUG: Crawled (200) <GET http://www.domain.com/robots.txt> (referer: None)
2016-07-18 12:11:20 [scrapy] DEBUG: Crawled (200) <GET http://www.domain.com/list> (referer: None)
2016-07-18 12:11:21 [scrapy] DEBUG: Crawled (200) <GET http://www.domain.com/link1> (referer: http://www.domain.com/list)
2016-07-18 12:11:21 [scrapy] DEBUG: Scraped from <200 http://www.domain.com/link1>
{'title': [u'\rlink1\r']}
</code></pre>
| 2 |
Prefix not found: 'tib' in Tibco designer
|
<p>I got the following error in Tibco.</p>
<blockquote>
<p>com.tibco.xml.data.primitive.PrefixToNamespaceResolver$PrefixNotFoundException: Prefix not found: 'tib'</p>
</blockquote>
| 2 |
How to write numpy where condition based on indices and not values?
|
<p>I have a 2d numpy array and I need to extract all elements <code>array[i][j]</code> if the conditions </p>
<p><code>x1range < i < x2range</code> and <code>y1range < j < y2range</code> are satisfied.</p>
<p>How do I write such conditions? Do I need to use mgrid/ogrid?</p>
<p>Edit: Should have written my additional requirement. I was looking for a where condition, and not splicing, because I want to change the values of all the elements to (0,0,0) which satisfy the above condition. I assumed if I have a where condition, I could do that.</p>
<p>Edit2: Also, is it possible to get the 'not' of the above condition?</p>
<p>As in,</p>
<pre><code>if i > x1range and i < x2range and j > y1range and j < y2range: # the above condition
do nothing # keep original value
else:
val = (0,0,0)
</code></pre>
| 2 |
Brotli compression multithreading
|
<p>It's my understanding <strong><a href="https://github.com/google/brotli" rel="nofollow noreferrer"><code>Brotli</code></a></strong> stores blocksize information in a meta-block header with only the final uncompressed size of the block, and no information about the compression length (<a href="https://datatracker.ietf.org/doc/html/draft-alakuijala-brotli-04#section-9.2" rel="nofollow noreferrer">9.2</a>). I'm guessing that a wrapper would be need to be created in order to use it with multiple threads, or possibly something similar to Mark Adler's <strong><a href="https://github.com/madler/pigz" rel="nofollow noreferrer"><code>pigz</code></a></strong>.</p>
<p>Would the same threading principles apply to Brotli as they do with gzip in this case, or are there any foreseeable issues to be aware of when it comes to multithreading implementations?</p>
| 2 |
Extract data from Partial least square regression on R
|
<p>I want to use the partial least squares regression to find the most representative variables to predict my data.
Here is my code:</p>
<pre><code>library(pls)
potion<-read.table("potion-insomnie.txt",header=T)
potionTrain <- potion[1:182,]
potionTest <- potion[183:192,]
potion1 <- plsr(Sommeil ~ Aubepine + Bave + Poudre + Pavot, data = potionTrain, validation = "LOO")
</code></pre>
<p>The <code>summary(lm(potion1))</code> give me this answer: </p>
<pre><code>Call:
lm(formula = potion1)
Residuals:
Min 1Q Median 3Q Max
-14.9475 -5.3961 0.0056 5.2321 20.5847
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.63931 1.67955 22.410 < 2e-16 ***
Aubepine -0.28226 0.05195 -5.434 1.81e-07 ***
Bave -1.79894 0.26849 -6.700 2.68e-10 ***
Poudre 0.35420 0.72849 0.486 0.627
Pavot -0.47678 0.52027 -0.916 0.361
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 7.845 on 177 degrees of freedom
Multiple R-squared: 0.293, Adjusted R-squared: 0.277
F-statistic: 18.34 on 4 and 177 DF, p-value: 1.271e-12
</code></pre>
<p>I deduced that only the variables <code>Aubepine</code> et <code>Bave</code> are representative. So I redid the model just with this two variables:</p>
<pre><code>potion1 <- plsr(Sommeil ~ Aubepine + Bave, data = potionTrain, validation = "LOO")
</code></pre>
<p>And I plot:</p>
<pre><code>plot(potion1, ncomp = 2, asp = 1, line = TRUE)
</code></pre>
<p>Here is the plot of predicted vs measured values:</p>
<p><img src="https://i.stack.imgur.com/z3rGj.png" alt="Plot of predited vs measured values"></p>
<p>The problem is that I see the linear regression on the plot, but I can not know its equation and <code>R²</code>. Is it possible ?</p>
<p>Is the first part is the same as a multiple regression linear (ANOVA)?</p>
| 2 |
Aws CloudFront Malformed Policy
|
<p>I have been trying to create a signed url for cloud front (that points to my s3 bucket) with limited privileges in php , but I keep getting malformed policy error. </p>
<p>I am using : </p>
<pre><code>$customPolicy = '{"Id":"Policy1319566876317","Statement":[{"Sid":"Stmt1319566860498","Action":["s3:GetObject"],"Effect":"Allow","Resource":"arn:aws:s3:::my-bucket/*","Principal":{"CanonicalUser":["92cd670939a0460a1b48cbbfedcb5178139bcb315881d9ec3833e497a9e62959762d560feec321a749217754e5d02e5f"]}}]}';
// Create a signed URL for the resource using the canned policy
$signedUrlCannedPolicy = $cloudFront->getSignedUrl([
'url' => $streamHostUrl . '/' . $resourceKey,
'private_key' => base_path().'/'.'mypem file',
'key_pair_id' => 'myid',
'policy' => $customPolicy
]);
</code></pre>
<p>Basically , i want the receiver of this signed url to have only those s3 object privileges that I specify (in the code above, its set to getObject, sometimes it may be put object ,sometimes it may be delete object.
How do I achieve that in cloud front ?</p>
| 2 |
How to get an element it's index in PROTRACTOR
|
<p>It's my first question here and I've been trying to use Protractor to do end to end test.
I need to get the first element from this group of code. As you can see, I have the same class and the same sub-class for these 3 element. So I thought to get it by using the index.</p>
<pre><code> <div class="col-md-4">
<div class="form-group">
<label>Número</label>
<input class="form-control ng-valid ng-touched ng-dirty" type="number">
</div>
</div>
<div class="form-group">
<label>Inicio Vigência</label>
<input class="form-control ng-untouched ng-pristine ng-valid" placeholder="dd/MM/yyyy" type="date" value="">
</div>
<div class="form-group">
<label>Fim Vigência</label>
<input class="form-control ng-untouched ng-pristine ng-valid" placeholder="dd/MM/yyyy" type="date" value="">
</div>
</code></pre>
<p>I've trying: </p>
<pre><code>var numero = element.all(by.className('form-group')).get(2).all(by.tagName('input'));
numero.sendKeys(aux2);
</code></pre>
<p>But it's not working. Protractor doesn't sentkeys in the input.</p>
| 2 |
No Android Tools in Xamarin Visual Studio
|
<p>For some reason, I have no controls/tools in my "toolbox" window for Xamarin Android development in Visual Studio 2015. In other words, I can't create any objects in the form designer because there are none to drag/drop. <a href="https://www.youtube.com/watch?v=zZHLHrkvUt0&list=PLCuRg51-gw5VqYchUekCqxUS9hEZkDf6l#t=114.111502" rel="nofollow">This Video</a></p>
<p>Clearly shows that there should be tools in my toolbox just like WinForms... Not sure what's going on. Anyone else experience this?</p>
| 2 |
Timer anti cheat technique
|
<p>Let's say I'm developing a game and there exists such thing as respawn. The user may respawn after 15 minutes. Is there any common practice to avoid time cheating? I mean, nothing can stop user from changing system time and set it to future. I know, partially this can be resolved by using server side, but nothing can stop user from disabling the network at all.
PS. the game is cross platform so the solution is interesting for both antroid and iOS. PS2. I know a couple of games that have the solution.</p>
| 2 |
ionic XHR failed loading: POST
|
<p>I'm getting this error:</p>
<pre><code>XMLHttpRequest cannot load http://localhost/authproject/public/api/auth/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8101' is therefore not allowed access.
ionic.bundle.js:15567 XHR failed loading: POST
</code></pre>
<p>Could someone tell me how do I solve this ? </p>
| 2 |
Python Deep Learning find Duplicates
|
<p>I want to try and learn Deep Learning with Python.
The first thing that came to my mind for a useful scenario would be a Duplicate-Check.</p>
<p>Let's say you have a customer-table with name,address,tel,email and want to insert new customers.
E.g.:</p>
<pre><code>In Table:
Max Test,Teststreet 5, 00642 / 58458,[email protected]
To Insert:
Max Test, NULL, (+49)0064258458, [email protected]
</code></pre>
<p>This should be recognised as a duplicate entry.</p>
<p>Are there already tutorials out there for this usecase? Or is it even possible with deep learning?</p>
| 2 |
g++ not finding library in /usr/local/lib
|
<p>I'm trying to get g++ to find <code>glog</code> on its own (OS X 10.11.5). I installed glog (tried with both cmake from a github pull as well as brew install - same result in both cases). Then I tried to compile this file:</p>
<pre><code>#include <glog/logging.h>
int main(int argc, char** argv) {
int* x = nullptr;
CHECK_NOTNULL(x);
return 0;
}
</code></pre>
<p>by running <code>g++ -lglog -I/usr/local/include test.cpp</code></p>
<p>This fails with the following error:</p>
<pre><code>ld: library not found for -lglog
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>However, when I compile with <code>g++ -L/usr/local/lib -lglog -I/usr/local/include test.cpp</code> it works fine.</p>
<p>I tried adding <code>/usr/local/lib</code> into my LD_LIBRARY_PATH to no avail.</p>
<p>Normally, I wouldn't mind, but I'm using CMake (which finds glog just fine), and I don't want to "hardcode" library paths in there so that it's portable. I tried this before on another Mac and it worked fine, so I'm not sure what's going on. Any advice on fixing this?</p>
| 2 |
Django ORM complex query
|
<p>I have the following models:</p>
<pre><code>class Invoice(models.Model):
amount = models.DecimalField()
date = models.DateTimeField()
class InvoiceItem(models.Model):
invoice = models.ForeignKey(Invoice)
description = models.CharField(max_length=256)
amount = models.DecimalField()
class PaymentDistribution(models.Model):
item = models.ForeignKey(invoiceItem)
amount = models.DecimalField()
select a.id,
a.amount,
a.amount-coalesce(sum(b.amount),0) as to_pay
from invoiceitems as a
left join paymentdistribution as b
on (a.id=b.invoiceitem_id)
group by a.id, a.amount
order by to_pay desc
</code></pre>
<p>This is a simple Invoice-items structure. I want to be able to distribute a payment among multiple items and keep track of the distribution of the payments. The SQL query provides me with a list of items I can pay and the max amount I can pay. Is there a way to do the same query using pure ORM instead of raw SQL? I'm trying to avoid raw SQL.</p>
| 2 |
Go sql - prepared statement scope
|
<p>I'm building an API using the Go (1.6.x) sql package along with with PostGres (9.4). Should my prepared statements have application or request scope? Having read the docs it would seem more efficient to scope them at the application level to reduce the number of preparation phases. However, perhaps there are other considerations and prepared statements are not designed to live that long? </p>
| 2 |
Google Search Console API: How do you implement multiple OR filters?
|
<p>After much fiddling, I've finally got the Search Console API working. Unfortunately, I can't figure out how to add multiple OR filters. I presume this is what dimensionFilterGroups[].groupType will eventually be for, but 'or' is not yet an option.</p>
<p>Basically, how do you implement a series of filters where the results are returned when any are true?</p>
<p>I've tried the following, but none seem to work:</p>
<pre><code>"dimensionFilterGroups": [
{
"filters": [
{
"dimension": 'query',
"operator": 'equals',
"expression": 'lockers'
},
{
"dimension": 'query',
"operator": 'equals',
"expression": 'shelving'
}
]
}
]
</code></pre>
<pre><code>"dimensionFilterGroups": [
{
"filters": [
{
"dimension": 'query',
"operator": 'equals',
"expression": 'lockers'
}
],
"filters": [
{
"dimension": 'query',
"operator": 'equals',
"expression": 'shelving'
}
]
}
]
</code></pre>
<pre><code>"filters": [
{
"dimension": 'query',
"operator": 'equals',
"expression": 'lockers'
},
{
"dimension": 'query',
"operator": 'equals',
"expression": 'shelving'
}
]
</code></pre>
| 2 |
signal handler not working in python
|
<p>I am writing an asynchronous video playing program on Raspberry Pi. I need to run omxplayer in a subprocess and receive input in main process. When some input is received, main process would send the signal to the subprocess. </p>
<p>Here is my code:</p>
<pre><code>def worker():
p = subprocess.Popen(['omxplayer', '1.mov'], stdin = subprocess.PIPE)
def handler(signum, frame):
print p.pid
p.stdin.write('q') # keystroke of 'q' will quit omxplayer FYI
signal.signal(signal.SIGUSR1, handler) # can only be trigger in code
</code></pre>
<p>So far it seems fine. I can run worker() and send SIGUSR1 in a code snippet and it works fine. Like this:</p>
<pre><code>def test():
worker()
time.sleep(5)
os.kill(int(os.getpid()), signal.SIGUSR1)
</code></pre>
<p>But when I try to start worker as a multiprocess, it seems the process cannot receive the signal.</p>
<pre><code>def main_process():
w = multiprocessing.Process(target=worker)
w.start()
time.sleep(5)
os.kill(w.pid, signal.SIGUSR1)
</code></pre>
<p>The handler will not be called in this way. Which part is probably wrong? The signal is not received, or the binding is not right?</p>
<p><strong>I think os.kill is not working as I thought. The signal is not received at all. How to fix this?</strong></p>
| 2 |
java generics: compiler error not shown in eclipse
|
<p>I have these classes:</p>
<pre><code>public class EntityDataModel<T extends AbstractEntity>
{
...
}
public abstract class BarChartBean<E extends ChartEntry, T>
{
protected EntityDataModel<? extends T> currentModel;
...
}
</code></pre>
<p>I can compile and run this code on eclipse without problem, but when I invoke <code>mvn compile</code>, this error is thrown:</p>
<pre class="lang-none prettyprint-override"><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project edea2: Compilation failure: Compilation failure:
[ERROR] C:\Develop\...\BarChartBean.java:[53,30] error: type argument ? extends T#1 is not within bounds of type-variable T#2
[ERROR] where T#1,T#2 are type-variables:
[ERROR] T#1 extends Object declared in class BarChartBean
[ERROR] T#2 extends AbstractEntity declared in class EntityDataModel
</code></pre>
<p>The error is pretty self-explanatory, and theoretically speaking, javac is right and eclipse compiler is wrong.</p>
<p>Why there's such a difference?</p>
<p>Here you are the details of the environment:</p>
<ul>
<li><p>Eclipse </p>
<ul>
<li>Mars.2 Release (4.5.2)</li>
<li>jdk 1.8.0_71</li>
<li>Compiler compliance level: 1.8</li>
<li><a href="https://i.stack.imgur.com/jPvME.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jPvME.png" alt="Errors/Warnings"></a></li>
</ul></li>
<li><p>Maven</p>
<ul>
<li>Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T13:57:37+02:00)</li>
<li>Maven home: C:\Develop\tools\apache-maven-3.3.3</li>
<li>Java version: 1.8.0_71, vendor: Oracle Corporation</li>
<li>Java home: C:\Program Files\Java\jdk1.8.0_71\jre</li>
<li>Default locale: it_IT, platform encoding: Cp1252</li>
<li>OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"</li>
<li><p>maven-compiler-plugin:</p>
<pre><code><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</code></pre></li>
</ul></li>
</ul>
<p><strong>Question</strong>: How can I <em>align</em> the eclipse compiler behavior to javac (but I don't want to use javac in eclipse)?</p>
| 2 |
How to make cv::setMouseCallback function work
|
<p>I've seen a few questions that are probably the same. I am still unable to make my code work after reading the answers. So I am sorry in advance if I am repeating the posts.</p>
<p>I managed to write this code :</p>
<pre><code> #include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
bool leftButtonDown = false, leftButtonUp = false;
cv::Mat img;
cv::Point cor1, cor2;
cv::Rect rect;
void mouseCall(int event, int x, int y, int, void*) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; cor1.x = x; cor1.y = y; std::cout << "Corner 1: " << cor1 << std::endl;
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - cor1.x)>20 && abs(y - cor1.y)>5) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; cor2.x = x; cor2.y = y; std::cout << "Corner 2: " << cor2 << std::endl;
}
else { std::cout << "Select more than 5 pixels" << std::endl; }
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is clicked and let off
{ //draw a rectangle continuously
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = img.clone();
rectangle(temp_img, cor1, pt, cv::Scalar(0, 0, 255));
cv::imshow("Original", temp_img);
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
cv::Mat cutTempImg(img, rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main(){
img = cv::imread("image.jpg");
cv::namedWindow("Original");
cv::imshow("Original", img);
cv::setMouseCallback("Original", mouseCall); //setting the mouse callback for selecting the region with mouse
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}
</code></pre>
<p>And it is working fine. Now I want to make same code, with using class.(OOP)</p>
<p>But <code>cv::setMouseCallback</code> function is not letting me do that.
Can any one help me fix this?</p>
<p>My second code :</p>
<pre><code> #include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
class ResizeImage {
cv::Mat img;
cv::Point cor1, cor2;
cv::Rect rect;
std::string name;
public:
void setImg(cv::Mat img) { this->img = img; };
cv::Mat getImg() { return img; };
void setRect();
int getCoordinates1X() { return cor1.x; };
int getCoordinates1Y() { return cor1.y; };
int getCoordinates2X() { return cor2.x; };
int getCoordinates2Y() { return cor2.y; };
void setCoordinates1(int x, int y) { this->cor1.x = x; this->cor1.y = y; };
void setCoordinates2(int x, int y) { this->cor2.x = x; this->cor2.y = y; };
void mouseCall(int event, int x, int y, int flags, void* param);
void showImgOriginal();
void setImgName(std::string name) { this->name = name; };
std::string getImgName() { return name; };
};
void ResizeImage :: showImgOriginal() {
cv::namedWindow(name, CV_WINDOW_AUTOSIZE);
cv::imshow(name, img);
};
void ResizeImage::setRect() {
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
}
void ResizeImage::mouseCall(int event, int x, int y, int flags, void* param) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; setCoordinates1(x,y); std::cout << "Corner 1: " << getCoordinates1X()<<" "<<getCoordinates1Y() << std::endl;
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - cor1.x)>20 && abs(y - cor1.y)>5) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; setCoordinates2(x, y); std::cout << "Corner 2: " << getCoordinates2X() << " " << getCoordinates2Y() << std::endl;
}
else { std::cout << "Select more than 5 pixels" << std::endl; }
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is down
{
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = img.clone();
rectangle(temp_img, cor1, pt, cv::Scalar(0, 0, 255)); //drawing a rectangle continuously
cv::imshow("Original", temp_img);
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
setRect();
cv::Mat cutTempImg(img, rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main(){
cv::Mat img = cv::imread("image.jpg");
ResizeImage img_;
img_.setImg(img);
img_.setImgName("original");
img_.showImgOriginal();
cv::setMouseCallback(img_.getImgName(),img_.mouseCall());
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}
</code></pre>
<p>Code after changes :</p>
<pre><code>//Program is loading image, and showing it to user.
//User can use mouse to make a rectangle and cut the loaded image.
//Command line is tracking mouse movements and the coordinates of the rectangle.
//User can end the program using 'q'.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
bool leftButtonDown = false, leftButtonUp = false; //flags for mouse clicks
class ResizeImage {
cv::Mat img; //image to process
cv::Point cor1, cor2; //coordinates of selected rectangle
cv::Rect rect; //rectangle
std::string name; //windows name
public:
//////////////////////////////////////////////////////////////////////////////
ResizeImage() { std::cout << "Starting..."<<std::endl; }; //Constructor/Destructor
~ResizeImage() { std::cout << "Ending..." << std::endl; };
//////////////////////////////////////////////////////////////////////////////
void setImg(cv::Mat img) { this->img = img; };
void setImgName(std::string name) { this->name = name; }; //set functions
void setRect();
void setCoordinates1(int x, int y) { this->cor1.x = x; this->cor1.y = y; };
void setCoordinates2(int x, int y) { this->cor2.x = x; this->cor2.y = y; };
//////////////////////////////////////////////////////////////////////////////
int getCoordinates1X() { return cor1.x; }; //getfunctions
int getCoordinates1Y() { return cor1.y; };
int getCoordinates2X() { return cor2.x; };
int getCoordinates2Y() { return cor2.y; };
cv::Mat getImg() { return img; };
std::string getImgName() { return name; };
//////////////////////////////////////////////////////////////////////////////
static void mouseCall(int event, int x, int y, int flags, void* param); //static function
//////////////////////////////////////////////////////////////////////////////
void showImgOriginal(); //show function (priting image)
//////////////////////////////////////////////////////////////////////////////
};
void ResizeImage :: showImgOriginal() { //showing image
cv::namedWindow(name, CV_WINDOW_AUTOSIZE);
cv::imshow(name, img);
};
void ResizeImage::setRect() { //calculating selected rectangle
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
}
void ResizeImage::mouseCall(int event, int x, int y, int flags, void* param) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; ((ResizeImage*)param)->cor1.x = x; ((ResizeImage*)param)->cor1.y = y; //saving coordinates
std::cout << "Corner 1: " << ((ResizeImage*)param)->cor1.x << " " << ((ResizeImage*)param)->cor1.y << std::endl; //printing coordinates
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - ((ResizeImage*)param)->cor1.x)>20 && abs(y - ((ResizeImage*)param)->cor1.y)>10) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; ((ResizeImage*)param)->cor2.x = x; ((ResizeImage*)param)->cor2.y = y; //saving coordinates
std::cout << "Corner 2: " << ((ResizeImage*)param)->cor2.x << " " << ((ResizeImage*)param)->cor2.y << std::endl; //printing coordinates
}
else { std::cout << "Select more than 10 pixels" << std::endl; } //warning if region is too small
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is down
{
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = ((ResizeImage*)param)->img.clone();
rectangle(temp_img, ((ResizeImage*)param)->cor1, pt, cv::Scalar(0, 0, 255)); //drawing a rectangle continuously
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
((ResizeImage*)param)->setRect();
cv::Mat cutTempImg(((ResizeImage*)param)->img, ((ResizeImage*)param)->rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main() {
cv::Mat img = cv::imread("image.jpg");
ResizeImage img_;
img_.setImg(img);
img_.setImgName("Original");
img_.showImgOriginal();
cv::setMouseCallback(img_.getImgName(),ResizeImage::mouseCall,&img_);
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}
</code></pre>
| 2 |
" javax.servlet.* " and "HttpServlet" can't be resolved to a type
|
<p>I am new in Java EE Development.
I have installed <strong>Java SE and JRE both 8u92</strong> latest version and using <strong>Eclipse JEE Neon version</strong> for EE Development.
My <strong>Tomcat Server 9 is running properly</strong>, But whenever i am creating a new simple servlet project I am getting error related to libraries as above mentioned.
Kindly help me to figure out this.
Also,please tell me <strong>instead of this can we use Java EE SDK 7?</strong>, if so then how to connect it with Eclipse and Tomcat?
Thank you.</p>
| 2 |
CHIP8 in C - How to correctly handle the delay timer?
|
<p><strong>TL;DR</strong> I need to emulate a timer in C that allows concurrent writes and reads, whilst preserving constant decrements at 60 Hz (not exactly, but approximately accurate). It will be part of a Linux CHIP8 emulator. Using a thread-based approach with shared memory and semaphores raises some accuracy problems, as well as race conditions depending on how the main thread uses the timer.</p>
<p><em>Which is the best way to devise and implement such a timer?</em></p>
<hr>
<p>I am writing a Linux CHIP8 interpreter in C, module by module, in order to dive into the world of emulation.</p>
<p>I want my implementation to be as accurate as possible with the specifications. In that matter, timers have proven to be the most difficult modules for me.</p>
<p>Take for instance the delay timer. In the specifications, it is a "special" register, initally set at 0. There are specific opcodes that set a value to, and get it from the register.</p>
<p>If a value different from zero is entered into the register, it will automatically start decrementing itself, at a frequency of 60 Hz, stopping once zero is reached.</p>
<p>My idea regarding its implementation consists of the following:</p>
<ol>
<li><p>The use of an ancillary thread that does the decrementing automatically, at a frequency of nearly 60 Hz by using <code>nanosleep()</code>. I use <code>fork()</code> to create the thread for the time being.</p></li>
<li><p>The use of shared memory via <code>mmap()</code> in order to allocate the timer register and store its value on it. This approach allows both the ancillary and the main thread to read from and write to the register.</p></li>
<li><p>The use of a semaphore to synchronise the access for both threads. I use <code>sem_open()</code> to create it, and <code>sem_wait()</code> and <code>sem_post()</code> to lock and unlock the shared resource, respectively.</p></li>
</ol>
<p>The following code snippet illustrates the concept:</p>
<pre><code>void *p = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
/* Error checking here */
sem_t *mutex = sem_open("timersem", O_CREAT, O_RDWR, 1);
/* Error checking and unlinking */
int *val = (int *) p;
*val = 120; // 2-second delay
pid_t pid = fork();
if (pid == 0) {
// Child process
while (*val > 0) { // Possible race condition
sem_wait(mutex); // Possible loss of frequency depending on main thread code
--(*val); // Safe access
sem_post(mutex);
/* Here it goes the nanosleep() */
}
} else if (pid > 0) {
// Parent process
if (*val == 10) { // Possible race condition
sem_wait(mutex);
*val = 50; // Safe access
sem_post(mutex);
}
}
</code></pre>
<p>A potential problem I see with such implementation relies on the third point. If a program happens to <em>update</em> the timer register once it has reached a value <em>different from zero</em>, then the ancillary thread <strong>must not</strong> wait for the main thread to unlock the resource, or else the 60 Hz delay will not be fulfilled. This implies both threads may freely update and/or read the register (constant writes in the case of the ancillary thread), which obviously introduces race conditions.</p>
<p>Once I have explained what I am doing and what I try to achieve, my question is this:</p>
<p><em>Which is the best way to devise and emulate a timer that allows concurrent writes and reads, whilst preserving an acceptable fixed frequency?</em></p>
| 2 |
How do you filter Algolia Results and omit a specific objectID
|
<p>I'm trying to filter algolia results and want to use the name of a product to find similar products in our database. I would prefer to ignore the current product so, in the case no results are found, the <code>removeWordsIfNoResults</code> option will be used.</p>
<p>I'm using the Ruby api.</p>
<p>This is basically what I'm trying but it is not working. Is it possible to filter out a specific objectID?</p>
<pre><code>Product.raw_search("Men's Bridge & Burn Camden Steel Blue",
{ :hitsPerPage => 10,
:page => 0,
:attributesToRetrieve => "objectID",
:filters => "objectID != '65411'",
:removeWordsIfNoResults => 'lastWords'
}
)
</code></pre>
| 2 |
Tensorflow variable Reuse in rnn module
|
<p>I'm very perplexed by TF variable reuse. For method rnn, I'm able to find this line of code:</p>
<pre><code> if time > 0: vs.get_variable_scope().reuse_variables()
</code></pre>
<p>However, for <code>dynamic_rnn</code> (the method I need to use), I do not find any reuse_variable line of code, or reuse=True.</p>
<p>All the RNN cells in <code>rnn_cells</code> module are initializing using <code>_linear</code> method, which does not check if a variable has been created or not, but in LSTM_cell, <code>_get_concat_variable</code> does nicely check if a variable's name exists in <code>graph_key</code> or not.</p>
<p>So does <code>dynamic_rnn</code> not reuse the variable? Should I write a method to explicitly check if a variable is created and return it if it is?</p>
| 2 |
How can I in Blender acces a polygon, which is given by indices, for an operator?
|
<p>In <code>Blender 2.77</code> I have a polygon, referenced as:</p>
<pre><code> bpy.data.objects['Cube.001'].data.polygons[0]
</code></pre>
<p>and an operator:</p>
<pre><code>bpy.ops.transform.resize(value=(0, 0, 1), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
</code></pre>
<p>How can I make the operator be executed on the polygon?
I have tried:</p>
<pre><code> bpy.data.objects['Cube.001'].data.polygons[0].select = True
</code></pre>
<p>for selecting it, but it didn't seemed to work.</p>
| 2 |
How to read results from Windows.Devices.Enumeration.DeviceInformation.FindAllAsync using await syntax?
|
<p>My computer has a working smartcard reader that should be returned by the code snippet below:</p>
<pre><code>string selector = Windows.Devices.SmartCards.SmartCardReader.GetDeviceSelector();
Windows.Devices.Enumeration.DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selector);
</code></pre>
<p>However, I am getting this error:</p>
<blockquote>
<p>Error CS4036 '<code>IAsyncOperation<DeviceInformationCollection></code>' does not contain a definition for '<code>GetAwaiter</code>' and no extension method '<code>GetAwaiter</code>' accepting a first argument of type '<code>IAsyncOperation<DeviceInformationCollection></code>' could be found (are you missing a using directive for '<code>System</code>'?)</p>
</blockquote>
<p>The code snippet is copied from <a href="https://code.msdn.microsoft.com/windowsapps/Smart-card-sample-c7d342e0" rel="nofollow">Microsoft's C# Sample Code</a></p>
<p>What can I do to solve this error?</p>
| 2 |
Why does a composer update need access to the database
|
<p>I am working with Symfony 2.8 and running into some issues launching a simple <code>composer update</code> command. </p>
<p>This error comes on my development environment. I am using a vagrant virtual machine. Here is the error:</p>
<pre><code>[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [2002] Connection refused
[PDOException]
SQLSTATE[HY000] [2002] Connection refused
Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-update-cmd event terminated with an exception
</code></pre>
<p>Of course, this is happening when I launch the command on my host machine. PHP cannot connect to the database because my host machine doesn't have any. So this is a normal behaviour. </p>
<p>The command works well when I ssh into my VM. </p>
<p>So I could stop here and just update my dependencies from my VM. </p>
<p>However, I don't want a <code>composer update</code> to access my database, and I don't see why it would need it. </p>
<p>Where should I look or what information could I give you to help me solve my problem? </p>
<p>EDIT: Here is my <code>composer.json</code> file:</p>
<pre><code>{
"name": "root/blog",
"license": "proprietary",
"type": "project",
"autoload": {
"psr-4": {
"": "src/",
"SymfonyStandard\\": "app/SymfonyStandard/"
}
},
"require": {
"php": ">=5.3.9",
"symfony/symfony": "2.8.*",
"doctrine/orm": "^2.4.8",
"doctrine/doctrine-bundle": "~1.4",
"symfony/assetic-bundle": "~2.3",
"symfony/swiftmailer-bundle": "~2.3",
"symfony/monolog-bundle": "~2.4",
"sensio/distribution-bundle": "~4.0",
"sensio/framework-extra-bundle": "^3.0.2",
"incenteev/composer-parameter-handler": "~2.0",
"jms/serializer": "^1.1",
"gedmo/doctrine-extensions": "dev-master",
"friendsofsymfony/user-bundle": "~2.0@dev",
"setasign/fpdf": "^1.8",
"picqer/php-barcode-generator": "^0.2.0",
"oneup/flysystem-bundle": "^1.3",
"itbz/fpdf": "^1.7",
"milon/barcode": "^5.2"
},
"require-dev": {
"sensio/generator-bundle": "~2.3"
},
"scripts": {
"post-root-package-install": [
"SymfonyStandard\\Composer::hookRootPackageInstall"
],
"post-install-cmd": [
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
],
"post-update-cmd": [
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
]
},
"config": {
"bin-dir": "bin"
},
"extra": {
"symfony-app-dir": "app",
"symfony-web-dir": "web",
"symfony-assets-install": "relative",
"incenteev-parameters": {
"file": "app/config/parameters.yml"
}
}
}
</code></pre>
| 2 |
Plot csv - define legend labels
|
<p>I created a csv-file (with pandas and the help of a friend) like the one in the picture.</p>
<p><a href="https://i.stack.imgur.com/MdWvs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MdWvs.png" alt="enter image description here"></a></p>
<p>Now I need to plot this file.
The first column is the time and should be used for x data. The rest is y data.</p>
<p>For the legend I just want the first row to be used for the labels, like "T_HS_Netz_03" for the second column.</p>
<p>Could not figure out how to do this.</p>
<p>My first attempt:</p>
<pre><code>csv_data = pd.read_csv('file', header=[0, 1], delimiter=';')
ax = csv_data.plot(legend=True)
plt.legend(bbox_to_anchor=(0., 1.0, 1.0, 0.), loc=3, ncol=2, mode="expand")
plt.show()
</code></pre>
<p>But this includes the second row in the labels too and the x ticks does not match the data (0.9 - 3.2).
<p></p>
<p>Second attempt:</p>
<pre><code>csv_data = pd.read_csv('file', header=[0, 1], delimiter=';')
x =csv_data.iloc[1:, [0]]
y = csv_data.iloc[1:, 1:]
plt.legend()
plt.plot(x, y)
</code></pre>
<p>This does not show any labels</p>
<p>The resulting plot should be something like</p>
<p><img src="https://i.stack.imgur.com/kHiIF.png" alt="enter image description here"></p>
<p><p><p></p>
<p>Thanks</p>
| 2 |
Command not found after I installed foreman
|
<p>I am trying to use foreman locally before send it to heroku.</p>
<p>I ran this line to install foreman npm install -g foreman</p>
<p><a href="https://i.stack.imgur.com/cHYQT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cHYQT.png" alt="enter image description here"></a></p>
<p>I get command not found</p>
<p><a href="https://i.stack.imgur.com/NEw1o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NEw1o.png" alt="enter image description here"></a></p>
<p>Please help. </p>
<p>Thanks</p>
| 2 |
Neo4J Java Bolt CREATE Node is slow. How to improve it?
|
<p>I'm trying to insert a bunch of nodes Neo4J using the following code:</p>
<pre><code>import org.neo4j.driver.v1.*;
public class BoltClass
{
public static void minimalWorkingExample() throws Exception
{
Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "neo4j", "admin4j" ) );
Session session = driver.session();
int k=0;
for (int i = 0; i < 1000; i++) {
int count = 1000;
long begin = System.currentTimeMillis();
for (int j = 0; j < count; j ++) {
session.run("CREATE (a:Person {id:" + k + ", name:'unknown'})");
}
long end = System.currentTimeMillis();
System.out.print("Inserting " + (double)count/((double)(end-begin)/count) + " nodes per second.\n");
k++;
}
session.close();
driver.close();
}
public static void main(String[] args)
{
try {
minimalWorkingExample();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>Results:</p>
<pre><code>Inserting 58.8235294117647 nodes per second.
Inserting 76.92307692307692 nodes per second.
Inserting 50.0 nodes per second.
Inserting 76.92307692307692 nodes per second.
Inserting 55.55555555555556 nodes per second.
Inserting 62.5 nodes per second.
Inserting 66.66666666666667 nodes per second.
Inserting 55.55555555555556 nodes per second.
Inserting 62.5 nodes per second.
Inserting 55.55555555555556 nodes per second.
Inserting 47.61904761904762 nodes per second.
Inserting 45.45454545454545 nodes per second.
Inserting 58.8235294117647 nodes per second.
Inserting 83.33333333333333 nodes per second.
</code></pre>
<p>I'm using Neo4j 3.0.3 and org.neo4j.driver 1.0.4.
The graph was blank before the insertions.
The machine used has an i5 2-2.6GHz CPU and 8GB RAM.</p>
<p>LE: I've just discovered transactions:</p>
<pre><code>public static void TransactionExample() throws Exception
{
Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "neo4j", "admin4j" ) );
Session session = driver.session();
int k=0;
for (int i = 0; i < 1000; i++) {
int count = 1000;
long begin = System.currentTimeMillis();
try ( Transaction tx = session.beginTransaction() )
{
for (int j = 0; j < count; j ++) {
tx.run("CREATE (a:Person {id:" + k + ", name:'unknown'})");
}
tx.success();
}
long end = System.currentTimeMillis();
System.out.print("Inserting " + (double)count/((double)(end-begin)/count) + " nodes per second.\n");
k++;
}
session.close();
driver.close();
}
</code></pre>
<p>Results:</p>
<pre><code>Inserting 20000.0 nodes per second.
Inserting 17857.142857142855 nodes per second.
Inserting 18867.924528301886 nodes per second.
Inserting 15384.615384615385 nodes per second.
Inserting 19607.843137254902 nodes per second.
Inserting 16666.666666666668 nodes per second.
Inserting 16393.44262295082 nodes per second.
</code></pre>
<p>Nice performance boost. Can it be improved even more?</p>
| 2 |
aggregating data in power bi query editor
|
<p>I have gone through this tutorial</p>
<p><a href="https://powerbi.microsoft.com/en-us/documentation/powerbi-desktop-tutorial-analyzing-sales-data-from-excel-and-an-odata-feed/" rel="nofollow">https://powerbi.microsoft.com/en-us/documentation/powerbi-desktop-tutorial-analyzing-sales-data-from-excel-and-an-odata-feed/</a></p>
<p>and was having some issues at Task 4 - Step 1 that I have somewhat resolved but would like to find a better way to complete the task. </p>
<p>The issue of this is that the title of my graph is Sum of UnitsInStock by ProductName but I just want it to be "UnitsInStock by ProductName". </p>
<p>See image below:</p>
<p><a href="http://i.stack.imgur.com/zOHWn.png" rel="nofollow">Sum of UnitsInStock by ProductName</a> </p>
<p>I think the issue is that in the tutorial link it has the "UnitsInStock" column is aggregated already (which you can see in the field pane) whereas I had to aggregate the data myself. I think to fix this I just have to aggregate the data in the query editor but I haven't been able to figure out how to do this.</p>
<p>If someone could point me in the right direction that would be great!</p>
| 2 |
Listen for event when user opens app switcher on iOS
|
<p>How can I listen for an event when a user opens the <a href="https://support.apple.com/en-us/HT202070" rel="noreferrer">app switcher</a> (the UI that comes up when a user double taps on the home button) on iOS.</p>
<p>I though <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/c/data/UIApplicationDidEnterBackgroundNotification" rel="noreferrer">UIApplicationDidEnterBackgroundNotification</a> would fire, but it doesn't fire when I open the app switcher. It only fires when I minimize the app by tapping the home button once.</p>
<pre><code>NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "onPause",
name: UIApplicationDidEnterBackgroundNotification,
object:nil)
func onPause() {
//Not invoked when app switcher is opened
}
</code></pre>
| 2 |
AWS API Gateway custom domain occasional "server DNS address could not be found"
|
<p>I have set up a custom domain on API Gateway, it is a subdomain. api.example.com. The gateway endpoints are pointing to lambda functions. When making a GET request to the subdomain, I am occasionally (and often) getting the error "server DNS address could not be found". It seems like it could be related to the Lambda cold start, but I can't be sure. If it was related to the cold start, wouldn't the request just timeout or hang, instead of sending back, in particular, a DNS error? The DNS error makes me think the cold starting Lambda isn't the issue.</p>
<p>Also, I need to hit the request 5-10 times before it begins returning successful responses.I do this manually right now, so there are brief pauses between each request.</p>
<p>The error seems to be domain specific too. If in one browser tab I make the request 5+ times, it begins to return successfully, but from another server, on a domain somewhere, I have to hit it 5+ times to get a successful response even though it is currently returning successfully from another domain or server. To me, this rules out lambda cold start being the issue, no?</p>
<p>The domain is registered in route 53. I have a hosted zone for example.com, and in that hosted zone I have an A record for api.example.com. The A record target is set to the CloudFront public DNS setup by API Gateway when I added the custom domain.</p>
<p>One of my questions is: Is this configuration incorrect? Should the subdomain be in its own hosted zone, with a new NS record for api.example.com created in the parent domain pointed to the subdomain's hosted zone? Could this configuration be my issue?</p>
| 2 |
Save selected dropdown value to JSON
|
<p>I want to save a value of the selected element of a dropdown to a JSON file.</p>
<pre class="lang-html prettyprint-override"><code><td contenteditable=true bgcolor="#F4F2F2">
<select>
<option value="default">${list.days}</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</code></pre>
<pre class="lang-js prettyprint-override"><code>function(i) {
var $tds = $(this).find('td'), status = $tds.eq(0).text();
console.log(status)
json = json + " {\"deviceType\": \"" + $tds.eq(1).text()+ "\"," + "\"days\": \"" + $tds.eq(2).text()+ "\"},";});
</code></pre>
| 2 |
Python: absolute path issue
|
<p>I have several files stored in a folder called controlFiles. The path to this folder is Users/Desktop/myproject/controlFiles.</p>
<p>I am attempting to run a subprocess command in my python script with the following code:</p>
<pre><code>def codeml(codeml_location, control_location):
runPath = codeml_location + '/codeml'
for file in os.listdir(control_location):
ctlPath = os.path.abspath(file)
subprocess.call([runPath, ctlPath])
</code></pre>
<p>The script's function is to run a command line tool called codeml, with the first argument being the location of the codeml executable, and the second being a folder of control files that codeml uses. When I run this script codeml runs but I get the error:</p>
<pre><code>error when opening file /Users/Desktop/myproject/subtree.39.tre.ctl
tell me the full path-name of the file?
</code></pre>
<p>My confusion comes from the fact that the controlFiles folder is not within that path, yet it still identifies the files within the folder.</p>
<p>To check I was entering the correct control_location argument I edited the code as such:</p>
<pre><code>def codeml(codeml_location, control_location):
runPath = codeml_location + '/codeml'
for file in os.listdir(control_location):
print os.path.abspath(file)
</code></pre>
<p>Running this printed all the files in the controlFiles folder, but again without the folder within the paths. Here is a sample of the print out:</p>
<pre><code>/Users/Desktop/myproject/subtree.68.tre.ctl
/Users/Desktop/myproject/subtree.69.tre.ctl
/Users/Desktop/myproject/subtree.70.tre.ctl
/Users/Desktop/myproject/subtree.71.tre.ctl
</code></pre>
<p>To run the function my control location argument is:</p>
<pre><code>control_location = /Users/Desktop/myproject/controlFiles
</code></pre>
<p>A final point is that my working directory in the terminal is /Users/Desktop/myproject and this is because this is the location of my Click project. Why are the files being picked up but not the folder containing them?</p>
| 2 |
Geocode and tweets in searchTwitter with TwitteR (r package)
|
<p>When searching for tweets in the UK, I specified the geocode option :</p>
<pre><code>tweets <- searchTwitter("british", n=100,
lang="en",since="2016-06-22", until="2016-06-24",
geocode='54.20,-2,700km')
</code></pre>
<p>However, in the resultats, the values of longitude and latitude are <code>NA</code>. (Only very few of them have values). Does that mean that twitter hides the results ?</p>
| 2 |
How do I check whether an element exists in the UI hierarchy?
|
<p>How do I check whether an element exists in the UI hierarchy? I dont want EarlGrey to fail if an element does not exist but just check if its there, I need this for UITableView where I must constantly scroll to top and scroll down searching an element but the element is sometimes already on the current view to begin with.</p>
| 2 |
How to align stacked Font-Awesome icons correctly
|
<p>I have been at this for way too long and have yet to figure out how to stack four font-awesome icons on top of each other. I've gotten to three but I am wanting my icons to look like this <a href="https://i.stack.imgur.com/Tmf9U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tmf9U.png" alt="four stacked icons"></a> (sorry for crummy image)</p>
<p>Here's the HTML for my three stacked.</p>
<pre><code><span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x icon-background4"></i>
<i class="fa fa-circle-thin fa-stack-2x icon-background6"></i>
<i class="fa fa-cutlery fa-inverse fa-stack-1x"></i>
</span>
</code></pre>
<p>The CSS</p>
<pre><code>.icon-stack-1x {
line-height: inherit;
}
.icon-stack-2x {
font-size: 1.5em;
}
</code></pre>
| 2 |
Image Button not working in Emulator and PhoneGap - Ionic 2
|
<p>I have this class in my home.scss</p>
<pre><code>.img_button{
color: #fff;
width: 200px;
height: 70px;
background: none;
box-shadow: 0px 0px 0px 0px;
background-image: url("/build/images/lotus_button.png");
background-repeat: no-repeat;
background-size: 100%;
background-size: 200px auto;
padding: 0 0 0 3em;
background-color: transparent !important;
}
</code></pre>
<p>In home.html</p>
<pre><code><ion-content class="home" padding>
<button class="img_button">Image Custom Button</button>
</ion-content>
</code></pre>
<p>It's working fine in the browser, but not in the <code>ionic emulate ios</code> or <code>phonegap serve</code>. </p>
<p>However, in the .img_button in home.scss I change background-image to url like this: <code>background-image: url("http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png");</code> It's working in all <code>ionic emulate ios</code>, <code>phonegap serve</code>, and in the browser. </p>
<p>I'm not sure of how to use my local path for background-image in scss. </p>
<p>Please help. Thanks. </p>
| 2 |
How to use carousel View in xamarin ios
|
<p>I am trying to implement Images carousel View as per the below image.
<a href="https://i.stack.imgur.com/JM6XY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JM6XY.png" alt="enter image description here"></a></p>
<p>I want to display multiple images using carousel view with highlighted dots when user scroll the images (Highlight the respective dot below the image) in Xamarin IOS.</p>
<p>I tried with iCarousel - Xamarin Component ( iCarousel Link ) to display images with dots. Here i am able to display the images in carousel view. Can any one suggest me to resolve this issue.</p>
| 2 |
Program in Qt Creator using opencv crashes unexpectedly
|
<p>I am a beginner in both Qt Programming and Opencv and I am just trying to run a basic program of showing an image in a window.</p>
<p>I went through a lot of tutorials online and I was finally able to install Opencv and link the libraries with Qt without any error. But when I run the program, it just gets unexpectedly finished without showing any error.</p>
<ul>
<li>I tried it in debug mode, but it just says "debugging has finished" in under a second, even if there are many breakpoints in the middle.</li>
<li>I also tried running the program using depends in order to find out what was missing and it showed up some dlls, and I tried downloading it and placing it in the required folder, but it still didn't work.</li>
</ul>
<p>Here are my code snippets:</p>
<p>My Pro file:</p>
<pre><code> QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = opencv2
TEMPLATE = app
INCLUDEPATH += C:/opencv/opencv/build/include
LIBS += -LC:/opencv/opencv/build/x86/vc11/lib
LIBS += -lopencv_core2413d \
-lopencv_highgui2413d \
-lopencv_imgproc2413d \
-lopencv_features2d2413d \
-lopencv_contrib2413d \
-lopencv_flann2413d \
-lopencv_gpu2413d \
-lopencv_legacy2413d \
-lopencv_ml2413d \
-lopencv_nonfree2413d \
-lopencv_objdetect2413d \
-lopencv_photo2413d \
-lopencv_stitching2413d \
-lopencv_superres2413d \
-lopencv_ts2413d \
-lopencv_video2413d \
-lopencv_videostab2413d \
-lopencv_calib3d2413d \
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
</code></pre>
<p>My mainwindow.h:</p>
<pre><code> #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QImage imdisplay;
QTimer* Timer;
public slots:
void DisplayImage();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
</code></pre>
<p>My main.cpp:</p>
<pre><code> #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
</code></pre>
<p>My mainwindow.cpp:</p>
<pre><code> #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
using namespace cv;
MainWindow::MainWindow(QWidget *parent)
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Timer = new QTimer(this);
connect(Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
Timer->start(); //Will start the timer
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::DisplayImage()
{
Mat img;
img = imread("D:\\Kumar\\amazon.jpeg");
cv::resize(img, img, Size(512, 384), 0, 0, INTER_LINEAR);
cv::cvtColor(img,img,CV_BGR2RGB);
QImage imdisplay((uchar*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
ui->display_image->setPixmap(QPixmap::fromImage(imdisplay));
}
</code></pre>
<p>And the screenshot from depends:</p>
<p><a href="https://i.stack.imgur.com/CbPWA.jpg" rel="nofollow noreferrer">This lists the dlls that are missing </a></p>
<p>And the locations I have added in my Path environment variable are:</p>
<pre><code>C:\opencv\opencv\build\x86\vc11\bin;
C:\Program Files (x86)\Qt\Tools\mingw492_32\bin\;
C:\opencv\opencv\build\bin\;
</code></pre>
<p>I have been trying to figure this out for the past two days, but I am totally stuck. If someone went through the same problem or if someone knows the solution, it would be really nice of you, if you could share it with me!</p>
<p>EDIT: Okay, I rebuilt opencv with a vc10 toolchain like <a href="https://stackoverflow.com/users/1468415/mvidelgauz">mvidelgauz</a> suggested, and I still get the same problem, although this time, the missing dlls are different. </p>
<p><a href="https://i.stack.imgur.com/eWLFa.jpg" rel="nofollow noreferrer">This is the new screenshot</a></p>
<p>Any other suggestions?</p>
| 2 |
Concatenate strings from two different RDD in Python Spark
|
<p>Let's say I have 2 rdds :
the first rdd is composed of strings which are html requests :</p>
<p><strong>rdd1 :</strong></p>
<pre><code>serverIP:80 clientIP1 - - [10/Jun/2016:10:47:37 +0200] "GET /path/to/page1 [...]"
serverIP:80 clientIP2 - - [11/Jun/2016:11:25:12 +0200] "GET /path/to/page2 [...]"
...
</code></pre>
<p>The second rdd is simply integers :</p>
<p><strong>rdd2 :</strong></p>
<pre><code>0.025
0.56
...
</code></pre>
<p>I would like to concatenate the string lines by lines in order to obtain a third rdd like this :
<strong>rdd3 :</strong></p>
<pre><code>serverIP:80 clientIP1 - - [10/Jun/2016:10:47:37 +0200] "GET /path/to/page1 [...]" 0.025
serverIP:80 clientIP2 - - [11/Jun/2016:11:25:12 +0200] "GET /path/to/page2 [...]" 0.56
...
</code></pre>
<p>By the way, this job is a streaming job. It's to say, I don't want to store permanently the data in some kind of sql table or something else.</p>
<p>Any idea on how to tackle this ?</p>
<p>Thanks in advance !</p>
<p><strong>EDIT :</strong> For people trying to join Dstream and not rdd, have a look at this : <a href="https://stackoverflow.com/questions/37466361/how-to-combine-two-dstreams-using-pyspark-similar-to-zip-on-normal-rdd">How to Combine two Dstreams using Pyspark (similar to .zip on normal RDD)</a></p>
| 2 |
ANTLR4 performance issue
|
<p>There has been some discussion on the performance of ANTL4 parsing e.g:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/19311864/antlr-4-parsing-large-c-file-takes-forever">Antlr 4 parsing large c file takes forever</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/32645754/is-there-any-good-ways-to-improve-the-parsers-performance-generated-using-antlr">Is there any good ways to improve the parser's performance generated using antlr4?</a></p></li>
</ul>
<p>and there is an open bug report:</p>
<ul>
<li><a href="https://github.com/antlr/antlr4/issues/994" rel="nofollow noreferrer">https://github.com/antlr/antlr4/issues/994</a></li>
</ul>
<p>that calls for using two phase strategy to improve the performance of ANTLR4. To do so you first call the parser in SLL mode and only on failure the slower LL mode is used. </p>
<p>This works nicely for small grammars like the one used in issue 994:</p>
<pre><code>grammar expr;
expr: ID
| 'not' expr
| expr 'and' expr
| expr 'or' expr
| expr 'between' expr 'and' expr
;
ID: [a-zA-Z_][a-zA-Z_0-9]*;
WS: [ \t\n\r\f]+ -> skip;
ERROR: .;
</code></pre>
<p>but if the grammar gets slightly more complicated and ambiguous:</p>
<pre><code>/**
* see https://github.com/antlr/antlr4/issues/994
*/
grammar numexpr;
numexpr: if_statement EOF;
if_statement:
if_part ( else_part ) ? 'endif';
if_part:
'if' expr statement_list|
'if' expr;
else_part:
'else' statement_list |
'else';
statement_list:
statement +;
statement: if_statement;
expr: ID
| VALUE
| 'not' expr
| expr '=' expr
| expr 'and' expr
| expr 'or' expr
| expr 'between' expr 'and' expr
;
VALUE: [0-9]+;
ID: [a-zA-Z_][a-zA-Z_0-9]*;
WS: [ \t\n\r\f]+ -> skip;
ERROR: .;
</code></pre>
<p>Using the two phase strategy doesn't work anymore.
The timing result is:</p>
<pre><code> 2 27 msecs 0,2
3 95 msecs 3,5
4 99 msecs 1,0
5 64 msecs 0,6
6 87 msecs 1,4
7 181 msecs 2,1
8 350 msecs 1,9
9 822 msecs 2,3
10 2912 msecs 3,5
11 7134 msecs 2,4
12 21420 msecs 3,0
ratio: 2,01
</code></pre>
<p>It takes more than double the time for each "and valuex=x" expression part being added starting with the input</p>
<pre><code>if Value=0 and not Value0=0 and not Value1=1 endif.
</code></pre>
<p>There needs to be some work on the grammar to make it fit for SLL.</p>
<p><strong>How would this be done?</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/29441249/how-do-i-diagnose-ambiguities-in-my-antlr4-grammar">How do I diagnose ambiguities in my ANTLR4 grammar?</a></li>
</ul>
<p>asks a related questions. So if I add </p>
<pre class="lang-java prettyprint-override"><code>if (mode.equals(PredictionMode.LL_EXACT_AMBIG_DETECTION)) {
parserHolder.parser.addErrorListener(new DiagnosticErrorListener());
}
</code></pre>
<p>and change the doTestParser line to:</p>
<pre class="lang-java prettyprint-override"><code>doTestParser(parserHolder, PredictionMode.LL_EXACT_AMBIG_DETECTION, PredictionMode.LL);
</code></pre>
<p>I also do not get any ambiguity lines but only:</p>
<pre><code>if Value=0 and not Value0=0 and not Value1=1 endif
line 1:20 reportAttemptingFullContext d=6 (expr), input='andnotValue0'
line 1:12 reportContextSensitivity d=6 (expr), input='and'
line 1:37 reportAttemptingFullContext d=6 (expr), input='andnotValue1'
line 1:29 reportContextSensitivity d=6 (expr), input='and'
</code></pre>
<p>Please find below a JUnit Test that shows the problem. It consists of two classes - an abstract base class and the test class that shows the timing issues with</p>
<ul>
<li><a href="https://github.com/antlr/antlr4/issues/994" rel="nofollow noreferrer">https://github.com/antlr/antlr4/issues/994</a>
and</li>
<li><a href="https://github.com/antlr/antlr4/issues/1232" rel="nofollow noreferrer">https://github.com/antlr/antlr4/issues/1232</a></li>
</ul>
<p><strong>JUnit Testcase</strong></p>
<pre class="lang-java prettyprint-override"><code>package com.bitplan.ruleparser;
import java.io.IOException;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.ParserRuleContext;
import org.junit.Test;
import com.bitplan.expr.exprLexer;
import com.bitplan.expr.exprParser;
import com.bitplan.numexpr.numexprLexer;
import com.bitplan.numexpr.numexprParser;
/**
* Test the Issue 994 performance
*
* @author wf
*
*/
public class TestIssue994 extends TestTwoPhaseParser {
public static class ExprParserHolderFactory extends ParserHolderFactory {
@Override
ParserHolder getParserHolder(int index) throws Exception {
return new ExprParserHolder(index);
}
}
/**
*
* @author wf
*
*/
public static class ExprParserHolder extends ParserHolder {
public ExprParserHolder(int index) throws IOException {
super(index);
}
private exprParser mParser;
@Override
protected org.antlr.v4.runtime.Parser getParser(CommonTokenStream tokens) {
mParser = new exprParser(tokens);
return mParser;
}
@Override
protected Lexer getLexer(ANTLRInputStream in) {
return new exprLexer(in);
}
@Override
protected ParserRuleContext parse() {
return mParser.expr();
}
@Override
protected String getInput(int index) {
String andClause = "not X0";
for (int i = 0; i <= index; i++) {
if (i % 4 == 1) {
andClause += " or X" + i;
} else {
andClause += " and not X" + i;
}
}
return andClause;
}
}
public static class NumExprParserHolderFactory extends ParserHolderFactory {
@Override
ParserHolder getParserHolder(int index) throws Exception {
return new NumExprParserHolder(index);
}
}
/**
*
* @author wf
*
*/
public static class NumExprParserHolder extends ParserHolder {
public NumExprParserHolder(int index) throws IOException {
super(index);
}
private numexprParser mParser;
@Override
protected org.antlr.v4.runtime.Parser getParser(CommonTokenStream tokens) {
mParser = new numexprParser(tokens);
return mParser;
}
@Override
protected Lexer getLexer(ANTLRInputStream in) {
return new numexprLexer(in);
}
@Override
protected ParserRuleContext parse() {
return mParser.numexpr();
}
@Override
protected String getInput(int index) {
String andClause = "if Value=0 ";
for (int i = 0; i <= index; i++) {
andClause += " and not Value" + i+"="+i;
}
andClause+=" endif";
return andClause;
}
}
/**
* see https://github.com/antlr/antlr4/issues/994
*
* @throws Exception
*/
@Test
public void testIssue994() throws Exception {
super.testDuration(new ExprParserHolderFactory(),60);
}
/**
* see https://github.com/antlr/antlr4/issues/994
*
* @throws Exception
*/
@Test
public void testIssue994NumExpr() throws Exception {
debug=true;
super.testDuration(new NumExprParserHolderFactory(),12);
}
}
</code></pre>
<p><strong>Base class</strong></p>
<pre class="lang-java prettyprint-override"><code>package com.bitplan.ruleparser;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.Parser;
/**
*
* @author wf
* see https://github.com/antlr/antlr4/issues/994
*/
public abstract class TestTwoPhaseParser {
static boolean debug = false;
public static abstract class ParserHolderFactory {
abstract ParserHolder getParserHolder(int index) throws Exception;
}
/**
* hold a parser and some input;
*/
public static abstract class ParserHolder {
ANTLRInputStream in;
CommonTokenStream tokens;
Parser parser;
private Lexer lexer;
private String input;
/**
* create a parser Holder for the given index
*
* @param index
* @throws IOException
*/
public ParserHolder(int index) throws IOException {
input = getInput(index);
init(input);
}
/**
* create a parser holder for the given input
*
* @param input
* @throws IOException
*/
public void init(String input) throws IOException {
if (debug)
System.out.println(input);
in = streamForText(input);
lexer = getLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
parser = getParser(tokens);
}
/**
* get an input of the given index/size
*
* @param index
* @return a string to be tested
*/
protected abstract String getInput(int index);
protected abstract Parser getParser(CommonTokenStream tokens);
protected abstract Lexer getLexer(ANTLRInputStream in);
protected abstract ParserRuleContext parse();
/**
* get the ANTLRInputStream for the given text
*
* @param text
* @return
* @throws IOException
*/
public static ANTLRInputStream streamForText(String text)
throws IOException {
InputStream stream = new ByteArrayInputStream(
text.getBytes(StandardCharsets.UTF_8));
ANTLRInputStream in = new ANTLRInputStream(stream);
return in;
}
}
/**
* test how long the parsing takes
*
* @param parserHolderFactory
* @throws Exception
*/
public void testDuration(ParserHolderFactory parserHolderFactory, int max)
throws Exception {
long prevduration = 0;
double ratiosum = 0;
int ratiocount = 0;
for (int i = 1; i <= max; i++) {
long start = System.currentTimeMillis();
ParserHolder parserHolder = parserHolderFactory.getParserHolder(i);
doTestParser(parserHolder, PredictionMode.SLL, PredictionMode.LL);
long stop = System.currentTimeMillis();
long duration = stop - start;
if (duration < 1)
duration = 1;
if (i >= 2) {
double ratio = duration * 1.0 / (prevduration * 1.0);
System.out.println(String.format("%3d %5d msecs %5.1f", i, duration,
ratio));
ratiosum += ratio;
ratiocount++;
}
prevduration = duration;
}
double averageRatio = ratiosum / ratiocount;
System.out.println(String.format("ratio: %3.2f", averageRatio));
assertTrue("Performance issue https://github.com/antlr/antlr4/issues/994",
averageRatio < 1.2);
}
/**
* tes the parser
*
* @param parserHolder
* @param mode
* @param fallBackMode
* @return
* @throws IOException
*/
protected ParserRuleContext doTestParser(ParserHolder parserHolder,
PredictionMode mode, PredictionMode fallBackMode) throws IOException {
ParserRuleContext result;
try {
BailErrorStrategy errorHandler = new BailErrorStrategy();
parserHolder.parser.setErrorHandler(errorHandler);
// set PredictionMode
parserHolder.parser.getInterpreter().setPredictionMode(mode);
result = parserHolder.parse();
} catch (Throwable th) {
if (th instanceof ParseCancellationException) {
ParseCancellationException pce = (ParseCancellationException) th;
if (pce.getCause() instanceof RecognitionException) {
RecognitionException re = (RecognitionException) pce.getCause();
ParserRuleContext context = (ParserRuleContext) re.getCtx();
throw context.exception;
}
}
if (fallBackMode != null) {
parserHolder.tokens.reset();
parserHolder.parser.reset();
parserHolder.parser.getInterpreter().setPredictionMode(fallBackMode);
result = parserHolder.parse();
} else {
throw th;
}
}
if (debug) {
System.out.println(result.toStringTree());
}
return result;
}
}
</code></pre>
<p><strong>Debug output</strong></p>
<pre><code>if Value=0 and not Value0=0 and not Value1=1 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] Value) = ([52 12 12 28 17 14] 0)) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value0)) = ([52 55 12 28 17 14] 0))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value1)) = ([52 55 28 17 14] 1)))) endif) <EOF>)
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] Value) = ([52 12 12 12 28 17 14] 0)) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value0)) = ([52 55 12 12 28 17 14] 0))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value1)) = ([52 55 12 28 17 14] 1))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value2)) = ([52 55 28 17 14] 2)))) endif) <EOF>)
2 27 msecs 0,2
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 28 17 14] 0))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value1)) = ([52 55 12 12 28 17 14] 1))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value2)) = ([52 55 12 28 17 14] 2))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value3)) = ([52 55 28 17 14] 3)))) endif) <EOF>)
3 96 msecs 3,6
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 28 17 14] 1))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value2)) = ([52 55 12 12 28 17 14] 2))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value3)) = ([52 55 12 28 17 14] 3))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value4)) = ([52 55 28 17 14] 4)))) endif) <EOF>)
4 99 msecs 1,0
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 28 17 14] 2))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value3)) = ([52 55 12 12 28 17 14] 3))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value4)) = ([52 55 12 28 17 14] 4))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value5)) = ([52 55 28 17 14] 5)))) endif) <EOF>)
5 65 msecs 0,7
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 12 28 17 14] 2))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value3)) = ([52 55 12 12 12 28 17 14] 3))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value4)) = ([52 55 12 12 28 17 14] 4))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value5)) = ([52 55 12 28 17 14] 5))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value6)) = ([52 55 28 17 14] 6)))) endif) <EOF>)
6 90 msecs 1,4
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 and not Value7=7 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 12 12 28 17 14] 2))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value3)) = ([52 55 12 12 12 12 28 17 14] 3))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value4)) = ([52 55 12 12 12 28 17 14] 4))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value5)) = ([52 55 12 12 28 17 14] 5))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value6)) = ([52 55 12 28 17 14] 6))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value7)) = ([52 55 28 17 14] 7)))) endif) <EOF>)
7 185 msecs 2,1
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 and not Value7=7 and not Value8=8 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 12 12 12 28 17 14] 2))) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value3)) = ([52 55 12 12 12 12 12 28 17 14] 3))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value4)) = ([52 55 12 12 12 12 28 17 14] 4))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value5)) = ([52 55 12 12 12 28 17 14] 5))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value6)) = ([52 55 12 12 28 17 14] 6))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value7)) = ([52 55 12 28 17 14] 7))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value8)) = ([52 55 28 17 14] 8)))) endif) <EOF>)
8 358 msecs 1,9
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 and not Value7=7 and not Value8=8 and not Value9=9 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 12 12 12 12 28 17 14] 2))) and ([55 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 28 17 14] Value3)) = ([52 55 12 12 12 12 12 12 28 17 14] 3))) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value4)) = ([52 55 12 12 12 12 12 28 17 14] 4))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value5)) = ([52 55 12 12 12 12 28 17 14] 5))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value6)) = ([52 55 12 12 12 28 17 14] 6))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value7)) = ([52 55 12 12 28 17 14] 7))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value8)) = ([52 55 12 28 17 14] 8))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value9)) = ([52 55 28 17 14] 9)))) endif) <EOF>)
9 837 msecs 2,3
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 and not Value7=7 and not Value8=8 and not Value9=9 and not Value10=10 endif
...
11 7346 msecs 2,5
if Value=0 and not Value0=0 and not Value1=1 and not Value2=2 and not Value3=3 and not Value4=4 and not Value5=5 and not Value6=6 and not Value7=7 and not Value8=8 and not Value9=9 and not Value10=10 and not Value11=11 and not Value12=12 endif
([] ([14] ([17 14] if ([28 17 14] ([12 28 17 14] ([12 12 28 17 14] ([12 12 12 28 17 14] ([12 12 12 12 28 17 14] ([12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 12 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] Value) = ([52 12 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] 0)) and ([55 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] Value0)) = ([52 55 12 12 12 12 12 12 12 12 12 12 12 12 28 17 14] 0))) and ([55 12 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 12 12 12 28 17 14] Value1)) = ([52 55 12 12 12 12 12 12 12 12 12 12 12 28 17 14] 1))) and ([55 12 12 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 12 12 28 17 14] Value2)) = ([52 55 12 12 12 12 12 12 12 12 12 12 28 17 14] 2))) and ([55 12 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 12 28 17 14] Value3)) = ([52 55 12 12 12 12 12 12 12 12 12 28 17 14] 3))) and ([55 12 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 12 28 17 14] Value4)) = ([52 55 12 12 12 12 12 12 12 12 28 17 14] 4))) and ([55 12 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 12 28 17 14] Value5)) = ([52 55 12 12 12 12 12 12 12 28 17 14] 5))) and ([55 12 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 12 28 17 14] Value6)) = ([52 55 12 12 12 12 12 12 28 17 14] 6))) and ([55 12 12 12 12 12 28 17 14] ([12 55 12 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 12 28 17 14] Value7)) = ([52 55 12 12 12 12 12 28 17 14] 7))) and ([55 12 12 12 12 28 17 14] ([12 55 12 12 12 12 28 17 14] not ([47 12 55 12 12 12 12 28 17 14] Value8)) = ([52 55 12 12 12 12 28 17 14] 8))) and ([55 12 12 12 28 17 14] ([12 55 12 12 12 28 17 14] not ([47 12 55 12 12 12 28 17 14] Value9)) = ([52 55 12 12 12 28 17 14] 9))) and ([55 12 12 28 17 14] ([12 55 12 12 28 17 14] not ([47 12 55 12 12 28 17 14] Value10)) = ([52 55 12 12 28 17 14] 10))) and ([55 12 28 17 14] ([12 55 12 28 17 14] not ([47 12 55 12 28 17 14] Value11)) = ([52 55 12 28 17 14] 11))) and ([55 28 17 14] ([12 55 28 17 14] not ([47 12 55 28 17 14] Value12)) = ([52 55 28 17 14] 12)))) endif) <EOF>)
12 21790 msecs 3,0
ratio: 2,01
</code></pre>
| 2 |
Simulating top, bottom, left and right margins in tkinter pack geometry
|
<p>What should be done to have <strong>left_margin</strong> (<em>cyan</em>) and <strong>right_margin</strong> (<em>magenta</em>) frames taking all vertical height from <strong>top_margin</strong> to <strong>bottom_margin</strong>?</p>
<pre><code>import Tkinter as tk
root = tk.Tk()
top_margin = tk.Frame(root, height=32, background='red')
left_margin = tk.Frame(root, background='cyan')
sheet_area = tk.Frame(root, background='white')
right_margin = tk.Frame(root, background='magenta')
bottom_margin = tk.Frame(root, height=32, background='blue')
top_margin.pack(side=tk.TOP, expand=tk.YES, fill=tk.X, anchor=tk.N)
bottom_margin.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.X, anchor=tk.S)
left_margin.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)
right_margin.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.BOTH)
root.mainloop()
</code></pre>
| 2 |
Bootstrap markdown not working as expected
|
<p>I am trying to use the Bootstrap markdown as documented <a href="http://www.codingdrama.com/bootstrap-markdown/" rel="nofollow">here</a>. This is what I have come up with: <a href="https://jsfiddle.net/ejhvkacm/" rel="nofollow">fiddle</a>.</p>
<p>HTML:</p>
<pre><code><textarea name="content" data-provide="markdown" rows="10" id = "foo"></textarea>
</code></pre>
<p>JS:</p>
<pre><code>$(function() {
$("#foo").markdown({autofocus:false,savable:true});
});
</code></pre>
<p>It is a pretty basic fiddle with just a text area and the markdown code, but as you can see, it does not work as expected, the buttons are not showing up correctly, and preview is not working.</p>
<p>How do I fix it to work as expected?</p>
| 2 |
chef SSL Validation failure connecting to host after Chef Development Kit installation
|
<p>I ran knife bootstrap on a node with, chef client ran and everything works.</p>
<p>After I installed on the node Chef Development Kit:</p>
<pre><code>wget https://packages.chef.io/stable/el/7/chefdk-0.15.16-1.el7.x86_64.rpm
sudo rpm -Uvh chefdk-0.15.16-1.el7.x86_64.rpm
</code></pre>
<p>Chef client versions:</p>
<p>Before the chefdk installation: starting Chef Client, version 11.8.2</p>
<p>After the chefdk installation: starting Chef Client, version 12.11.18</p>
<p>The error message:</p>
<pre><code>ERROR: SSL Validation failure connecting to host: xxx.mychefserver.mydomain.com - SSL_connect returned=1 errno=0 state=error: certificate verify failed
================================================================================
Chef encountered an error attempting to load the node data for "xxx.mychefnode.mydomain.com"
================================================================================
Unexpected Error:
-----------------
OpenSSL::SSL::SSLError: SSL Error connecting to https://xxx.mychefserver.mydomain.int/nodes/xxx.mychefnode.mydomain.com - SSL_connect returned=1 errno=0 state=error: certificate verify failed
</code></pre>
<p>Any idea how to fix it ?
Thanks!</p>
| 2 |
JavaScript error in Firefox only: Permission denied to access property "toJSON"
|
<p>In Google picker on the file selection, I am converting the token into JSON Like this:</p>
<pre><code>access_token = JSON.stringify(token);
</code></pre>
<p>It is giving an error in Firefox</p>
<blockquote>
<p>Permission denied to access property "toJSON"</p>
</blockquote>
<p>The same code is working fine in Chrome and IE11.</p>
| 2 |
Structure of $FILE_NAME attribute in NTFS file system
|
<p>I'm reading about the NTFS attribute types and it come to the $FILE_NAME attribute structure. Here it is:</p>
<pre><code>Offset Size Description
~ ~ Standard Attribute Header
0x00 8 File reference to the parent directory.
0x08 8 C Time - File Creation
0x10 8 A Time - File Altered
0x18 8 M Time - MFT Changed
0x20 8 R Time - File Read
0x28 8 Allocated size of the file
0x30 8 Real size of the file
0x38 4 Flags, e.g. Directory, compressed, hidden
0x3c 4 Used by EAs and Reparse
0x40 1 Filename length in characters (L)
0x41 1 Filename namespace
0x42 2L File name in Unicode (not null terminated)
</code></pre>
<p>What is "Filename Namespace" at the offset 0x41? I know a little about namespace i think. How can it be stored in just 1 byte? Can anyone clear this for me? Thank you.</p>
| 2 |
Postgres JSONB: where clause for arrays of arrays
|
<p>there is in postgres (v 9.5, if it is matter):</p>
<pre><code>create table json_test(
id varchar NOT NULL,
data jsonb NOT NULL,
PRIMARY KEY(id)
);
</code></pre>
<p>Where data is json and contains array of arrays</p>
<pre><code>{
"attribute": "0",
"array1": [{
"id": "a12",
"attribute": "1",
"array2": [{
"id": "a21",
"attribute": "21"
}]
},
{
"id": "a12",
"attribute": "2",
"array2": [{
"id": "22",
"attribute": "22"
}]
}]
}
</code></pre>
<p>Required: </p>
<pre><code>select id from json_test where
json_test->>'attribute'='0' and
array1.[id='a12'].array2.attribute='22'
</code></pre>
<p>Query should mean: give me all ids where </p>
<ol>
<li>some top level attributes have particular values</li>
<li>particular object in array has required attributes</li>
<li>some object (from array2) in particular array1 has required attributes</li>
</ol>
<p>the trick is how to implement the last condition.</p>
<hr>
<p>another example:</p>
<pre><code>{
"attribute": "0",
"array1": [{
"id": "a12",
"attribute": "1",
"array2": [{
"id": "a21_1",
"attribute_1": "21_1"
},{
"id": "a21_2",
"attribute_2": "21_2"
}]
}]
}
select * from json_test where
array1.[id='a12'].array2.attribute_1='21_1' and
array1.[id='a12'].array2.attribute_2='21_2'
</code></pre>
| 2 |
troubleshooting kafka + flink example using scala sbt?
|
<p>New to the kafka/flink/scala/sbt combo and trying to setup the following </p>
<ul>
<li>A multi-topic Kafka Queue</li>
<li>Flink streaming job using scala jar</li>
<li>A scala jar that reads data from a topic, process and then pushes data to another topic </li>
</ul>
<p>Uptil now </p>
<ul>
<li>Able to properly setup Kafka and Flink. <br></li>
<li>Able to read kafka queue using the Kafka.jar example that comes with flink binary. </li>
</ul>
<p>Able to create a wordcount jar ( Thanks to ipoteka ) <br>
Now trying to create a streaming-word-count jar but running into sbt issues <br>
<s>Now trying to create an example wordcount.jar before attempting the actual kafka/spark streaming example.</s><br>
But Running into simSBT issues
Any idea what am i overlooking. <br> Also let me know if i have any unnecessary declarations. <br>
Also would appreciate if someone shares a simple program to read/write kakfa queue. </p>
<p><strong>Project setup</strong> - <br></p>
<pre><code>|- project/plugins.sbt
|- build.sbt
|- src/main/scala/WordCount.scala
</code></pre>
<p><strong>build.sbt</strong> </p>
<pre><code>name := "Kakfa-Flink Project"
version := "1.0"
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.2.0"
// Updated : Correction pointed by ipoteka
libraryDependencies += "org.apache.kafka" % "kafka_2.10" % "0.10.0.0"
libraryDependencies += "org.apache.flink" %% "flink-scala" % "1.0.0"
libraryDependencies += "org.apache.flink" %% "flink-clients" % "1.0.0"
libraryDependencies += "org.apache.flink" %% "flink-streaming-scala" % "1.0.0"
// for jar building
mainClass in compile := Some("StreamWordCount")
</code></pre>
<p><strong>plugins.sbt</strong> </p>
<pre><code>// *** creating fat jar
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.1")
</code></pre>
<p><strong>WordCount.scala</strong> </p>
<pre><code>package prog
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.scala.DataStream
import org.apache.flink.streaming.api.windowing.time.Time
object WordCount {
type WordCount = (String, Int)
def main(lines: DataStream[String], stopWords: Set[String], window: Time): DataStream[WordCount] = {
lines
.flatMap(line => line.split(" "))
.filter(word => !word.isEmpty)
.map(word => word.toLowerCase)
.filter(word => !stopWords.contains(word))
.map(word => (word, 1))
.keyBy(0)
.timeWindow(window)
.sum(1)
}
}
</code></pre>
<p><strong>StreamWordCount.scala</strong></p>
<pre><code>package prog
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer082
import org.apache.flink.streaming.util.serialization.SimpleStringSchema
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.scala.DataStream
import org.apache.flink.streaming.api.windowing.time.Time
object Main {
def main(args: Array[String]) {
type WordCount = (String, Int)
val env = StreamExecutionEnvironment.getExecutionEnvironment
val properties = new Properties()
properties.setProperty("bootstrap.servers", "localhost:9092")
properties.setProperty("zookeeper.connect", "localhost:2181")
properties.setProperty("group.id", "test")
val stream = env
.addSource(new FlinkKafkaConsumer082[String]("topic", new SimpleStringSchema(), properties))
.flatMap(line => line.split(" "))
.filter(word => !word.isEmpty)
.map(word => word.toLowerCase)
.filter(word => !stopWords.contains(word))
.map(word => (word, 1))
.keyBy(0)
.timeWindow(window)
.sum(1)
.print
env.execute("Flink Kafka Example")
}
}
</code></pre>
<p><strong>Error while creating jar</strong> ( UPDATED )</p>
<pre><code>[vagrant@streaming ex]$ /opt/sbt/bin/sbt package
[error] /home/vagrant/ex/src/main/scala/StreamWordCount.scala:4: object connectors is not a member of package org.apache.flink.streaming
[error] import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer082
[error] ^
[error] /home/vagrant/ex/src/main/scala/StreamWordCount.scala:18: not found: type Properties
[error] val properties = new Properties()
[error] ^
[error] /home/vagrant/ex/src/main/scala/StreamWordCount.scala:23: not found: type FlinkKafkaConsumer082
[error] .addSource(new FlinkKafkaConsumer082[String]("topic", new SimpleStringSchema(), properties))
[error] ^
[error] three errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 31 s, completed Jul 3, 2016 9:02:18 PM
</code></pre>
| 2 |
Springs Qualifier error
|
<p>I'm learning Springs and while learning <code>@Autowiring</code>, came across <code>@Qualifier</code>. I've declared a qualifier but still there is an Exception thrown.</p>
<p>Below is my Code</p>
<p><strong>Spring.xml:</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="pointA" class="org.xyz.practice.Point">
<qualifier value="myCircle" />
<constructor-arg index="0" value="${pointA.pointX}"></constructor-arg>
<constructor-arg index="1" value="${pointA.pointY}"></constructor-arg>
</bean>
<bean id="pointB" class="org.xyz.practice.Point">
<constructor-arg index="0" value="${pointA.pointX}"></constructor-arg>
<constructor-arg index="1" value="${pointA.pointY}"></constructor-arg>
</bean>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="configurations.properties"></property>
</bean>
<bean id="circle" class="org.xyz.practice.Circle">
</bean>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>
</code></pre>
<p><strong>Circle.java:</strong></p>
<pre class="lang-java prettyprint-override"><code>package org.xyz.practice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Circle implements Shape {
private Point center;
public Point getCenter() {
return center;
}
@Autowired
@Qualifier("myCircle")
public void setCenter(Point center) {
this.center = center;
}
@Override
public void draw() {
System.out.println("Drawing a circle...");
System.out.println("Circle point si (" + center.getX() + " , " + center.getY() + ")");
}
}
</code></pre>
<p><strong>MainClass:</strong></p>
<pre class="lang-java prettyprint-override"><code>package org.xyz.practice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Shape shape = (Shape) context.getBean("circle");
shape.draw();
}
}
</code></pre>
<p><strong>Exception:</strong></p>
<pre><code>WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'circle': Unsatisfied dependency expressed through method 'setCenter' parameter 0: No qualifying bean of type [org.xyz.practice.Point] is defined: expected single matching bean but found 2: pointA,pointB; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.xyz.practice.Point] is defined: expected single matching bean but found 2: pointA,pointB
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'circle': Unsatisfied dependency expressed through method 'setCenter' parameter 0: No qualifying bean of type [org.xyz.practice.Point] is defined: expected single matching bean but found 2: pointA,pointB; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.xyz.practice.Point] is defined: expected single matching bean but found 2: pointA,pointB
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:647)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.xyz.practice.DrawingApp.main(DrawingApp.java:10)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.xyz.practice.Point] is defined: expected single matching bean but found 2: pointA,pointB
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:172)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
... 15 more
</code></pre>
<p>Please don't mark this as a duplicate of <code>@Resource</code>(related) question, I want to go step-by-step.</p>
| 2 |
Validators are not working even with validation group to make sure that update input of custom update button is valid
|
<p>I want to be able to <code>update</code> the data in the <code>Gridview</code> row by <code>row</code> and make sure that the data in the <code>textbox</code> fields is valid input. However with my code it is checking if the whole page has valid input and is preventing me from making the update changes even if the data in the row that I am trying to update is valid. Also my <code>label message</code> is not displaying the <code>error message</code> in case of <code>invalid data</code>. How can I make it to check that the <code>row</code> I am trying to <code>update</code> has valid input and if not output the <code>error message</code>?
Here is my HTML code:</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><br />
<asp:Label ID="MessageLbl" runat="server"></asp:Label>
<br />
<asp:Label ID="Label1" runat="server" Text="Editing Table"></asp:Label>
<br />
<asp:GridView ID="GridView4" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView4_RowCommand" OnSelectedIndexChanged="GridView4_SelectedIndexChanged" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton OnClick="UpdateRow_Click" ID="LinkButton1" runat="server" CausesValidation="false" CommandName="UpdateGCommand" Text="Update">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="textBox1" runat="server" Text='<%#Eval("Name")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ValidationGroup="UpdatingGrid" ID="rfvName" runat="server" ErrorMessage="Name is a required field" ControlToValidate="textBox1" Text="*" ForeColor="Red">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox ID="textBox2" runat="server" Text='<%#Eval("Email")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ValidationGroup="UpdatingGrid" ID="rfvEmail" runat="server" ErrorMessage="Email is a required field" ControlToValidate="textBox2" Text="*" ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ValidationGroup="UpdatingGrid" ID="RegularExpressionValidatorEmail" runat="server" ErrorMessage="*Invalid Email" ForeColor="Red" ControlToValidate="textBox2" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile">
<ItemTemplate>
<asp:TextBox ID="textBox3" runat="server" Text='<%#Eval("Mobile")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ValidationGroup="UpdatingGrid" ID="rfvMobile" runat="server" ErrorMessage="Mobile is a required field" ControlToValidate="textBox3" Text="*" ForeColor="Red">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView></code></pre>
</div>
</div>
</p>
<p>Here is my c# code:</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> protected void GridView4_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "UpdateGCommand") {
if (IsPostBack) {
Page.Validate("UpdatingGrid");
while (!Page.IsValid) {
if (Page.IsValid) {
DataSet EditT = new DataSet();
DataSet ValidT = new DataSet();
DataRow row;
if (Session["Edit"] != null) {
EditT = (DataSet) Session["Edit"];
}
if (Session["Valid"] != null) {
ValidT = (DataSet) Session["Valid"];
}
DataTable dtEdit = EditT.Tables[0];
DataTable dtValid = ValidT.Tables[0];
GridViewRow gvr = (GridViewRow)(((LinkButton) e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
row = dtEdit.Rows[RowIndex];
string txtName = ((TextBox) GridView4.Rows[RowIndex].FindControl("textBox1")).Text;
string txtEmail = ((TextBox) GridView4.Rows[RowIndex].FindControl("textBox2")).Text;
string txtMobile = ((TextBox) GridView4.Rows[RowIndex].FindControl("textBox3")).Text;
if (txtName != null) {
EditT.Tables[0].Rows[RowIndex]["Name"] = txtName;
}
if (txtEmail != null) {
EditT.Tables[0].Rows[RowIndex]["Email"] = txtEmail;
}
if (txtMobile != null) {
EditT.Tables[0].Rows[RowIndex]["Mobile"] = txtMobile;
}
dtValid.Rows.Add(row.ItemArray);
dtEdit.Rows[RowIndex].Delete();
GridView4.DataSource = EditT;
GridView5.DataSource = ValidT;
GridView4.DataBind();
GridView5.DataBind();
} else {
MessageLbl.Text = "Invalid Input";
}
}
}
}
}</code></pre>
</div>
</div>
</p>
| 2 |
Can't add Label on Image with using Xamarin.forms?
|
<p>I'm making iOS and Android app with using Xamarin.forms.</p>
<p>Can't I add Label on the Image?</p>
<p>Of course I know using many layout styles.
But that question is what I want to ask.</p>
| 2 |
How to add custom property to Symfony Doctrine YAML mapping file
|
<p>Can anyone tell me how to add custom property to doctrine ORM yml file?</p>
<p>My idea is to add a property like this:</p>
<pre><code>fields:
name:
type: string
localizable: true
</code></pre>
<p>Then I would like to get information about this <strong>localizable</strong> property by using</p>
<pre><code>protected function getEntityMetadata($entity)
{
$factory = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
return $factory->getClassMetadata($entity)->getMetadata();
}
</code></pre>
<p>and then:</p>
<pre><code> $met = $this->getEntityMetadata($bundle.'\\Entity\\'.$entity);
$this->metadata = $met[0];
$fields = $this->metadata->fieldMappings;
if (isset($fields)) {
foreach ($fields as $field => $fieldMapping) {
if (isset($fieldMapping['localizable']) && $fieldMapping['localizable'] == true) {
// Do sth with it
}
}
}
</code></pre>
| 2 |
Mail does not sent in Squirrelmail in Localhost
|
<p>I have recently make a web mail server in ubuntu 14.04 LTS .
I have complete all the steps and configuration of postfix , dovecot and squirrelmail .
Now I'm log into squirrelmail and send a mail to another user. The mail is going to the sent mail box that seems that the mail is sent.
But when log into that user account where the mail sent , there is no mail in inbox.
any solution ??
-- my english may be not so good , sorry for that.
thanks in advance. </p>
| 2 |
Using CMake to find dependencies in an application-specific subfolder
|
<p>In spite of many years of coding large-scale C++ applications, I do not understand how find_package is supposed to work in a medium-size CMake project, ASSUMING that I want to build the source to dependent packages myself and not simply rely on large systems like opencv, pcl or boost being installed somewhere in a system folder. I can't can't believe that I'm the only person in the world who has shipped multiple OpenCV and other open-source apps, has worked with meta-build systems like NAnt and SCons on major game projects, yet can't understand the most basic things about how CMake works or find a tutorial answering these questions. </p>
<p>In the past, I have essentially hacked around not understaning find_package by setting all the foo_DIR values by hand as CMake complains until I get a working folder. </p>
<p>I would like to run through a simple example which I'm working on right now, and dearly hope someone can explain what I'm doing so wrong. </p>
<p>Firstly, some assumptions:
I want to build everything for both MacOS and Windows, ideally via CMakeGUI. MacOS should build XCodeProjects and Windows should build Visual Studio Solutions. </p>
<p>Where there are dependencies, I want to compile them myself, so I have debug symbols and can modify the dependency source (or at least debug into it.)
No installation of pre-built binaries into system folders, i.e. no use of sudo port install opencv/pcl, etc on mac.
I have multiple projects, and prefer to keep a project and its dependencies in a single folder.
For the purposes of a concrete example, suppose I am building this project, although it's an arbitrary choice to illustrate the process and confusion I suffer: </p>
<p><a href="https://github.com/krips89/opendetection" rel="nofollow">https://github.com/krips89/opendetection</a></p>
<p>This lists dependencies, which I have intentionally reordered here so that I can take them in order, as follows: </p>
<pre><code>find_package(OpenCV REQUIRED)
find_package(Eigen REQUIRED)
find_package(Boost 1.40 COMPONENTS program_options REQUIRED )
find_package(PCL REQUIRED)
find_package(VTK REQUIRED)
</code></pre>
<p>I would like to have all of these dependencies downloaded and configured in a single path (let's say c:\src on Windows, and ~\src on Mac for simplicity), NOT in a system path. Assume that the actual folder is a sub-folder for this project, and no a sub-folder for all projects. This should also allow for side-by-side installation of multiple projects on the same computer.</p>
<p>Taking this one step at a time: </p>
<p>(1) I clone openCV from <a href="https://github.com/opencv/opencv" rel="nofollow">https://github.com/opencv/opencv</a>, sync to tag 3.1, configure into the folder opencv_build folder, build and install into opencv_install. I've done this so many times it's pretty straightforward.
(2) As above, but for eigen (although building for eigen doesn't actually do anything s it's a template library. I install to a folder eigen_install</p>
<p>Taking directory shows a series of folders for downloaded dependencies. I have assumed a convention where , and are source repos, and their following _build folders are the "WHere to build the binaries" folders in CMakeGui.</p>
<pre><code>$ ls
boost_1_40_0 opencv opendetection_build
eigen opencv-build opendetection_data
eigen_build opencv_contrib pcl
eigen_install opendetection
</code></pre>
<p>All good so far, now let's try to configure opendetection and generate a solution into opendetection_build, and find pendetection's dependencies <em>from within the ~/src folder</em>, that is for the first two dependencies, I hope to find opencv and eigen in the opencv-build and eigen-build folders. </p>
<p>OpenCV immediately fails, as expected, saying: </p>
<pre><code>Could not find a package configuration file provided by "OpenCV" with any of the following names:
OpenCVConfig.cmake
opencv-config.cmake
Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set "OpenCV_DIR" to a directory containing one of the above files. If "OpenCV" provides a separate development package or SDK, be sure it has been installed.
</code></pre>
<p>That's good, because I want to explicitly tell CMake to look for dependent packages under my ~/src folder. Question: Is the use of CMAKE_PREFIX_PATH=/users/foo/src the recommended way to accomplish what I want - looking for all sub-packages under a specific path? </p>
<p>Following this, CMake finds OpenCV (good), and sets OpenCV_DIR = /Users/foo/src/opencv-build. </p>
<p>Question: Given that I have made an "install" to opencv-install (using CMAKE_INSTALL_PREFIX and building the Install Target Of OpenCV, shouldn't it find OpenCV in the opencv-install folder not opencv-build? </p>
<p>Moving on to eigen, I have configured and built eigen, and installed it to ~/src/eigen-install, which since it is a subfolder of CMAKE_PREFIX_PATH (~/src) I might expect to be found. But it doesn't seem to be. Can somebody explain to me what I'm not understanding? Particularly given that Eigen in a template library, and that there are at least three folders (eigen, eigen_build and eigen_install) under CMAKE_PREFIX_PATH which I would have thought CMake would find something in, I assume I must be doing something wrong here. I KNOW from past experience, I can set EIGEN_INCLUDE_DIR by hand in CMakeGUI by hand, and continue hacking forth, but that just seems wrong. </p>
<p>I'm more than willing to write up a web page explaining this for future people as dumb as me if one does not already exist, although I can't understand how use of CMake for basic project configuration and generation is apparently so obvious to everyone but so opaque for me. I have actually been using CMake for some years, usually by just manually setting Boost_INCLUDE_Dir, Foo_INCLUDE_PATH etc manually, but clearly this is not the right solution. Generally, after spending a couple of days fighting through the various packages to generate a solution by manually setting INCLUDE PATHS, LIBRARY PATHS and other options, I just deal with the solution and don't touch CMake again. But I would love to understand what I'm missing about find_package for my (surely not uncommon) use case of wanting to control my project dependencies rather than just using sudo port install * and installing random versions of projects to my global system folders. </p>
| 2 |
Count number of days since a specific date
|
<p>I have got a dataframe with a column Date in which the observations range from 1974-10-01 to 2014-30-09. I would like to create a new column ("Day") in the dataframe which specify the number of day since the first time period day (i.e. 1974-10-01).</p>
<p>I already have the code and it worked perfectly for a really similar dataframe but I do not know why with this 2nd dataframe it does not work.</p>
<p>1) The code is the following:</p>
<pre><code>library(lubridate)
ref_date <- dmy("01-10-1974")
df$Day <- as.numeric(difftime(df$Date, ref_date))
</code></pre>
<p>2) The first rows of my dataframe are:</p>
<pre><code> Code Area Date Height
1 2001 551.4 1975-04-01 120.209
2 2001 551.4 1976-01-06 158.699
3 2001 551.4 1977-01-21 128.289
4 2001 551.4 1978-02-23 198.254
5 2001 551.4 1979-07-31 131.811
[....]
</code></pre>
<p>3) What I obtain with my code (1) is the following:</p>
<pre><code> Code Area Date Day Height
1 2001 551.4 1975-04-01 15724800 120.209
2 2001 551.4 1976-01-06 39916800 158.699
3 2001 551.4 1977-01-21 72835200 128.289
4 2001 551.4 1978-02-23 107222400 198.254
5 2001 551.4 1979-07-31 152409600 131.811
[....]
</code></pre>
<p>I spent more than 2 hours wondering why without any clue.</p>
<p>Any suggestion?</p>
| 2 |
How to enable read from StatefulService secondary replicas?
|
<p>Many of the official Service Fabric articles states that it should be possible to do read operations on secondary replicas, but I am unable to find a single code example that shows how to configure or use this advanced feature.</p>
<p>A good example would be to elaborate on this simple code sample: <a href="https://github.com/Azure-Samples/service-fabric-dotnet-getting-started/tree/master/Services/AlphabetPartitions" rel="nofollow">https://github.com/Azure-Samples/service-fabric-dotnet-getting-started/tree/master/Services/AlphabetPartitions</a></p>
<p>Where reads on secondaries are just HTTP Get operations.</p>
<p>I would like to use it as a way to scale out read intensive operations on StatefulServices.</p>
| 2 |
In PHPhotoLibrary, how to know whether video file can save on iPhone or not
|
<p>I'm changing over from ALAssetsLibrary to PHPhotoLibrary and want to know whether or not video file can save or not.
In <strong>ALAssetsLibray</strong>, you know, we could know it before start saving video file with the API</p>
<pre><code>- (BOOL)videoAtPathIsCompatibleWithSavedPhotosAlbum:(NSURL *)videoPathURL;
</code></pre>
<p>Does anyone knows the substitute API for <em>videoAtPathIsCompatibleWIthSavedPhotoAlbum</em> in <strong>PHPhotoLibrary</strong> ?</p>
<p>Or do you know the exact error code which means that a video file cannot save on the iOS device ?</p>
<p>My code for saving video file is like below,</p>
<pre><code>- (void)saveVideoFile:(NSURL *)videoURL completion:(savePhotoFileCompletion)completion
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetChangeRequest;
assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
PHAssetCollectionChangeRequest *assetCollectionChangeRequest =
[PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.assetCollection];
[assetCollectionChangeRequest addAssets:@[ [assetChangeRequest placeholderForCreatedAsset] ]];
}
completionHandler:^(BOOL success, NSError *_Nullable error) {
DBGLog(@"success=%@, error=%@", (success ? @"YES" : @"NO"), error);
completion(success, error);
}];
}
</code></pre>
<p>I found the question talking about the same issue.</p>
<p><a href="https://stackoverflow.com/questions/33500266/how-to-use-phphotolibrary-like-alassetslibrary">How to use PHPhotoLibrary like ALAssetsLibrary</a></p>
<p>But it doesn't refer to the exact answer.</p>
| 2 |
How can you give ApplicationPoolIdentity permissions to write to the Application Event Log?
|
<p>How can you give <code>ApplicationPoolIdentity</code> permissions to write to the Application Event Log?</p>
<p>I've read about adding a user to the permissions for <code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog</code> but I can't find the user <code>ApplicationPoolIdentity</code></p>
<p>And how can I have this as part of the deployment for a web site? ... specifically to Azure Web App Service</p>
| 2 |
How can I check if database exists and user of that database has permission to connect that database - Laravel
|
<p>I'm getting this kind of error <code>SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost'</code> when I'm trying to check this </p>
<pre><code>if(DB::connection())
{
//do something
}
</code></pre>
<p>Now what I want to do is I want to check if the database on which application is trying to connect <strong>exists</strong>. If yes then it should check if the user defined in the application has privileges to connect to that database. And if yes then I want to migrate all the tables.</p>
<p>Please help me with this. Thank you</p>
| 2 |
How to call custom back-end methods (parsing objects) using Typescript and Angular resources
|
<p>I've been struggling for weeks now to get custom service calls to work using Typescript / Angular / C#. I can't seem to find any viable solution online, and the more I look the more I get confused.</p>
<p>My current solution has been structured based mostly on Pluralsight courses.
I'm understanding the general connectivity from HTML => Angular (controllers/ models / services), but struggling with the Angular services => C# API controller connection.</p>
<p>Current structure:</p>
<p><strong>app.ts</strong></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>module App {
var main = angular.module("Scheduler", ["ngRoute", "App.Services"]);
main.config(routeConfig);
routeConfig.$inject = ["$routeProvider"];
function routeConfig($routeProvider: ng.route.IRouteProvider): void {
$routeProvider
.when("/schedule",
{
templateUrl: "/app/scheduler/views/scheduler.html",
controller: "ScheduleCtrl as sch"
})
.otherwise("/schedule");
}
}</code></pre>
</div>
</div>
</p>
<p><strong>services.ts</strong></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>module App.Services {
angular.module("App.Services", ["ngResource"]);
}</code></pre>
</div>
</div>
</p>
<p><strong>controller.ts</strong></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>module App.Scheduler {
export interface IScheduleParams extends ng.route.IRouteParamsService {
scheduleId: number;
}
export class ScheduleCtrl implements IScheduleModel {
scheduleResource: ng.resource.IResourceClass<App.Services.IScheduleResource>;
static $inject = ["$routeParams", "scheduleService", "$scope"];
constructor(private $routeParams: IScheduleParams,
private scheduleService: App.Services.SchedulerService,
public schedule: Schedule) {
this.scheduleResource = scheduleService.getScheduleResource();
this.schedule = new Schedule(0, 0, new Array<PaymentEntry>(), 0, new Array <ScheduleEntry>());
}
generateSchedule(): void {
//todo: Need to call the backend service here to generate entries
var returnedSchedules = this.scheduleService.generateSchedules(this.schedule);
}
}</code></pre>
</div>
</div>
</p>
<p><strong>schedulerService.ts</strong></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>module App.Services {
//INTERFACES
//services
export interface ISchedulerService {
getScheduleResource(): ng.resource.IResourceClass<IScheduleResource>;
generateSchedules(schedule: App.Scheduler.Schedule): App.Scheduler.ScheduleEntry[]; //custom service call
}
//resources
export interface IScheduleResource
extends ng.resource.IResource<App.Scheduler.ISchedule> {
}
//CLASSES
//Schedule Service
export class SchedulerService implements ISchedulerService {
static $inject = ["$resource"];
constructor(private $resource: ng.resource.IResourceService) {
}
//Read operations (single / list) -- this works fine
getScheduleResource(): ng.resource.IResourceClass<IScheduleResource> {
return this.$resource("api/scheduler/GetSchedules/:scheduleId");
}
//custom operations -- **!! NEED HELP HERE PLEASE !!**
generateSchedules(schedule: App.Scheduler.Schedule): App.Scheduler.ScheduleEntry[] {
return this.$resource("api/schedule/GenerateSchedules/:schedule");
//I need to be able to pass in a Schedule object and receive an array of objects back
}
}
angular
.module("Scheduler")
.service("schedulerService", SchedulerService);
}</code></pre>
</div>
</div>
</p>
<p><strong>models.ts</strong></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>module App.Scheduler {
//INTERFACES
export interface ISchedule {
param1: number;
payments: Array<IPaymentEntry>;
schedules?: Array<IScheduleEntry>;
}
export interface IPaymentEntry {
param1: number;
param2: number;
}
export interface IScheduleEntry {
param1: number;
param2: string;
param3: number;
}
//CLASSES
export class Schedule {
constructor(public param1?: number,
public payments?: Array<IPaymentEntry>,
public schedules?: Array<IScheduleEntry>) {
}
}
export class PaymentEntry implements IPaymentEntry {
constructor(public param1?: number,
public param2?: number) {
}
}
export class ScheduleEntry implements IScheduleEntry {
constructor(public param1: number,
public param2: string,
public param3: number) {
}
}
}</code></pre>
</div>
</div>
</p>
<p><strong>ApiController.CS</strong></p>
<pre><code>public class SchedulerController : ApiController
{
public IEnumerable<Schedule> GetSchedules()
{
//...
}
public Schedule GetSchedules(int id)
{
//...
}
[HttpPost]
public IEnumerable<PaymentEntry> GenerateSchedules([FromBody]Schedule schedule)
{
//todo: add random logic here
return new Schedule();
}
</code></pre>
<p>Any guidance or a working example of how to successfully call the <em>generateSchedules</em> method from the <strong>schedulerService.ts</strong> to the <strong>ApiController.CS</strong> would be greatly appreciated to and from the API controller would be greatly appreciated.</p>
| 2 |
Using supertest in WebStorm produce 'Argument type is not assignable to parameter type' and 'Unresolved function or method'
|
<p>I have a nodejs project developed in WebStorm IDE. I'm using Mocha with supertest as my unit test framework. </p>
<p>WebStorm showed 2 warnings: <code>Argument type app|exports|module.exports is not assignable to parameter type Function|Server</code> and <code>Unresolved function or method get()</code>.</p>
<p>I've tried to download and install supertest libraries from <code>File -> Settings -> Languages & Frameworks -> JavaScript -> Libraries -> Download</code> but nothing happened. So I downloaded them directly from <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/supertest" rel="nofollow">https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/supertest</a> and added them manually but WebStorm still produced the same warnings.</p>
<p>This is my server.js code:</p>
<pre><code>const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.status(200).end();
});
app.listen(3000);
module.exports = app;
</code></pre>
<p>This is my servertest.js code:</p>
<pre><code>/* eslint-env mocha*/
const request = require('supertest');
const app = require('../server');
describe('GET /', () => {
it('should respond OK', (done) => {
request(app) //Argument type app|exports|module.exports is not
//assignable to parameter type Function|Server
.get('/') //Unresolved function or method
.expect(200, done);
});
});
</code></pre>
<p>How do I get rid of these warnings?</p>
| 2 |
read external properties files in spring batch admin
|
<p>Premise : i'm new to spring batch.<br/>
I'm trying to customize the spring batch admin but , till now, i'm not been able to let my classes read some properties from an external file . <br/>
My jobs extract data from a third party database to print a report , therefore i need two datasource : one to gather the report information and one to store the job's status and metadata.<br/>
I've read the tutorial : <a href="http://docs.spring.io/spring-batch-admin/reference/customization.html" rel="nofollow noreferrer">http://docs.spring.io/spring-batch-admin/reference/customization.html</a> <br/> and many other tutorials and the following post <a href="https://stackoverflow.com/questions/30465345/load-external-config-file-in-spring-batch-admin?noredirect=1&lq=1">load external config file in spring batch admin</a> .
<br/>Yet i'm not been able to start the application .
It must run on Tomcat 6 .
<br>
this is a screen shoot of my project tree, adapted by the official example :<br/><a href="https://i.stack.imgur.com/O52Aa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O52Aa.jpg" alt="enter image description here"></a></p>
<p>this is my configuration class :</p>
<pre><code> @Configuration
@EnableBatchProcessing
public class RegistroGiornalieroConfiguration extends DefaultBatchConfigurer {
private final static Logger log = LoggerFactory.getLogger(RegistroGiornalieroConfiguration.class);
private final static Date data = null;
@Autowired
public JobBuilderFactory jobFactory;
@Autowired
public StepBuilderFactory stepFactory;
@Autowired
VolumiPropertySource volumiPropertySource;
@Value("${batch.jdbc.driver}")
private String driverName;
/**
* datasource di default, viene resitituito dall'annotazione Autowired
* @return
* @throws SQLException
*/
@Bean(name="springBatchDatasource")
@Primary
public DataSource springBatchDatasource() throws SQLException {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverName);//"com.mysql.jdbc.Driver");
// dataSource.setUrl(env.getProperty("springBatchUrl"));//"jdbc:mysql://localhost/spring_batch_annotations");
// dataSource.setUsername(env.getProperty("springBatchUser"));//"root");
// dataSource.setPassword(env.getProperty("springBatchPassword"));//"root");
return dataSource;
}
/**
* Datasource secondario, viene restituito da getDatasource
* @return
* @throws SQLException
*/
@Bean(name="estarDatasource")
public DataSource estarDatasource() throws SQLException {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverName);//"com.mysql.jdbc.Driver");
// dataSource.setUrl(env.getProperty("url"));//"jdbc:mysql://localhost/spring_batch_annotations");
// dataSource.setUsername(env.getProperty("user"));//"root");
// dataSource.setPassword(env.getProperty("password"));//"root");
return dataSource;
}
// @PostConstruct
// public void init()
// {
// Properties p = volumiPropertySource.getIniProperties();
// MutablePropertySources sources = env.getPropertySources();
// sources.addFirst(new PropertiesPropertySource("volumi",p));
// env.getActiveProfiles();
// }
@Bean
@StepScope
public JdbcCursorItemReader<RegistroGiornaliero> reader(
@Value("#{jobParameters[data]}")
Date data)
{
System.out.println("reader");
// select protocol.nprotoc,protocol.dataprot,protocol.arrpar,protocol.numdoc,
// protocol.datadoc,protocol.OGGETTO,protocol.ANNULLATO,protocol.USERINS as protuser,
// protimg.DOCID,protimg.USERINS imguser ,protimg.PRINCIPALE,
// assegna.livello,assegna.possesso,assegna.SEQUENZA,
// organigramma.LIVELLO,organigramma.DESCRIZIONE,
// protente.ente
// from
// protocol left outer join protimg on protocol.NPROTOC = protimg.NPROTOC
// left outer join protente on protocol.NPROTOC = protente.NPROTOC
// left outer join assegna on protocol.NPROTOC = assegna.NPROTOC
// left outer join organigramma on assegna.LIVELLO = organigramma.LIVELLO
// where
// protocol.dataprot = 20160616 and protocol.NPROTOC = '201600014709'
// order by protocol.nprotoc,assegna.SEQUENZA;
StringBuilder sb = new StringBuilder("select")
.append(" protocol.nprotoc,protocol.dataprot,protocol.arrpar,protocol.numdoc,")
.append(" protocol.datadoc,protocol.OGGETTO,protocol.ANNULLATO,protocol.USERINS as protuser,")
.append(" protimg.DOCID,protimg.USERINS imguser ,protimg.PRINCIPALE,")
.append(" assegna.possesso,assegna.SEQUENZA,")
.append(" organigramma.LIVELLO,organigramma.DESCRIZIONE,")
.append(" protente.ente ")
.append(" from protocol left outer join protimg on protocol.NPROTOC = protimg.NPROTOC ")
.append(" left outer join protente on protocol.NPROTOC = protente.NPROTOC ")
.append(" left outer join assegna on protocol.NPROTOC = assegna.NPROTOC ")
.append(" left outer join organigramma on assegna.LIVELLO = organigramma.LIVELLO ")
.append(" where ")
.append(" protocol.dataprot = ? ")
.append(" order by protocol.nprotoc,assegna.SEQUENZA ");
// StringBuilder sb = new StringBuilder("select")
// .append(" protocol.nprotoc,protocol.dataprot,protocol.arrpar,protocol.numdoc,")
// .append(" protocol.datadoc,protocol.OGGETTO,protocol.ANNULLATO,protocol.USERINS as protuser, ")
// .append(" protimg.DOCID,protimg.USERINS imguser ,protimg.PRINCIPALE, ")
// .append(" assegna.livello,assegna.possesso,assegna.SEQUENZA, ")
// .append(" organigramma.LIVELLO as livelloOrg,organigramma.DESCRIZIONE, ")
// .append(" protente.ente ")
// .append(" from protocol,protimg,protente,assegna,operatori,organigramma ")
// .append(" where ")
// .append(" protocol.NPROTOC = protimg.NPROTOC and protocol.NPROTOC = assegna.NPROTOC ")
// .append(" and protocol.NPROTOC = protente.NPROTOC and assegna.LIVELLO = organigramma.LIVELLO ")
// .append(" and protocol.dataprot = ? ");
JdbcCursorItemReader<RegistroGiornaliero> reader = new JdbcCursorItemReader<RegistroGiornaliero>();
try {
reader.setDataSource(estarDatasource());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader.setPreparedStatementSetter(new ParameterSetter(data));
reader.setSql(sb.toString());
reader.setRowMapper(estarRowMapper());
reader.setVerifyCursorPosition(false);
return reader;
}
@Bean
public RegistroGiornalieroProcessor processorGenerazioneRegistro() {
return new RegistroGiornalieroProcessor();
}
@Bean
public ItemWriter<RegistroGiornaliero> pdfwriter() {
return new PDFItemWriter<RegistroGiornaliero>();
}
@Bean
public JobExecutionListener listener() {
return new JobCompletionNotificationListener();
}
@Bean
public RegistroGiornalieroRowMapper estarRowMapper() {
return new RegistroGiornalieroRowMapper();
}
@Bean
public Job generaRegistroGiornaliero()
{
return jobFactory
.get("generaRegistroGiornaliero")
.incrementer(new RunIdIncrementer())
.flow(leggiDocumentiProtocollo())
.end()
.build();
}
@Bean
public Step leggiDocumentiProtocollo()
{
return stepFactory.get("leggiDocumentiProtocollo")
.<RegistroGiornaliero, RegistroGiornaliero> chunk(10)
.reader(reader(data))
.processor(processorGenerazioneRegistro())
.writer(pdfwriter())
.build();
}
@Override
public JobRepository getJobRepository() {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
// use the autowired data source
try {
factory.setDataSource(springBatchDatasource());
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
factory.setTransactionManager(getTransactionManager());
try {
factory.afterPropertiesSet();
return factory.getObject();
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
return null;
}
}
</code></pre>
<p>this is my job configuration (registrogiornaliero.xml):</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="it.infogroup.estav.registrogiornaliero"/>
</beans>
</code></pre>
<p>and finally this is my env.xml , as by stackoverflow post :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Use this to set additional properties on beans at run time -->
<bean id="placeholderProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/batch/admin/bootstrap/batch.properties</value>
<value>classpath:batch-default.properties</value>
<!-- <value>classpath:batch-${ENVIRONMENT:hsql}.properties</value>-->
<value>classpath:batch-${ENVIRONMENT:mysql}.properties</value>
<!-- here we load properties from external config folder -->
<value>file:${app.conf}</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="order" value="1" />
</bean>
</beans>
</code></pre>
<p>any help will be appreciated</p>
| 2 |
Opening import file for module 'Swift'
|
<p>I have added Objective c files to swift , I am getting following error :</p>
<blockquote>
<p>Opening import file for module 'Swift': Not a directory</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/WVDIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WVDIR.png" alt="enter image description here"></a></p>
| 2 |
Using form in view component ASP.NET Core 1.0
|
<p>I have view component1:</p>
<pre><code><form class="form-horizontal">
<input type="text" name="ip1" class="form-control"/>
<input type="submit" name="btnSubmit" class="btn btn-default" />
</form>
</code></pre>
<p>and view component2:</p>
<pre><code><form class="form-horizontal">
<input type="text" name="ip1" class="form-control"/>
<input type="submit" name="btnSubmit" class="btn btn-default" />
</form>
</code></pre>
<p>Two view components is in the same page. But I don't know how to handle post request inside each view component. And how to post a model to a view component?
Example code behind or similar:</p>
<pre><code> public class Component1ViewComponent : ViewComponent
{
public Component1ViewComponent()
{
}
public async Task<IViewComponentResult> InvokeAsync(bool isPost)
{
if (isPost)
{
//handle post request and get model value here
} else
{
}
return View(model);
}
}
</code></pre>
| 2 |
Huge memory allocation running a julia function?
|
<p>I try to run the following function in julia command, but when timing the function I see too much memory allocations which I can't figure out why. </p>
<pre><code>function pdpf(L::Int64, iters::Int64)
snr_dB = -10
snr = 10^(snr_dB/10)
Pf = 0.01:0.01:1
thresh = rand(100)
Pd = rand(100)
for m = 1:length(Pf)
i = 0
for k = 1:iters
n = randn(L)
s = sqrt(snr) * randn(L)
y = s + n
energy_fin = (y'*y) / L
@inbounds thresh[m] = erfcinv(2Pf[m]) * sqrt(2/L) + 1
if energy_fin[1] >= thresh[m]
i += 1
end
end
@inbounds Pd[m] = i/iters
end
#thresh = erfcinv(2Pf) * sqrt(2/L) + 1
#Pd_the = 0.5 * erfc(((thresh - (snr + 1)) * sqrt(L)) / (2*(snr + 1)))
end
</code></pre>
<p>Running that function in the julia command on my laptop, I get the following shocking numbers: </p>
<pre><code>julia> @time pdpf(1000, 10000)
17.621551 seconds (9.00 M allocations: 30.294 GB, 7.10% gc time)
</code></pre>
<p>What is wrong with my code? Any help is appreciated.</p>
| 2 |
How do I open up a download dialog box using Flask?
|
<p>I'm trying to let the user download an mp3 file after a text-to-speech convert using gTTS. The flash message appears but the download dialog does not open.</p>
<p>Here is the Python code:</p>
<pre><code>def mytts():
if request.method == 'POST':
if not request.form['text']:
flash('Text needed to proceed', 'error')
else:
text_input = request.form['text']
tts = gTTS(text=text_input, lang='en')
f=TemporaryFile()
tts.write_to_fp(f)
flask.send_file(f,as_attachment=True,attachment_filename="MyTTSOutput.mp3", mimetype="audio/mpeg")
f.close()
flash('Successful Text-to-Speech Convert')
return redirect(url_for('mytts'))
return render_template('mytts.html')
</code></pre>
<p>HTML Code (the form part only):</p>
<pre><code> <form action="" method=post class="form-horizontal">
<h2>Convert Text To Speech</h2>
<div class="control-group">
<div class="controls">
<textarea name="text" rows=10 class="input-xlarge" placeholder="Enter text to be converted here" required>{{ request.form.text }}</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">CONVERT!</button>
<a href="{{ url_for('index') }}"><button type="button" class="btn btn-info">HOME</button></a>
</div>
</div>
</form>
</code></pre>
<p>Please help.</p>
| 2 |
Error in rowMeans(results, na.rm = T) : 'x' must be an array of at least two dimensions
|
<p>I am trying to follow an example of some R code from <a href="http://www2.hawaii.edu/~lgarmire/RNASeqPowerCalculator.htm" rel="nofollow">this site</a>, but am getting the error as seen below. </p>
<pre><code>>Results = RS_simulation(sims=5, params=params, budget=3000, designtype = "one factor", nmax = 20, nmin = 5, program="DESeq")
[1] "DESeq"
> plot(rownames(results),rowMeans(results, na.rm=T), main="DESeq simulations on Bottomly Dataset", xlab = "number of replicates", ylab = "Power")
Error in rowMeans(results, na.rm = T) :
'x' must be an array of at least two dimensions
</code></pre>
<p>I have tried this command as well, but get this:</p>
<pre><code>> plot(rownames(results),rowMeans(results[, na.rm=T, drop=FALSE]), main="DESeq simulations on Bottomly Dataset", xlab = "number of replicates", ylab = "Power", drop=FALSE)
Error in results[, na.rm = T, drop = FALSE] :
object of type 'closure' is not subsettable
</code></pre>
<p>Any help with this? Always trying to get better at R</p>
| 2 |
Iterate over n successive elements of list (with overlapping)
|
<p>The <a href="https://docs.python.org/2.7/library/itertools.html" rel="nofollow">itertools</a> python module implements some basic building blocks for iterators. As they say, "they form an iterator algebra". I was expecting, but I could not find a succinctly way of doing the following iteration using the module. Given a list of ordered real numbers, for example</p>
<pre><code>a = [1.0,1.5,2.0,2.5,3.0]
</code></pre>
<p>... return a new list (or just iterate) grouping by some <code>n</code> value, say <code>2</code></p>
<pre><code>b = [(1.0,1.5),(1.5,2.0),(2.0,2.5),(2.5,3.0)]
</code></pre>
<p>The way I found of doing this was as follows. First split the list in two, with evens and odds indexes:</p>
<pre><code>even, odds = a[::2], a[1::2]
</code></pre>
<p>Then construct the new list:</p>
<pre><code>b = [(even, odd) for even, odd in zip(evens, odds)]
b = sorted(b + [(odd, even) for even, odd in zip(evens[1:], odds)])
</code></pre>
<p>In essence, it is similar to a moving mean. </p>
<p><strong>Is there a succinctly way of doing this (with or without itertools)?</strong> </p>
<hr>
<p>PS.:</p>
<p><strong>Application</strong></p>
<p>Imagine the <code>a</code> list as the set of timestamps of some events occurred during an experiment:</p>
<pre><code>timestamp event
47.8 1a
60.5 1b
67.4 2a
74.5 2b
78.5 1a
82.2 1b
89.5 2a
95.3 2b
101.7 1a
110.2 1b
121.9 2a
127.1 2b
...
</code></pre>
<p>This code is being used to segment those events in accord with different temporal windows. Right now I am interested in the data between <code>2</code> successive events; 'n > 2' would be used only for exploratory purposes.</p>
| 2 |
Change the Center color of doughnut chart in Chart.Js
|
<p>Is there a way to change the color of the middle circle in Chart.Js? I don't seem to find it on their documentation? </p>
| 2 |
C# DataGridView (DataSet source) Column SortMode resets when changing DataMember
|
<p><strong><em>TL;DR</strong>: When changing DataMember tables in a DataSet bound to a DataGridView with NotSortable column SortMode and ColumnSelect SelectionMode, an InvalidOperationException is thrown because the SortMode appears as "Automatic".</em></p>
<p>I have implemented an Excel input feature into my app, and I'm using the <a href="https://github.com/ExcelDataReader/ExcelDataReader" rel="nofollow noreferrer">ExcelDataReader</a> package from NuGet to do so. This is reading my Excel files and converting them into DataSet as expected.</p>
<p>However, when I tried to bind that DataSet to a DataGridView, with the intention of allowing the user to "select" what cells/columns/rows to use, I received the error the following InvalidOperationException when enabling Column selection mode:</p>
<pre><code> Column's SortMode cannot be set to Automatic while the DataGridView control's SelectionMode is set to ColumnHeaderSelect.
</code></pre>
<p>This was solved using <a href="https://stackoverflow.com/a/4335035/2664719">this answer</a> on another question, which works as expected on initial bind.</p>
<p><strong>However</strong>, the Excel spreadsheet may have multiple Worksheets, so I have displayed them using a ComboSelectBox -- and on SelectionChangeCommitted, I am changing the DataGridView's DataMember to the index of the selected Worksheet.</p>
<p>On this change I am still getting the InvalidOperationException above, even though I am repeating the exact same code as in the initial bind -- that is working correctly.</p>
<p><strong>So question is, how can I stop the SortMode from apparently being reset to Automatic or get the same code that's working for the initial Bind to work on the DataMember change.</strong></p>
<p>Thanks :)</p>
<p><strong>ExcelForm.cs</strong></p>
<pre><code>// This works fine on initial Bind, no errors
private void PrepareUI()
{
// DataGridView dataGridContents
dataGridContents.DataSource = _contents;
dataGridContents.DataMember = _contents.Tables[0].TableName;
dataGridContents.SetColumnSortMode(DataGridViewColumnSortMode.NotSortable);
dataGridContents.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DataTable worksheets = GetWorksheetValues(_contents);
comboWorksheet.DataSource = worksheets;
comboWorksheet.ValueMember = "index";
comboWorksheet.DisplayMember = "name";
}
// On SelectionChangeCommitted, same code -- but throws an InvalidOperationException
private void comboWorksheet_SelectionChanged(object sender, EventArgs e)
{
dataGridContents.DataMember = _contents.Tables[int.Parse(((ComboBox)sender).SelectedValue.ToString())].TableName;
dataGridContents.SetColumnSortMode(DataGridViewColumnSortMode.NotSortable);
dataGridContents.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
}
</code></pre>
<p><strong>DataGridViewExtensions.cs</strong></p>
<pre><code>static class DataGridViewExtensions
{
public static void SetColumnSortMode(this DataGridView dataGridView, DataGridViewColumnSortMode sortMode = DataGridViewColumnSortMode.NotSortable)
{
foreach (DataGridViewColumn c in dataGridView.Columns)
{
c.SortMode = sortMode;
}
}
}
</code></pre>
| 2 |
How to make N-level Catetgory Sub category structure in codeigniter
|
<p>I have database table as below:</p>
<p><a href="https://i.stack.imgur.com/4nmKB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4nmKB.png" alt="enter image description here"></a></p>
<p>i try this code..its work as list but i want to store data into array.i would like to make menu like e-commerce and selectbox also contain level of catagory.</p>
<pre><code>public function get_catagory($parent_id=0)
{
$this->db->where('parent_id', $parent_id);
$result = $this->db->get('catagory')->result();
foreach ($result as $row){
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' .$row->catagory;
$this->get_catagory($row->id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
}
}
</code></pre>
<p>i need array like below..</p>
<pre><code>Array
(
[43] => Array
(
[id] => 43
[catagory] => ASTM
[parent_id] => 3
[sub_categories] => Array
(
)
)
[44] => Array
(
[id] => 44
[catagory] => DIN
[parent_id] => 3
[sub_categories] => Array
(
[50] => Array
(
[id] => 50
[catagory] => BS
[parent_id] => 44
[sub_categories] => Array
(
[52] => Array
(
[id] => 52
[catagory] => UNE
[parent_id] => 50
[sub_categories] => Array
(
)
)
)
)
[49] => Array
(
[id] => 49
[catagory] => ISO
[parent_id] => 44
[sub_categories] => Array
(
[51] => Array
(
[id] => 51
[catagory] => GOST
[parent_id] => 49
[sub_categories] => Array
(
)
)
)
)
)
)
)
</code></pre>
| 2 |
how to get reproducible result in Tensorflow
|
<p>I built 5-layer neural network by using tensorflow. </p>
<p>I have a problem to get reproducible results (or stable results). </p>
<p>I found similar questions regarding reproducibility of tensorflow and the corresponding answers, such as <a href="https://stackoverflow.com/questions/36288235/how-to-get-stable-results-with-tensorflow-setting-random-seed?rq=1">How to get stable results with TensorFlow, setting random seed</a></p>
<p>But the problem is not solved yet. </p>
<p>I also set random seed like the following</p>
<pre><code>tf.set_random_seed(1)
</code></pre>
<p>Furthermore, I added seed options to every random function such as</p>
<pre><code>b1 = tf.Variable(tf.random_normal([nHidden1], seed=1234))
</code></pre>
<p>I confirmed that the first epoch shows the identical results, but not identical from the second epoch little by little.</p>
<p>How can I get the reproducible results? </p>
<p>Am I missing something?</p>
<p>Here is a code block I use. </p>
<pre><code>def xavier_init(n_inputs, n_outputs, uniform=True):
if uniform:
init_range = tf.sqrt(6.0 / (n_inputs + n_outputs))
return tf.random_uniform_initializer(-init_range, init_range, seed=1234)
else:
stddev = tf.sqrt(3.0 / (n_inputs + n_outputs))
return tf.truncated_normal_initializer(stddev=stddev, seed=1234)
import numpy as np
import tensorflow as tf
import dataSetup
from scipy.stats.stats import pearsonr
tf.set_random_seed(1)
x_train, y_train, x_test, y_test = dataSetup.input_data()
# Parameters
learningRate = 0.01
trainingEpochs = 1000000
batchSize = 64
displayStep = 100
thresholdReduce = 1e-6
thresholdNow = 0.6
#dropoutRate = tf.constant(0.7)
# Network Parameter
nHidden1 = 128 # number of 1st layer nodes
nHidden2 = 64 # number of 2nd layer nodes
nInput = 24 #
nOutput = 1 # Predicted score: 1 output for regression
# save parameter
modelPath = 'model/model_layer5_%d_%d_mini%d_lr%.3f_noDrop_rollBack.ckpt' %(nHidden1, nHidden2, batchSize, learningRate)
# tf Graph input
X = tf.placeholder("float", [None, nInput])
Y = tf.placeholder("float", [None, nOutput])
# Weight
W1 = tf.get_variable("W1", shape=[nInput, nHidden1], initializer=xavier_init(nInput, nHidden1))
W2 = tf.get_variable("W2", shape=[nHidden1, nHidden2], initializer=xavier_init(nHidden1, nHidden2))
W3 = tf.get_variable("W3", shape=[nHidden2, nHidden2], initializer=xavier_init(nHidden2, nHidden2))
W4 = tf.get_variable("W4", shape=[nHidden2, nHidden2], initializer=xavier_init(nHidden2, nHidden2))
WFinal = tf.get_variable("WFinal", shape=[nHidden2, nOutput], initializer=xavier_init(nHidden2, nOutput))
# biases
b1 = tf.Variable(tf.random_normal([nHidden1], seed=1234))
b2 = tf.Variable(tf.random_normal([nHidden2], seed=1234))
b3 = tf.Variable(tf.random_normal([nHidden2], seed=1234))
b4 = tf.Variable(tf.random_normal([nHidden2], seed=1234))
bFinal = tf.Variable(tf.random_normal([nOutput], seed=1234))
# Layers for dropout
L1 = tf.nn.relu(tf.add(tf.matmul(X, W1), b1))
L2 = tf.nn.relu(tf.add(tf.matmul(L1, W2), b2))
L3 = tf.nn.relu(tf.add(tf.matmul(L2, W3), b3))
L4 = tf.nn.relu(tf.add(tf.matmul(L3, W4), b4))
hypothesis = tf.add(tf.matmul(L4, WFinal), bFinal)
print "Layer setting DONE..."
# define loss and optimizer
cost = tf.reduce_mean(tf.square(hypothesis - Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learningRate).minimize(cost)
# Initialize the variable
init = tf.initialize_all_variables()
# save op to save and restore all the variables
saver = tf.train.Saver()
with tf.Session() as sess:
# initialize
sess.run(init)
print "Initialize DONE..."
# Training
costPrevious = 100000000000000.0
best = float("INF")
totalBatch = int(len(x_train)/batchSize)
print "Total Batch: %d" %totalBatch
for epoch in range(trainingEpochs):
#print "EPOCH: %04d" %epoch
avgCost = 0.
for i in range(totalBatch):
np.random.seed(i+epoch)
randidx = np.random.randint(len(x_train), size=batchSize)
batch_xs = x_train[randidx,:]
batch_ys = y_train[randidx,:]
# Fit traiing using batch data
sess.run(optimizer, feed_dict={X:batch_xs, Y:batch_ys})
# compute average loss
avgCost += sess.run(cost, feed_dict={X:batch_xs, Y:batch_ys})/totalBatch
# compare the current cost and the previous
# if current cost > the previous
# just continue and make the learning rate half
#print "Cost: %1.8f --> %1.8f at epoch %05d" %(costPrevious, avgCost, epoch+1)
if avgCost > costPrevious + .5:
#sess.run(init)
load_path = saver.restore(sess, modelPath)
print "Cost increases at the epoch %05d" %(epoch+1)
print "Cost: %1.8f --> %1.8f" %(costPrevious, avgCost)
continue
costNow = avgCost
reduceCost = abs(costPrevious - costNow)
costPrevious = costNow
#Display logs per epoch step
if costNow < best:
best = costNow
bestMatch = sess.run(hypothesis, feed_dict={X:x_test})
# model save
save_path = saver.save(sess, modelPath)
if epoch % displayStep == 0:
print "step {}".format(epoch)
pearson = np.corrcoef(bestMatch.flatten(), y_test.flatten())
print 'train loss = {}, current loss = {}, test corrcoef={}'.format(best, costNow, pearson[0][1])
if reduceCost < thresholdReduce or costNow < thresholdNow:
print "Epoch: %04d, Cost: %.9f, Prev: %.9f, Reduce: %.9f" %(epoch+1, costNow, costPrevious, reduceCost)
break
print "Optimization Finished"
</code></pre>
| 2 |
How to configure WSO2 API Manager to an external Identity Provider?
|
<p>All,</p>
<p>I'm trying to configure the wso2 product with an external IDP, not the IS IDP. What configuration files need to updated and with what information? Also, when I add an IDP from the API Manager browser, where is that file being saved server-side and is it being used?</p>
<p>Thanks,
Hunter</p>
| 2 |
Display log into console with tf_logging
|
<p>I'm playing with <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/learning.py" rel="nofollow">slim.learning.train</a> and want to display the log in the console. According to the source code this is done using <code>tf_logging</code> module :</p>
<pre><code>if 'should_log' in train_step_kwargs:
if sess.run(train_step_kwargs['should_log']):
logging.info('global step %d: loss = %.4f (%.2f sec)',
np_global_step, total_loss, time_elapsed)
</code></pre>
<p>I can run my training loop but there's no logs in the console. How can I enable it ?</p>
| 2 |
Exporting jobs listed in Oozie Web Console
|
<p>Apologies if this question sounds basic, I'm totally new to Hadoop environment.</p>
<p><strong>What am I looking for?</strong></p>
<p>In my case, there are jobs scheduled to run everday and <em>I would want to export the list of failed jobs in an excel sheet each day</em>. </p>
<p><strong>How do I view the workflow jobs?</strong></p>
<p>Currently I use the Oozie web console to view the jobs and I don't have/see an option to export. Also,
I was not able to find this information from the <a href="https://oozie.apache.org/docs/3.1.3-incubating/DG_CommandLineTool.html#Checking_the_Status_of_multiple_Workflow_Jobs" rel="nofollow">Oozie documentation</a>.</p>
<p>However, I found that jobs can be listed using commands like</p>
<p><code>$ oozie jobs -oozie http://localhost:8080/oozie -localtime -len 2 -fliter status=RUNNING</code></p>
<p><strong>Where am I stuck?</strong></p>
<p>I want to filter the failed jobs for a given date and <strong>would want to export it as csv/excel data</strong>.</p>
| 2 |
How to construct a matrix based on user input?
|
<p>How to solve the problem to create a matrix with random numbers (user input)?
I also how a problem with this: </p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
23: ordinal not in range(128)</p>
</blockquote>
<pre><code>array = list()
i = int(input("How many row: "))
j = int(input("How many column: "))
for x in range(i):
if i <= 0 or i>10:
print("Failure!")
break
elif j <= 0 or j>10:
print("Failure!")
break
else:
for y in range(j):
num = raw_input("Value: ")
array.append(int(num))
a = np.reshape((i,j))
print a
</code></pre>
| 2 |
How can I remove proxies field in symfony json
|
<p>I want to remove proxies fields like <code>__initializer__: null,__cloner__: null, __isInitialized__: true,</code> from my returned json but I have no idea.</p>
<p>I dont want to use <code>* @Serializer\Exclude()</code> because there are some more fields next to those fields.</p>
<p>here is a sample json:</p>
<pre><code>emails: [
{
id: 1,
subject: "Mrs. Astrid Wuckert",
body: "Excepturi.",
sendCopy: false,
roles: [
{
__initializer__: null,
__cloner__: null,
__isInitialized__: true,
name: "ROLE_ADMIN"
},
{
name: "ROLE_RESELLER"
},
{
name: "ROLE_RETAILER"
},
{
name: "ROLE_CLUB_SHOP"
}
]
},
]
</code></pre>
<p>Thanks in advance.</p>
| 2 |
Select Test As [text()]
|
<p>I have inherited this line of code. Normally, I would expect what occurs after the As to be an alias. However, I have never seen an alias in square brackets. Also, I'm not sure what the parens in text() signify? Is text an obsolete data type? Is there any link someone can send me so I can figure out what this means?</p>
<p>Thank you.</p>
| 2 |
Best way of client server communication in Java
|
<p>I am building an application where in the requirement is that, there is a main server, which will send signal to client server, based on this signal the client performs certain action and send back the response to the main server. Here there will be only one main server and can be multiple client servers. At a given time the main server can send multiple signal to multiple clients.
I am presently planning to do this using socket programming in Java using two ports. Do let me know the best way of achieving this? and also do we have any good existing API's that can be used?</p>
| 2 |
Standard way of comparing the password/sensitive fields
|
<p>I have a scenario where I have to match the password/sensitive information and check for the validation.
Now there are two ways here I can come up with.</p>
<p>1) We can compare the password/sensitive field in the encrypted form by fetching the right password from DB which is stored there in encrypted form.</p>
<p>2) Or we can decrypt the passwords first in to the plain text form and then compare them. Now in this scenario there is an extra call to decrypt utility, which sort of an overhead.</p>
<p>I have looked at the "equals()" method of String class which runs in amortized constant time. So if the encrypted string is insanely long string then it will have impact on the performance of the "equals()" method.
But here in my case encrypted strings are not so long.</p>
<p>But my main concern is what is the standard generally followed.
<strong><em>UPDATE 1:</em></strong></p>
<pre><code>public static String encrypt(String text, String algo, byte[] bytes) throws NoSuchPaddingException, NoSuchAlgorithmException,
IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
if (text == null || algo == null || bytes == null) {
//log properly
System.out.println("Please provide a valid text, algo or key bytes");
return null;
}
Key key = generateKey(bytes, algo);
Cipher c = Cipher.getInstance(algo);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] envValue = c.doFinal(text.getBytes());
String encVal2 = new BASE64Encoder().encode(envValue);
return encVal2;
}`
</code></pre>
<p><strong><em>Update 2:</em></strong></p>
<pre><code> while (i < 300000) {
String value = KeyValidator.getSystemLicKey(KEY_);
if (!value.equals(value1))
System.out.println("--- : false");
value1 = value;
i++;
}
</code></pre>
| 2 |
Python 2.7 Socket connection on 2 different networks?
|
<p>Title says all. I have a client and a server setup, but they only work with localhost. How can I connect to the socket from a different network?</p>
<p>Client</p>
<pre><code># Echo client program
import socket
print "Client"
HOST = "localhost" # Symbolic name meaning all available interfaces
PORT = 5001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
data2 = raw_input()
s.sendall(data2)
</code></pre>
<p>Server</p>
<pre><code># Echo server program
import socket
print "Server"
HOST = "" # Symbolic name meaning all available interfaces
PORT = 5001 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
print data
if data == "Ping":
print "Pong!"
conn.close()
</code></pre>
| 2 |
XPath to access an attribute value with a name that has special characters
|
<p>I'm trying to access to attribute value, but the attribute name has special characters, for example:</p>
<pre><code><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<ELEMENT1 at:it="true">W</ELEMENT1>------
<ELEMENT2>IN</ELEMENT2>
<ELEMENT3>RP</ELEMENT3>
<ELEMENT4>KKK</ELEMENT4>
</row>
<row>
<ELEMENT1 acón='sys'>2</ELEMENT1>------
<ELEMENT2>ARQ</ELEMENT2>
<ELEMENT3>MR</ELEMENT3>
<ELEMENT4>AC</ELEMENT4>
</row>
<row>
<ELEMENT1>3</ELEMENT1>
<ELEMENT2>I</ELEMENT2>
<ELEMENT3 at:it="true" >RP</ELEMENT3>------
<ELEMENT4>KKK</ELEMENT4>
</row>
<row>
<ELEMENT1>1</ELEMENT1>
<ELEMENT2>CC</ELEMENT2>
<ELEMENT3>XX</ELEMENT3>
<ELEMENT4 eléct='false' >I</ELEMENT4>------
</row>
<row>
<ELEMENT1>12</ELEMENT1>
<ELEMENT2 at:it="true" >IN</ELEMENT2>------
<ELEMENT3>3</ELEMENT3>
<ELEMENT4></ELEMENT4>
</row>
</root>
</code></pre>
<p>if I change the names of the attributes and remove them special characters, I can access them:</p>
<pre><code>at:it ------> atit
Acón ------> Acon
eléctr ------> elect
</code></pre>
<p>but attribute names with special characters I can not access them with XPath query expression.</p>
<p>How I can access an XML file to values of attributes with names that have special characters?</p>
<p>To transform the XML file to DOM I used Java6, javax.xml.<em>, org.w3c.dom.</em></p>
| 2 |
get public shareble link after uploading file to google drive using nodejs
|
<p>i want to upload files to google drive using nodeJS as backend. I have used google drive API v3. I get the file id and type in response after uploading a file.</p>
<pre><code>drive.files.create({
resource: {
name: 'Test',
mimeType: 'image/jpeg'
},
media: {
mimeType: 'image/jpeg',
body: fileData
}
}, function(err, result){
if(err)
res.send(err);
else
res.send(result);
});
</code></pre>
<p>but what i want is when i upload a file i want it as publicly accessible. i want the shareable link of that file in response. Is there any way to do so ? i have implemented the way given here : <a href="https://developers.google.com/drive/v3/web/manage-sharing" rel="nofollow">https://developers.google.com/drive/v3/web/manage-sharing</a> which works fine with s.showSettingsDialog(). But i want the shareable link at the time i upload the file.</p>
| 2 |
Get Facebook user's details using Spring social and oAuth sccess token
|
<p>I got an OAuth access token in the response url after I make a call to - </p>
<pre><code>https://www.facebook.com/dialog/oauth?client_id=<CLIENT_ID>&redirect_uri=http://localhost:8080&response_type=token
</code></pre>
<p>I want to use this access token to get User details (firstname, lastname, email etc) using Spring social.</p>
<p>When I try (userToken is the token I get in redirect url)- </p>
<pre><code>Facebook facebook = new FacebookTemplate(userToken);
String email = facebook.userOperations().getUserProfile().getEmail();
</code></pre>
<p>I get below error - </p>
<blockquote>
<p>Error from Facebook:
{"error":{"message":"(#100) Tried accessing nonexisting field
(address) on node type
(User)","type":"OAuthException","code":100,"fbtrace_id":"F/2+IETr1op"}}</p>
</blockquote>
<p>When I try below url - </p>
<pre><code>https://graph.facebook.com/v2.6/me?access_token=<ACCESS_TOKEN>&debug=all
</code></pre>
<p>I get a valid response - </p>
<pre><code>{
"name": "Ranu Verma",
"id": "1753649031517471",
"__debug__": {
}
}
</code></pre>
<p>So, is it right way to access User details if you already have the oauth access token? What am I missing here?</p>
| 2 |
TypeScript : how to declare an enum across multiple files?
|
<p>file AppActions.ts</p>
<pre class="lang-ts prettyprint-override"><code>export enum Actions {
START = 0,
RECOVER,
FIRST_RUN,
ALERT_NETWORK,
LOADING_DATA,
RECEIVED_DATA,
GO_OFFLINE,
GO_ONLINE
}
</code></pre>
<p>file PlayerActions.ts</p>
<pre class="lang-ts prettyprint-override"><code>import {Actions} from "./AppActions.ts"
enum Actions {
HEAL_SINGLE,
HIT_SINGLE
}
</code></pre>
<p>Normally, regarding <a href="https://basarat.gitbooks.io/typescript/content/docs/enums.html" rel="nofollow noreferrer">this manual</a> it should throw an error at compile time. But:</p>
<p>1- the PlayerActions.ts does not seem to extend the existing Actions enum. (in WebStorm <code>import {Actions} from "./AppActions.ts"</code> is in grey)</p>
<p>2- the compiler does not throw any errors.</p>
<p>So what is the right way to declare Enum across multiple files?</p>
| 2 |
how to attach a EBS volume to my container using docker-compose.yml and ecs-cli
|
<p>I am using <code>docker-compose.yml</code> to define a set of containers. And use <code>ecs-cli compose (service) up</code> to create my application on <code>AWS</code>.</p>
<p>I know <code>AWS ECS</code> comes with 100GB <code>EBS</code> automatically when a container is created. (Even though the <code>EC2</code> instance that hosts the container only have 8GB of hard drive.)
I want to have a persistent storage so that even if I updated my container, it can still point to the same 100GB <code>EBS</code>. I am pretty sure I can do the following to achieve this goal:</p>
<blockquote>
<p>Attach an external <code>EBS</code> to the EC2 instance, and use <code>volume</code> in the
compose file to attach that volume to the container.</p>
</blockquote>
<p>However, I feel there might be a better way to do so on ECS since it gives you 100GB ELB automatically. That is, if I use the above approach, then I am really 'wasting' the 100GB volume that comes with each container.
So, what is the best way to achieve this. Could you give an answer in the form of a docker-compose.yml format like the following?</p>
<pre><code>container1:
image: image1
container2:
image: image2
links:
- "container1"
</code></pre>
| 2 |
Delay loading data in Angular JS
|
<p>I have code like this </p>
<pre><code>(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
</code></pre>
<p>So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this? </p>
| 2 |
How to draw routes that aren't on roads, MKMapView
|
<p>So i've been experimenting with the MKMapView and overlay to create "roads that aren't on roads". That may sound weird but what I was trying to do is that in my app for iOS i want to draw the excursion routes that a specific hotel offers, however all the posts i found so far were focusing on existing roads, since the excursions go through forests, over rivers etc. there are no roads to help me.</p>
<p>Since there were no roads i had to improvise so I decided to make a plist(I probably could have taken another type of file too, I just liked the working with plist's) for every excursion and in there make an array of all the coordinates and getting these coordinates with google earth, but after 60 different coordinates I stopped because it was just ridiculous.</p>
<p>So then I tried to make a script that writes, when I tap on the map at run-time, the coordinates to the plist. Whilst this works it is still really uncomfortable, because I can't save the automatically created file in the Xcode project, and because it overall just doesn't work as good as I wished it to.</p>
<p>So my question is if there is something easier that I may've missed on how to create routes that aren't on streets.</p>
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.