title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
How to find log inverse in python2.7
<pre><code>log x=0.0795 </code></pre> <p>How to find the value of x?. Is there any inbuilt function for log inverse in Python2.7? Thank You.</p>
1
bash check all file in a directory for their extension
<p>I am writing a shell script to read all the files in the give directory by the user input then count how many files with that extension. I just started learning Bash and I am not sure why it this not locating the files or reading the directory. I am only putting 2 example but my count is always 0.</p> <p>This is how I run my script</p> <pre><code>$./check_ext.sh /home/user/temp </code></pre> <p>my script check_ext.sh</p> <pre><code>#!/bin/bash count1=0 count2=0 for file in "ls $1" do if [[ $file == *.sh ]]; then echo "is a txt file" (( count1++ )) elif [[ $file == *.mp3 ]]; then echo "is a mp3 file" (( count2++ )) fi done; echo $count $count2 </code></pre>
1
Closing Popup by Clicking Anywhere Outside It
<p>I was able to successfully add a popup that loads automatically when the page loads:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//with this first line we're saying: "when the page loads (document is ready) run the following script" $(document).ready(function () { //select the POPUP FRAME and show it $("#popup").hide().fadeIn(1000); //close the POPUP if the button with id="close" is clicked $("#close").on("click", function (e) { e.preventDefault(); $("#popup").fadeOut(1000); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/*we need to style the popup with CSS so it is placed as a popup does*/ #popup { display:none; position:absolute; margin:0 auto; top: 50%; left: 50%; transform: translate(-50%, -50%); box-shadow: 0px 0px 50px 2px #000; } body { background:url('http://i.imgur.com/kO2Ffje.png?1') center top; width: 100%; height: 100%; margin: 0 auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- let's call the following div as the POPUP FRAME --&gt; &lt;div id="popup" class="popup panel panel-primary"&gt; &lt;!-- and here comes the image --&gt; &lt;img src="http://i.imgur.com/cVJrCHU.jpg" alt="popup"&gt; &lt;!-- Now this is the button which closes the popup--&gt; &lt;div class="panel-footer"&gt; &lt;button id="close" class="btn btn-lg btn-primary"&gt;Close button&lt;/button&gt; &lt;/div&gt; &lt;!-- and finally we close the POPUP FRAME--&gt; &lt;!-- everything on it will show up within the popup so you can add more things not just an image --&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>(per <a href="https://stackoverflow.com/questions/26131542/how-do-i-make-an-image-automatically-popup-on-my-main-page-when-someone-goes-to/">How do I make an image automatically popup on my main page when someone goes to it?</a>'s instructions), </p> <p>But instead of clicking a button to close the popup, I would like to know how to modify the javascript so that it closes when you click anywhere outside of it.</p>
1
Draw rounded fancyarrowpatch with midpoint arrow in matplotlib
<p>I've been trying to push the boundaries of matplotlib's patches and instruct it to draw a rounded <code>FancyArrowPatch</code> with a directional arrow on its midpoint. This would prove incredibly useful in a network representation I am trying to create. </p> <p>My coding hours with python are not yet in the double digit, so I can't say I have a clear understanding of matplotlib's patches.py, but I have narrowed down the solution to two possible strategies:</p> <ol> <li>the smart, possibly pythonic way: create a custom <code>arrowstyle</code> class which further requires a modification of the <code>_get_arrow_wedge()</code> function to include a midpoint coordinates. This may be beyond my possibilities for now, or</li> <li>the lazy way: extract the midpoint coordinates from an elicited FancyArrowPatch and draw the desired <code>arrowstyle</code> on such coordinates.</li> </ol> <p>Of course, so far I've chosen the lazy way. I did some early experimenting with extracting the midpoint coordinates of a curved <code>FancyArrowPatch</code> using <code>get_path()</code> and <code>get_path_in_displaycoord()</code>, but I can't seem to predict the precise midpoint coordinates. Some help would be very appreciated.</p> <p>My fiddling so far:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch n1 = (2,3) n2 = (4,6) # Try with multiple arc radius sizes, draw a separate plot each time for rad in range(20): #setup figure figure = plt.figure() ax = plt.subplot(111) plt.annotate('rad:' + str(rad/25.),xy=(2,5)) # create rounded fancyarrowpatch t = FancyArrowPatch(posA=n1,posB=n2, connectionstyle='arc3,rad=%s'%float(rad/25.), arrowstyle='-&gt;', shrinkA=0, shrinkB=0, mutation_scale=0.5) # extract vertices from get_path: points P# path = t.get_path().vertices.tolist() lab, px, py = ['P{0}'.format(i) for i in range(len(path))], [u[0] for u in path],[u[1] for u in path] for i in range(len(path)): plt.annotate(lab[i],xy=(px[i],py[i])) # extract vertices from get_path_in_displaycoord (but they are useless) : points G# newpath = t.get_path_in_displaycoord() a,b = newpath[0][0].vertices.tolist(), newpath[0][1].vertices.tolist() a.extend(b) glab, gx, gy = ['G{0}'.format(i) for i in range(len(a))], [u[0] for u in a],[u[1] for u in a] for i in range(len(a)): plt.annotate(glab[i],xy=(gx[i],gy[i])) #point A: start x1, y1 = n1 plt.annotate('A',xy=(x1,y1)) #point B:end x2, y2 = n2 plt.annotate('B',xy=(x2,y2)) #point M: the 'midpoint' as defined by class Arc3, specifically its connect() function x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2. dx, dy = x2 - x1, y2 - y1 cx, cy = x12 + (rad/100.) * dy, y12 - (rad/100.) * dx plt.annotate('M',xy=(cx,cy)) #point O : midpoint between M and P1, the second vertex from get_path mx,my = (cx + px[1])/2., (cy + py[1])/2. plt.annotate('O',xy=(mx,my)) ax.add_patch(t) plt.scatter([x1,cx,x2,mx,gx].extend(px),[y1,cy,y2,my,gy].extend(py)) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/61hcc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/61hcc.png" alt="objective"></a></p> <p>EDIT: taking onboard @cphlewis suggestions: I tried to reconstruct the Bezier curve:</p> <pre><code>def bezcurv(start,control,end,tau): ans = [] for t in tau: B = [(1-t)**2 * start[i] + 2*(1-t)*t*end[i] + (t**2)*control[i] for i in range(len(start))] ans.append(tuple(B)) return ans </code></pre> <p>I thus add the generated line to the original plot:</p> <pre><code>tau = [time/100. for time in range(101)] bezsim = bezcurv(n1,n2,(cx,cy),tau) simx,simy = [b[0] for b in bezsim], [b[1] for b in bezsim] </code></pre> <p>The green line below is (should be?) the reconstructed bezier curve, though it's clearly not. <a href="https://i.stack.imgur.com/61wnc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/61wnc.png" alt="attempt at bezier curve reconstruction"></a></p>
1
difference between alert("Hi!") and function(){alert("Hi!")}
<p>When we are doing inline command in the button:</p> <pre><code>&lt;button id="myButton" onclick="alert('Hi!')"&gt; </code></pre> <p>Why does </p> <pre><code>document.getElementById("myButton").onclick = alert('Hi!') </code></pre> <p>not work but give the alert as the page is loaded? I can't understand how it works with <code>function()</code> added to it and without <code>function()</code>. I hope you guys understand my question. I'm missing something here.</p>
1
PyQt to exe. No module named 'PyQt5.QtCore'
<p>I am trying to compile PyQt py to exe using py2exe.<br> import sys from PyQt5 import QtWidgets</p> <pre><code>#PythonApplication1.py def main(): app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() button = QtWidgets.QPushButton("Hello world") window.setCentralWidget(button) window.show() app.exec_() </code></pre> <p>-</p> <pre><code>#setup.py from distutils.core import setup import py2exe setup(windows=[{"script":"PythonApplication1.py"}], options={"py2exe":{"includes":["sip"]}}) </code></pre> <p>$python setup.py py2exe --includes sip</p> <p>When I run exe there is only error window: See the logfile 'C:\dist\PythonApplication1.log' for details.</p> <pre><code>#PythonApplication1.log Traceback (most recent call last): File "PythonApplication1.py", line 5, in &lt;module&gt; File "&lt;loader&gt;", line 10, in &lt;module&gt; File "&lt;loader&gt;", line 8, in __load ImportError: (No module named 'PyQt5.QtCore') 'C:\\dist\\PyQt5.QtWidgets.pyd' </code></pre>
1
How to pass listbox items as arguments to a method in c#?
<p>For example i have these values stored in the listbox.</p> <pre><code>int pid = (int)reader["pid"]; string FirstName = (string)reader["Fname"]; string LastName = (string)reader["Lname"]; string gender = (string)reader["gender"]; string address = (string)reader["address"]; string email = (string)reader["email"]; string item = string.Format("{0} - {1} - {2} -{3} - {4} - {5}" pid,FirstName, LastName,gender,address,email); this.listBox1.Items.Add(item); </code></pre> <p>How do i pass these items to another class method ? Thanks </p>
1
Maximum number of tuples in this relation R , ER model?
<p><a href="https://i.stack.imgur.com/sekhs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sekhs.jpg" alt="ER DIAGRAM"></a></p> <p>Answer given is : <code>1000</code></p> <p>I don't understand which side it's many-one relation and which side it's one-one relation.</p>
1
Hibernate-Criteria: Select distinct column from table ordered by another column
<p><strong>What I want to achieve:</strong> Get list of unique ids ordered by another column, using Hibernate Criteria.</p> <p><strong>My code so far:</strong></p> <pre><code> Criteria crt = createCriteria(); //complex method returning Criteria //with joined tables, restrictions and ordering crt.setProjection( Projections.distinct( Projections.property( "id"))); List&lt;Integer&gt; ids = crt.list(); </code></pre> <p><strong>What is wrong:</strong> When I set order by column let's say "date" I get query:</p> <pre><code>SELECT DISTINCT id FROM table \\JOIN, WHERE...\\ ORDER BY date); </code></pre> <p>which is obviously wrong and results in error:</p> <pre><code>ORA-01791: not a SELECTed expression </code></pre> <p><strong>My idea how to solve it:</strong> Somehow force Hibernate to generate this query:</p> <pre><code>SELECT DISTINCT id FROM (SELECT * FROM table \\JOIN, WHERE...\\ ORDER BY date); </code></pre> <p><strong>Problems and what I tried:</strong> There is <code>createCriteria()</code> method, which I don't want to modify if it's not absolutely necessary. I didn't find a way to use this Criteria as DetachedCriteria.</p>
1
`display: inline-block` not working in IE10
<p>I've got a horizontal scrolling image list:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;img src="..."/&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="..."/&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I set the <code>li</code>'s to be <code>inline-block</code> and have <code>height: 100%</code>:</p> <pre><code>ul { height: 100%; white-space: nowrap; } li { height: 100%; display: inline-block; } img { height: 100%; width: auto; } </code></pre> <p>This seems to work fine on all the browsers I have running on my macbook. Yet it fails to work on IE10. </p> <p>In IE10, the <code>li</code>s are correctly positioned after each other, but their width does not adapt to the width of the images (which is dynamic, since it follows the browser height). Instead, they have the width of the full-size image.</p> <p>I thought setting <code>inline-block</code> on the <code>li</code>s should make them adapt their with to their content, but apparently this isn't so on IE10.</p> <p>What can I do to fix this?</p> <p>The dev version of the site is online at: <a href="http://clients-are-heroes.jackietreehorn.be/tombubbe/project/flor/" rel="nofollow">http://clients-are-heroes.jackietreehorn.be/tombubbe/project/flor/</a></p>
1
Setting Java System.Property (to Enable TLS1.1) for older grails site (Grails 2.3)
<p>We have a rather ancient Grails site (2.3) that has been serving our needs for quite a while. The server needs to call out to another service for customer details, and that service will soon require TLS 1.1 or higher only. Our site is running on java 1.7, which should support TLS 1.1 and 1.2, but requires it to be enabled explicitly. I'm having trouble enabling it in the grails site.</p> <p>Primarily what I've tried is to start grails by running</p> <pre><code>grails -Dhttps.protocols=TLSv1.1 run-app </code></pre> <p>based on the instructions <a href="https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https" rel="nofollow">here</a>, and the hint <a href="http://www.tothenew.com/blog/setting-system-property-from-command-line-in-grails/" rel="nofollow">here</a>. But when I do, the socket is still closed when I try to login to the other site:</p> <pre><code>Message: Connection reset Line | Method -&gt;&gt; 196 | read in java.net.SocketInputStream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 122 | read in '' | 82 | flushBuffer . . . . . . in java.io.BufferedOutputStream | 140 | flush in '' | 191 | flush . . . . . . . . . in org.apache.commons.httpclient.ChunkedOutputStream | 99 | flush in com.ctc.wstx.io.UTF8Writer | 214 | flush . . . . . . . . . in com.ctc.wstx.sw.BufferingXmlWriter | 311 | flush in com.ctc.wstx.sw.BaseStreamWriter | 50 | flush . . . . . . . . . in org.apache.axiom.util.stax.wrapper.XMLStreamWriterWrapper | 230 | flush in org.apache.axiom.om.impl.MTOMXMLStreamWriter | 91 | serialize . . . . . . . in org.apache.axis2.databinding.ADBDataSource | 638 | internalSerialize in org.apache.axiom.om.impl.llom.OMSourcedElementImpl | 563 | serializeChildren . . . in org.apache.axiom.om.impl.util.OMSerializerUtil | 846 | internalSerialize in org.apache.axiom.om.impl.llom.OMElementImpl | 267 | serializeInternally . . in org.apache.axiom.soap.impl.llom.SOAPEnvelopeImpl | 229 | internalSerialize in '' | 188 | serializeAndConsume . . in org.apache.axiom.om.impl.llom.OMSerializableImpl | 74 | writeTo in org.apache.axis2.transport.http.SOAPMessageFormatter | 84 | writeRequest . . . . . in org.apache.axis2.transport.http.AxisRequestEntity | 499 | writeRequestBody in org.apache.commons.httpclient.methods.EntityEnclosingMethod | 2114 | writeRequest . . . . . in org.apache.commons.httpclient.HttpMethodBase | 1096 | execute in '' | 398 | executeWithRetry . . . in org.apache.commons.httpclient.HttpMethodDirector | 171 | executeMethod in '' | 397 | executeMethod . . . . . in org.apache.commons.httpclient.HttpClient | 621 | executeMethod in org.apache.axis2.transport.http.AbstractHTTPSender | 193 | sendViaPost . . . . . . in org.apache.axis2.transport.http.HTTPSender | 75 | send in '' | 404 | writeMessageWithCommons in org.apache.axis2.transport.http.CommonsHTTPTransportSender | 231 | invoke in '' | 443 | send . . . . . . . . . in org.apache.axis2.engine.AxisEngine | 406 | send in org.apache.axis2.description.OutInAxisOperationClient | 229 | executeImpl . . . . . . in '' | 165 | execute in org.apache.axis2.client.OperationClient | 3916 | login . . . . . . . . . in com.zuora.api.ZuoraServiceStub | 51 | ___init___ in com.zuora.zortal.util.ZApi$$EPbnSoym | 48 | &lt;init&gt; . . . . . . . . in com.zuora.zortal.repository.ZuoraRepository | 40 | login in saaseiportal.unauthorized.LoginController | 195 | doFilter . . . . . . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter | 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter | 1145 | runWorker . . . . . . . in java.util.concurrent.ThreadPoolExecutor | 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker ^ 745 | run . . . . . . . . . . in java.lang.Thread </code></pre> <p>I have confirmed that my system and system's java support TLS 1.1. I created an example java client to connect directly to the site. It gets a similar connection reset message when I run it regularly, but it gets a valid response when I try</p> <pre><code>java -Dhttps.protocols=TLSv1.1 SampleHttpTest </code></pre> <p>I suspect somewhere in grails is actually clearing out my setting. Immediately before the login call that generates the exception, I added a logging call to </p> <pre><code>System.out.println(System.getProperty("https.protocols")); </code></pre> <p>And it just logs a null. Setting that property immediately before I try to login has no effect, possibly because it's far too late in the application's life (some factory already created or something).</p> <p>I'm actually something of a grails novice, so upgrading the app to grails 2.5 and java 8 is actually a rather daunting prospect. I'm hoping someone can point out something simple like:</p> <p>"Here's where grails lets you set system properties before running any other java code" or "Here's where grails sets a bunch of default settings and you should check the values there already" or "It's probably the authentication plugin (or something) that needs to clear/fiddle with those settings"</p> <p>Thanks in advance for any help!!</p>
1
jQuery how to queue fadeIn and fadeOut
<p>I have two different events that call fadeIn / fadeOut on a div. In some cases, the element could be the same.</p> <pre><code>&lt;div class="details"&gt;Details&lt;/div&gt; &lt;div class="details"&gt;Details2&lt;/div&gt; swiper.on('TouchStart', function () { $(".details:eq(" + swiper.previousIndex + ")").fadeOut({queue:true}); }); swiper.on('TouchEnd', function () { $(".details:eq(" + swiper.activeIndex + ")").fadeIn({queue: true}); }); </code></pre> <p>I need the effect to wait if (and only if) the other is still running.</p>
1
Rounding float value off with 0.5 accuracy
<p>How do you go about rounding a float value with lets say a single number after the decimal point off to for example given 18.0-18.4 I would like to display 18.0 or given 18.5-19.0 show 19.0 etc? thanks folks</p>
1
JS Scroll window while mouseover
<p>I would like to scroll up or down the window while the mouse is over a specific element.</p> <p>What I have so far basically works but it's not "smooth". It starts and stops on and on, not looking nice. Do you have any idea how to make a more constant smooth scrolling?</p> <p>This is my code:</p> <pre><code>doScroll = 0; $(".helperDown").mouseenter(function() { scrollHandler = setInterval( function() { console.log('scrolling down...'); if(doScroll == 0) { doScroll = 1; $("html, body").animate({scrollTop: fromTop+50}, 200, 'linear', function() { doScroll = 0; }); } }, 200); }); $(".helperDown").mouseleave(function() { clearInterval(scrollHandler); }); </code></pre> <p><code>.helperDown</code> is the area where the mouse has to be in to start scrolling. <code>fromTop</code> is always recalculated after a scroll event.</p>
1
Regex matching text in brackets over multiple lines
<p>I have the following text:</p> <pre><code>node [ id 2 label "node 2" thisIsASampleAttribute 43 ] node [ id 3 label "node 3" thisIsASampleAttribute 44 ] </code></pre> <p>And I want to group each node and its content inside the brackets e.g:</p> <pre><code> node [ id 2 label "node 2" thisIsASampleAttribute 43 ] </code></pre> <p>However I'm grouping the entire text with my following code:</p> <pre><code>Pattern p = Pattern.compile("node \\[\n(.*|\n)*?\\]", Pattern.MULTILINE); Matcher m = p.matcher(text); while(m.find()) { System.out.println(m.group()); } </code></pre> <p>Edit text:</p> <pre><code> node [\n" + " id 2\n" + " label \"node 2\"\n" + " thisIsASampleAttribute 43\n" + " ]\n" + " node [\n" + " id 3\n" + " label \"node 3\"\n" + " thisIsASampleAttribute 44\n" + " ]\n" </code></pre>
1
Is it possible to read from stdout?
<p>If I use <code>printf ("Hello!");</code> are there any ways to read what I've printed into stdout?</p> <p>I saw <a href="https://stackoverflow.com/questions/17071702/c-language-read-from-stdout">C language. Read from stdout</a> (it uses pipe) but it doesn't work:</p> <pre><code>#define _XOPEN_SOURCE #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #define DIM 10 int main(void) { char s[DIM]; int fds[2]; pipe(fds); dup2(fds[1], fileno(stdout)); //I added fileno() printf("Hello world!"); read(fds[0], s, DIM); printf("\n%s",s); return 0; } </code></pre> <p>I also tried using a file descriptor but neither it doesn't work:</p> <pre><code>#define _XOPEN_SOURCE #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #define DIM 10 #define MYFILE "/path/file" int main(void) { FILE *fd; char s[DIM]; fd = fopen(MYFILE,"w+"); dup2(STDOUT_FILENO, fileno(fd)); printf("Hello world!"); fseek(fd, 0, SEEK_SET); fgets(s, DIM, fd); printf("\n%s",s); return 0; } </code></pre> <p>How can I do?</p>
1
Within Golang struct shared among multiple goroutines, do non-shared members need mutex protection?
<p>I have one Golang struct shared among multiple goroutines. For concurrent access to struct members, there is the mutex sync.RWMutex. For struct member that is accessed by one single goroutine, is there need of mutex protection?</p> <p>For example, in the code below, one single writer goroutine accesses the member shared.exclusiveCounter, without any lock protection. Is this correct/safe? Or is there need of mutex because the whole struct is accessed by multiple goroutines thru a shared pointer?</p> <pre><code>package main import ( "fmt" "sync" "time" ) func main() { s := &amp;shared{mutex: &amp;sync.RWMutex{}} readerDone := make(chan int) writerDone := make(chan int) go reader(s, readerDone) go writer(s, writerDone) &lt;-readerDone &lt;-writerDone } type shared struct { mutex *sync.RWMutex sharedCounter int // member shared between multiple goroutines, protected by mutex exclusiveCounter int // member exclusive of one goroutine -- is mutex needed? } func (s *shared) readCounter() int { defer s.mutex.RUnlock() s.mutex.RLock() return s.sharedCounter } func (s *shared) setCounter(i int) { defer s.mutex.Unlock() s.mutex.Lock() s.sharedCounter = i } func reader(s *shared, done chan&lt;- int) { for { time.Sleep(2 * time.Second) counter := s.readCounter() fmt.Printf("reader: read counter=%d\n", counter) if counter &gt; 5 { break } } fmt.Printf("reader: exiting\n") done &lt;- 1 } func writer(s *shared, done chan&lt;- int) { s.exclusiveCounter = 0 for { time.Sleep(1 * time.Second) s.exclusiveCounter++ fmt.Printf("writer: writing counter=%d\n", s.exclusiveCounter) s.setCounter(s.exclusiveCounter) if s.exclusiveCounter &gt; 5 { break } } fmt.Printf("writer: exiting\n") done &lt;- 1 } </code></pre> <p><a href="http://play.golang.org/p/gzOsuYOAKm" rel="noreferrer" title="Run it on playground">Run it on playground</a></p>
1
How to get the 10 highest values for each group in a data frame?
<p>I am assuming this is an easy thing but I am unable to solve my problem. </p> <p>I have a data frame with 9 columns and I want to get the highest 3 values of the 4th column (LumenLenght) sorted for each group given in the first column.</p> <p>I would like to be able to: a) find the 10 rows with the highest values for column 4 separated for each SampleID (first column) b) average the 10 values for each SampleID</p> <p><img src="https://i.stack.imgur.com/ysjla.jpg" alt="data frame"></p> <p>My current code a) sorts first the values according to SampleID and LumenLength and b) separates the highest, second highest and third highest LumenLength value per SampleID. </p> <pre><code>sorted.v= arrange(sorted.v, desc(SampleId), LumenLength) maxlength1 = aggregate(sorted.v$LumenLength,by = list(sorted.v$SampleId), FUN = tail, n = 1)#highest value maxlength2 = aggregate(sorted.v$LumenLength,by = list(sorted.v$SampleId), FUN = tail, n = 2)#second highest value maxlength3 = aggregate(sorted.v$LumenLength,by = list(sorted.v$SampleId), FUN = tail, n = 3)#3. highest value </code></pre> <p>As you can see, I haven't really reached my goal jet. I am also pretty sure there is a better way of doing it but I stuck right now. </p>
1
Django Global base.html template
<p>I am new to Django. I am using Django 1.8.6 with Python 2.7. I am trying to use a base.html template that can be used globaly through out the entire site, where every app and access it. Here is my test site's current structure:</p> <blockquote> <p>twms</p> <blockquote> <p>polls</p> <blockquote> <p>migrations</p> <p>static</p> <p>templates</p> </blockquote> <p>project</p> <blockquote> <p>migrations</p> <p>static</p> <p>templates</p> <blockquote> <p>project</p> <blockquote> <p>index.html</p> </blockquote> </blockquote> </blockquote> <p>tmws</p> <blockquote> <p>static</p> <p>templates</p> <blockquote> <p>tmws</p> <blockquote> <p>base.html</p> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> <p>Here is the code for project/templates/project/index.html</p> <pre><code>{% extends 'tmws/base.html' %} {% block content %} &lt;h1&gt;Projects&lt;/h1&gt; &lt;ul&gt; {% for project in project_list %} &lt;li&gt;&lt;a href="{% url 'project:detail' project.id %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; end of list {% endblock %} </code></pre> <p>This is the error I am receiving:</p> <blockquote> <p>TemplateDoesNotExist at /project/</p> <p>tmws/base.html</p> </blockquote> <p>How do I access tmws/tmws/templates/tmws/base.html from any of my apps?</p> <p>Any help would be greatly appreciated!</p> <p>Let me know if any additional information is needed.</p> <p><strong>EDIT</strong></p> <p>Here are my template settings from settings.py:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), # If i leave both or just comment one one out I still get the same error 'tmws.tmws.templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] </code></pre>
1
ClosedXML - Style Rows and Columns in C#
<p>I'm working on a ASP.net Excel project, and I'm trying to add some different color (red) to an specific cell (M2,N2,O2,P2,Q2).</p> <pre><code>using (DataTable dt = new DataTable()) { sda.Fill(dt); using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Customers"); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=Excel.xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } </code></pre> <p>I'm trying to add some rows after <code>wb.Worksheets.Add(dt, "Customers");</code> but i cant find the way.</p> <p>I'm trying to implement this:</p> <pre><code>dt.Rows(13, 14, 15, 16, 17).Style.Fill.BackgroundColor = XLColor.Red; </code></pre>
1
How to deal with $(document).foundation() call and WebPack?
<p>According to the Foundation's <a href="http://foundation.zurb.com/sites/docs/v/5.5.3/javascript.html" rel="noreferrer">documentation</a>: </p> <blockquote> <p>After you have included the Foundation JavaScript, just add a simple call to initialize all plugins on your page.</p> <p>We recommend that you initialize Foundation at the end of the page .</p> </blockquote> <pre><code>&lt;script&gt; $(document).foundation(); &lt;/script&gt; </code></pre> <p>My app uses WebPack and therefore modules loads are <strong>async</strong>.<br> It means that the classical script at the bottom of the body runs BEFORE a <code>ui-view</code> is populated with a template. (using Angular).</p> <p>If I put the script at the bottom, the DOM is populated before being parsed by Foundation's scripts, resulting in no effect at all of Foundation's components's behaviour.</p> <p>Have you experienced the same? </p> <p>I don't want to trigger <code>$(document).foundation();</code> in each controller's template.</p>
1
Linker cannot find .so file
<p>I am building an executable and a <code>.so</code> file using another <code>.so</code></p> <pre><code>mylib.so: mylib.o ld -shared -o mylib.so packer.o mylib.o -ldl -L../lib -lcustombuild server: server.o packer.o gcc packer.o server.o -o server -L../lib -lcustombuild </code></pre> <p>The file <code>libcustombuild</code> is in dir lib one level above current dir (i.e. ../lib) When I run my <code>./server</code> it throws error: <code>error while loading shared libraries: libcustombuild.so: cannot open shared object file: No such file or directory</code> I am sure the .so file is in right directory. <br/> <code>ls ../lib</code> output: <code>libcustombuild.so</code></p>
1
CardLayout for JFrames?
<p>I've been looking around, including in the Java documentation, but there isn't a clear answer that I've found for my question : I would like to switch from one JFrame to another at the click of a button; that is, have the old JFrame close while the new one opens. I've heard of "CardLayout" but I'm not so sure how it works. Would anyone mind explaining it, or some other method? </p> <p>Thanks</p>
1
Stop Service in Activity onDestroy
<p>Can I safely stop a Service in my main Activity's onDestroy method? I know that onDestroy is not guaranteed to be called, but I also do want to keep my Service running until the app is destroyed.</p> <p>I'm thinking that maybe in all situations where the activity is destroyed, the service would also be destroyed?</p>
1
CVS repository missing connection types
<p>I'm new to using CVS repositories. I'm trying to import a repo by right clicking in the CVS repositories area, New -> Repository Location and then a window pops up with Add CVS repository. Under connection type, in Eclipse Luna I have 'extssh', but in Eclipse Mars I only have 'ext' and 'pserver'.</p> <p>I need to use extssh. What is it and how do I configure it?</p>
1
'gradlew eclipse' command is not working
<p>I have checked in code from the following URL</p> <p><a href="https://github.com/spring-projects/spring-integration-samples" rel="nofollow">https://github.com/spring-projects/spring-integration-samples</a></p> <p>Now I am try to build the code and give the command <code>'gradlew eclipse'</code></p> <p>and I am getting 522 error code. Could you please help us to resolve the erro</p>
1
Dependency org.apache.httpcomponents:httpclient:4.5 is ignored for debug as it may be conflicting with the internal version provid
<p>I was trying to upload a image to server. As im new for the android i was trying with the others code.</p> <p>This is my error:<a href="https://i.stack.imgur.com/rZnw6.jpg" rel="nofollow noreferrer">Error file</a></p> <p>This is my activity file:-</p> <pre><code>import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.ByteArrayOutputStream; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button btpic, btnup; private Uri fileUri; String picturePath; Uri selectedImage; Bitmap photo; String ba1; public static String URL = &quot;http://127.0.0.1/image.php&quot;; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btpic = (Button) findViewById(R.id.cpic); btpic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { clickpic(); } }); btnup = (Button) findViewById(R.id.up); btnup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { upload(); } }); } private void upload() { // Image location URL Log.e(&quot;path&quot;, &quot;----------------&quot; + picturePath); // Image Bitmap bm = BitmapFactory.decodeFile(picturePath); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); ba1 = Base64.encodeToString(ba,Base64.DEFAULT); Log.e(&quot;base64&quot;, &quot;-----&quot; + ba1); // Upload image to server new uploadToServer().execute(); } private void clickpic() { // Check Camera if (getApplicationContext().getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA)) { // Open default camera Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, 100); } else { Toast.makeText(getApplication(), &quot;Camera not supported&quot;, Toast.LENGTH_LONG).show(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100 &amp;&amp; resultCode == RESULT_OK) { selectedImage = data.getData(); photo = (Bitmap) data.getExtras().get(&quot;data&quot;); // Cursor to get image uri to display String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); picturePath = cursor.getString(columnIndex); cursor.close(); Bitmap photo = (Bitmap) data.getExtras().get(&quot;data&quot;); ImageView imageView = (ImageView) findViewById(R.id.Imageprev); imageView.setImageBitmap(photo); } } public class uploadToServer extends AsyncTask&lt;Void, Void, String&gt; { private ProgressDialog pd = new ProgressDialog(MainActivity.this); protected void onPreExecute() { super.onPreExecute(); pd.setMessage(&quot;Wait image uploading!&quot;); pd.show(); } @Override protected String doInBackground(Void... params) { ArrayList&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(); nameValuePairs.add(new BasicNameValuePair(&quot;base64&quot;, ba1)); nameValuePairs.add(new BasicNameValuePair(&quot;ImageName&quot;, System.currentTimeMillis() + &quot;.jpg&quot;)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(URL); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); String st = EntityUtils.toString(response.getEntity()); Log.v(&quot;log_tag&quot;, &quot;In the try Loop&quot; + st); } catch (Exception e) { Log.v(&quot;log_tag&quot;, &quot;Error in http connection &quot; + e.toString()); } return &quot;Success&quot;; } protected void onPostExecute(String result) { super.onPostExecute(result); pd.hide(); pd.dismiss(); } }} </code></pre> <p>gradle page: <a href="https://i.stack.imgur.com/gKPMm.jpg" rel="nofollow noreferrer">enter image description here</a></p>
1
Displaying NULL values as 'unknown' in SQL Server
<p>I have a table that has two columns; one for Name (datatype nvarchar), the other for ID (datatype int and allows null).</p> <p>I am trying to display all data from the table including those with null values but I want the query result to display the null value as 'unknown'. I ran the following query:</p> <pre><code>Select Name, ID Case When ID is null then 'unknown' When id is not null then (ID) End From table </code></pre> <p>The problem is I am getting this message:</p> <blockquote> <p>Conversion failed when converting the varchar value 'unknown' to data type int</p> </blockquote>
1
How to find standard deviation in R using sqldf package?
<p>All i can do with sqldf package is calculate " avg" "count " and "sum". Can i define my own function for standard deviation?</p> <p>It is really necessary for me to calculate Standard deviation using sqldf only.</p>
1
How to use ls command output in rm for a particular directory
<p>I want to delete oldest files in a directory when the number of files is greater than 5. I'm using </p> <blockquote> <p>(ls -1t | tail -n 3)</p> </blockquote> <p>to get the oldest 3 files in the directory. This works exactly as I want. Now I want to delete them in a single command with rm. As I'm running these commands on a Linux server, cd into the directory and deleting is not working so I need to use either find or ls with rm and delete the oldest 3 files. Please help out. Thanks :)</p>
1
Regex for price, requiring decimal point and 2 decimal places
<p>I am trying to validate a price field in Javascript.</p> <p>The value can only be numbers, must have 1 decimal point, and must have 2 decimal places after it. Only 7 digits can be in front of the decimal point. Like: 1000000.00</p> <pre><code>Accepted: 123.00 1.01 0.01 4576.23 1234567.00 1.00 </code></pre> <hr> <pre><code>Not accepted: 0.00 (Cannot be free) 0.1 (not 2 decimal places) 1.0 (not 2 decimal places) 01.01 (Cannot start with 0) 12345678.00 (too many digits) 123 (no decimal point and 2 places) -123.12 (negative, and unacceptable character) 123.123 (too many places) </code></pre> <p>I am unsure how to approach this problem and any help would be appreciated. A simple guide on how to do write my own regex would be helpful too as English is not my strong point. Thanks in advance.</p> <p>Here's what I tried on my own: /^[0-9]+.[0-9]{2}$/ But I am unsure how to approach the 0 and length problem.</p>
1
Unable to create lxc container on centos "lxc_container: utils.c: get_template_path: 1128 No such file or directory - bad template: centos"
<p>I am trying to create an lxc container on centos but I am running into the following error: [user@sdn3-lnx-01 ~]$ lxc-create -t centos -n container1</p> <p>lxc_container: utils.c: get_template_path: 1128 No such file or directory - bad template: centos</p> <p>lxc_container: lxccontainer.c: lxcapi_create: 1223 bad template: centos</p> <p>lxc_container: lxc_create.c: main: 274 Error creating container container1</p> <p>[user@sdn3-lnx-01 ~]$</p> <p>Could you please help me?</p>
1
colon after class name in java what is for
<p>I have a question about colon in java code, in the next piece of code the line <code>OuterClass:showMsg(text);</code> and the line <code>OuterClass:InnerClass:showMsg(text);</code> give no error and makes me think that the colon character works somethink like double colon in C++ (Scope Resolution) but the output after running leave me with the question, what is the colon for?</p> <pre><code>public class OuterClass { public void showMsg(String msg) { System.out.format("OuterShow : %s%n", msg); } public static abstract class InnerClass { public abstract void command(); public void showMsg(String msg) { System.out.format("InnerShow : %s%n", msg); } } public void someAction(){ new InnerClass() { @Override public void command() { String text = "some text here"; this.showMsg(text); OuterClass.this.showMsg(text); InnerClass:showMsg(text); OuterClass:showMsg(text); OuterClass:InnerClass:showMsg(text); } }.command(); } public static void main(String[] args) { new OuterClass().someAction(); } } </code></pre> <p>The output:</p> <pre><code> --- exec-maven --- InnerShow : some text here OuterShow : some text here InnerShow : some text here InnerShow : some text here InnerShow : some text here </code></pre> <p>tested on windows 7 with jdk1.8.0_25 and maven-3.2.3</p>
1
How do i create a notification in a fragment in android
<p>I am trying to create a notification in a fragment. I am having errors. Can any help ?</p> <p>Here is my code</p> <pre><code>NotificationManager notification = (Notification) getSystemService(getActivity().NOTIFICATION_SERVICE); int icon = R.drawable.ic_launcher; CharSequence tickerText = "your daily tip"; long when System.currentTimeMillis(); Context context = getActivity(); CharSequence contentTitle = "AutoKit"; CharSequence = contentText = "hi"; Intent notificationIntent = new Intent(); PendingIntent contentIntent = PendingIntent.getActivity(getActivity(), 0, notificationIntent, 0); Notification notification = new Notification(icon, tickerText, when); notification.setLatestEventInfo(context, contextTitle, contentText, contentIntent); notificationManager.notify(1, notification); </code></pre> <p>The error lies in the first line.</p>
1
Why does this getOrElse statement return type ANY?
<p>I am trying to follow the tutorial <a href="https://www.jamesward.com/2012/02/21/play-framework-2-with-scala-anorm-json-coffeescript-jquery-heroku" rel="noreferrer">https://www.jamesward.com/2012/02/21/play-framework-2-with-scala-anorm-json-coffeescript-jquery-heroku</a> but of course play-scala has changed since the tutorial (as seems to be the case with every tutorial I find). I am using 2.4.3 This requires I actually learn how things work, not necessarily a bad thing.</p> <p>One thing that is giving me trouble is the getOrElse method.</p> <p>Here is my Bar.scala model</p> <pre><code>package models import play.api.db._ import play.api.Play.current import anorm._ import anorm.SqlParser._ case class Bar(id: Option[Long], name: String) object Bar { val simple = { get[Option[Long]]("id") ~ get[String]("name") map { case id~name =&gt; Bar(id, name) } } def findAll(): Seq[Bar] = { DB.withConnection { implicit connection =&gt; SQL("select * from bar").as(Bar.simple *) } } def create(bar: Bar): Unit = { DB.withConnection { implicit connection =&gt; SQL("insert into bar(name) values ({name})").on( 'name -&gt; bar.name ).executeUpdate() } } } </code></pre> <p>and my BarFormat.scala Json formatter</p> <pre><code>package models import play.api.libs.json._ import anorm._ package object Implicits { implicit object BarFormat extends Format[Bar] { def reads(json: JsValue):JsResult[Bar] = JsSuccess(Bar( Option((json \ "id").as[Long]), (json \ "name").as[String] )) def writes(bar: Bar) = JsObject(Seq( "id" -&gt; JsNumber(bar.id.getOrElse(0L)), "name" -&gt; JsString(bar.name) )) } } </code></pre> <p>and for completeness my Application.scala controller:</p> <pre><code>package controllers import play.api.mvc._ import play.api.data._ import play.api.data.Forms._ import javax.inject.Inject import javax.inject._ import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang } import play.api.libs.json._ import views._ import models.Bar import models.Implicits._ class Application @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport { val barForm = Form( single("name" -&gt; nonEmptyText) ) def index = Action { Ok(views.html.index(barForm)) } def addBar() = Action { implicit request =&gt; barForm.bindFromRequest.fold( errors =&gt; BadRequest, { case (name) =&gt; Bar.create(Bar(None, name)) Redirect(routes.Application.index()) } ) } def listBars() = Action { implicit request =&gt; val bars = Bar.findAll() val json = Json.toJson(bars) Ok(json).as("application/json") } </code></pre> <p>and routes</p> <pre><code> # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page POST /addBar controllers.Application.addBar GET / controllers.Application.index GET /listBars controllers.Application.listBars # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) </code></pre> <p>When I try to run my project I get the following error:</p> <p><a href="https://i.stack.imgur.com/MI5Af.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MI5Af.png" alt="Compilation Error"></a></p> <p>now bar.id is defined as an Option[Long] so bar.id.getOrElse(0L) should return a Long as far as I can tell, but it is clearly returning an Any. Can anyone help me understand why?</p> <p>Thank You!</p>
1
What's the difference between using CGSizeMake and CGSize? Is one better than the other?
<p><code>CGSize(width: 360, height: 480)</code> and <code>CGSizeMake(360, 480)</code> seem to have the same effect. Is one preferred to the other? What is the difference?</p>
1
java.net.ProtocolException: unexpected end of stream in retrofit
<p>I am using retrofit and okhttp to make a server call. But sometimes I get an error which crashes with the following log.(I am using a GET call):</p> <p>Log:</p> <pre><code>: java.net.ProtocolException: unexpected end of stream   at com.squareup.okhttp.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:442) at okio.RealBufferedSource$1.read(RealBufferedSource.java:371) at java.io.InputStream.read(InputStream.java:162) at retrofit.Utils.streamToBytes(Utils.java:43) at retrofit.Utils.readBodyToBytesIfNecessary(Utils.java:81)   at retrofit.RestAdapter.logAndReplaceResponse(RestAdapter.java:483) at retrofit.RestAdapter.access$500(RestAdapter.java:107) at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:338) at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220) at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278) at retrofit.CallbackRunnable.run(CallbackRunnable.java:42) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at retrofit.Platform$Android$2$1.run(Platform.java:142) at java.lang.Thread.run(Thread.java:818) </code></pre> <p>Code: </p> <pre><code> final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setReadTimeout(60, TimeUnit.SECONDS); okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS); RestAdapter restAdapter = new RestAdapter.Builder() .setClient(new OkClient(okHttpClient)) .setEndpoint(URL).build(); myapi myapi_rest = restAdapter.create(myapi.class); myapi_rest.my_call( sno, new Callback&lt;Response&gt;() { @Override public void success(Response result, Response response) { } @Override public void failure(RetrofitError error) { // Log.i("Failure", "Error"+error.getMessage()); } }); </code></pre>
1
pandas - linear regression of dataframe columns values
<p>I have a pandas dataframe <code>df</code> like:</p> <pre><code>A,B,C 1,1,1 0.8,0.6,0.9 0.7,0.5,0.8 0.2,0.4,0.1 0.1,0,0 </code></pre> <p>where the three columns have sorted values [0,1]. I'm trying to plot a linear regression over the three series. So far I was able to use <code>scipy.stats</code> as following:</p> <pre><code>from scipy import stats xi = np.arange(len(df)) slope, intercept, r_value, p_value, std_err = stats.linregress(xi,df['A']) line1 = intercept + slope*xi slope, intercept, r_value, p_value, std_err = stats.linregress(xi,df['B']) line2 = intercept + slope*xi slope, intercept, r_value, p_value, std_err = stats.linregress(xi,df['C']) line3 = intercept + slope*xi plt.plot(line1,'r-') plt.plot(line2,'b-') plt.plot(line3,'g-') plt.plot(xi,df['A'],'ro') plt.plot(xi,df['B'],'bo') plt.plot(xi,df['C'],'go') </code></pre> <p>obtaining the following plot:</p> <p><a href="https://i.stack.imgur.com/EWT0g.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EWT0g.jpg" alt="enter image description here"></a></p> <p>Is it possible to obtain a single linear regression that summarize the three single linear regressions within <code>scipy.stats</code>?</p>
1
how to use ignore case in spring JPA @query?
<p>I have query as below:</p> <pre><code>@Query("SELECT b FROM Brand b WHERE b.name1 LIKE %:name1% or b.name2 like %:name2%") List&lt;Brand&gt; findSome(@Param("name1") String name1, @Param("name2") String name2); </code></pre> <p>I want to ignore case so that I tried to modified it</p> <pre><code>@Query("SELECT b FROM Brand b WHERE lower(b.name1) LIKE lower(%:name1%) or lower(b.name2) like lower(%:name2%)") </code></pre> <p>But this looks like don't work, how can I do?</p>
1
Application.Filedialog support in Mac excel 2011
<p>Couple of questions</p> <ul> <li>Is Application.Filedialog(msoFileDialogSaveAs) support in Mac excel 2011 vba?</li> <li>Difference between Application.Filedialog(msoFileDialogSaveAs) and Application.Dialogs(xlDialogSaveAs)? </li> </ul>
1
Defining the size of an array using a const int
<p>When I try to run this, it gives me an error saying that the value in variable <code>a</code> isn't constant. That doesn't make sense to me because I explicitly made the variable <code>a</code> constant. Does the size of an array have to more constant than that? Meaning, only <code>#define a 5</code>, or initializing it as <code>int arr[5]</code> or using <code>malloc</code>? What is wrong with what I did?</p> <pre><code>int main{ const int a = 5; int i; int arr [a]; for (i = 0; i &lt; 5; i++) { arr[i] = i * 2; } printf("%d", arr[1]); return 0; } </code></pre>
1
how to peek and delete a message from deadletter in azureservicebus
<p>I have created an azure service bus topic application which peek all messages in <strong>deadletter</strong>. Some specific messages(with particular messageid) which i peeked need to be removed from the deadletter queue. Please provide help for implementing this.</p>
1
jquery POST response successful BUT data empty
<p>im using jquery to send a post to a session endpoint of my api to get a login token. the request returns success, however the data is empty. if i do the same request in cURL it returns json. Im new to jquery. does anyone have any suggestions as to what the problem might be?</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt; login &lt;/TITLE&gt; &lt;/HEAD&gt; &lt;LINK rel="stylesheet" type="text/css" href="login.css" /&gt; &lt;BODY&gt; &lt;DIV id="container"&gt; &lt;DIV id="header"&gt; &lt;IMG src="image.bmp" alt="logo" style="width:64px;height:64px;"/&gt; &lt;H1&gt; my service &lt;/H1&gt; &lt;/DIV&gt; &lt;DIV id="content"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { $("button").click(function() { $.post("www.mydomain.com/api/session", { username: "batman", password: "123" }, function(data,status) { alert("Data: " + data + "\nStatus: " + status); }); }); }); &lt;/script&gt; &lt;DIV id="loginform"&gt; &lt;form method="POST"&gt; Username: &lt;input type="text" name="username" /&gt;&lt;br /&gt; Password: &lt;input type="password" name="password" /&gt;&lt;br /&gt; &lt;button&gt; welcome! &lt;/button&gt; &lt;/form&gt; &lt;/DIV&gt; &lt;DIV id="description"&gt; &lt;P&gt;mydomain description&lt;/P&gt; &lt;P&gt;Join now to see what people are doing near you!&lt;/P&gt; &lt;/DIV&gt; &lt;DIV id="register"&gt; &lt;P&gt;Dont have an account with us? &lt;/P&gt; &lt;P&gt;Register here now !!&lt;/P&gt; &lt;/DIV&gt; &lt;/DIV&gt; &lt;DIV id="nav"&gt; &lt;/DIV&gt; &lt;/DIV&gt; &lt;/DIV&gt; &lt;/BODY&gt; &lt;/HTML&gt;</code></pre> </div> </div> </p>
1
Display image in the center of screen when hovering on a link
<p>I'm trying to display an image in the center of the screen when you hover on a link. I've got an image to appear when hovering on a link, but now I can't get it to center. </p> <p>Here's my html:</p> <pre><code>&lt;div class="hover_img"&gt; &lt;a href="#"&gt;A picture of my face&lt;span&gt;&lt;img src="/image.png"/&gt;&lt;/span&gt;&lt;/a&gt; </code></pre> <p></p> <p>And CSS:</p> <pre><code>.hover_img a { position:relative; } .hover_img a span { position:absolute; display:none; z-index:99;} .hover_img a:hover span { display:block;} </code></pre>
1
How can I compare two DateTime fields in MySQL?
<p>You can read the question in the title. Let's say Table A have a datetime field with "2015-12-01 00:00:00" and Table B "2014-12-01 00:00:00".</p> <p>I want the data row from that table which has the bigger datetime.</p> <p>Something like "datetime(A.datetime) > datetime(B.datetime)" isn't working.</p> <p>Help me.</p>
1
Limiting the number of concurrent tasks running
<p>So I come accross this issue with <code>go</code> a lot. Let's say I have a text file with 100,000 lines of text. Now I wanna save all these lines to a db. So I would do something like this:</p> <pre><code>file, _ := iotuil.ReadFile("file.txt") fileLines := strings.Split(string(file), "\n") </code></pre> <p>Now I would loop over all the lines in the file:</p> <pre><code>for _, l := range fileLines{ saveToDB(l) } </code></pre> <p>Now I wanna run this <code>saveToDB</code> func concurrently:</p> <pre><code>var wg sync.WaitGroup for _, l := range fileLines{ wg.Add(1) go saveToDB(l, &amp;wg) } wg.Wait() </code></pre> <p>I don't know if this is a problem or not but that would run 100,000 concurrent functions. Is there any way of saying hey run 100 concurrent functions wait for all of those to finish then run 100 more. </p> <pre><code>for i, _ := range fileLine { for t = 0; t &lt; 100; t++{ wg.Add(1) go saveToDB(fileLine[i], &amp;wg) } wg.Wait() } </code></pre> <p>Do I need to do something like that or is there a cleaner way to go about this? Or is me running the 100,000 concurrent tasks not an issue?</p>
1
In Android, how to place image at center on a button without stretching?
<p>In a Android layout file, I have a button. And I want to present an image for the button without any text. The problem I have is, the image is stretched to cover the whole button area. Instead of stretching, I'd like to have the button placed at the center of the button without any distortion to the image.</p> <pre><code>&lt;Button android:layout_width="38dp" android:layout_height="match_parent" android:background="@drawable/icon_more" android:id="@+id/button" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" /&gt; </code></pre> <p>Right now, it looks like this:</p> <p><a href="https://i.stack.imgur.com/IxX8u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IxX8u.png" alt="enter image description here"></a></p> <p>It's horizontally stretched, which is not what I want.</p>
1
boto3 throws error in when packaged under rpm
<p>I am using boto3 in my project and when i package it as rpm it is raising error while initializing ec2 client.</p> <pre><code>&lt;class 'botocore.exceptions.DataNotFoundError'&gt;:Unable to load data for: _endpoints. Traceback -Traceback (most recent call last): File "roboClientLib/boto/awsDRLib.py", line 186, in _get_ec2_client File "boto3/__init__.py", line 79, in client File "boto3/session.py", line 200, in client File "botocore/session.py", line 789, in create_client File "botocore/session.py", line 682, in get_component File "botocore/session.py", line 809, in get_component File "botocore/session.py", line 179, in &lt;lambda&gt; File "botocore/session.py", line 475, in get_data File "botocore/loaders.py", line 119, in _wrapper File "botocore/loaders.py", line 377, in load_data DataNotFoundError: Unable to load data for: _endpoints </code></pre> <p>Can anyone help me here. Probably boto3 requires some run time resolutions which it not able to get this in rpm.</p> <p>I tried with using LD_LIBRARY_PATH in /etc/environment which is not working.</p> <pre><code>export LD_LIBRARY_PATH="/usr/lib/python2.6/site-packages/boto3:/usr/lib/python2.6/site-packages/boto3-1.2.3.dist-info:/usr/lib/python2.6/site-packages/botocore: </code></pre>
1
Where to start as frontend WPF / Xaml developer
<p>What should custom controls and even to change some application styles when it comes to, for example, change the thumb of a slider or add multiple thumbs to the slider bar. In web development, people usually have a guy I have 1 year of experience working with WPF, but it still looks hard for me when it comes to custom stuff. dependency properties.</p>
1
Is it possible to stream data into a ZeroMQ message as it is being sent via UDP?
<p>We're working with a latency-critical application at <strong><code>30fps</code></strong>, with multiple stages in the pipeline (e.g. compression, network send, image processing, 3D calculations, texture sharing, etc).</p> <p>Ordinarily we could achieve these multiple stages like so:</p> <pre><code>[Process 1][Process 2][Process 3] ---------------time-------------&gt; </code></pre> <p>However, if we can stack these processes, then it is possible that as <code>[Process 1]</code> is working on the data, it is continuously passing its result to <code>[Process 2]</code>. This is similar to how <code>iostream</code> works in c++, i.e. "streaming". With threading, this can result in reduced latency:</p> <pre><code>[Process 1] [Process 2] [Process 3] &lt;------time-------&gt; </code></pre> <p>Let's presume that <code>[Process 2]</code> is our a <code>UDP</code> communication (i.e. <code>[Process 1]</code> is on Computer A and <code>[Process 3]</code> is on Computer B).</p> <p>The output of <code>[Process 1]</code> is approximately <strong><code>3 MB</code></strong> (i.e. typically > 300 jumbo packets at 9 KB each), therefore we can presume that when we call <strong><code>ZeroMQ</code></strong>'s:</p> <pre><code>socket-&gt;send(message); // message size is 3 MB </code></pre> <p>Then somewhere in the library or OS, the data is being split into packets which are sent in sequence. This function presumes that the message is already fully formed.</p> <p>Is there a way (e.g. API) for parts of the message to be 'under construction' or 'constructed on demand' when sending large data over <code>UDP</code>? And would this also be possible on the receiving side (i.e. be allowed to act on the beginning of the message, as the remainder of the message is still incoming). Or.. is the only way to manually split the data into smaller chunks ourselves?</p> <p><code>Note:</code><br>the network connection is a straight wire GigE connection between Computers A and B.</p>
1
Reading GRUB2 debug logs
<p>I want to see GRUB2 debug logs generated by grub_dprintf(), for example, at mmap.c:</p> <pre><code> grub_dprintf ("mmap", "EFI memory region 0x%llx-0x%llx: %d\n", (unsigned long long) desc-&gt;physical_start, (unsigned long long) desc-&gt;physical_start + desc-&gt;num_pages * 4096, desc-&gt;type); </code></pre> <p>After some research, I found out the way to enable this log is by setting debug env variable at grub menu (I changed it on grub.cfg, probably am not supposed to do this)</p> <pre><code>set debug=all </code></pre> <p>How can I check the logs? The grub logs scrolled so fast during boot that it is hard to check. Perhaps there is a way to check the logs after kernel boots?</p> <p>I am using CENTOS 7.</p>
1
Best way to control the ggplot size
<p>I was wondering how I can modify the below code to control the size of the plot (Forexample: How I can bring y elements more close to each other to make the plot smaller)</p> <pre><code>Year &lt;- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4)) Category &lt;- c(rep(c("A", "B", "C", "D"), times = 4)) Frequency &lt;- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251) Data &lt;- data.frame(Year, Category, Frequency) library(dplyr) Data &lt;- group_by(Data,Year) %&gt;% mutate(pos = cumsum(Frequency) - (0.5 * Frequency)) library(ggplot2) p &lt;- ggplot(Data, aes(x = Year, y = Frequency)) + geom_bar(aes(fill = Category), stat="identity", show.legend = FALSE) + geom_text(aes(label = Frequency, y = pos), size = 3, nudge_y = -25) + geom_text(aes(label = Category, y = pos), size = 3, nudge_y = 25) </code></pre>
1
WebRTC: How to calculate user bandwidth/network latency of RTC Peer Connection
<p>So, I'm working on an App that utilises WebRTC to provide video/audio communication between peers.</p> <p>I'd like to provide some feedback to users in regard to their network connection/bandwidth/latency etc in order to suggest possible solutions if bandwidth etc is terrible. </p> <p>WebRTC has a <a href="https://www.w3.org/TR/webrtc-stats/" rel="nofollow"><code>getStats()</code></a> API which provides a number of key pieces of information. When a Peer Connection is active, <code>getStats()</code> gives me the following object...</p> <pre><code>{ "googLibjingleSession_5531731670954573009":{ "id":"googLibjingleSession_5531731670954573009", "timestamp":"2016-02-02T11:14:43.467Z", "type":"googLibjingleSession", "googInitiator":"true" }, "googTrack_SCEHhCOl":{ "id":"googTrack_SCEHhCOl", "timestamp":"2016-02-02T11:14:43.467Z", "type":"googTrack", "googTrackId":"SCEHhCOl" }, "ssrc_360347109_recv":{ "id":"ssrc_360347109_recv", "timestamp":"2016-02-02T11:14:43.467Z", "type":"ssrc", "googDecodingCTN":"757", "packetsLost":"0", "googSecondaryDecodedRate":"0", "googDecodingPLC":"3", "packetsReceived":"373", "googExpandRate":"0.00579834", "googJitterReceived":"0", "googDecodingCNG":"0", "ssrc":"360347109", "googPreferredJitterBufferMs":"20", "googSpeechExpandRate":"0.00140381", "googTrackId":"SCEHhCOl", "transportId":"Channel-audio-1", "googDecodingPLCCNG":"10", "googCodecName":"opus", "googDecodingNormal":"744", "audioOutputLevel":"6271", "googAccelerateRate":"0", "bytesReceived":"21796", "googCurrentDelayMs":"64", "googDecodingCTSG":"0", "googCaptureStartNtpTimeMs":"-1", "googPreemptiveExpandRate":"0.00292969", "googJitterBufferMs":"42" } } </code></pre> <p>It's with this information that I hope to calculate the users...</p> <p>a) Bandwidth (Ideally Audio and Video separately but straight up bandwidth would suffice)</p> <p>b) Network Latency</p> <p>Thanks in advance...</p> <p><strong>NB</strong>: I have already seen <a href="https://github.com/muaz-khan/getStats/blob/master/getStats.js" rel="nofollow">this wrapper</a> but I'd like to be able to do this myself really (with a little bit of your help of course :D) as the example code for this wrapper uses a "bytesSent" property which I don't seem to get back from <code>getStats()</code>?</p> <p>I am also aware of the <a href="https://test.webrtc.org/" rel="nofollow">WebRTC test</a> available on GitHub, but again, I should be able to achieve what I want without relying on third party "plugins" etc.</p>
1
Javascript error: TypeError: 'null' is not an object (evaluating 'event.target') on safari
<p>I have difficulty on integrating my JavaScript syntax. My code is working on Internet Explorer (IE). However, I encountered a JavaScript error when running it on Safari.</p> <p>This is my test code:</p> <pre><code>document.onmouseup = function hideaddrspopup () { if (event.srcElement.id != 'fieldName') { alert(event.srcElement.id); } } </code></pre> <p>I tried something like:</p> <pre><code>document.onmouseup = function hideaddrspopup() { if (event.srcElement.id != 'fieldName' || event.target.id != 'fieldName') { alert(event.srcElement.id); alert(event.target.id); } } </code></pre> <p>But still an error is appearing on the console:</p> <blockquote> <p>'TypeError: 'null' is not an object (evaluating 'event.target')'</p> </blockquote> <p>I am aware that <code>event.scrElement</code> is only working in IE. How to make it work on the other browsers?</p>
1
Facebook Native Ads in RycyclerView android
<p>I found similar issue <a href="https://stackoverflow.com/questions/33908308/facebook-native-ads-in-recycler-view-android">Facebook Native ads in recycler view android</a> , but had some problems with integration with Custom Ad.</p> <p>For the first I tried to describe <code>NativeAdsManager</code> :</p> <pre><code> @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); manager = new NativeAdsManager(getActivity(), "892769720837476_892772047503910", 5); manager.setListener(this); manager.loadAds(); nativeAd = new NativeAd(getActivity(), "892769720837476_892772047503910"); nativeAd.setAdListener(this); nativeAd.loadAd(); ... } </code></pre> <p>Then I included <code>Native ad</code> as a parameter in <code>RecyclerAdapter</code> constructor:</p> <pre><code> adapter = new RecyclerAdapter(foodDataList, getActivity(), nativeAd); </code></pre> <p>In this <code>Class</code> I also implement <code>AdListener</code> and <code>NativeAdsManager.Listener</code> methods:</p> <pre><code>@Override public void onError(Ad ad, AdError adError) { } @Override public void onAdLoaded(Ad ad) { } @Override public void onAdClicked(Ad ad) { } @Override public void onAdsLoaded() { System.out.println("Loaded in fragment"); nativeAd = manager.nextNativeAd(); nativeAd.setAdListener(this); adapter.notifyDataSetChanged(); } @Override public void onAdError(AdError adError) { } </code></pre> <p>After that in <code>RecyclerAdapter</code> class :</p> <pre><code> public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { switch (holder.getItemViewType()) { ... case 2: AdditionalHolder new_holder = (AdditionalHolder) holder; adView = NativeAdView.render(context, nativeAd, NativeAdView.Type.HEIGHT_100); new_holder.templateContainer.addView(adView); return; ... public class AdditionalHolder extends RecyclerView.ViewHolder { protected LinearLayout templateContainer; public AdditionalHolder(View view) { super(view); templateContainer = (LinearLayout) view.findViewById(R.id.ad_test2); } } </code></pre> <p>After all of that my <code>Fragment</code> with <code>RecyclerView</code> becomes very "luggy" and every time I can see more and more ads items (1 - from the beginning, 2 - after 10 items, 3 - after next 10 and so on).</p> <p>It's my first time of using multiple <code>RecyclerView</code> <code>holders</code>, and find this issue difficult.</p> <p>Provide you with gist of 2 <code>Classes</code></p> <p><a href="https://gist.github.com/burnix/6af8196ee8acf5c8f94e" rel="nofollow noreferrer">https://gist.github.com/burnix/6af8196ee8acf5c8f94e</a> - <code>RecyclerAdapter.class</code> <a href="https://gist.github.com/burnix/53dc2ed7446969b78f07" rel="nofollow noreferrer">https://gist.github.com/burnix/53dc2ed7446969b78f07</a> - <code>FragmentList.class</code></p> <p>Help me please to solve lugs problem and to place <code>AudienceNetwork</code> as it needs to be.</p> <p>Thanks in advance!</p>
1
C# Split String - Split String into Array
<p>I am trying to split a string that the user tiped in. For example: He types in "Hello". So I want to split this up into an array: ["H","E","L",...]. So how do I use this .split() function? </p> <p>And how do I save it into an Array?</p> <p>Thank you guys.</p>
1
Can't Draw Filled Rectangle in OpenGL
<p>I am trying to draw a simple filled rectangle in OpenGL. All Google searching tells me that glRectf() should do this, by specifying the color beforehand with glColor4f(), however the rectangle is always drawn unfilled (borders only).</p> <p>Is there anything I am missing, or need to specify in the code beforehand? Thanks!</p>
1
osx: launchd daemon not running my script file
<p>This launchd daemon is a system daemon (not a user agent) and is designed to run the script file upon wakeup from sleep</p> <p>the install code: </p> <pre><code>#!/bin/sh #find current working directory. store as $curr. use to reference anything in $curr/mysecureview. curr=$(pwd) echo "+copy the plist to the system daemons directory." cp $curr/sleepwatcher/config/sleepwatcher.system.plist /System/Library/LaunchDaemons/sleepwatcher.system.plist echo "+create the /etc/mysecureview directory to contain all program files." sudo mkdir /etc/mysecureview echo "+copy the log file to contain the compiled set of log entries." sudo cp $curr/log.txt /etc/mysecureview/log.txt echo "+create the file to contain the individual set of pre-compiled log-entries." sudo mkdir /etc/mysecureview/logs echo "+copy the shell script to be used at bootup/wakeup" sudo cp $curr/sleepwatcher/config/rc.wakeup /etc/mysecureview/rc.wakeup echo "+move imagesnap" sudo cp $curr/imagesnap-master/imagesnap /etc/mysecureview/imagesnap #establishing root ownership of /etc/mysecureview/ #sudo chmod 700 /etc/mysecureview #echo "+establishing root ownership of /etc/mysecureview/" echo "========================" echo "~Installation Succesful~" echo "========================" </code></pre> <p>The plist: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;sleepwatcher.system&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;/usr/local/sbin/sleepwatcher&lt;/string&gt; &lt;string&gt;-V&lt;/string&gt; &lt;string&gt;-w /etc/mysecureview/rc.wakeup&lt;/string&gt; &lt;/array&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;true/&gt; &lt;key&gt;KeepAlive&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>The script itself:</p> <pre><code>#!/bin/sh sudo cd /etc/mysecureview/ sudo ./imagesnap </code></pre> <p>./imagesnap takes a picture and places it in the same directory. the file is named "snapshot.jpg". I've searched the entire mac, and there isn't any .jpg with this name. I think the issue is with creating or installing the plist, but searching the OSX developer page on launchd isn't much of a help.</p>
1
WPF textbox/password box text disappear on click
<p>I'm making a login screen for a wpf application. I want 2 textboxes, one for username and password. </p> <p>For username, I have used a textbox and added text to it ('Username') which disappears when the user clicks on it to enter their username. I done it with the code below.</p> <p>I can't seem to replicate this for password. I don't believe i'll be able to use a textbox as I wont be able to disguise the user input to *'s or whatever, and I cant figure out a way to hardcode 'password' into the box for it to disappear when the user clicks.</p> <p>How can I do this? I know its possible as loads of sites have this functionality but I cant figure it out after googling for a long time! </p> <p>I should stress that im completely new to programming so answers aimed at a complete novice would be much appreciated!</p> <p>Thanks</p> <p>xaml: GotFocus="UserNameTextbox_OnGotFocus" Foreground="#FFA19DA1"/> </p> <pre><code>private void UserNameTextbox_OnGotFocus(object sender, RoutedEventArgs e) { UserNameTextbox.Text = ""; } </code></pre> <p><a href="http://i.stack.imgur.com/qPAOT.png" rel="nofollow">Username example here</a></p>
1
C# collection or array with string keys and values of different types
<p>I need to store data about one article in multiple fields, 3 fields in this example:</p> <pre><code>article["title"] = "Article Title"; // string article["description"] = "Article Description"; // string article["total_pages"] = 15; // int </code></pre> <p>Then I need to be able to use the stored data:</p> <pre><code>int pages = article["total_pages"]; // cast not required MessageBox.Show(pages.ToString()); MessageBox.Show(article["title"]); </code></pre> <p><strong>Question:</strong></p> <p>What would be the proper way of storing data like this?</p> <p>I could simply create variables like <code>string article_title</code>, <code>string article_description</code>, <code>int article_total_pages</code> but if the article actually has more than 10 fields, then the code gets quite messy.</p> <p><strong>Edit:</strong></p> <p>It's fine if all fields can be defined somewhere in one place. What I need is to be able to have a clean code when I use these data in the program.</p> <p>E.g. <code>Article["Title"]</code> or <code>Article.Title</code> (very clean usage)</p>
1
Default values not working in phpmyadmin/mysql database
<p>I can't get a table to accept "" or '' and use the default value. It is inserting NULL instead. </p> <p>I am trying these commands in the direct input sql window. </p> <pre><code>INSERT INTO test01 VALUES ("", now(), ""); INSERT INTO test01 VALUES ('', now(), ''); </code></pre> <p>But both just give NULL in the 3rd column. The structure is set to non-null with a default value of "yes". (Without quotation marks).</p> <p>Here is a screenshot of the structure. You can see NULL is not checked. <a href="http://garryjones.se/extras/so3.png" rel="nofollow noreferrer">http://garryjones.se/extras/so3.png</a> <a href="https://i.stack.imgur.com/NS4dv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NS4dv.png" alt="enter image description here"></a></p>
1
Unable to start activity ComponentInfo.....java.lang.IllegalStateException: Already attached
<p><strong>I m getting that error ,as you can see i m adding the data that i grabbed from the first activity and storing it into the my array in the second activity . Then i use the array to populate the list view .So the problem is whenever i click to the save button on the first view</strong> public class Main2Activity extends AppCompatActivity {</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); super.onCreate(savedInstanceState); // setContentView(Your_Layout); //Bundle extras = null; //if(getIntent().getExtras() != null){ // extras = getIntent().getExtras(); //} Intent intent = getIntent(); // ListView lv = (ListView) findViewById(R.id.View); String data = intent.getStringExtra("data"); String first = intent.getStringExtra("stringOne"); String second = intent.getStringExtra("stringTwo"); String Third = intent.getStringExtra("stringThree"); String Fourth = intent.getStringExtra("stringFour"); String Fifth = intent.getStringExtra("stringFive"); String Sixth = intent.getStringExtra("stringSix"); // Find the ListView resource. ListView lv = (ListView) findViewById( R.id.View ); // Create and populate a List of planet names. String[] dataUser = new String[] { first,second,Third,Fourth,Fifth,Sixth}; ArrayList&lt;String&gt; dataList = new ArrayList&lt;String&gt;(); dataList.addAll(Arrays.asList(dataUser)); // Create ArrayAdapter using the planet list. ArrayAdapter&lt;String&gt; listAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, dataList); // Set the ArrayAdapter as the ListView's adapter. lv.setAdapter(listAdapter); } </code></pre> <p>}</p>
1
"We were able to connect to the database server" error in WordPress
<p>I could not find an answer. Have a production website with production DB. Have backed up the DB and restored to a development environment where I also created a development website in the same server, same cPanel, same user and same password for both DBs. Is a Magento platform 1.9.2, although I do not think is important. Here is the issue: I can execute SQL in the development DB but the same SQL sentence would not execute in the production DB. Also I have uploaded WP to the development and isntalled using the development db for the magento installation, but when I try to run the WP installation for the production site, WP replies "We were able to connect to the database server". Remote MySQL, firewall, etc are the same for both DB, what could be the cause of this and how do I solve it? Thank you.</p>
1
How to ignore field with org.json.JSONObject(Object)
<p>I am using the <a href="http://mvnrepository.com/artifact/org.json/json" rel="nofollow">org.json</a> library. I am creating a <code>JSONObject</code> like so:</p> <pre><code>Geometry geometry = new Geometry(); JSONObject featureObject = new JSONObject(geometry); </code></pre> <p>How can I tell JSONObject to ignore one or more fields of the <code>Geometry</code> object? I have tried <code>@Transient</code> but that did not work. </p>
1
Entity Framework core one to many relationship
<p>I'm trying to build a code first data model with a one to many relationship.</p> <p>There is a UserDTO and a RoleDTO model with the User containing one to many roles.</p> <p>Some simplified code for the RoleDTO is:</p> <pre><code>internal class RoleDTO { public UserDTO User { get; set; } public string Value { get; set; } public RoleDTO() { } } </code></pre> <p>And the simplified UserDTO:</p> <pre><code>internal class UserDTO { public string Email { get; set; } public string FullName { get; set; } public string UserName { get; set; } public virtual ICollection&lt;RoleDTO&gt; Roles { get; set; } public UserDTO() { } } </code></pre> <p>And finally the class that inherits from DBContext</p> <pre><code>class StorageContext : DbContext { public DbSet&lt;UserDTO&gt; Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"My_Connection_String"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity&lt;UserDTO&gt;().HasKey(entity =&gt; entity.Email); modelBuilder.Entity&lt;UserDTO&gt;().HasMany(entity =&gt; entity.Roles); modelBuilder.Entity&lt;RoleDTO&gt;().HasOne&lt;UserDTO&gt;().WithMany(x =&gt; x.Roles); modelBuilder.Entity&lt;RoleDTO&gt;().HasKey(x =&gt; x.Value); } } </code></pre> <p>When I run my add migration and I have no database or migrations folder (and even if I ran it after having some columns anyways) the Role table gets created with an extra columns referring the the User's email address. </p> <p>I only want 2 columns in my role table, one that is the user's email address and is a FK to the User email PK, and the other which is a string value that combined with the foreign key make a compound primary key in the user table. Diagram below:</p> <pre> ******************************* * Role * ******************************* * User_Email - string/varchar * * Value - string /varchar * ******************************* FK - User_Email to User table Email column PK - User_Email, Value compound primary key </pre> <p>Does anyone know how to achieve this using either the fluent API or data annotations?</p> <p>Thanks!</p>
1
Encoding::UndefinedConversionError ("\xE2" from ASCII-8BIT to UTF-8): error in ROR + MongoDB based app
<p>Had a developer write this method and its causing a Encoding::UndefinedConversionError ("\xE2" from ASCII-8BIT to UTF-8): error. </p> <p>This error only happens randomly so the data going in is original DB field is what is causing the issue. But since I don't have any control over that, what can I put in the below method to fix this so bad data doesn't cause any issues?</p> <pre><code>def scrub_string(input, line_break = ' ') begin input.an_address.delete("^\u{0000}-\u{007F}").gsub("\n", line_break) rescue input || '' end end </code></pre> <p>Will this work?</p> <pre><code> input = input.encode('utf-8', :invalid =&gt; :replace, :undef =&gt; :replace, :replace =&gt; '_') </code></pre>
1
Owin Authentication creates a redirect loop
<p>I have an ASP.NET 4.6 WebForms application which exploits the Identity 2.1 package for the registration and authentication system. It uses <strong>Owin authentication</strong>, not Forms or Windows.</p> <p>My attempt is to allow no anonymous user to see any page of the website and to redirect them to the Login page. This is why I have added the following in my Web.config (according to <a href="http://www.codeproject.com/Articles/751897/ASP-NET-Identity-with-webforms" rel="nofollow">this article</a>) :</p> <pre><code>&lt;system.web&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; &lt;authentication mode="None" /&gt; &lt;/system.web&gt; &lt;location path="~/Account/Login.aspx"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; </code></pre> <p> <p>Since then, I always get a Redirect Loop when running the app in the browser. I have found different solutions for MVC, but none for WebForms. <p>What may be the cause and how to remove it?</p> <p>This is my Configuration method in the Startup.Auth.cs file:</p> <pre><code>public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create); app.CreatePerOwinContext&lt;ApplicationRoleManager&gt;(ApplicationRoleManager.Create); app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(ApplicationSignInManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login.aspx"), CookieSecure = CookieSecureOption.Always, Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager)) } }); } </code></pre>
1
What provides libicui18n.so.52.1()(64bit) on Fedora (23)?
<p>I'm trying to install libQt5Core from an rpm and I get:</p> <blockquote> <p>Error: nothing provides libicui18n.so.52.1()(64bit) needed by libQt5Core5-5.5.1-4.1.x86_64</p> </blockquote>
1
How to return a URL Access generated PDF from a Web API method
<p>I've seen a number of examples of returning a PDF (or other file type) using Web API from a file that was stored on disk. However, in my case, I'm attempting to generate the document on the fly using SSRS's URL Access. Here is an example of the URL:</p> <pre><code>https://reporting.mydomain.biz/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=%2fquest%2fQUEST%2520Reports%2fReview.rdl&amp;rp%3aReview=220 </code></pre> <p>I've tried a number of approaches but most of them were from way back in 2012 and relevant to <code>ASP.Net MVC</code> such as:</p> <pre><code>public async Task&lt;FileStreamResult&gt; GenerateReport() { CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri("http://domainORipaddress"), "NTLM", new NetworkCredential( ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"] )); Stream report = null; using (var httpClient = new HttpClient(new HttpClientHandler { Credentials = credentialCache })) { httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); report = await httpClient.GetStreamAsync("reportUrl"); } var contentDisposition = new ContentDisposition { FileName = "Report.pdf", Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return File(report, "application/pdf"); //or use //Response.AppendHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", reportName)); //return File(reportPath, MediaTypeNames.Application.Pdf); } </code></pre> <p>This example code came from this website: <a href="http://webstackoflove.com/sql-server-reporting-service-with-asp-net-mvc/" rel="nofollow noreferrer">http://webstackoflove.com/sql-server-reporting-service-with-asp-net-mvc/</a></p> <p>Here's a similar question but based on <code>ASP.NET</code>: <a href="https://stackoverflow.com/questions/10898999/reporting-services-get-the-pdf-of-a-generated-report">Reporting services: Get the PDF of a generated report</a></p> <p>I tried to use this code above returning a <code>HttpResponseMessage</code> but I'm getting back a file with no data. </p> <p>Here's what I'm using now and it's returning a file with 0 KB:</p> <pre><code>public HttpResponseMessage PrintQualityReview([FromUri] int reviewId) { var reportUrl = String.Format("https://reporting.mydomain.biz/quest/_vti_bin/reportserver?https://reporting.mydomain.biz/quest/QUEST%20Reports/{0}Review.rdl&amp;rs:Format=PDF&amp;Review={1}", ConfigurationManager.AppSettings["ReportingServiceDatabase"], reviewId); CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri("https://reporting.mydomain.biz"), "NTLM", new NetworkCredential( ConfigurationManager.AppSettings["ReportingServiceAccount"], ConfigurationManager.AppSettings["ReportingServiceAccountPwd"] )); MemoryStream mStream = new MemoryStream(); using (WebClient wc = new WebClient()) { wc.Credentials = credentialCache; using (Stream stream = wc.OpenRead(reportUrl)) { stream.CopyTo(mStream); } } HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(mStream); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); response.Content.Headers.ContentDisposition.FileName = "Report.pdf"; return response; } </code></pre> <p>I'm wondering how to do his with <code>ASP.Net Web API</code>? </p>
1
html Transform rotate 90 deg with div
<p>I am adding several divs to make the last div in a parent div to appear on the right side of parent div but rotated 90 degrees. However my content is being pushed out of the div. Below is the code so far:</p> <pre><code> &lt;div style="width:20px; float: right; margin: 0; padding: 0; "&gt; &lt;div style="margin: 5px 5px 5px 0; vertical-align:bottom;"&gt; &lt;div style="transform: rotate(90deg); vertical-align: bottom;margin-bottom: 0;left:0; font-size: 8px; width: 56px ; height: 55px"&gt; TESTING NOW &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
1
Error:create function must be the only statement in the batch
<p>I am trying to firstly check if the function exists then create it, if it doesn't exist.</p> <p>I'm getting this error from the function:</p> <pre><code>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetRelativeExpiry]') AND type in (N'U')) BEGIN SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE FUNCTION [dbo].[GetRelativeExpiry] ( @Date DATE, @N INT ) RETURNS DATE AS BEGIN -- Declare the return variable here DECLARE @Expiry as DATE; IF @N &gt; 0 BEGIN SELECT @Expiry = MAX(E2.Expiry) FROM (SELECT TOP(@N) Expiry FROM ExpiryDates E1 WHERE E1.Expiry &gt;= @date ORDER BY E1.Expiry) AS E2 END ELSE BEGIN SELECT @Expiry = MIN(E2.Expiry) FROM (SELECT TOP(-@N) Expiry FROM ExpiryDates E1 WHERE E1.Expiry &lt;= @date ORDER BY E1.Expiry DESC) AS E2 END RETURN @Expiry END END </code></pre> <p>I am not sure why I am getting this error, could someone please help? I am using Microsoft SQL Server Management Studio 2014</p>
1
Angular2 - How is best to do sorting of a pipe list?
<p>I'm using Typescript and Angular2. I have a pipe that filters a list of results. Now, I want to sort that list in alphabetical etc. How would I do this?</p>
1
Loop through object in nunjucks?
<p>I have a file called "list.json" set up like this:</p> <pre><code>{ "thing1": "Thing1", "thing2": "Thing2", "thing3": "Thing3" } </code></pre> <p>How can I loop through this? I want to do something like:</p> <pre><code>{% for item in list%} &lt;option&gt;{{ thing }}&lt;/option&gt; {% endfor %} </code></pre>
1
Aligning text view below text view in card view
<p>I just implemented card view in my app, and want to put 2 different texts in it (one is 18dp, second is 9dp) in white space bellow image. Also I want to put arrow image to the right side of card view. But I'm getting problem there. If I use 2 different Textviews I can't allign the other one below the first one. And if I use only one Text view, I can't make the text have 2 different sizes.</p> <p>Here's what I'm talking about:</p> <p><a href="https://i.stack.imgur.com/XIepg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XIepg.png" alt="Image"></a></p> <p>As you can see, this is only one Text view wroten as <code>Text1\nText2</code> I can't put size of 18dp to Text 1 and 9dp to Text 2.</p> <p>Any solution to this??</p> <p>Here's the XML code:</p> <pre><code> &lt;android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:foreground="?android:attr/selectableItemBackground" android:clickable="true" android:id="@+id/Vjezbe" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardCornerRadius="2dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginBottom="10dp" android:layout_weight="1" card_view:cardBackgroundColor="#ffffff" android:layout_marginTop="55dp" android:onClick="Vjezbe"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="130dp" android:id="@+id/imageView6" android:background="#000000" android:layout_marginBottom="3dp" android:layout_row="0" android:layout_column="0" /&gt; &lt;TableRow android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Text 1\nText 2" android:id="@+id/textView25" android:textSize="18dp" android:layout_marginLeft="10dp" android:layout_weight="0.9" /&gt; &lt;ImageView android:layout_width="40dp" android:layout_height="40dp" android:id="@+id/imageView17" android:background="@mipmap/strelica" android:layout_marginRight="6dp" android:layout_marginTop="1dp" android:layout_marginBottom="1dp" /&gt; &lt;/TableRow&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre>
1
Android Studio Not Showing Colors
<p>I was using android studio for layers theme and it was easy to theme with android studio as i can see the colors in studio itself on left side check the screenshot what i was referring</p> <p><a href="https://i.stack.imgur.com/2WcTl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2WcTl.png" alt="enter image description here"></a></p> <p>but in CM13 template i dont know whats wrong its not showing colors. i am new to android studio is there something wrong?</p> <p><a href="https://i.stack.imgur.com/CV98U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CV98U.png" alt="enter image description here"></a></p>
1
Pop up calendar for date selection in place of input box
<p>I am currently using a macro, in which I am using input box for manually typing date for <code>.autofilter</code> The two lines as below.</p> <pre><code>key1 = InputBox("Expiry Date", "Title") .Range("A1").CurrentRegion.AutoFilter Field:=2, Criteria1:=key1 </code></pre> <p>Here I need and pop up a calendar, so that instead of manually typing date, I can choose a date from calendar.</p>
1
SQL Server Circle
<p>I'm trying to create a circle in a SQL Server based on a midpoint and a radius. </p> <p>This seems to be close as a solution, but it creates an oval or an ellipse vs a circle. Is there another way to create a circle?</p> <pre><code>DECLARE @g geometry; SET @g = geometry::STGeomFromText('POINT(-88.0 44.5)', 4326); select @g.BufferWithTolerance(5, .01, 1) </code></pre> <p>I'm currently using SQL Server 2008. </p> <p>This code also demonstrates the problem. The spatial results look like a circle, but when I draw the circle on google maps it is oval. Also, when I use <code>STContains</code> to see what points are in the circle, it is definitely following the oval outline. </p> <pre><code>IF EXISTS (SELECT * FROM [tempdb].[sys].[objects] WHERE [name] = N'##circle') DROP TABLE ##circle; CREATE TABLE ##circle ( [Polygon] [geometry] NOT NULL ) DECLARE @g geometry; SET @g = geometry::STGeomFromText('POINT(-88.0 44.5)', 4326); insert into ##circle (Polygon) values (@g.BufferWithTolerance(.5,.01,1)) select Polygon from ##circle </code></pre>
1
How to set transparent background color in UIImageView
<p>I want to know how to set <strong>Transparent background Color</strong> in iOS. I have searched everywhere but I can't find anything. I want to set transparent background color like this:</p> <p><a href="https://i.stack.imgur.com/HFHfT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HFHfT.png" alt="Image"></a></p>
1
Java GridBagLayout does not fill frame horizontally
<p>I am writing the GUI for a chat program. I can't seem to get the <code>scroller</code> to fill the frame horizontally and vertically and the <code>messageInput</code> to fill the frame horizontally. This is how it looks:</p> <p><a href="https://i.stack.imgur.com/bUtro.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bUtro.png" alt="enter image description here"></a></p> <pre><code>import javax.swing.*; import java.awt.*; public class GUI extends JFrame{ private JPanel panel; private JEditorPane content; private JTextField messageInput; private JScrollPane scroller; private JMenu options; private JMenuBar mb; private JMenuItem item; public GUI(){ /** This is the frame**/ this.setPreferredSize(new Dimension(380,600)); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; /** This is where the context shows up **/ content = new JEditorPane(); content.setEditable(false); /** Scroller that shows up in the context JEditorPane **/ scroller = new JScrollPane(content); c.weightx = 0.0; c.weighty = 0.0; c.gridx = 0; c.gridy = 0; panel.add(scroller, c); /** This is where you type your message **/ messageInput = new JTextField(); c.weightx = 0.0; c.weighty = 0.0; c.gridx = 0; c.gridy = 1; c.weighty = 0.5; panel.add(messageInput, c); mb = new JMenuBar(); options = new JMenu("Options"); mb.add(options); this.setJMenuBar(mb); this.add(panel); this.pack(); this.setVisible(true); } public static void main(String[] args) { new GUI(); } } </code></pre>
1
Declare a variable of a table type in postgres
<p>I need to write a stored procudere like the following:</p> <pre><code>CREATE OR REPLACE FUNCTION foo() RETURNS TABLE(user_id integer, count bigint) AS $$ some_array integer[]; ret_val __WHAT_TYPE_; BEGIN FOR i IN 1 .. array_upper(some_array, 1) LOOP //modify the ret_val END LOOP; RETURN ret_val; END $$ LANGUAGE plpgsql; </code></pre> <p>But I don't know what type of <code>ret_val</code> I should declare?</p>
1
Artisan command not recognized
<p>I am trying to do <code>artisan update</code>. It says that the command <code>artisan</code> is not recognized as a command. I am using xampp, so I have added PATH to <code>c:\xampp\php</code> but this command is still not working. Any ideas on how to do this?</p>
1
Programming with dplyr and lazyeval
<p>I am having issues refactoring dplyr in a way that preserves non-standard evaluation. Lets say I want to create a function that always selects and renames.</p> <pre><code>library(lazyeval) library(dplyr) df &lt;- data.frame(a = c(1,2,3), f = c(4,5,6), lm = c(7, 8 , 9)) select_happy&lt;- function(df, col){ col &lt;- lazy(col) fo &lt;- interp(~x, x=col) select_(df, happy=fo) } f &lt;- function(){ print('foo') } </code></pre> <p><code>select_happy()</code> is written according to the answer to this post <a href="https://stackoverflow.com/questions/26058182/refactor-r-code-when-library-functions-use-non-standard-evaluation">Refactor R code when library functions use non-standard evaluation</a>. <code>select_happy()</code> works on column names that are either undefined or defined in the global environment. However, it runs into issues when a column name is also the name of a function in another namespace.</p> <pre><code>select_happy(df, a) # happy # 1 1 # 2 2 # 3 3 select_happy(df, f) # happy # 1 4 # 2 5 # 3 6 select_happy(df, lm) # Error in eval(expr, envir, enclos) (from #4) : object 'datafile' not found environment(f) # &lt;environment: R_GlobalEnv&gt; environment(lm) # &lt;environment: namespace:stats&gt; </code></pre> <p>Calling <code>lazy()</code> on f and lm shows a difference in the lazy object, where the function definition for lm is appearing in the lazy object, and for f it is just the name of the function.</p> <pre><code>lazy(f) # &lt;lazy&gt; # expr: f # env: &lt;environment: R_GlobalEnv&gt; lazy(lm) # &lt;lazy&gt; # expr: function (formula, data, subset, weights, na.action, method = "qr", ... # env: &lt;environment: R_GlobalEnv&gt; </code></pre> <p><code>substitute</code> appears to work with lm. </p> <pre><code> select_happy&lt;- function(df, col){ col &lt;- substitute(col) # &lt;- substitute() instead of lazy() fo &lt;- interp(~x, x=col) select_(df, happy=fo) } select_happy(df, lm) # happy # 1 7 # 2 8 # 3 9 </code></pre> <p>However, after reading <a href="https://cran.r-project.org/web/packages/lazyeval/vignettes/lazyeval.html" rel="nofollow noreferrer">the vignette on <code>lazyeval</code></a> it seems that <code>lazy</code> should serve as a superior substitute for <code>substitute</code>. Additionally, the regular <code>select</code> function works just fine.</p> <pre><code>select(df, happy=lm) # happy # 1 7 # 2 8 # 3 9 </code></pre> <p>My question is how can I write <code>select_happy()</code> so that it works in all the ways that <code>select()</code> does? I'm having a hard time wrapping my head around the scoping and non-standard evaluation. More generally, what would be a solid strategy for programming with dplyr that could avoid these and other issues?</p> <p><strong>Edit</strong></p> <p>I tested out docendo discimus's solution and it worked great, but I would like to know if there is a way to use arguments, rather than dots, for the function. I think it is also important to be able to use <code>interp()</code> because you might want to feed input into a more complicated formula, like in the post I linked to earlier. I think the core of the issue come down to the fact that <code>lazy_dots()</code> is capturing the expression differently from <code>lazy()</code>. I would like to understand why they are behaving differently, and how to use <code>lazy()</code> to get the same functionality as <code>lazy_dots()</code>.</p> <pre><code>g &lt;- function(...){ lazy_dots(...) } h &lt;- function(x){ lazy(x) } g(lm)[[1]] # &lt;lazy&gt; # expr: lm # env: &lt;environment: R_GlobalEnv&gt; h(lm) # &lt;lazy&gt; # expr: function (formula, data, subset, weights, na.action, method = "qr", ... # env: &lt;environment: R_GlobalEnv&gt; </code></pre> <p>Even changing <code>.follow__symbols</code> to <code>FALSE</code> for <code>lazy()</code> so that it is the same as <code>lazy_dots()</code> does not work. </p> <pre><code>lazy # function (expr, env = parent.frame(), .follow_symbols = TRUE) # { # .Call(make_lazy, quote(expr), environment(), .follow_symbols) # } # &lt;environment: namespace:lazyeval&gt; lazy_dots # function (..., .follow_symbols = FALSE) # { # if (nargs() == 0) # return(structure(list(), class = "lazy_dots")) # .Call(make_lazy_dots, environment(), .follow_symbols) # } # &lt;environment: namespace:lazyeval&gt; h2 &lt;- function(x){ lazy(x, .follow_symbols=FALSE) } h2(lm) # &lt;lazy&gt; # expr: x # env: &lt;environment: 0xe4a42a8&gt; </code></pre> <p>I just feel really kind of stuck as to what to do.</p>
1
How to create a submenu in the sidebar
<p>I'm trying to create this type of submenu for social in the sidebar <a href="http://t-phys.web.nitech.ac.jp/sidebar.html" rel="nofollow">url</a>.The options for social submenu are : fb,twitter,youtube.</p> <p>My html :</p> <pre><code>&lt;ul class="sidebar-nav" id="sidebar"&gt; &lt;li class="sub-sidebar-brand"&gt;&lt;a href="#/abc"&gt;abc&lt;span class="sub_icon fa fa-upload"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="sub-sidebar-brand"&gt;&lt;a href="#/System"&gt;System&lt;span class="sub_icon fa fa-hdd-o"&gt;&lt;/span&gt; &lt;/a&gt;&lt;/li&gt; &lt;li class="sub-sidebar-brand"&gt;&lt;a href="#/web"&gt;Web&lt;span class="sub_icon fa fa-hdd-o"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="sub-sidebar-brand"&gt;&lt;a href="#/social"&gt;Social&lt;span class="sub_icon fa fa-hdd-o"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Here I'm trying to create a submenu for social.social should be a dropdownlist with 3 options.Onclick of one option in the social dropdown,should redirect to other page.</p> <p>How can I do this over here? can anyone please help me out regarding this.</p>
1
line simplification algorithm: Visvalingam vs Douglas-Peucker
<p>I am trying to implement a <em>line simplification algorithm</em>. The main 2 algorithms I found are:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm" rel="noreferrer">Ramer-Douglas-Peucker</a></li> <li><a href="https://bost.ocks.org/mike/simplify" rel="noreferrer">Visvalingam-Whyat</a></li> </ul> <p>Currently I am running a few simulations of them on Matlab in order to determine which answers my needs better.</p> <p>The main goal for the algorithm is to simlipfy polygons in a map. My Input is a polygon\polyline and a threshold for mistake- epsilon.</p> <p>I need the simplified polygon to be as close as possible to the original, and I do not have a requirment for number of points to keep.</p> <p>I am having difficulties in comparing the two algorithms because: epsilon for RDP is a distance while epsilon for VW is an area. I need help understanding how to compare between the two algorithms. which can give me less points to keep within the threshold?</p>
1
Angularjs value not updating
<p>I know similar questions have been asked but they don't apply to my case. I have defined some variables in my controller and display their values in a panel. My controller related to the part is like this:</p> <pre><code>var vm = this; vm.wellId = "id"; vm.wellSeq = "sequence"; vm.onWellSelected = onWellSelected; ... function onWellSelected(wells) { ... vm.wellId = wells[0]["id"]; vm.wellSeq = wells[0]["sequence"]; ... } </code></pre> <p>and my html component is like this:</p> <pre><code>&lt;div plate id="plate-layout" on-well-selected="vm.onWellSelected(wells)"&gt; &lt;/div&gt; &lt;ul class="list-group" style="width: 400px; overflow: auto"&gt; &lt;li class="list-group-item"&gt;{{vm.wellId}}&lt;/li&gt; &lt;li class="list-group-item"&gt;{{vm.wellSeq}}&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I checked the source and set break points in the function onWellSelected: vm.wellId and vm.wellSeq are indeed changed to the correct values after the operation, but the new value cannot be displayed. The definition of plate involves quite a number of other js files so not easy to show here, but plate itself is a directive, with support from two services. What could be the reasons? Thanks!</p>
1
PHPExcel, Copy sheet from one to another xls document with style
<p>I need to create an xls file using lists of other files</p> <p>I do something like this:</p> <pre><code> $objReader = PHPExcel_IOFactory::createReader('Excel5'); $file_tmpl = $objReader-&gt;load('doc10.xls'); </code></pre> <p>$file_tmpl - the resulting file</p> <pre><code> $file1 = $objReader-&gt;load('doc11.xls'); </code></pre> <p>$file1 - file that is copied sheet</p> <pre><code> $file1-&gt;setActiveSheetIndex(1); $sheet = $file1-&gt;getActiveSheet(); $file_tmpl-&gt;addSheet($sheet,1); </code></pre> <p>As a result, the sheet is copied, except for the style of the cell: the borders, fonts, text size, text color. How to move all together with style? </p> <p>Thank you.</p>
1
Get index of regex in filename in powershell
<p>I'm trying to get the starting position for a regexmatch in a folder name.</p> <pre><code>dir c:\test | where {$_.fullname.psiscontainer} | foreach { $indexx = $_.fullname.Indexofany(&quot;[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]&quot;) $thingsbeforeregexmatch.substring(0,$indexx) } </code></pre> <p>Ideally, this should work but since indexofany doesn't handle regex like that I'm stuck.</p>
1
how to add items to shopping cart without adding button just on click on the picture
<p>Recently i have been doing my own shopping cart but i have a problem , i don't want to add "add to cart" button on the item , i want to add items to the shopping cart by clicking on the items pictures; in the first click adding to cart and in the second one remove it from the cart .</p> <p>I used this code but it does not work it needs a button;</p> <pre><code>$(document).ready(function(e) { $('#submitbutton').click(function(e) { var pos = $('#inputid').val(); alert(pos); return false; }); }); </code></pre> <p>thanks for advice </p>
1
Heroku: PG::ConnectionBad: could not connect to server: No such file or directory
<p>I´m having some trouble sharing a postgres database between my two Heroku apps. </p> <p>I want the database of App A to be shared with App B, so I attached the App A postgres to App B, then I deleted App B´s original database.</p> <p>However, trying to connect to from App B to the database results in this message:</p> <blockquote> <p>PG::ConnectionBad: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?</p> </blockquote> <p>I have tried to restart the dynos and such but still no luck. Does anyone have any ideas on how to solve this?</p>
1
How to add deselecting to UICollectionView but without multiple selection?
<p>I currently have 4 different collection views on a view, and I want to allow deselection. For this I have to set:</p> <pre><code>//Stop multiple selections on collectionview self.bagsCollectionView.allowsMultipleSelection = YES; self.shoesCollectionView.allowsMultipleSelection = YES; self.dressesCollectionView.allowsMultipleSelection = YES; self.jewelleryCollectionView.allowsMultipleSelection = YES; </code></pre> <p>However I only want to be able to select one cell from each collectionview. E.g., in bagsCollectionView the user can choose one bag but can also deselect that and pick another bag. They cannot pick two bags or two shoes. Same for the other three collection views!</p> <p>How do I do this?</p>
1
Header banner in html and css
<p>I'm getting frustrated with this responsive web design. I'm trying to create a banner for a one page site that i'm trying to build (for exercise purpose). </p> <p>Instead of making the image as a background of the header, i wrote it inside the header tag in the html, making it look like a banner is not that hard for me but i wanna put some text on top of the image and it works perfectly fine with absolute positioning of the hgroups.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>header#main img{ max-width: 100%; max-height: auto; opacity: 2; margin: 0 auto; } header#main hgroup h1{ position: absolute; top: 50%; left: 20%; opacity: .5; margin-top: 0; color: #E7E7E7; font-size: 3.5em; font-family: 'Open Sans'; font-weight: lighter; max-width: 100%; margin: auto; } header#main hgroup h2{ font-family: 'Open Sans'; opacity: .9; font-style: italic; color: #E7E7E7; font-size: 1em; font-family: 'Open Sans'; font-weight: lighter; text-align: justify; position: absolute; top: 60%; left: 42%; max-width: 100%; margin: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header id="main"&gt; &lt;img src="imgs/mountain.jpg"/&gt; &lt;hgroup&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;h2&gt; subtitle &lt;/h2&gt; &lt;/hgroup&gt; &lt;/header&gt; </code></pre> </div> </div> </p> <p>And when i try to resize the browser they go missing. Any technique on making a header banner?</p>
1
angularjs and PHP : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
<p>I'm trying to do a simple POST from angularjs to a dummy php file to understand how this works. Here in my angularjs part: </p> <pre><code>&lt;html ng-app="loginApp"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Login&lt;/title&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"&gt;&lt;/script&gt; &lt;script&gt; var logindata = {username:'abc', password:'abc'} var loginApp = angular.module('loginApp', []); loginApp.controller('loginCtrl', function ($scope, $http){ var request = $http({ method: "POST", url: "http://different-ip/a.php", data: logindata, headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(logindata.username + logindata.password), 'Access-Control-Allow-Origin': "*"} }); request.success( function( data ) { $scope.someVariableName = data; } ); }); &lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="loginCtrl"&gt; &lt;h2&gt;Angular.js JSON Fetching Example&lt;/h2&gt; &lt;p&gt; {{ someVariableName }} &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is my PHP part (a.php) that resides on <a href="http://different-ip" rel="nofollow">http://different-ip</a></p> <pre><code>&lt;?php header("Access-Control-Request-Method: *"); header("Access-Control-Request-Headers: *"); header("Access-Control-Allow-Origin: *"); file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true)); file_put_contents("aaa.txt", getallheaders()); ?&gt; </code></pre> <p>When I execute my angularjs file, the chrome console gives me this error: </p> <pre><code>Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. </code></pre> <p>When I try doing a post to this a.php using Postman, everything works fine. So why is angularjs not allowing it? I've tried to read about CORS and there is no straightforward answer to how this issue can be resolved (code wise). Can someone please help me out? Thanks in advance. </p>
1
How to get the time zone from a datetime string
<p>How can I get the time zone from a datetime string with this format <code>2013-08-15T13:00:00-07:00</code>?</p>
1
How do your link to a favicon in ruby on rails?
<p>Here is what I am trying.</p> <p><code>&lt;%= image_tag 'favicon.ico', rel="icon" type="image/x-icon" %&gt;</code></p>
1
count the number of times a number (factor) occurs within each group
<p>With the reproducible data below,</p> <pre><code>dat &lt;- data.frame(Bin = rep(1:4, each = 50), Number = sample(5, 200, replace = T, prob = c(1,1,1,2,3))) &gt; head(dat) Bin Number 1 1 3 2 1 5 3 1 4 4 1 5 5 1 5 6 1 1 </code></pre> <p>I want to count the number of times each <code>Number</code> occurs within each <code>Bin</code>, preferably using <code>dplyr.</code> Said differently, how many occurrences of each level of <code>Number</code> are in each <code>Bin</code>?</p> <p>Thanks!</p>
1
Populate list from enum
<p>I want to populate a list that provides both enum values and descriptions. How do I do this in C#?</p> <p>I know how to create a list of values but I also want to include the descriptions. Here's what my enums looks like:</p> <pre><code>using System.ComponentModel; public enum BusinessCategory { [Description("Computers &amp; Internet")] ComputersInternet = 1, [Description("Finance &amp; Banking")] FinanceBanking = 2, [Description("Healthcare")] Healthcare = 3, [Description("Manufacturing")] Manufacturing = 4 } </code></pre> <p>I'd like my list to look like:</p> <pre><code>[ { 1, "Computers &amp; Internet" }, { 2, "Finance &amp; Banking" }, { 3, "Healthcare" }, { 4, "Manufacturing" } ] </code></pre>
1
bootstrap sliding panel from the bottom of the screen
<p>Hie guys, i want to design a floating panel that works like the iPad/iPhone Control Center menu.i tried searching around but all i could find were simple in page collapsible panels.When collapsed, the panel should only show a small arrow/ button at the bottom of the screen that will expand the panel in an upward direction.Also the panel should be floating as demonstrated in the dashboard below. A sample of what i want is demonstrated in the weather dashboard below.<a href="http://i.stack.imgur.com/9c4dk.gif" rel="nofollow">Check out that panel floating from below in this dashboard image</a>. <a href="http://i.stack.imgur.com/eg3xF.png" rel="nofollow">This is what i currently have</a>. The side panel is a plugin for the Leaflet.js api i am using</p>
1
gcloud docker push 403 Forbidden
<p>I am trying to push a docker image to eu.gcr.io and I am getting 403 Forbidden</p> <pre><code>gcloud docker push eu.gcr.io/&lt;projectname&gt;/&lt;image&gt;:latest The push refers to a repository [eu.gcr.io/&lt;projectname&gt;/&lt;image&gt;] (len: 1) 663cd9de01fe: Preparing Post https://eu.gcr.io/v2/w&lt;projectname&gt;/&lt;image&gt;/blobs/uploads/: token auth attempt for registry: https://eu.gcr.io/v2/token?account=_token&amp;scope=repository%3A&lt;projectname&gt;%2F&lt;image&gt;3Apush%2Cpull&amp;service=eu.gcr.io request failed with status: 403 Forbidden </code></pre> <p>I have checked </p> <ol> <li>curl <a href="https://eu.gcr.io/v1/_ping" rel="noreferrer">https://eu.gcr.io/v1/_ping</a> => works </li> <li>gcloud config list => project id is setup </li> <li>Storage api is enabled in console</li> <li>if I use the project name in the url I get 403 Forbidden</li> <li>if I use the project id in the url I get "Repository does not exist"</li> <li>gcloud auth list => shows the owner as active</li> <li>gcloud components update => All components are up to date.</li> </ol>
1
Stripe with angularJS integration
<p>I am trying to implement Stripe with AngularJS. In a html a introduced their code snippet for checkout:</p> <pre><code>&lt;form&gt; &lt;script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="&lt;pk_key&gt;" data-amount="100" data-name="name" data-description="description" data-image="img.png" data-locale="auto"&gt; &lt;/script&gt; &lt;/form&gt; </code></pre> <p>Now, after submiting the checkout form, I expect a token. The checkout form changes my url to something like this:</p> <pre><code>&lt;path&gt;/?stripeToken=tok_17VlKKLZ8lYIAVgOX7viLFlm&amp;stripeTokenType=card&amp;stripeEmail=mihai.t.pricop%40gmail.com#/ </code></pre> <p>I need this angular to trigger a scope function with this token when the form is submited. How can I achieve something like this ?</p> <pre><code>$scope.checkout = function(token) { &lt;do stuff with the token&gt; } </code></pre> <p>Thank you.</p>
1
how can I avoid storing a command in ipython history?
<p>In bash I can prevent a command from being saved to bash history by putting a space in front of it. I cannot use this method in ipython. How would I do the equivalent in ipython?</p>
1