input
stringlengths
51
42.3k
output
stringlengths
18
55k
Modifying elements with same directive <p>I have several elements in a container. One of the rows has two icons in it: zoom in and zoom out. When you click Zoom In, I'd like all the row's widths to grow. </p> <pre><code>&lt;div id="events"&gt; &lt;year&gt;year 1&lt;/year&gt; &lt;year&gt;year 2&lt;/year&gt; &lt;year&gt;year 3&lt;/year&gt; &lt;year&gt;year 4&lt;/year&gt; &lt;div id="scaling"&gt; &lt;md-icon aria-label="Zoom In" class="material-icons" ng-click="zoomIn()"&gt;zoom_in&lt;/md-icon&gt; &lt;md-icon aria-label="Zoom Out" class="material-icons" ng-click="zoomOut()"&gt;zoom_out&lt;/md-icon&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I have a year directive:</p> <pre><code>angular.module("app").directive("year", ['$rootScope', function ($rootScope) { return { link: function($scope, element, attr) { var events = element; $scope.zoomIn = function(ev) { console.log('zoomin'); $scope.zoom = $scope.zoom + $scope.scale; if($scope.zoom &lt; 100) { $scope.zoom = 100; } events.html($scope.zoom); events.css({ 'width': $scope.zoom + '%' }); } $scope.zoomOut = function(ev) { $scope.zoom = $scope.zoom - $scope.scale; if($scope.zoom &lt; 100) { $scope.zoom = 100; } events.css({ 'width': $scope.zoom + '%' }); } } } }]); </code></pre> <p>However the width is only applied to the very last year element. Why is that? </p>
<p>You are overwriting the scope every time. So each instance of your <code>year</code> directive is clobbering the <code>zoomIn</code> and <code>zoomOut</code> methods each time it is instantiated.</p> <p>Normally you could solve this by using a new or isolate scope in your directive definition object:</p> <pre><code>//new scope { scope: true } //isolate scope { scope: {} } </code></pre> <p>However, since you want to bind click handlers <strong>outside</strong> your individual <code>year</code> directives you will have to do something else.</p> <p>A better solution would be to pass in the attributes and simply respond to their changes:</p> <pre><code>return { scope: { zoom: '=' }, link: function(scope, elem, attrs){ scope.$watch('zoom', function(){ //Do something with 'scope.zoom' }); } }; </code></pre> <p>Now your external <code>zoomIn</code> and <code>zoomOut</code> functions can just modify some <code>zoom</code> property on the parent scope, and you can bind your <code>year</code> components to that.</p> <pre><code>&lt;year zoom="myZoomNumber"&gt;&lt;/year&gt; </code></pre> <p><em>And just for posterity</em>, here is a working snippet.</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>function EventsController() { var $this = this; var zoom = 1; $this.zoom = zoom; $this.zoomIn = function() { zoom *= 1.1; $this.zoom = zoom; console.log({ name: 'zoomIn', value: zoom }); }; $this.zoomOut = function() { zoom *= 0.9; $this.zoom = zoom; console.log({ name: 'zoomOut', value: zoom }); }; } function YearDirective() { return { restrict: 'E', template: '&lt;h1 ng-transclude&gt;&lt;/h1&gt;', transclude: true, scope: { zoom: '=' }, link: function(scope, elem, attr) { var target = elem.find('h1')[0]; scope.$watch('zoom', function() { var scaleStr = "scale(" + scope.zoom + "," + scope.zoom + ")"; console.log({ elem: target, transform: scaleStr }); target.style.transform = scaleStr; target.style.transformOrigin = 'left'; }); } }; } var mod = angular.module('my-app', []); mod .controller('eventsCtrl', EventsController) .directive('year', YearDirective);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.scaling{ z-index:1000; position:fixed; top:10px; left:10px; } .behind{ margin-top:50px; z-index:-1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="my-app" ng-controller="eventsCtrl as $ctrl"&gt; &lt;div class="scaling"&gt; &lt;button type="button" aria-label="Zoom In" ng-click="$ctrl.zoomIn()"&gt;zoom_in&lt;/button&gt; &lt;button type="button" aria-label="Zoom Out" ng-click="$ctrl.zoomOut()"&gt;zoom_out&lt;/button&gt; &lt;/div&gt; &lt;div class="behind"&gt; &lt;year zoom="$ctrl.zoom"&gt;year 1&lt;/year&gt; &lt;year zoom="$ctrl.zoom"&gt;year 2&lt;/year&gt; &lt;year zoom="$ctrl.zoom"&gt;year 3&lt;/year&gt; &lt;year zoom="$ctrl.zoom"&gt;year 4&lt;/year&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Create multiple arrays using a for loop <p>I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.</p> <p>This is the code I was using, but it doesn't work:</p> <pre><code>public static void main(String[] args){ Scanner s = new Scanner(System.in); System.out.println("Enter the numbers of variables: "); int i = s.nextInt(); for(int j = 0;j &lt; i;j++){ int[] var = new int[j]; System.out.println("Enter the number of values: "); int p = s.nextInt(); for(int q = 0;q &lt; p;p++){ int n = s.nextInt(); var[q] = n; } } } </code></pre> <p>And how could I compare these arrays that the user inputs?</p>
<p>The problem is that each time you are creating the array. try this:</p> <pre><code>Scanner s = new Scanner(System.in); System.out.println("Enter the numbers of variables: "); int i = s.nextInt(); int[][] var = new int[i][]; for(int j = 0;j &lt; i;j++){ System.out.println("Enter the number of values: "); int p = s.nextInt(); var[j] = new int[p]; for(int q = 0;q &lt; p;p++){ int n = s.nextInt(); var[j][q] = n; } } </code></pre> <p>Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (<code>i</code>) and then continues to fill the arrays.</p> <p>To check whether two collections have no commons values, you can use </p> <pre><code>Collections.disjoint(); </code></pre> <p>For other operations, you can look <a href="http://stackoverflow.com/questions/13270491/how-do-i-get-the-intersection-between-two-arrays-as-a-new-array">here</a></p>
PostgresQL, only contain not null values <p>I'm trying to output a query where if any of the following columns contains NULL value (or for current sheet does not contain an empty string), then output the results, but it is still outputting results with null values. What am I doing incorrectly?</p> <pre><code>select * FROM public._http_requests WHERE ((_http_requests.currentsheet IS NOT NULL OR _http_requests.currentsheet != '') OR _http_requests.session_id IS NOT NULL OR _http_requests.http_referer IS NOT NULL) </code></pre>
<p>Replace <code>OR</code> with <code>AND</code> to make sure all columns in <code>where</code> clause does not have any <code>NULL</code> value</p> <pre><code>SELECT * FROM PUBLIC._http_requests WHERE (_http_requests.currentsheet IS NOT NULL OR _http_requests.currentsheet != '') AND _http_requests.session_id IS NOT NULL AND _http_requests.http_referer IS NOT NULL </code></pre>
Unit test IOException for InputStream <p>Is there a way to unit test the following code without using <strong>PowerMock</strong>? We have sonar unit test code coverage and it does not recognise code tested via PowerMockRunner. So I was looking for a way to simulate <strong>IOException</strong> or use Mockito somehow to test this code so that it throws exception.</p> <pre><code>public void readFile(byte[] bytes) { try (final InputStream inputStream = new ByteArrayInputStream(bytes)) { ..... } catch (IOException e) { throw new SystemException("Error reading file"); } } @Test(expected = SystemException.class) public void testException { } </code></pre> <p>Any suggestion would be great.</p> <p>Thanks.</p>
<p>A <code>ByteArrayInputStream</code> will never throw an Exception so subsequently your <code>try</code> / <code>catch</code> is pointless. Just create the <code>ByteArrayInputStream</code> and use it directly and dump the exception handling. If you check the method signatures of <code>ByteArrayInputStream</code> you'll notice that the exceptions are removed so you don't have to worry about it.</p> <p>Update:</p> <p>You can safely interact with the <code>ByteArrayInputStream</code> like this:</p> <pre><code>public void readFile(byte[] bytes) { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); .... // no need to close the inputStream as it's a NO-OP } </code></pre>
Why doesn't this work? Is this a apscheduler bug? <p>When I run this it waits a minute then it prints 'Lights on' then waits two minutes and prints 'Lights off'. After that apscheduler seems to go nuts and quickly alternates between the two very fast. </p> <p>Did i just stumble into a apscheduler bug or why does this happen?</p> <pre><code>from datetime import datetime, timedelta import time import os, signal, logging logging.basicConfig(level=logging.DEBUG) from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() def turn_on(): #Turn ON print('##############################Lights on') def turn_off(): #Turn off print('#############################Lights off') def schedule(): print('Lights will turn on at'.format(lights_on_time)) if __name__ == '__main__': while True: lights_on_time = (str(datetime.now() + timedelta(minutes=1))) lights_off_time = (str(datetime.now() + timedelta(minutes=2))) scheduler.add_job(turn_on, 'date', run_date=lights_on_time) scheduler.add_job(turn_off, 'date', run_date=lights_off_time) try: scheduler.start() signal.pause() except: pass print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: # This is here to simulate application activity (which keeps the main thread alive). while True: time.sleep(2) except (KeyboardInterrupt, SystemExit): # Not strictly necessary if daemonic mode is enabled but should be done if possible scheduler.shutdown() </code></pre>
<p>You are flooding the scheduler with events. You are using the BackgroundScheduler, meaning that scheduler.start() is exiting and not waiting for the event to happen. The simplest fix may be to not use the BackgroundScheduler (use the BlockingScheduler), or put a sleep(180) on your loop.</p>
TeamCity NuGet package build for different .NET Frameworks <p>I've been doing updates to .NET Framework targeted versions of projects updating to latest .NET (4.6.2).</p> <p>Some of these projects are NuGet packages, built in TeamCity 9.0.2.</p> <p>I've use the steps in <a href="http://shazwazza.com/post/multi-targeting-a-single-net-project-to-build-for-different-framework-versions/" rel="nofollow">this</a> guide to create multiple build configurations for different .NET Framework version as some of the projects I haven't updated to 4.6.2 reference the NuGet packages. So I am trying to get TeamCity to use these build configurations to output the various Net40, Net45, Net46 and Net462 versions so that I have full compatibility without forcing the need to upgrade all projects that use the NuGet when updating the packages.</p> <p>I really can't figure out how to do this in TeamCity. I am fairly sure that this should be done in the "Build Steps" configuration, but so far I've not managed to get this to work.</p> <p><a href="https://i.stack.imgur.com/EQtlI.png" rel="nofollow"><img src="https://i.stack.imgur.com/EQtlI.png" alt="Current Build Steps"></a></p> <p>So one thing I've tried, which I think I need to do but am not sure is duplicate the first build step and set the <code>Configuration</code> to <code>Release-Net46</code>. I think this is necessary otherwise this version of the assembly wouldn't be built (please correct me if I'm wrong about that!)</p> <p>The second thing I've tried is to duplicate the <code>NuGet Pack</code> step and in <code>Properties</code> set <code>Configuration=Release-Net46</code> but all that did was replace the Net462 version with Net46 and not include both in the artifacts like I'd hoped.</p> <p>I also tried in the <code>Properties</code> of <code>NuGet Pack</code> to have multiple <code>Configuration</code> elements like <code>Configuration=Release;Configuration=Release-Net46</code> or <code>Configuration=Release,Release-Net46</code> but both of those resulted in the build failing altogether so clearly that's not the answer.</p> <p><a href="https://i.stack.imgur.com/3nnYM.png" rel="nofollow"><img src="https://i.stack.imgur.com/3nnYM.png" alt="NuGet Pack Properties"></a></p> <p>I think there must be a way to get this <code>NuGet Pack</code> build step to pick up the output from the other build configurations and output all available versions of the assembly to the artifacts.</p> <p>Is that possible? I had thought about creating separate projects for each build configuration in TeamCity but I'm unsure if that's the correct way or it that would cause issues with the package feed and it would seem untidy to duplicate the project four times for each .NET Framework version.</p>
<p>Ok I ended up solving this through trial and error and learning about NuSpec. Note, I didn't find a way to do this using purely TeamCity settings but this is equally good.</p> <p>I was correct that you need extra build steps to build the assemblies in the solution/project level build configurations and point each <code>Configuration</code> at <code>Release-NetX</code>.</p> <p><a href="https://i.stack.imgur.com/2Zfbe.png" rel="nofollow"><img src="https://i.stack.imgur.com/2Zfbe.png" alt="TeamCity Build Steps"></a></p> <p><em>EDIT</em> I've found it's actually best in the above to point the <code>NetX</code> build steps at the <code>.csproj</code> rather than the <code>.sln</code>. That way you don't need the build configurations at a solution level, as long as they exist in the <code>.csproj</code> then it will all build fine.</p> <p>Once this is done, TC will then be building all versions into their respective <code>bin\Release-NetX</code> directories.</p> <p>Next was to add a <code>.nuspec</code> file to the root directory of the solution project to build the NuGet for.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"&gt; &lt;id&gt;Foo.Bar.Package&lt;/id&gt; &lt;version&gt;1.0.23&lt;/version&gt; &lt;authors&gt;FooBar Industries&lt;/authors&gt; &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt; &lt;description&gt;FooBar Industries package&lt;/description&gt; &lt;/metadata&gt; &lt;files&gt; &lt;file src="bin\Release\*.dll" target="lib\net462" /&gt; &lt;file src="bin\Release-Net46\*.dll" target="lib\net46" /&gt; &lt;file src="bin\Release-Net45\*.dll" target="lib\net45" /&gt; &lt;file src="bin\Release-Net4\*.dll" target="lib\net40" /&gt; &lt;/files&gt; &lt;/package&gt; </code></pre> <p>Next is to alter the <code>NuGet Pack</code> TeamCity Build Step and in <code>Specification files</code> section and point this to your <code>.nuspec</code> file. There's a checkbox for <code>Prefer project files to .nuspec</code>. It worked for my just by unchecking this and I didn't even need to point to <code>.nuspec</code> file.</p> <p><a href="https://i.stack.imgur.com/F4u3p.png" rel="nofollow"><img src="https://i.stack.imgur.com/F4u3p.png" alt="TeamCity NuGet Pack build step"></a></p> <p>Then on triggering a build, all versions are outputted and are then available to use without upgrading all projects that reference this package.</p> <p><a href="https://i.stack.imgur.com/H4Qxl.png" rel="nofollow"><img src="https://i.stack.imgur.com/H4Qxl.png" alt="enter image description here"></a></p>
XSLT: Add attribute to all descendants of rootnode <p>I have the following xml document:</p> <pre><code>$ cat data.xml &lt;rootnode&gt; &lt;section id="1" &gt; &lt;outer param="p1"&gt; &lt;inner /&gt; &lt;inner /&gt; &lt;/outer&gt; &lt;outer param="p1"&gt; &lt;inner /&gt; &lt;/outer&gt; &lt;outer /&gt; &lt;outer param="p5"/&gt; &lt;/section&gt; &lt;section id="2" &gt; &lt;outer &gt; &lt;inner anotherparam="ap1"/&gt; &lt;inner param="p4"/&gt; &lt;inner /&gt; &lt;/outer&gt; &lt;/section&gt; &lt;/rootnode&gt; </code></pre> <p>I want to add a new attribute to every element, except for the <code>rootnode</code>. This XSLT transformation does almost what I want:</p> <pre><code>$ cat add.xsl &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="@*|node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="node()"&gt; &lt;xsl:copy&gt; &lt;xsl:attribute name="newattribute"&gt;NEW&lt;/xsl:attribute&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>However, it also adds the new attribute to <code>rootnode</code>. How can I ommit the <code>rootnode</code> so the it will be just copied ?</p>
<p>I would suggest you do it this way:</p> <p><strong>XSLT 1.0</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;!-- identity transform --&gt; &lt;xsl:template match="@*|node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*[not(self::rootnode)]"&gt; &lt;xsl:copy&gt; &lt;xsl:attribute name="newattribute"&gt;NEW&lt;/xsl:attribute&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
PHP echoing in wrong location of html <p>I'm attempting to make a template based system to deliver content but I've run into a problem that I just can't seem to solve. When I try to echo out variables that have data from includes it gets outputted in the wrong section of my html.</p> <p>Below is 'newstuff.php' which is my page to be executed on the browser, the offending variables are <code>$php $head $content</code>.</p> <pre><code>&lt;?php $php = include "templates/content/newstuff/phpCode.php"; $head = include "templates/content/newstuff/head.html"; $content = include "templates/content/newstuff/content.php"; include realpath(dirname(__FILE__)).'/templates/templateMain.php'; ?&gt; </code></pre> <p>Below is 'tempalteMain.php' this is my tempalte. Note the location of the echoing of <code>$php $head $content</code>.</p> <pre><code>&lt;?php echo $php; ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;?php echo $head; ?&gt; &lt;/head&gt; &lt;body class="body1" onload="inputBlur2()"&gt; &lt;div class="borderLine"&gt;&lt;/div&gt; &lt;div class="banner"&gt;&lt;/div&gt; &lt;div class="mainContent1" &gt; &lt;div class="header1" &gt; &lt;div class="headerContainer" &gt; &lt;ul class="navList1"&gt; &lt;li&gt;&lt;a id = "B0" href="index.php"&gt;New Stuff&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B1" href="MainPage.php"&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B2" href="ProjectsPage.php"&gt;Projects&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B3" href="AOrdering.php"&gt;About Ordering&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B4" href="ContactMe.php"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B5" href="FAQPage.php"&gt;FAQ&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "B6" href="SCart.php"&gt;My Cart&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="content1"&gt; &lt;?php echo $content; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Below is 'head.html' this provides the code to be delivered by the <code>$head</code> PHP variable.</p> <pre><code>&lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="/../StylePR.css"&gt; &lt;title&gt;KickUp Electronics&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <p>Below is 'content.php' this provides the code to be delivered by the <code>$content</code> PHP variable.</p> <pre><code>&lt;p&gt;Welcome to the new stuff page!!!&lt;/p&gt; </code></pre> <p>Finally, this is the page source that gets outputted taken from the chrome DOM editor. Note the locations of the information from content.php are wrong and there are strange '1's that are echoed out (also, when viewing the page source, the information from head.html is placed outside the html tags).</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="/../StylePR.css"&gt; &lt;title&gt;KickUp Electronics&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body class="body1" onload="inputBlur2()"&gt; &lt;p&gt;Welcome to the new stuff page!!!&lt;/p&gt; &lt;!--Wrong Location!--&gt; 1 1 &lt;div class="borderLine"&gt;&lt;/div&gt; &lt;div class="banner"&gt;&lt;/div&gt; &lt;div class="mainContent1"&gt; &lt;div class="header1"&gt; &lt;div class="headerContainer"&gt; &lt;ul class="navList1"&gt; &lt;li&gt;&lt;a id="B0" href="index.php"&gt;New Stuff&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B1" href="MainPage.php"&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B2" href="ProjectsPage.php"&gt;Projects&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B3" href="AOrdering.php"&gt;About Ordering&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B4" href="ContactMe.php"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B5" href="FAQPage.php"&gt;FAQ&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="B6" href="SCart.php"&gt;My Cart&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="content1"&gt; 1 &lt;/div&gt; &lt;/div&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>I tried searching many times for a solution to no avail. Is this a problem with the echo being executed before the html fully loads? Any help would be highly appreciated!</p>
<p>You're using includes wrong.</p> <pre><code>$php = include "templates/content/newstuff/phpCode.php"; </code></pre> <p>is <em>immediately</em> outputting the output of that file, and setting <code>$php</code> to <code>1</code> (i.e. "it worked!").</p> <blockquote> <p>Handling Returns: include returns <code>FALSE</code> on failure and raises a warning. Successful includes, unless overridden by the included file, return <code>1</code>. - <a href="http://php.net/manual/en/function.include.php" rel="nofollow">http://php.net/manual/en/function.include.php</a></p> </blockquote> <p>You can use <a href="http://php.net/manual/en/function.ob-start.php" rel="nofollow">output buffering</a> to capture the output, but a better solution is probably moving the <code>include</code> calls directly into <code>templateMain.php</code>.</p>
ASP.NET MVC 5 Model Navigation Properties Error <p>So I have two models that I am trying to get working,</p> <pre><code>public class Contract { [Key] public int Id { get; set; } public string AwardId { get; set; } [ForeignKey("Id")] public virtual ICollection&lt;ContractHistory&gt; contractHistory { get; set; } } </code></pre> <p>And</p> <pre><code>public class ContractHistory { [Key] public int Id { get; set; } public string AwardId { get; set; } [ForeignKey("Id")] public virtual Contract contract { get; set; } } </code></pre> <p>There are many ContractHistory related to one Contract.</p> <p>I keep getting a run-time InvalidCastException with that setup but when I remove the navigation property within the ContractHistory, and modify the Contract navigation property to:</p> <pre><code>public virtual ContractHistory contractHistory { get; set; } </code></pre> <p>It performs the join correctly without any errors.</p> <p>I only have a year of experience working with .NET and at a lose as to what the issue could be. Ideally, I would like to navigate from Contract to a list of ContractHistory and from ContractHistory to one Contract. Worst case would be for me to create independent data repository methods to explicitly pull in these records but would prefer to figure out the solution to this problem for future reference.</p> <p>Any advice or follow up questions are welcomed and thanks in advance!</p>
<p>As far as I see you want to implement one-to-many relationship, if so you have to remove the foreginkey attribute from the contract history collection in the contract class, and add contractId property as foreignkey in the contract history class as below:</p> <pre><code>public class Contract { [Key] public int Id { get; set; } public string AwardId { get; set; } public virtual ICollection&lt;ContractHistory&gt; contractHistory { get; set; } } public class ContractHistory { [Key] public int Id { get; set; } public string AwardId { get; set; } public int ContractId { get; set;} [ForeignKey("ContractId")] public virtual Contract contract { get; set; } } </code></pre>
MS-Access using Dlookup to pull results from query into textbox on form <p>I am very new to access and I am using the Dlookup function to pull the results from a query into a text box to appear on a form. I have the following expression in the Data Control Source field for the text box and it is pulling in the very first result from the query. =DLookUp("SumOfSales","qTtlSalesbyComp","Company = Company")</p> <p>I need it to act as a vlookup and match the Company in the query to the Company in the Company text box and pull the SumofSales that corresponds. Any hep would be greatly appreciated. </p>
<p>If <code>Company</code> is text:</p> <pre><code>=DLookUp("SumOfSales","qTtlSalesbyComp","Company = '" &amp; Company &amp; "'") </code></pre> <p>If it is numerical:</p> <pre><code>=DLookUp("SumOfSales","qTtlSalesbyComp","Company = " &amp; Company ) </code></pre>
How to properly write my .htaccess to ignore a folder <p>I've been searching arround for anwsers about what I am trying to do. I have an Angular.js application with the html5mode seted to true. So I created a .htaccess file to be able to run.</p> <p>So far I have this.</p> <p></p> <pre><code># Rewrite Engine RewriteEngine On # Force HTTPS RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE] # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html </code></pre> <p></p> <p>I have an admin panel palced in the folder /backend/ and when I try to get to it, I keep getting redirect to the /index.html.</p> <p>I think it might have something to do with :</p> <blockquote> <p>'-d' (is directory) Treats the TestString as a pathname and tests whether or not it exists, and is a directory.</p> </blockquote> <p>So far, I tried to add a new condition to the file, but I'm only getting 500 Internal errors so far.</p> <p></p> <pre><code># Rewrite Engine RewriteEngine On # Force HTTPS RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE] # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !^/backend/ RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html </code></pre> <p></p> <p><strong>My goal</strong> : Make the .htaccess ignore the RewriteRule if I stand in /backend/ folder pages.</p> <p>Thank you for your help.</p>
<p>Try with:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_URI} ^/backend/ RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html </code></pre>
Trying to you =COUNT on 30 sheet workbook for exel <p>I am trying to put a count in to a 30 sheet workbook to track if a time is put in a cell, how would I go about writing the the formal for that ?</p> <p>I think it may be <code>=COUNT(‘1:31’!I12)</code> with <code>I12</code> being the cell that I need the count of how many times a time <code>(exp (9:48AM)</code> is put in there.</p>
<p>Consider using <em>COUNTA()</em> instead:</p> <pre><code>=COUNTA('1:31'!I1) </code></pre> <p>as this will handle both numbers and text.</p> <p><a href="https://i.stack.imgur.com/uqWAo.png" rel="nofollow"><img src="https://i.stack.imgur.com/uqWAo.png" alt="enter image description here"></a></p>
How do I actually write/end an async method in c#? <p>I get that I need to await thing in an <code>async</code> marked method to make it asynchronous, but I don't get how to actually end the hole it makes. </p> <pre><code>static async void Example() { int t = await getIntAsync(); WriteLine($"computer: {t}"); } </code></pre> <p>Since getIntAsync is marked async I have to await in that method or I get a warning. But oh no in the method I await on in getIntAsync I have to mark that as aasync, then unless there is an await in there I get a warning. And so on and so forth to infinity it seems. How do I just make it stop? </p> <p>I've had a few people tell me to put </p> <pre><code>await Task.Delay(1000); </code></pre> <p>In my code, but I know the answer can't be as smelly as putting a delay of a second in all my production code.</p> <p>A couple others said a task method to end it such as</p> <pre><code>static Task task() { //code } </code></pre> <p>But unless I mark that <code>async</code> it throws the same warning that got me into this confusion. I know </p> <pre><code>static Task task() { //code return Task.FromResult(0); } </code></pre> <p>Technically it works, but again that seems too much of a code smell to have all over production.</p> <p>I just don't get it...</p> <p>EDIT: Because it was asked for. I know its a very trivial method, but its also just one I'm using for practice.</p> <pre><code> static async Task&lt;int&gt; getIntAsync() { Console.Write("Enter the number: "); int n = int.Parse(Console.ReadLine()); return n; } </code></pre>
<p>What is confusing here is that you don't really do something <em>asynchronous</em>. <code>Console.ReadLine()</code> is a synchronous method. Simply typing <code>async</code> or <code>await</code> somewhere does not magically make this asynchronous.</p> <p>Since this code is only for testing and learning, one way to make it asynchronous is to put it on another thread using <a href="https://msdn.microsoft.com/en-us/library/hh194921(v=vs.110).aspx" rel="nofollow"><code>Task.Run()</code></a> (I would not suggest this for many cases in production code):</p> <pre><code>static Task&lt;int&gt; getIntAsync() { Console.Write("Enter the number: "); return Task.Run(() =&gt; int.Parse(Console.ReadLine()); } </code></pre> <p>There is no <code>async</code> keyword needed here as you are not awaiting something. You just return a <code>Task&lt;int&gt;</code> that is completed when the user has entered a value and that value was parsed.</p> <p>And your <code>Example()</code> method then works like that:</p> <pre><code>static async void Example() { int t = await getIntAsync(); WriteLine($"computer: {t}"); } </code></pre> <p>When the <code>await</code> is hit, the control flow is returned to the caller and the rest of this method (the assignment to <code>t</code> and the call to <code>Console.WriteLine()</code>) are scheduled as a continuation that is executed when the <code>Task&lt;int&gt;</code> returned by <code>getIntAsync()</code> has finished.</p>
Django add field to auth_user <p>I am trying to implement the above to add a field 'posts' to the user model using the first option, extended it.</p> <p>models.py</p> <pre><code> from django.contrib.auth.models import User class NewUserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) posts = models.IntegerField(default=0) </code></pre> <p>views.py</p> <pre><code>def site_users(request): site_users = User.objects.all().reverse() paginator = Paginator(site_users, 10) page = request.GET.get('page') try: users_model = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. users_model = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. users_model = paginator.page(paginator.num_pages) return render(request, 'site_users.html', {'users_model': users_model, 'current_time': timezone.now()}) </code></pre> <p>But how can I get the posts field in the template, (updated, corrected and working!)</p> <pre><code>{% for item in users_model %} &lt;tr&gt; &lt;td&gt;&lt;a href="{% url 'profile' item.id %}"&gt;{{ item.username }}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{ item.newusermodel.posts }}&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>The tables in the sqlite3 DB have no User model, but it does have auth_user. Should i be using that instead of User?</p> <p><a href="https://i.stack.imgur.com/13DPF.png" rel="nofollow"><img src="https://i.stack.imgur.com/13DPF.png" alt="enter image description here"></a></p> <p>Thanks,</p>
<p><code>users_model</code> doesn't reference <code>NewUserModel</code>, it references <code>User</code>. You need to access the related model in your template like so:</p> <pre><code>{% for item in users_model %} &lt;tr&gt; &lt;td&gt;&lt;a href="{% url 'profile' item.id %}"&gt;{{ item.username }}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{ item.newusermodel.posts }}&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre>
Stopping a CancellationTokenSource which times out after a given TimeSpan to keep its state? <p>I have a method that accepts a <code>CancellationToken</code> which allows a user of the method to cancel what it is doing. Within the method I used this <code>CancellationToken</code> along with a <code>CancellationTokenSource</code> to created a linked <code>CancellationTokenSource</code>.</p> <pre><code>var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(msTimeout)); var timeoutAndCancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource( timeoutTokenSource.Token, cancelWaitToken); </code></pre> <p>I then start a <code>while</code> loop that continually checks to see if some value has reached a target, otherwise I <code>await</code> a <code>Task.Delay</code>. The loop has two exit conditions, if the target value is reached or if the <code>timeoutAndCancelTokenSource.IsCancellationRequested</code> is true. </p> <p>When the loop exits I can interrogate <code>timeoutTokenSource</code> and <code>cancelWaitToken</code> to determine if the loop cancelled as a result of a timeout, it was cancelled, or if the target value was reached. </p> <p>The issue I see is that when the loop exits, the <code>timeoutTokenSource</code> is still counting down. So if there is only a few milliseconds left on the timeout that I could possibly make false assumptions about what happened within the loop.</p> <p><strong>Is there a way to stop a <code>CancellationTokenSource</code> so that it does not timeout?</strong></p>
<blockquote> <p>Is there a way to stop a CancellationTokenSource so that it does not timeout?</p> </blockquote> <p>Wrong question. (BTW, it's not possible to stop one).</p> <p>The correct question would be "How do I determine if the loop cancelled as a result of a timeout, it was cancelled, or if the target value was reached?"</p> <p>And the answer is to fix this:</p> <blockquote> <p>The loop has two exit conditions, if the target value is reached or if the timeoutAndCancelTokenSource.IsCancellationRequested is true.</p> </blockquote> <p>Your loop should only exit if the target value is reached. It should pass the (linked) <code>CancellationToken</code> into <code>Task.Delay</code>.</p> <p>Then, when you <code>catch</code> the <code>OperationCanceledException</code>, you check your <code>cancelWaitToken</code> and <code>timeoutTokenSource.Token</code> to see which one is cancelled.</p> <blockquote> <p>So if there is only a few milliseconds left on the timeout that I could possibly make false assumptions about what happened within the loop.</p> </blockquote> <p>Yes. If you change your loop exit condition, you will only know if it has reached its target value or not. It is possible that <em>both</em> cancellation tokens may be signalled by the time you check them, but I believe this is a benign race condition. If <code>cancelWaitToken</code> is signalled, does it really matter whether it timed out?</p>
Get all XElement parents with a recursive function <p>I'm trying to get all the parents of a given XElement. I tried to write this function but it does not work. the page loads endlessly.</p> <pre><code>public List&lt;XElement&gt; GetParents(XElement element) { List&lt;XElement&gt; parentList = new List&lt;XElement&gt;(); XElement cParent = element.Parent; while (cParent != null) { parentList.Add(cParent); GetParents(cParent); } return parentList; } </code></pre> <p>Call : </p> <pre><code>Parents = GetParents(nodeOfPage); </code></pre> <p>Does anyone know how to fix my problem ? Thank you </p>
<p>Just call the <a href="https://msdn.microsoft.com/en-us/library/bb353466"><code>.Ancestors()</code> extension method</a>.</p>
How to count or group relations from two colums with SQL <p>I know the basics of SQL but is not more than a beginner, so I have no idea how to search for this question the right way. </p> <p>Question: How do I count matching relations in a two column set up? Example: </p> <p>I use: </p> <pre><code>SELECT "from", "to", COUNT(*) Count FROM "LocationDestination" GROUP BY "from", "to" HAVING COUNT(*) &gt; 1 ORDER BY COUNT(*) DESC </code></pre> <p>which get me:</p> <pre><code>from to Count Germany USA 6 USA Spain 5 Marocco Spain 4 USA Germany 2 Spain Marocco 2 </code></pre> <p>What I want is a table that lookes like this:</p> <pre><code>Destination1 Destionation2 Count Germany USA 8 Marocco Spain 6 USA Spain 5 </code></pre> <p>Thus combining the trips Germany - USA with USA - Germany, and Marocco - Spain with Spain - Marocco, and so forth.. </p> <p>How can that be achieved? </p>
<p>MySQL - Use <code>least</code> and <code>greatest</code> to get only one combination in case symmetric pairs exist.</p> <pre><code>SELECT least("from", "to"), greatest("from", "to"), COUNT(*) Count FROM "LocationDestination" GROUP BY least("from", "to"), greatest("from", "to") HAVING COUNT(*) &gt; 1 ORDER BY COUNT(*) DESC </code></pre>
Process run in loop not logging every time <p>I have a class in which I can run rsync commands from a shell script.</p> <p>It all works as it should, except when logging the process output (instream and error stream) to file.</p> <p>I have a loop in my class which allows 5 runs if the process fails, and in each run every stream/writer/reader is initialised and closed completely.</p> <p>The problem is that the file is only written to once or twice in the 5 runs, and it's never the same runs that are output. I set a 10 second sleep after the process to make the output more readable and I could see the only output being written to file was after 20 and 30 seconds, or after 10 and 40 seconds etc. </p> <p>Every output from the process in written to console but not to file.</p> <p>My code is as follows. Any advice would be appreciated.</p> <pre><code>private static void run() throws IOException { while (retry &amp;&amp; NUMBER_OF_TRIES &gt;= tries){ InputStream in = null; PrintStream out = null; InputStream errIn = null; try { // get runtime object to run cmd Runtime RT = Runtime.getRuntime(); Process PR = RT.exec( cmd ); errIn = PR.getErrorStream(); in = PR.getInputStream(); out = new PrintStream(new FileOutputStream(new File(output), true)); System.out.println("file output initialised"); StreamGobbler inConsumer = new StreamGobbler( in, new Date() + " OUTPUT: ", out ); StreamGobbler errConsumer = new StreamGobbler( errIn, new Date() + " ERROR: ", out ); System.out.println("Starting consumer threads"); inConsumer.start(); errConsumer.start(); Thread.sleep(10000); int exitVal = PR.waitFor(); if (exitVal &gt; 0){ retry = true; tries++; } else { retry = false; } System.out.println("ExitValue: " + exitVal); // Wait for the consumer threads to complete inConsumer.join(); errConsumer.join(); } catch ( Exception e ) { e.printStackTrace(); System.out.println( "failed: " + e.getMessage() ); } finally { // the StreamConsumer classes will close the other streams if ( out != null ){ out.close(); } if (in != null){ in.close(); } if (errIn != null){ errIn.close(); } } } } </code></pre>
<p>i don't ever see your printstream object "out" ever being used besides it getting initialized. If you want to write to the file you should call the printstream object.</p> <pre><code>System.out.println("ExitValue: " + exitVal); //now call the printstream object out.print("ExitValue: " + exitVal); //flushing will force the string to be written to the file out.flush(); </code></pre> <p>You can follow the above code everytime you write to console and you want to write to the file you created your printstream object with.</p>
Macro to Save as from Excel to .txt file with same file name and same location as original file <p>I am trying to write a macro to save as excel file to a .txt file but with the same original filename as the excel file and the same path as the excel file. If i record a macro it has me pick a path and a file name and when I run the macro again it chooses the same path and same file name.</p> <p>Could someone please help me. I need a simple macro that can do this please. This is the one I recorded but I can't figure out how to edit it to make it save as the same filename as in the original excel file and in the same path as the original excel file.</p> <pre><code> Sub saveastxt() ' ' saveastxt Macro ' ' ChDir "C:\Users\mcupp\Desktop" ActiveWorkbook.SaveAs Filename:="C:\Users\mcupp\Desktop\Test Macros.txt", _ FileFormat:=xlText, CreateBackup:=False ActiveWorkbook.Close End Sub </code></pre>
<p>Code below will work with any file extension and saves the workbook as text file.</p> <pre><code>Sub saver() Dim fn As String Dim l As Long Dim wb As Workbook Set wb = ActiveWorkbook fn = wb.FullName l = InStrRev(fn, ".") fn = Left(fn, l) fn = fn &amp; "txt" wb.SaveAs Filename:=fn, FileFormat:=xlText wb.Close End Sub </code></pre>
Delphi: How to set TWebResponse to contain gzip and read it in Android App? <p>I'm building a WebServer for Android App.(WebBroker->VC).</p> <p>How can I compress my response string to gzip, I tried this:</p> <pre><code> a:=[{.......}];//json data srcbuf := BytesOf(a.ToString); ZCompress(srcbuf, destbuf, zcDefault); Response.Content := ''; Response.ContentStream := TMemoryStream.Create; Response.ContentEncoding := 'deflate'; Response.ContentType := 'application/json'; Response.ContentStream.Write(@(destbuf[0]),length(destbuf)); Response.ContentLength := (length(destbuf)); </code></pre> <p>In my android app I get error:</p> <p><strong>Uknown format (magic number...)</strong></p> <p>I also have server side written in PHP and android app works fine, I think that Delphi System.ZLib doesn't compress as gzip?</p> <p>Any idea how solve this?</p>
<p>I found the solution:</p> <p><strong>Delphi:</strong></p> <pre><code>//------------------------------------------------------------------------------ procedure doGZIP(Input, gZipped: TMemoryStream);//helper function const GZIP = 31;//very important because gzip is a linux zip format var CompactadorGZip: TZCompressionStream; begin Input.Position:=0; CompactadorGZip:=TZCompressionStream.Create(gZipped, zcMax, GZIP); CompactadorGZip.CopyFrom(Input, Input.Size); CompactadorGZip.Free; gZipped.Position:=0; end; //------------------------------------------------------------------------------ . . . strJSON:=a.ToString;//a-&gt;TJSONArray //init Original:=TMemoryStream.Create; gZIPStream:=TMemoryStream.Create; //copy result to stream oString := UTF8String(strJSON); len := length(oString); Original.WriteBuffer(oString[1], len); //make it gzip doGZIP(Original,gZIPStream); //prepare responsestream and set content encoding and type Response.Content := ''; Response.ContentStream:=gZIPStream; Response.ContentEncoding := 'gzip'; Response.ContentType := 'application/json'; //clear... Original.Free; </code></pre> <p><strong>Android:</strong></p> <pre><code>conn.setRequestProperty("Accept-Encoding", "gzip");//do not forget this </code></pre>
Integrate Google Maps MarkerClusterer with infowindow <p>I'm trying to put InfoWindow in multiple markers grouped with MarkerClusterer, but without sucess. I only can generate maps with infowindows OR with cluster; not both at same time. Searching over web makes me more confuse....</p> <p>The start point was <a href="https://developers.google.com/maps/documentation/javascript/marker-clustering" rel="nofollow">google developers page</a>: with my needs, I created the following code: </p> <pre class="lang-html prettyprint-override"><code> &lt;div id="map"&gt;&lt;/div&gt; &lt;script&gt; function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: {lat: -15.7942357, lng: -47.8821945} }); // Add some markers to the map. // Note: The code uses the JavaScript Array.prototype.map() method to // create an array of markers based on a given "locations" array. // The map() method here has nothing to do with the Google Maps API. var markers = locations.map(function(location, i) { return new google.maps.Marker({ position: location, }); }); // Add a marker clusterer to manage the markers. var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}); } var locations = [ {lat: -19.9286, lng: -43.93888}, {lat: -19.85758, lng: -43.9668}, {lat: -18.24587, lng: -43.59613}, {lat: -20.46427, lng: -45.42629}, {lat: -20.37817, lng: -43.41641}, {lat: -20.09749, lng: -43.48831}, {lat: -21.13594, lng: -44.26132}, ] &lt;/script&gt; &lt;script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"&gt; &lt;/script&gt; &lt;script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"&gt; &lt;/script&gt; </code></pre> <p>Then I stoped here. The code shown in <a href="https://developers.google.com/maps/documentation/javascript/infowindows" rel="nofollow">InfoWindow</a> calls another objetcs than the "locations". More than I try, worst results are...</p> <p>I would like to add just simple infos to EACH marker: only a title and a unique weblink per marker. </p> <p>Can someone help?</p>
<p>Add the "unique information" for each marker to your locations array (like the answer to this question: ). </p> <p>Add a click listener to each marker which opens the InfoWindow with that unique content.</p> <pre><code>var infoWin = new google.maps.InfoWindow(); var markers = locations.map(function(location, i) { var marker = new google.maps.Marker({ position: location }); google.maps.event.addListener(marker, 'click', function(evt) { infoWin.setContent(location.info); infoWin.open(map, marker); }) return marker; }); </code></pre> <p><a href="http://jsfiddle.net/geocodezip/wyn4mk8n/" rel="nofollow">proof of concept fiddle</a></p> <p><strong>code snippet:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: { lat: -15.7942357, lng: -47.8821945 } }); var infoWin = new google.maps.InfoWindow(); // Add some markers to the map. // Note: The code uses the JavaScript Array.prototype.map() method to // create an array of markers based on a given "locations" array. // The map() method here has nothing to do with the Google Maps API. var markers = locations.map(function(location, i) { var marker = new google.maps.Marker({ position: location }); google.maps.event.addListener(marker, 'click', function(evt) { infoWin.setContent(location.info); infoWin.open(map, marker); }) return marker; }); // Add a marker clusterer to manage the markers. var markerCluster = new MarkerClusterer(map, markers, { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' }); } var locations = [{ lat: -19.9286, lng: -43.93888, info: "marker 1" }, { lat: -19.85758, lng: -43.9668, info: "marker 2" }, { lat: -18.24587, lng: -43.59613, info: "marker 3" }, { lat: -20.46427, lng: -45.42629, info: "marker 4" }, { lat: -20.37817, lng: -43.41641, info: "marker 5" }, { lat: -20.09749, lng: -43.48831, info: "marker 6" }, { lat: -21.13594, lng: -44.26132, info: "marker 7" }, ]; google.maps.event.addDomListener(window, "load", initMap);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #map { height: 100%; width: 100%; margin: 0px; padding: 0px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://maps.googleapis.com/maps/api/js"&gt;&lt;/script&gt; &lt;script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"&gt;&lt;/script&gt; &lt;div id="map"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
Handling a form with Spring MVC without using the Spring <form:form> tag? <p>All is in the question. Is it possible to handle a form using Spring annotation @ModelAttribute without using the Spring tag . I saw this <a href="https://spring.io/guides/gs/handling-form-submission/" rel="nofollow">way to do</a> but it seems complex with using Thymeleaf (I don't know anything about it). Spring is supposed to be a non-intrusive framework so is there an alternate solution to my problem?</p> <p>Many thanks for your replies. Regards</p>
<p>If you build your form using Spring tags, it will be converted to HTML. Run your project and check the source code of your JSP site. Spring tags just make things a bit easier for a coder. For example</p> <pre><code>&lt;form:form modelAttribute="newUser" action="/addUser" method="post"&gt; &lt;form:input path="firstName" /&gt; &lt;form:input path="lastName" /&gt; &lt;button type="submit"&gt;Add&lt;/button&gt; &lt;/form:form&gt; </code></pre> <p>will be converted to HTML</p> <pre><code>&lt;form id="newUser" action="/addUser" method="post"&gt; &lt;input id="firstName" name="firstName" type="text" value="" /&gt; &lt;input id="lastName" name="lastName" type="text" value="" /&gt; &lt;button type="submit"&gt;Add&lt;/button&gt; &lt;/form&gt; </code></pre> <p>In Controller you add a data transfer object (DTO) to Model, for example</p> <pre><code>@RequestMapping(value = "/index", method = RequestMethod.GET) public ModelAndView homePage() { ModelAndView model = new ModelAndView(); model.addObject("newUser", new User()); model.setViewName("index"); return model; } </code></pre> <p>and receive the form data</p> <pre><code>@RequestMapping(value = "/addUser", method = RequestMethod.POST) public ModelAndView addUser( @ModelAttribute("newUser") User user) { ... } </code></pre> <p>Using Spring tags is totally optional as long as the naming of the form fields is exactly the same as in your bean object (here User class) and model.</p>
How to wait for all pending completion handlers to be executed before stopping io_service? <p>I'm writing a server using <a href="http://www.boost.org/doc/libs/1_62_0/doc/html/boost_asio.html" rel="nofollow">boost::asio</a>. I have multiple threads each owning it's own <code>io_service</code> object. I'm using <code>io_service::work</code> object to keep <code>io_service</code> running when there is no completion handlers to execute. In certain moment I'm calling <code>stop</code> method of <code>io_service</code> objects to finish threads which called <code>io_serice::run</code>. But in some cases when I'm calling <code>stop</code> I have posted in <code>io_service</code> object competion handlers which are not finished. Calling <code>stop</code> prevents posted competion handlers from executing, but this is unacceptable for me because I need all pending work to be finished before stopping the thread. How to wait for all pending completion handlers first to be executed before calling <code>stop</code> method of <code>io_service</code>?</p>
<p>Just reset the <code>work</code>.</p> <p>Any <code>io_service::run()</code> will return when all pending work has been completed.</p> <p>The common pattern is to use <code>optional&lt;work&gt;</code> so you can clear it. If it is a frequent thing, you could reduce some mental overhead by wrapping it in a RAII-enabled class:</p> <p><strong><kbd><a href="http://coliru.stacked-crooked.com/a/2cfbbbc6e278eca0" rel="nofollow">Live On Coliru</a></kbd></strong></p> <pre><code>#include &lt;boost/asio.hpp&gt; #include &lt;boost/optional.hpp&gt; struct work { using io_service = boost::asio::io_service; work(io_service&amp; svc) : _work(io_service::work(svc)) { } void release() { _work.reset(); } void enlist(io_service&amp; svc) { _work.emplace(io_service::work(svc)); } private: boost::optional&lt;io_service::work&gt; _work; }; #include &lt;thread&gt; #include &lt;iostream&gt; using namespace std::chrono_literals; int main() { boost::asio::io_service svc; work lock(svc); std::thread background([&amp;] { svc.run(); }); std::this_thread::sleep_for(1s); std::cout &lt;&lt; "releasing work"; lock.release(); background.join(); } </code></pre> <p>Which finishes the background thread after 1 second.</p>
Efficient way of getting last value in a specific column <p>I wrote a function to get the last value in a single column in a Google Sheet.</p> <pre><code>// Returns the row number of the first empty cell // Offset should be equal to the first row that has data function getLastRowInColumn(sheet, column, rowOffset) { var lastRow = sheet.getMaxRows(); for (var row = rowOffset; row &lt; lastRow; row++) { var range = sheet.getRange(row, column); if (range.isBlank()) { return row; }; } } </code></pre> <p>I can assume that all values are filled out, therefore the function is actually returning the first empty cell it finds (in this case, that is equivalent to the first empty row).</p> <p>The function is taking a long time to run for a sheet with ~1000 rows. How can I make it more efficient?</p> <p>Thanks in advance.</p>
<p>See the answer here to a similar question. It is about getting the first empty row, you are just one higher. <a href="http://stackoverflow.com/questions/6882104/faster-way-to-find-the-first-empty-row/27179623#27179623">Faster way to find the first empty row</a></p>
How to create a before or after Trigger that can catch DUP_VAL_ON_INDEX on Oracle PL/SQL <p>I have a table like this</p> <pre><code>KD_C KD_PLA KD_T GABUNG BERAKHIR GAJI_PL BUYOUT ---- ------ ---- ---------- ---------- ---------- ---------- C001 MA001 T006 2003 2014 50000 5200000 C002 SC001 T006 2012 2016 65000 20280000 C003 TW001 T006 2005 2018 90000 46800000 C004 TV001 T006 2008 2017 60000 24960000 C005 PC001 T001 2003 2016 80000 24960000 C006 AC001 T001 1996 2014 90000 9360000 C007 DB001 T001 2010 2016 65000 20280000 C008 EH001 T001 2011 2018 85000 44200000 C009 JC001 T002 1996 2014 60000 6240000 C010 SG001 T002 1998 2016 87000 27144000 C011 LS001 T002 2010 2018 81000 42120000 C012 PR001 T002 2004 2016 60000 18720000 C013 JH001 T003 2005 2018 72000 37440000 C014 GC001 T003 2003 2015 65000 13520000 C015 ED001 T003 2010 2018 100000 52000000 C016 GB001 T003 2010 2016 80000 24960000 C017 DG001 T004 2011 2018 73000 37960000 C018 RG001 T004 1992 2014 90000 9360000 C019 PJ001 T004 2011 2018 80000 41600000 C020 RP001 T004 2012 2017 92000 38272000 C021 GB002 T005 2006 2018 102000 53040000 C022 EA001 T005 2011 2015 70000 14560000 C023 HL001 T005 2012 2018 65000 33800000 C024 KW001 T005 2009 2017 67000 27872000 C025 MA001 T005 2017 2022 50000 26000000 C028 MA001 T001 2016 2018 15000 3120000 C029 MA001 T001 2016 2018 15000 3120000 C030 MA001 T001 2016 2018 15000 3120000 </code></pre> <p>And then I tried to make a Trigger for updating instead of insert to the table when duplicate a primary key. The primary key is the first coloumn 'KD_CONTRACT'.</p> <pre><code>CREATE OR REPLACE TRIGGER INSERT_TABEL_CONTRACT BEFORE INSERT ON CONTRACT FOR EACH ROW DECLARE KODE VARCHAR2(20); TEMPCARIKODE NUMBER; BEGIN SELECT LPAD(TO_NUMBER(NVL(SUBSTR(MAX(KD_CONTRACT),2),0))+1,3,'0') INTO KODE FROM CONTRACT; SELECT COUNT(KD_CONTRACT) INTO TEMPCARIKODE FROM CONTRACT WHERE KD_CONTRACT = :NEW.KD_CONTRACT; IF(TEMPCARIKODE = 0) THEN :NEW.KD_CONTRACT := 'C'||KODE; :NEW.GABUNG := TO_NUMBER(TO_CHAR(SYSDATE,'YYYY')); :NEW.BERAKHIR := :NEW.GABUNG + :NEW.BERAKHIR; :NEW.BUYOUT := (:NEW.GAJI_PL * 52) * (:NEW.Berakhir-:NEW.Gabung) * 2; END IF; EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE(''); DBMS_OUTPUT.PUT_LINE(''); DBMS_OUTPUT.PUT_LINE('ERROR at Line 1:'); DBMS_OUTPUT.PUT_LINE('ORA-20003: Data sudah ada, data akan diupdate!'); END; / show err; </code></pre> <p>anyway maybe the code show that I tried not to update when the primary key is duplicated. But please the until end first.</p> <p>it show no error... So the trigger successfully created. then I tried to insert a duplicated primary key. <code>INSERT INTO CONTRACT VALUES('C001','MA001','T001',2013,2,15000,2500000);</code></p> <p>the result</p> <pre><code>INSERT INTO CONTRACT VALUES('C001','MA001','T001',2013,2,15000,2500000) * ERROR at line 1: ORA-00001: unique constraint (TUGAS.PK_CONTRACT) violated </code></pre> <p>It did raise ORA-00001 but it never touched the DUP_VAL_ON_INDEX and showed nothing or the custom message. Anyone have Idea? When it never even touch DUP_VAL_ON_INDEX then how could I event paste an update query at the when case... Thanks... * anyway my oracle is XE or express edition.</p>
<p>The <code>EXCEPTION</code> block from your trigger will never be executed since your trigger doesn't contain any <code>INSERT</code> or <code>UPDATE</code> statements. You have to consider <code>INSTEAD OF</code> Trigger instead.</p>
Will promoting aws rds read replica to db instance maintain the replication for new DB instance? <p>I am trying to understand if promoting a read replica to DB instance will maintain the replication/mirroring on the newly create DB instance? Wondering if the newly created DB instance will go out of sync with master.</p>
<p>Yes, it will immediately and permanently be out of sync from the master. Once promoted, you can't undo.</p> <p>That is the reason you promote a replica -- to disconnect it from the master and make it an independent instance.</p> <blockquote> <p>The Read Replica, when promoted, stops receiving WAL communications and is no longer a read-only instance. </p> <p><a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html" rel="nofollow">http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html</a></p> </blockquote>
svg pseudo background-image file not showing on live site but works on localhost why? <p>I have simple svg arrow but it doesn't show when I use as pseudo background-image online but it works fine on my localhost: any idea?</p> <pre><code>span a:after { content: ""; background-image: url(arrow_right.svg); width: 24px; height: 18px; display: inline-block; margin: 0px 0 0 10px; position: relative; top: 3px; } </code></pre> <p>svg:</p> <pre><code>&lt;svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 18" enable-background="new 0 0 24 18" xml:space="preserve"&gt; &lt;path fill="#F9C32C" d="M19.8,10.1l-6.6,6.4l1.5,1.5L24,9l-9.3-9l-1.5,1.5l6.6,6.4H0v2.1H19.8z"/&gt; &lt;/svg&gt; </code></pre>
<p>Add content-type=image/svg+xml to your .htaccess file at the root instead of content-type=text/xml</p>
Apache Spark update a row in an RDD or Dataset based on another row <p>I'm trying to figure how I can update some rows based on another another row.</p> <p>For example, I have some data like</p> <pre><code>Id | useraname | ratings | city -------------------------------- 1, philip, 2.0, montreal, ... 2, john, 4.0, montreal, ... 3, charles, 2.0, texas, ... </code></pre> <p>I want to update the users in the same city to the same groupId (either 1 or 2)</p> <pre><code>Id | useraname | ratings | city -------------------------------- 1, philip, 2.0, montreal, ... 1, john, 4.0, montreal, ... 3, charles, 2.0, texas, ... </code></pre> <p>How can I achieve this in my RDD or Dataset ?</p> <p>So just for sake of completeness, what if the <code>Id</code> is a String, the dense rank won't work ?</p> <p>For example ?</p> <pre><code>Id | useraname | ratings | city -------------------------------- a, philip, 2.0, montreal, ... b, john, 4.0, montreal, ... c, charles, 2.0, texas, ... </code></pre> <p>So the result looks like this:</p> <pre><code>grade | useraname | ratings | city -------------------------------- a, philip, 2.0, montreal, ... a, john, 4.0, montreal, ... c, charles, 2.0, texas, ... </code></pre>
<p>A clean way to do this would be to use <code>dense_rank()</code> from <code>Window</code> functions. It enumerates the unique values in your <code>Window</code> column. Because <code>city</code> is a <code>String</code> column, these will be increasing alphabetically.</p> <pre><code>import org.apache.spark.sql.functions.rank import org.apache.spark.sql.expressions.Window val df = spark.createDataFrame(Seq( (1, "philip", 2.0, "montreal"), (2, "john", 4.0, "montreal"), (3, "charles", 2.0, "texas"))).toDF("Id", "username", "rating", "city") val w = Window.orderBy($"city") df.withColumn("id", rank().over(w)).show() +---+--------+------+--------+ | id|username|rating| city| +---+--------+------+--------+ | 1| philip| 2.0|montreal| | 1| john| 4.0|montreal| | 2| charles| 2.0| texas| +---+--------+------+--------+ </code></pre>
redirect another action with params in controller <p>When I post to delete action in below:</p> <pre><code>public function deletenews($newsid) { $news = News::where('id',$newsid)-&gt;first();//find($comment_id) $message = 'a string'; $msgstatus = 'another string'; ... return redirect()-&gt;route('usernews',[$message,$msgstatus]); } </code></pre> <p>I want to direct to this action with parameters:</p> <pre><code>public function usernews($message=null,$msgstatus=null) { ... return view('usercontrol.usernews',compact(['news','msgstatus','message'])); } </code></pre> <p>it redirects and works fine but somehow parameters always null, I will use this parameters to inform user that record deleted..</p>
<pre><code>public function deletenews($newsid) { $news = News::where('id',$newsid)-&gt;first();//find($comment_id) $message = 'a string'; $msgstatus = 'another string'; ... return redirect()-&gt;route('usernews' ['message'=&gt;$message,'msgstatus'=&gt;$msgstatus]); } public function usernews(Request $request) { $message = $request-&gt;input('message'); $msgstatus = $request-&gt;input('msgstatus'); ... return view('usercontrol.usernews',compact(['news','msgstatus','message'])); } </code></pre>
Extracting available time slots from a scheduled time frame <p>I'm trying to create a view that will output me all available time slots from a Scheduling calendar table, having the already booked time slots on another table.</p> <p>Given the tables:</p> <pre><code>Table Calendar ID Date StartTime EndTime 56 18-OCT-16 10.00.00 18.00.00 62 21-OCT-16 11.00.00 20.30.00 72 27-OCT-16 09.30.00 17.00.00 72 28-OCT-16 08.40.00 18.00.00 Table ScheduledTimes ID Date StartTime EndTime 62 21-OCT-16 13.00.00 14.30.00 62 21-OCT-16 16.00.00 17.00.00 62 21-OCT-16 17.20.00 18.00.00 72 27-OCT-16 09.30.00 10.00.00 72 27-OCT-16 10.00.00 11.00.00 72 28-OCT-16 09.41.00 11.00.00 72 28-OCT-16 12.40.00 18.00.00 </code></pre> <p>I'm looking for a way to achieve this:</p> <pre><code>ID Date StartTime EndTime 56 18-OCT-16 10.00.00 18.00.00 62 21-OCT-16 11.00.00 13.00.00 62 21-OCT-16 14.30.00 16.00.00 62 21-OCT-16 17.00.00 17.20.00 62 21-OCT-16 18.00.00 20.30.00 72 27-OCT-16 11.00.00 17.00.00 72 28-OCT-16 08.40.00 09.41.00 72 28-OCT-16 11.00.00 12.40.00 </code></pre> <p>The values at ScheduledTimes are all verified, sure to be inside the time frame of the Calendar times and not conflicting within each other.</p>
<p>Assuming your input columns are all strings:</p> <pre><code>with calendar ( id, dt, starttime, endtime ) as ( select 56, '18-OCT-16', '10.00.00', '18.00.00' from dual union all select 62, '21-OCT-16', '11.00.00', '20.30.00' from dual union all select 72, '27-OCT-16', '09.30.00', '17.00.00' from dual union all select 72, '28-OCT-16', '08.40.00', '18.00.00' from dual ), scheduledtimes ( id, dt, starttime, endtime ) as ( select 62, '21-OCT-16', '13.00.00', '14.30.00' from dual union all select 62, '21-OCT-16', '16.00.00', '17.00.00' from dual union all select 62, '21-OCT-16', '17.20.00', '18.00.00' from dual union all select 72, '27-OCT-16', '09.30.00', '10.00.00' from dual union all select 72, '27-OCT-16', '10.00.00', '11.00.00' from dual union all select 72, '28-OCT-16', '09.41.00', '11.00.00' from dual union all select 72, '28-OCT-16', '12.40.00', '18.00.00' from dual ), u ( id, dt, startdatetime, enddatetime ) as ( select id, dt, to_date(dt || starttime, 'dd-MON-yyhh24.mi.ss'), to_date(dt || endtime , 'dd-MON-yyhh24.mi.ss') from scheduledtimes union all select id, dt, null, to_date(dt || starttime, 'dd-MON-yyhh24.mi.ss') from calendar union all select id, dt, to_date(dt || endtime, 'dd-MON-yyhh24.mi.ss'), null from calendar ), prep ( id, dt, starttime, endtime ) as ( select id, dt, to_char(enddatetime, 'hh24:mi:ss') as starttime, to_char(lead(startdatetime) over (partition by id, dt order by enddatetime), 'hh24:mi:ss') as endtime from u ) select id, dt, starttime, endtime from prep where starttime &lt; endtime order by id, dt, endtime; </code></pre>
Count Pageviews in MVC and log in Database <p>First let me thank everyone who has contributed in my education, it has helped a great deal and I have learned a lot in 7 months.</p> <p>I have been requested to count every pageview when someone visits a details page. I updated my database to add a pageview column but I am unsure of how to do anything else. I think I should put the code on my details ActionResult on my controller since that is the page I want to be tracked. If this is wrong please correct me.</p> <pre><code> public ActionResult Details(int id, int? yearId) { var dbTest = _testRepository.Id(id); var year = yearId == null ? dbTest.LastYear : dbTest.Date.Single(i =&gt; i.Id == yearId); var vm = new DetailsVM { Test = _mapper.Map&lt;TestVM&gt;(year) }; return View(vm); } </code></pre> <p>Above is my action result. What it does is collects everything from the database and displays it on a details cshtml page. This code works. How do I get each pageview to count and log into my database using the column name pageview. Please explain your methods so I can learn from it. </p> <p><strong>Edit:</strong><br> I have looked into Google Analytics and it isn't what I am looking for. I just want something to use for organization.</p> <p>I have also included my database model which hopefully provides more information.</p> <pre><code>public class Test { public int Id { get; set; } public string Name { get; set; } public string Title { get; set; } public ICollection&lt;TestYear&gt; Years { get; set; } [NotMapped] public TestYear LastYear { get { return this.Years.OrderByDescending(i =&gt; i.Year).FirstOrDefault(); } } public int PageViews { get; set; } } </code></pre>
<p>I ended up just making a method in my repository to add a counter to the page-views column in my database every time an id was hit.</p> <pre><code>public void AddView(int id) { var view = _context.Tests.Single(i =&gt; i.Id == id); view.PageViews++; _context.SaveChanges(); } </code></pre>
Can't call function with onclick attribute <p>Why doesn't this work?</p> <p>html : </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;button onclick="test21()"&gt;test&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>javascript:</p> <pre><code>function test21(){ console.log("yey"); } </code></pre>
<p>You can create a single function that calls both of those, and then use it in the event.</p> <pre><code>function myFunction(){ pay(); cls(); } </code></pre> <p>And then, for the button:</p> <pre><code>&lt;input id="btn" type="button" value="click" onclick="myFunction();"/&gt; </code></pre>
how do I get the User's previous photo? <p>The problem is that previous_modal method is returning the previous photo in the database, not <strong>@user</strong> previous photo.</p> <p>For example, if @user has photos with id's 10, 9, 8, 7, 6, 1 and I open the modal for photo id 6 and I click previous, it sets the href to 5, instead of 1. </p> <pre><code>UsersController def show @user = User.find(params[:id]) @photos = @user.photos.approved.order('created_at desc').paginate(page: params[:page], per_page: 9) respond_to do |format| format.html format.js end end users/show.html.erb &lt;% @photos.in_groups_of(3, false).each do |group| %&gt; &lt;% group.each do |photo| %&gt; ... &lt;div class="modal" id=&lt;%="#{photo.id}"%&gt; tabindex="-1" role="dialog"&gt; ... &lt;a class="previouslink" data-dismiss="modal" data-toggle="modal" href=&lt;%="#"+"#{photo.previous_modal.id}"%&gt;&gt; ... class Photo def previous_modal if self.class.approved.where("id &lt; ?", id).last == nil return self else return self.class.approved.where("id &lt; ?", id).last end end </code></pre>
<p>On your previous_modal method, instead of searching by id, you could search by created_at... something like:</p> <pre><code>def previous_modal if self.class.approved.where("created_at &lt; ?", self.created_at).last == nil return self else return self.class.approved.where("created_at &lt; ?", self.created_at).last end end </code></pre> <p>And for a cleaner code, I would suggest:</p> <pre><code>def previous_modal last_photo = self.class.approved.where("created_at &lt; ?", self.created_at).last last_photo ? last_photo : self end </code></pre> <p>It would work as same as above. Hope it helps!</p> <p>EDIT:</p> <p>I'm not sure how you would get that [ 10, 9, 8, 7, 6, 1 ] array, but once you have it, it's easy... you just had to find the photo by the id on the next/previous position. Could think of something like:</p> <pre><code>def previous_modal photo_ids = self.user.photos.map(&amp;id) #Get all photos ids for that user self_index = photos_ids.index(self.id) #Get the index of this particular object id previous_photo = Photo.find_by_id(photos_ids[self_index-1]) #Find the previous one return (previous_photo || self) end </code></pre> <p>But I guess, in this case, the photo_ids returned would be ordered, so produced the same result as above. You have to figure out a way to maintain that array with the history of photos order... good luck!</p>
How to automatically display a user email in an HTML form field using Google Apps Script and JavaScript <p>I've created an HTML form using Google HTML service. How do I automatically display the user's email in the email field when they open the form? I already have a function for <code>onload</code> for the date. I tried using <code>google.script.run</code>, but it's not working. Here is my HTML code: </p> <pre><code>&lt;body onload="todaysDate()"&gt; &lt;form&gt; &lt;label&gt;&lt;span&gt; Requestor: &lt;/span&gt;&lt;input id="reqEmail" type="text" name="reqEmail" placeholder="Your email..."&gt;&lt;/label&gt; &lt;br&gt; &lt;label&gt;&lt;span&gt;Requestor's department: &lt;/span&gt;&lt;input id="reqDept" type="text" name="reqDepartment" placeholder="Your deparment..."&gt;&lt;/label&gt; &lt;br&gt; &lt;label&gt;&lt;span&gt;Date of Submission: &lt;/span&gt;&lt;input id="subDate" type="text" name="dateSubmission"&gt;&lt;/label&gt; &lt;br&gt; &lt;label&gt;&lt;span&gt;Required delivery date: &lt;/span&gt;&lt;input id="delDate" type="date" name="dateDelivery"&gt;&lt;/label&gt; &lt;br&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>Here is my Code.gs:</p> <pre><code>//Get user email function getUserEmail() { var userEmail = Session.getActiveUser().getEmail(); Logger.log(userEmail); } </code></pre> <p>Here is my JavaScript:</p> <pre><code>//Insert todays's date to "Date of Submission" var d = new Date(); var curr_day = d.getDate(); var curr_month = d.getMonth() +1; var curr_year = d.getFullYear(); function todaysDate() { document.getElementById('subDate').value=(curr_month + "-" + curr_day + "-" + curr_year); }; google.script.run.getUserEmail(userEmail); var email = document.getElementById('reqEmail'); email.value = userEmail; </code></pre>
<p>I guess, you read <a href="https://developers.google.com/apps-script/guides/html/communication" rel="nofollow">this</a> but still worth mentioning.</p> <p>How does <code>google.script.run</code> work? It just runs a function on "server" side. This server side function can <code>return</code> some result (which was suggested by Darren in the previous answer) but you'd still need to tell your script what to do with this result afterwards.</p> <p>And if you want to do something with the result on client side, you'll need to use <code>.withSuccessHanlder</code> part — with its help you specify your client side function which will accept the result of the server function's work. In your case — this result is the user email. So it'll be something like <code>google.script.run.withSuccessHandler(todaysDate).getUserEmail()</code> — you aren't passing any parameters to <code>getUserEmail()</code> because it doesn't need them.</p> <p>But you need to change your <code>todaysDate()</code> function a bit.</p> <pre><code>function todaysDate(userEmail) { document.getElementById('subDate').value = (curr_month + "-" + curr_day + "-" + curr_year); document.getElementById('reqEmail').value = userEmail; }; </code></pre> <p>And instead of assigning an <code>onload</code> function to the <code>&lt;body&gt;</code> tag you can just add this line into your <code>&lt;script&gt;</code> <code>google.script.run.withSuccessHandler(todaysDate).getUserEmail();</code>.</p> <p>As a whole, it'll look something like this:</p> <pre><code>&lt;script&gt; //Insert todays's date to "Date of Submission" var d = new Date(); var curr_day = d.getDate(); var curr_month = d.getMonth() +1; var curr_year = d.getFullYear(); google.script.run.withSuccessHandler(todaysDate).getUserEmail(); function todaysDate(userEmail) { document.getElementById('subDate').value = (curr_month + "-" + curr_day + "-" + curr_year); document.getElementById('reqEmail').value = userEmail; }; &lt;/script&gt; </code></pre>
Pass commandline args into another script <p>I have couple of scripts which call into each other. However when I pass </p> <p>Snippet from buid-and-run-node.sh</p> <pre><code>OPTIND=1 # Reset getopts in case it was changed in a previous run while getopts "hn:c:f:s:" opt; do case "$opt" in h) usage exit 1 ;; n) container_name=$OPTARG ;; c) test_command=$OPTARG ;; s) src=$OPTARG ;; *) usage exit 1 ;; esac done $DIR/build-and-run.sh -n $container_name -c $test_command -s $src -f $DIR/../dockerfiles/dockerfile_node </code></pre> <p>Snippet from build-and-run.sh</p> <pre><code>OPTIND=1 # Reset getopts in case it was changed in a previous run while getopts "hn:c:f:s:" opt; do case "$opt" in h) usage exit 1 ;; n) container_name=$OPTARG ;; c) test_command=$OPTARG ;; f) dockerfile=$OPTARG ;; s) src=$OPTARG ;; *) usage exit 1 ;; esac done </code></pre> <p>I am calling it as such </p> <pre><code>build-and-run-node.sh -n test-page-helper -s ./ -c 'scripts/npm-publish.sh -r test/test-helpers.git -b patch' </code></pre> <p>with the intention that npm-publish.sh should run with the -r and -b parameters. However when I run the script I get </p> <pre><code>build-and-run.sh: illegal option -- r </code></pre> <p>which obviously means it is the build-and-run command that is consuming the -r. How do I avoid this?</p>
<p>You need double quotes around <code>$test_command</code> in buid-and-run-node.sh, otherwise that variable is being split on the white space and appears to contain arguments for buid-and-run.sh. Like this:</p> <pre><code>$DIR/build-and-run.sh -n $container_name -c "$test_command" -s $src -f $DIR/../dockerfiles/dockerfile_node </code></pre> <h3>Further Info</h3> <p>As the comment below rightly points out, it's good practice to quote <em>all</em> variables in Bash, unless you know you want them off (for example, to enable shell globbing). It's also helpful, at least in cases where the variable name is part of a larger word, to use curly braces to delineate the variable name. This is to prevent later characters from being treated as part of the variable name <a href="http://stackoverflow.com/questions/28114999/what-are-the-rules-for-valid-identifiers-e-g-functions-vars-etc-in-bash">if they're legal</a>. So a better command call might look like:</p> <pre><code>"${DIR}/build-and-run.sh" -n "$container_name" -c "$test_command" -s "$src" -f "${DIR}/../dockerfiles/dockerfile_node" </code></pre>
What is the difference between app engine and cloud endpoints when developing with Android studio? <p>I've been trying to do this for a while, but I'm confused as to the difference between the two applications. </p> <p>I know that endpoints helps you expose an API and generate the client libraries that allow you to interact with your Android app. </p> <p>But in the examples, it seems as though endpoints is the only code you write for the backend at all. </p> <p>I thought that app engine was what the actual application ran on - that is, do I need a separate project with the app engine backend, then my android studio project with the Android app and the endpoints API, or does writing the endpoints API also serve as the app engine backend? </p>
<p>The endpoints backend API is just a piece of a GAE app functionality. </p> <p>If you only have that functionality in your app you can extend it by adding the desired stuff to the existing <code>app.yaml</code> file (and the related app code), you don't <strong>have to</strong> create a new app. Especially if the endpoints functionality and the additional desired functionality are related.</p> <p>You can also add endpoints backend support to an existing GAE app by merging the endpoints backend <code>app.yaml</code> content into the existing app's <code>app.yaml</code> file and adding the class file and API server file to the app's code.</p>
Changing labels with logo images <p>I'm trying to build a graph with <a href="http://www.chartjs.org/" rel="nofollow">chart.js</a> and i would like to replace the labels with logtype small images.</p> <p>Is it possible ? Can't find the way to do it. Thanks.</p> <p>This is my chart options:</p> <pre><code>var horizontalBarChartData3 = { labels: ["mark1", "mark2", "mark3", "mark4","mark5"], datasets: [ { label: 'USA', backgroundColor: "rgba(196,196,196,0.5)", data: [0.07,0.02,0.26,0.68,0.21] }, { hidden: false, label: 'EUROPA', backgroundColor: "rgba(125,125,125,0.5)", data: [0.09,0.02,0.31,0.74,0.23] }, { label: 'CHINA', backgroundColor: "rgba(165,157,4,0.5)", data: [0.15,0.02,0.38,0.99,0.27] }] }; </code></pre>
<p>Adding an image to the labels is a tricky adjustment, and will require fiddling with chart.js code, as it isn't natively supported. My best suggestion is to avoid attempts to add your images to the labels themselves.</p> <p>Best solution for using icons would be one of:</p> <ol> <li><p>Use images of your own, but place them around the chart in proper positions, and if needed, refer to em in labels.</p></li> <li><p>Use an icon font to insert icons as characters of text. Here's an example using <a href="http://fontawesome.io/" rel="nofollow">Font Awesome</a>, using your data (based off of <a href="http://jsfiddle.net/JWp7W/5/" rel="nofollow">this</a> fiddle):</p></li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var randomScalingFactor = function () { return Math.round(Math.random() * 100); }; var barChartData = { pointLabelFontFamily: "'FontAwesome'", labels: ["\uf000", "\uf001", "\uf002", "\uf003", "\uf004"], datasets: [ { label: 'USA', backgroundColor: "rgba(196,196,196,0.5)", data: [0.07,0.02,0.26,0.68,0.21] }, { hidden: false, label: 'EUROPA', backgroundColor: "rgba(125,125,125,0.5)", data: [0.09,0.02,0.31,0.74,0.23] }, { label: 'CHINA', backgroundColor: "rgba(165,157,4,0.5)", data: [0.15,0.02,0.38,0.99,0.27] }] }; var ctx = document.getElementById("canvas").getContext("2d"); window.myBar = new Chart(ctx).Bar(barChartData, { responsive: true, scaleFontFamily: "'FontAwesome'" });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="http://chartjs.org/assets/Chart.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css"&gt; &lt;div style="width: 75%"&gt; &lt;span style="font-family: FontAwesome"&gt;&amp;#xf015;&lt;/span&gt; &lt;canvas id="canvas" height="450" width="600"&gt;&lt;/canvas&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Successful compiling the Node module and "Module did not self-register." <p>I decided to write a native module for Node using VS2015 compiler and node-gyp under Windows 8.1 32bit. I worked with the instructions from <a href="https://github.com/nodejs/node-gyp" rel="nofollow">this page</a>. I searched the internet (including StackOverflow) in search of a solution to my problem. </p> <p>I use following versions:</p> <ul> <li>Node: 4.6.0</li> <li>Node-gyp: 3.4.0</li> </ul> <p>The source code of the module: </p> <pre><code>// main.c++ #include &lt;node.h&gt; #include &lt;v8.h&gt; void Method(const v8::FunctionCallbackInfo&lt;v8::Value&gt;&amp; args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, "world")); } void init(v8::Local&lt;v8::Object&gt; target) { NODE_SET_METHOD(target, "hello", Method); } NODE_MODULE(sapphire, init); </code></pre> <pre class="lang-json prettyprint-override"><code>// binding.gyp { "targets": [ { "target_name": "sapphire", "sources": [ "main.c++" ] } ] } </code></pre> <p>Every time compilation (<code>node-gyp rebuild</code> called inside addon's source code folder) succeeds. Before compilation Node-Gyp prints that compiles for <code>node@4.6.0 | win32 | ia32</code>. Everything looked good until that point.</p> <p>For the test, I wrote the simplest possible script. </p> <pre><code>// test.js try { var sapphire = require('/build/Release/sapphire'); console.log(sapphire.hello()); } catch(err) { console.log(err); } </code></pre> <p>The result was printed error <code>Error: Module did not self-register.</code>. I tried to replace Node and V8 with NAN (following <a href="http://stackabuse.com/how-to-create-c-cpp-addons-in-node/" rel="nofollow">this tutorial</a>). But the result was the same.</p> <p>During the search for a solution to my problem I came across two possible reasons:</p> <ul> <li>Incorrect versions (libraries compared to the interpreter). Unfortunately eliminated this possibility, Node-Gyp clearly uses the library versions of the same as the interpreter, the one I use.</li> <li>Re-download modules from node_modules. I honestly do not understand why. All the necessary modules have been updated during the installation of Node-Gyp, the rest does not matter.</li> </ul> <p>What can cause this error? The source code of the module was downloaded from the tutorial from the documentation for the Node (v4.6.0). I also tried to make small changes and use all sorts of unofficial guides including of NAN. Each time the problem is the same.</p>
<p>node-gyp (the tool used to build node addons) tends to make some assumptions, at least when it comes to compiling your source files. For example, it will automatically choose the "right" compiler based on the source file's extension. So if you have a '.c' file it uses the C compiler and if you have a '.cc' file (or perhaps '.cpp' file) it uses the C++ compiler.</p> <p>'.c++' isn't a common file extension for C++ source files, so node-gyp may be interpreting the extension in an unexpected way (probably as a C source file). Changing the extension to something more common may help things.</p>
Is RectF.centerpoint wrong? <p>I do not understand something. If I have a <code>TRectF</code> with a width of 4 pixels:</p> <pre><code>aRectF := TRectF.Create(TPointF.Create(0,0),4,1); </code></pre> <p></p> <pre><code>X = 0 1 2 3 4 * * * * </code></pre> <p>Why does <code>aRectF.centerpoint.x</code> return 2 instead of 1.5? is it a <em>bug</em>?</p> <p>With a <code>TRectF</code> of 5 pixels:</p> <pre><code>X = 0 1 2 3 4 5 * * * * * </code></pre> <p><code>aRectF.centerpoint.x</code> return 2.5, but it must be 2 !</p> <p>Am I missing something?</p>
<p>The X coordinates span from 0.0 to 4.0 inclusive in the first example. The half way point is at 2.0.</p> <p>For the second example they span from 0.0 to 5.0. The half way point is therefore 2.5. </p> <p>Your mistake is in your belief that the right hand edge is one pixel to the left of where I have described. </p>
Method call chaining with generic types (Curiously Recurring Generic Pattern) <p>I'm getting a compile error that I don't understand the reason for.</p> <p>I'm trying to create a builder that extends another builder, all using generic types.</p> <p>The problem is that the return type of some generic methods is the parent class, not the child, which then prevents me from chaining any of the child methods.</p> <p>Here is simple example:</p> <pre><code>public class BuilderParent { public static class BuilderParentStatic&lt;B extends BuilderParentStatic&lt;B&gt;&gt; { public BuilderParentStatic() {} public B withParentId(int rank) { return self(); } protected B self() { return (B)this; } } } public class BuilderChild extends BuilderParent { public static class BuilderChildStatic&lt;B extends BuilderChildStatic&lt;B&gt;&gt; extends BuilderParent.BuilderParentStatic&lt;B&gt; { public BuilderChildStatic() {} public B withChildStuff(String s) { return (B)this.self(); } protected B self() { return (B)this; } } } public class Test { public static void main(String args[]) { BuilderChild.BuilderChildStatic builder = new BuilderChild.BuilderChildStatic(); // OK (uses child first, then parent): builder.withChildStuff("childStuff").withParentId(1); // compile error (uses parent first, then child): builder.withParentId(1).withChildStuff("childStuff"); } } </code></pre> <p>Why do I get the compilation error? How can I make it work as expected ?</p> <hr> <p><strong>EDIT:</strong></p> <p>I managed to resolve the issue thanks to the answers below using the following 2 changes </p> <p>1- I changed the BuilderChildStatic class generic to be a normal bounded generic type without the (Curiously Recurring Generic Pattern) stuff, </p> <p>so it will be as the following:</p> <pre><code> public static class BuilderChildStatic&lt;B extends BuilderChildStatic&gt; extends BuilderParent.BuilderParentStatic&lt;BuilderChildStatic&lt;B&gt;&gt; { </code></pre> <p>2- the other change is that I avoided raw types in the declaration in main method since now i can specify the type while declaring</p> <pre><code> BuilderChild.BuilderChildStatic&lt;BuilderChild.BuilderChildStatic&gt; builder = new BuilderChild.BuilderChildStatic&lt;&gt;(); </code></pre> <p>Everything else in the question other than those 2 points remained the same </p> <p>This way it behaved as I expected.</p> <p>thanks for the great answers and explanation</p>
<p>You use raw types, so in first case <code>builder.withChildStuff("childStuff")</code> returns value of <code>BuilderChildStatic</code> (from type parameter bounds) and this value has parent' method <code>withParentId</code>; in the second case <code>builder.withParentId(1)</code> returns value of <code>BuilderParentStatic</code> and thus this value doesn't have child method.</p>
Nil value for latitude when writing to local file <p>In a swift app, I need to write to a local file the latitude of the user. Here is the function is use to write to a local file:</p> <pre><code> func writeToFile(content: String) { let contentToAppend = content+"\n" //Check if file exists if let fileHandle = NSFileHandle(forWritingAtPath: filePathWrite) { //Append to file fileHandle.seekToEndOfFile() fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!) } else { //Create new file do { try contentToAppend.writeToFile(filePathWrite, atomically: true, encoding: NSUTF8StringEncoding) } catch { print("Error creating \(filePathWrite)") } } } </code></pre> <p>I use it like this: </p> <pre><code>writeToFile(String(locations.last!.coordinate.latitude)) </code></pre> <p>For the line above, I get this error: "unexpectedly found nil while unwrapping an Optional value"</p> <p>However, I tested the function with a random string ("hello" for example) and it works fine. For the latitude, it also works fine since I get the updated latitude value on the screen when it changes.</p> <p>I've added a condition to avoid nil values:</p> <pre><code>if locations.last!.coordinate.latitude != nil{ writeToFile(String(locations.last!.coordinate.latitude)) } </code></pre> <p>But now I get "CLLocationdegrees can never be nil, comparison nos allowed". </p> <p>So it can't be nil, but I still get an error because it's nil. What am I missing ?</p> <p>Any input will be much appreciated </p>
<p>The part causing the "unexpectedly found nil" is the force-unwrapping of <code>locations.last</code>. Avoid using <code>!</code> to force unwrap.</p> <p>Your <code>if</code> statement should just check to see if <code>locations.last</code> is <code>nil</code>:</p> <pre><code>if locations.last != nil { writeToFile(String(locations.last!.coordinate.latitude)) } </code></pre> <p>But you should do this the "correct" way:</p> <pre><code>if let last = locations.last { writeToFile(String(last.coordinate.latitude)) } </code></pre>
sql: how to add a constraint about 'always contains something' <p>I just wanted to know, how to write the constraint on sql server, where it should always contain a <code>'@'</code> sign and a <code>'.'</code>. Should I use check or what? It's about an email actually. </p>
<p>You can create a <code>CHECK</code> constraint like this</p> <p>Using <code>LIKE</code> operator </p> <pre><code>ALTER TABLE Yourtable ADD CHECK (email_col like '%@%.%') </code></pre> <p>Using <code>CHARINDEX</code> function</p> <pre><code>ALTER TABLE Yourtable ADD CHECK (Charindex('@',email_col)&gt;0 AND Charindex('.', email_col, Charindex('@', email_col)+1 )&gt;0) </code></pre>
InvalidCastException Casting Dictionary Values <p>I'm trying to load a list of values from a Dictionary. I can iterate through the list and get the values, but get an InvalidCastException </p> <blockquote> <pre><code> Additional information: Unable to cast object of type 'WhereListIterator`1[PumpTubing.Tubing]' to type 'PumpTubing.Tubing'. </code></pre> </blockquote> <p>when trying to use the following:</p> <pre><code>Dim tb2 As List(Of Tubing) = pd.pumps.Values. Select(Function(f) f. Where(Function(t) t.Tube.Equals("Tube3"))). Cast(Of Tubing)().ToList() </code></pre> <p>Is there a way to do this? I've tried several variations and cannot get it to work.</p> <p>I've included a method to Load some test data.</p> <p>Following is my code:</p> <pre><code>Module Module1 Private pd As New PumpData Sub Main() LoadTestData() ' This works and returns a a List with 3 entries Dim tb1 As New List(Of Tubing) For Each x As KeyValuePair(Of Pumps, List(Of Tubing)) In pd.pumps For Each t As Tubing In x.Value If t.Tube.Equals("Tube3") Then tb1.Add(t) Next Next ' The following throws an InvalidCastExcption: ' ' Additional information: Unable to cast object of type ' 'WhereListIterator`1[PumpTubing.Tubing]' to type 'PumpTubing.Tubing'. Dim tb2 As List(Of Tubing) = pd.pumps.Values. Select(Function(f) f. Where(Function(t) t.Tube.Equals("Tube3"))). Cast(Of Tubing)().ToList() End Sub Private Sub LoadTestData() pd.pumps.Add(New Pumps With {.Model = "Pump1", .MaxFlowRate = 300}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube1", .VPR = 1.1}, New Tubing With {.Tube = "Tube2", .VPR = 1.2}}) pd.pumps.Add(New Pumps With {.Model = "Pump2", .MaxFlowRate = 400}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube3", .VPR = 1.3}, New Tubing With {.Tube = "Tube4", .VPR = 1.4}}) pd.pumps.Add(New Pumps With {.Model = "Pump3", .MaxFlowRate = 500}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube5", .VPR = 1.1}, New Tubing With {.Tube = "Tube6", .VPR = 1.2}}) pd.pumps.Add(New Pumps With {.Model = "Pump4", .MaxFlowRate = 600}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube3", .VPR = 1.33}, New Tubing With {.Tube = "Tube7", .VPR = 1.4}}) pd.pumps.Add(New Pumps With {.Model = "Pump5", .MaxFlowRate = 700}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube1", .VPR = 1.15}, New Tubing With {.Tube = "Tube8", .VPR = 1.2}}) pd.pumps.Add(New Pumps With {.Model = "Pump6", .MaxFlowRate = 800}, New List(Of Tubing) From {New Tubing With {.Tube = "Tube3", .VPR = 1.35}, New Tubing With {.Tube = "Tube9", .VPR = 1.4}}) End Sub End Module </code></pre> <p>Here are the classes:</p> <pre><code>Public Class Pumps Property Model As String Property MaxFlowRate As Integer End Class Public Class Tubing Property Tube As String Property VPR As Decimal End Class Public Class PumpData Property pumps As New Dictionary(Of Pumps, List(Of Tubing)) End Class </code></pre>
<p>I'm not so good at VB syntax (coming from c#), but I guess you meant to use <code>SelectMany</code> instead of <code>Select</code>:</p> <pre><code>Dim tb2 As List(Of Tubing) = pd.pumps.Values. SelectMany(Function(f) f. Where(Function(t) t.Tube.Equals("Tube3"))). Cast(Of Tubing)().ToList() </code></pre>
php sendmail doesn't work after I changed the router <p>I'm running a web server that uses PHP sendmail function, which is directly connected to a router and after I replaced my old router to a new router it doesn't work anymore.</p> <p>Old router - Cisco RV082 - regular firmware New router - Netgear R7000 - DD-WRT v3.0-r30700M kongac</p> <p>I tried with all ports open and firewalls off but still didn't work. Please help.</p> <p>Here is the part of the log. Oct 11 is the working one and Oct 13 is not.</p> <p>/var/log/mail.log</p> <pre><code>Oct 11 13:58:08 localhost sm-mta[3613]: STARTTLS=client, relay=aspmx.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-AES128-GCM-SHA256, bits=128/128 Oct 11 13:58:08 localhost sm-mta[3613]: u9BKw7pL003611: to=&lt;joe@ctclogis.com&gt;, ctladdr=&lt;www-data@localhost.localdomain&gt; (33/33), delay=00:00:01, xdelay=00:00:01, maile$ Oct 11 13:58:09 localhost sm-mta[3613]: u9BKw7pL003611: to=&lt;export@ypusa21.com&gt;, ctladdr=&lt;www-data@localhost.localdomain&gt; (33/33), delay=00:00:02, xdelay=00:00:02, mai$ Oct 11 13:58:09 localhost sm-mta[3613]: STARTTLS=client, relay=alt1.aspmx.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-AES128-GCM-SHA256, bits=128$ Oct 11 13:58:10 localhost sm-mta[3613]: u9BKw7pL003611: to=&lt;joe@ctclogis.com&gt;, ctladdr=&lt;www-data@localhost.localdomain&gt; (33/33), delay=00:00:03, xdelay=00:00:03, maile$ Oct 13 19:20:26 localhost sm-mta[6369]: u9E2KQ20006369: from=&lt;&gt;, size=2122, class=0, nrcpts=1, msgid=&lt;201610140220.u9E2K13e006368@localhost.localdomain&gt;, proto=ESMTP, $ Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9E2K13e006368: to=www-data, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31509, relay=[127.0.0.1] [127.0.0.1], dsn$ Oct 13 19:20:26 localhost sm-mta[6370]: u9E2KQ20006369: to=&lt;www-data@localhost.localdomain&gt;, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=32350, dsn=2.0.0, stat=$ Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9DM8URU004818: u9E2K13f006368: sender notify: Warning: could not send message for past 4 hours </code></pre>
<p>Marc B is correct in his comment. This is not the best site for you to be asking this kind of question on. Try the <a href="http://networkengineering.stackexchange.com">Network Engineering Stack Exchange</a> or something similar.</p> <p>Now if this is a PHP issue then yes you have posted to the correct site but need to re-word your question to be more compliant. If this is the case have you double checked all the cautions from the <a href="http://php.net/manual/en/function.mail.php" rel="nofollow">PHP manual on the send mail function</a>? From a programming stand point your error could be simply in how you are trying to send the emails. The old router may have just ignored your errors (incorrectly formatted messages) and sent stuff out anyway; from my experience this is not the case because your router usually has nothing to do with this except doing its job of routing or forwarding depending on your setup.</p> <p>More specifically I'm trying to pick apart your log and I think on the PHP side of things you may have made a few errors.</p> <blockquote> <p>Oct 13 19:20:26 localhost sm-mta[6369]: u9E2KQ20006369: from=&lt;>, size=2122, class=0, nrcpts=1, msgid=&lt;201610140220.u9E2K13e006368@localhost.localdomain>, proto=ESMTP, $</p> </blockquote> <p>Your server didn't log a From email address on this line. In your PHP script using the mail function did you forget to set one?</p> <blockquote> <p>Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9E2K13e006368: to=www-data, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31509, relay=[127.0.0.1] [127.0.0.1], dsn$ Oct 13 19:20:26 localhost sm-mta[6370]: u9E2KQ20006369: to=, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=32350, dsn=2.0.0, stat=$</p> </blockquote> <p>I could be reading this wrong (again this is a programming site) but your mail relay is setup as your localhost. Why? Your old logs from the 11th show you using a google relay.</p> <p>It seems that either in a PHP script your using to send the emails or your PHP configuration/ server itself has been mis-configured. </p>
show blog Author , title , label and time in a specific div blogger <hr> <p>For SEO purposes I wanted to copy this blog post design <a href="http://www.th3professional.com/2016/10/blog-post_14.html" rel="nofollow">this website</a> the specific part I want to copy is the div with id="enter-posts" which has the title, the author, date, labels of the post</p> <p>I tried to put tags like:</p> <p><code>&lt;div class='author-profile' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'&gt; &lt;meta expr:content='data:post.authorProfileUrl' itemprop='url'/&gt; &lt;b:if cond='data:post.authorPhoto.url'&gt;&lt;a expr:href='data:post.authorProfileUrl' itemprop='url'&gt; &lt;div class='auhtor-image'&gt;&lt;img expr:src='data:post.authorPhoto.url' itemprop='image'/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/b:if&gt; &lt;div&gt;&lt;span class='author-about'&gt;About &lt;/span&gt;&lt;a class='g-profile' expr:href='data:post.authorProfileUrl' rel='author' title='author profile'&gt;&lt;span itemprop='name'&gt;&lt;data:post.author/&gt;&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;&lt;p class='description' itemprop='description'&gt;&lt;data:post.authorAboutMe/&gt;&lt;/p&gt;&lt;/div&gt;</code></p> <p>for author and so on for the other elements I want to add but the problem is:</p> <p>Nothing is displayed, <strong>BUT</strong> when I put these tags inside the post body before the title or at the end of the post they appear normally. what should I do?</p>
<p>You can't use blogger data tags like <code>&lt;data:post.author/&gt;</code> inside the post body or outside widgets. please read <a href="https://support.google.com/blogger/answer/47270" rel="nofollow">Layouts Data Tags</a></p>
Line Counting Function no longer works in Swift 3.0 <p>I had a function that I was using in Swift 2.2 that I never had any problems with, now I'm getting an error when I try to use it.</p> <p>The code is to change the number of lines a UILabel has to accommodate the size of the string.</p> <pre><code>func countLabelLines(label: UILabel) -&gt; Int { if let text = label.text { let myText = text as NSString let attributes = [NSFontAttributeName: label.font] let width = label.bounds.width let height = CGFloat.greatestFiniteMagnitude let size = CGSize(width: width, height: height) let labelSize = myText.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil) //Code errors here let lines = ceil(CGFloat(labelSize.height) / label.font.lineHeight) return Int(lines) } return 0 } </code></pre> <p>And this is my error message:</p> <pre> > 2016-10-14 09:47:37.213 EZ Lists[23136:1997134] -[_SwiftValue pointSize]: unrecognized selector sent to instance 0x608000247380 2016-10-14 09:47:37.218 EZ Lists[23136:1997134] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue pointSize]: unrecognized selector sent to instance 0x608000247380' *** First throw call stack: ( 0 CoreFoundation 0x000000010e2ef34b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010d93321e objc_exception_throw + 48 2 CoreFoundation 0x000000010e35ef34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x000000010e274c15 ___forwarding___ + 1013 4 CoreFoundation 0x000000010e274798 _CF_forwarding_prep_0 + 120 5 UIFoundation 0x000000011362a2ba __NSStringDrawingEngine + 3204 6 UIFoundation 0x0000000113629610 -[NSString(NSExtendedStringDrawing) boundingRectWithSize:options:attributes:context:] + 202 7 EZ Lists 0x000000010d2beaf2 _TZFC8EZ_Lists11CustomFuncs15countLabelLinesfT5labelCSo7UILabel_Si + 1218 8 EZ Lists 0x000000010d2be0f2 _TZFC8EZ_Lists11CustomFuncs21fitLabelTextForHeightfT5labelCSo7UILabel10constraintCSo18NSLayoutConstraint11extraHeightV12CoreGraphics7CGFloat_T_ + 82 9 EZ Lists 0x000000010d2ce445 _TFC8EZ_Lists9AddItemVC21viewDidLayoutSubviewsfT_T_ + 309 10 EZ Lists 0x000000010d2ce472 _TToFC8EZ_Lists9AddItemVC21viewDidLayoutSubviewsfT_T_ + 34 11 UIKit 0x000000010eee73a8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1337 12 QuartzCore 0x000000011478dcdc -[CALayer layoutSublayers] + 146 13 QuartzCore 0x00000001147817a0 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 14 QuartzCore 0x000000011478161e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 15 QuartzCore 0x000000011470f62c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 16 QuartzCore 0x000000011473c713 _ZN2CA11Transaction6commitEv + 475 17 UIKit 0x000000010ee1c067 _UIApplicationFlushRunLoopCATransactionIfTooLate + 206 18 UIKit 0x000000010f62bb30 __handleEventQueue + 5672 19 CoreFoundation 0x000000010e294311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 20 CoreFoundation 0x000000010e27959c __CFRunLoopDoSources0 + 556 21 CoreFoundation 0x000000010e278a86 __CFRunLoopRun + 918 22 CoreFoundation 0x000000010e278494 CFRunLoopRunSpecific + 420 23 GraphicsServices 0x0000000113f9da6f GSEventRunModal + 161 24 UIKit 0x000000010ee22f34 UIApplicationMain + 159 25 EZ Lists 0x000000010d2caa4f main + 111 26 libdyld.dylib 0x00000001120ce68d start + 1 27 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException </pre> <p>I'm still pretty new at Xcode / Swift and I understand that one of my Arguments isn't right, but I don't understand which is the problem. After first I was thinking it was with the CGSize, but I broke that out into it's own line and that doesn't have an issue.</p>
<p>It's the <em>font</em>. The problem is this line:</p> <pre><code>let attributes = [NSFontAttributeName: label.font] </code></pre> <p>Try writing this:</p> <pre><code>let attributes = [NSFontAttributeName: label.font!] </code></pre> <p>I think the exclamation mark should fix it.</p>
django urlpattern wrong? need to accept 2 different parameters <p>I'm working on building a django app for a small little game I'm building to integrate it. Instead of re-writing my app to use django's membership system I've added my small little game login system to the django site. My issue is with my ChangePassword url pattern.</p> <pre><code>url(r'^ChangePassword/(?P&lt;userID&gt;[0-9]+)/(?P&lt;token&gt;/?$)', changepassword, name='Change Password'), </code></pre> <p>I get the following error in the terminal while trying to go to the page.</p> <blockquote> <p>Not Found: /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== [14/Oct/2016 16:53:53] "GET /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== HTTP/1.1" 404 3294</p> </blockquote> <p>Am I missing a regex or do I have the pattern wrong? I've been going through user docs and question on here and found a solution yet. It needs to accept the userID and a special token so we know that we can reset/change the password.</p>
<p>Your regex pattern for the token:</p> <pre><code>(?P&lt;token&gt;/?$) </code></pre> <p>Will match an optional forward slash <code>/</code> that <em>ends</em> the url. In other words it will match <code>/members/ChangePassword/11/</code> or <code>/members/ChangePassword/11//</code>.</p> <p>You will need to modify so that it captures the characters in your token. Since it looks like <code>base64</code> encoding, which includes <code>[A-Z][a-z][0-9][+/=]</code>, you should be able to edit as follows:</p> <pre><code>(?P&lt;token&gt;[A-Za-z0-9+/=]+$) </code></pre>
reference and literals in C++ <p>I know that "literals" (c strings, int or whatever) are stored somewhere (in a read only data section apparently .rodata) maybe this is not accurate...</p> <p>I want to understand why this code causes a runtime error:</p> <pre><code>#include &lt;iostream&gt; using namespace std; const int&amp; foo() { return 2; } const char* bar() { return "Hello !"; } int main() { cout &lt;&lt; foo() &lt;&lt; endl; // crash cout &lt;&lt; bar() &lt;&lt; endl; // OK return 0; } </code></pre> <p>foo returns a const reference on a literal (2) why does this cause a crash ? is the integer 2 stored in the stack of foo() ?</p> <p>See also : <a href="http://stackoverflow.com/questions/10004511/why-are-string-literals-l-value-while-all-other-literals-are-r-value">Why are string literals l-value while all other literals are r-value?</a></p>
<p>I see why this is confusing so I will try to break it down.</p> <p><strong>First case:</strong></p> <pre><code>const int&amp; foo() { return 2; } </code></pre> <p>The return statement makes a <em>temporary object</em> which is a <strong>copy</strong> of the literal <code>2</code>. So its address is either <em>non-extant</em> or different from the location of the literal <code>2</code> (assuming literal <code>2</code> has a location - not guaranteed).</p> <p>It is that temporary whose reference is returned.</p> <p><strong>Second case:</strong></p> <pre><code>const char* bar() { return "Hello !"; } </code></pre> <p>The return statement makes a <em>temporary object</em> which is a <strong>copy</strong> of a <strong>pointer</strong> to the <em>address</em> of the <em>first element</em> of the literal char array. That <em>pointer</em> contains the actual address of the literal array and that address is returned <em>by copy</em> to the caller.</p> <p>So to sum up. The second one works because the return statement takes a copy of the literal's <em>address</em> and not a copy of the literal itself. It doesn't matter that the storage for the <em>address</em> is temporary because the <em>address</em> still points to the correct place after the temporary holding its value collapses.</p>
Only allow site to be viewed through its proper domain <p>I'm hosting multiple sites on the same Apache server (and IP address) using the standard method of virtual hosts. So I have folders like the following: <code>/var/www/website1.com/</code>, <code>/var/www/website2.com/</code>, and so on.</p> <p>I know how to change the DocumentRoot so that requests for a certain domain point to the appropriate directory, but the problem is that the site is also accessible via <code>123.456.789.000/website1.com/</code>, where <code>123.456.789.000</code> is the server's IP address.</p> <p>This is especially bad because it's built using Laravel, so the DocumentRoot is actually <code>/var/www/website1.com/public</code>, with the main <code>website1.com</code> directory being where Laravel stores config files and other private files. It's currently possible to view these files by visiting it at the IP address (thankfully this isn't a critical project).</p> <p>So how I make sure that a site can only be visited at <code>website.com</code> and not <code>123.456.789.000/website.com/</code>? I don't necessarily want this to apply globally - I want to be able to choose on a site per site basis whether it should only be accessible through its proper domain name.</p>
<p>You need to add a redirect which sends clients to your 'canonical' domain name</p> <pre><code>RewriteCond %{HTTP_HOST} !^example\.com [NC] RewriteRule ^/(.*) https://example.com/$1 [R=301,L] </code></pre> <p>(I don't know anything about 'Laravel', but storing config/private files in web accessible directories sounds really bad)</p>
How to exit the program when a user enters a negative value - Java <p>Scanner input = new Scanner(System.in);</p> <pre><code> System.out.print("How much can you afford for meals per day? Enter it now "); double mealAmount = input.nextDouble(); </code></pre>
<p>This because your tests are performed <strong>only after getting the 3 double values</strong>. You should move the tests corresponding to each variable just after getting its value thanks to <code>input.nextDouble()</code>.</p> <p><strong>Your code should rather be:</strong></p> <pre><code>System.out.print("How much can you afford for meals per day? Enter it now "); double mealAmount = input.nextDouble(); if (mealAmount &lt;0) System.exit(0); else if (mealAmount &lt; 15.00 &amp;&amp; mealAmount &gt;=0) System.out.println("No meal for you. Tough luck."); else if (mealAmount &gt;= 15.00 &amp;&amp; mealAmount &lt; 30.00) System.out.println("You can afford bronze meals."); else if (mealAmount &gt;= 30.00 &amp;&amp; mealAmount &lt; 60.00) System.out.println("You can afford silver meals."); else if (mealAmount &gt;= 60.00) System.out.println("You can afford gold meals."); ... </code></pre> <p><strong>NB:</strong> No need to explicitly call <code>System.exit(0)</code> simply use <code>return</code>.</p>
excel 2013 vba range names count not working <p>I am using Excel 2013 and cannot get the count nor a listing of range names. I can open the Names Manager dialog box and the names and ranges are listed. I added the names (List1,List2, and List3) to the workbook using VBA (Set rngTable = c.CurrentRegion.ListObjects.Add). I can iterate through the named ranges by using "List" &amp; intCounter to get the ranges associated with each list. But I cannot get the number of names nor a list of names.</p> <p>I tried following code in Excel 2013 and 2007 and when execution gets to the line <strong><em>For i = 1 To namedRanges.Count</em></strong> it returns zero (0). What can I do to get the number of named ranges in the workbook and list the names of the named ranges? Your help is greatly appreciated!</p> <p>Private Sub Something()</p> <pre><code>Dim namedRanges As Names Set namedRanges = ActiveSheet.Names Dim targetSheet As Worksheet Set targetSheet = Sheet3 targetSheet.Cells.Clear Dim i As Integer For i = 1 To namedRanges.Count targetSheet.Cells(i, 2).Value = namedRanges(i).Name targetSheet.Cells(i, 3).Value = namedRanges(i).RefersToRange.Address Next </code></pre> <p>End Sub</p>
<p>Are your named ranges scoped to the worksheet, or the workbook? If they're not limited to a single worksheet, you'll need to reference the workbook.Names collection instead.</p> <pre><code>Set namedRanges = ActiveWorkbook.Names </code></pre>
Mongo DB and Names with special characters <p>I am processing a large text file that has names with an occasional special character. An example would be "CASTA¥EDA, JASON". When I process the file the line comes across as UTF-8. However when the insert to Mongo is about to happen, it shows error:</p> <pre><code>[MongoDB\Driver\Exception\UnexpectedValueException] Got invalid UTF-8 value serializing 'Jason Casta�eda' </code></pre> <p>I then proceeded to do this:</p> <pre><code> $name = iconv("UTF-8","UTF-8//IGNORE",$name); </code></pre> <p>And now this produces: Jason Castaeda</p> <p>Is there a way to find if a name has special characters that are non-utf-8. </p> <p>Ideally it would be nice to know if a line of file has characters that will not make the cut to Mongo. Any tips?</p> <p>I mean I could take the length of the name before and then do an iconv and compare the string lengths but that seems trivial. Any better way?</p>
<p>I'd recommend converting all user-input strings <a href="https://nodejs.org/api/buffer.html" rel="nofollow">into a Buffer</a>. Or check for insert/update errors by using <a href="http://stackoverflow.com/questions/21588871/check-if-there-is-an-error-in-update-insert-mongodb-java-driver">ACKNOWLEDGED</a></p> <p><em>EDIT:</em> Sorry about that, totally ignored the php tag. try this:</p> <pre><code>function bin2text($your_binary_number) { $text_str = ''; $chars = explode("\n", chunk_split(str_replace("\n", '', $bin_str), 8)); $_i = count($chars); for ($i = 0; $i &lt; $_i; $text_str .= chr(bindec($chars[$i])), $i ); return $text_str; } function text2bin($txt_str) { $len = strlen($txt_str); $bin = ''; for($i = 0; $i &lt; $len; $i ) { $bin .= strlen(decbin(ord($txt_str[$i]))) &lt; 8 ? str_pad(decbin(ord($txt_str[$i])), 8, 0, str_pad_left) : decbin(ord($txt_str[$i])); } return $bin; } </code></pre> <p>taken from: <a href="http://psoug.org/snippet/PHP-Binary-to-Text-Text-to-Binary_380.htm" rel="nofollow">http://psoug.org/snippet/PHP-Binary-to-Text-Text-to-Binary_380.htm</a></p> <p><code>text2bin</code> basically converts your string into binaries and <code>bin2text()</code> converts the binaries back into text </p>
Change DateFormat from DatePickerDialog using SimpleDateFormat in Android <p>I'm new to Java and Android. I took the following code from different Tutorials on DatePickerDialog (mainly the official one). Now I want the selected date to be in a specific format ("EE, DD.MM.YY") and tried to do this with SimpleDateFormat but I don't understand where to get the selected date from since I "only" have year, month and day as arguments:</p> <pre><code>public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { public Date date; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); date = c.getTime(); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { TextView textView = (TextView) getActivity().findViewById(R.id.textView_Date); String selectedDate = String.valueOf(day) + "." + String.valueOf(month) + "." + String.valueOf(year); textView.setText(selectedDate); } } </code></pre> <p>So I tried to change the line</p> <pre><code>String selecteDate = ... </code></pre> <p>into something like</p> <pre><code>SimpleDateFormat simpledateformat = new SimpleDateFormat("EE, DD.MM.YY"); String selectedDate = simpledateformat.format(date); </code></pre> <p>But since "date" is not the selected one but the current one and because the result of simpledateformat.format is probably not a String, it doesn't work. Can anyone tell me how to make it work? It doesn't need to be SimpleDateFormat though, that's just the way I thought it might work. Thanks a lot!</p>
<p>Try this:</p> <pre><code>SimpleDateFormat simpledateformat = new SimpleDateFormat("EE, dd.MM.yy"); Calendar newDate = Calendar.getInstance(); newDate.set(year, month, day); String selectedDate = simpledateformat.format(newDate.getTime()); </code></pre>
Multiple string search in txt file (java) <pre><code>BufferedReader br2 = new BufferedReader( new InputStreamReader(new FileInputStream(id_zastavky), "windows-1250") ); for (int i = 0; i &lt; id_linky_list.size(); i++) { while ((sCurrentLine2 = br2.readLine()) != null) { String pom = id_linky_list.get(i); String[] result = sCurrentLine2.split("\\|"); if((result[1].toString()).equals(pom.toString())) { System.out.println(result[1].toString()+" " +pom.toString() + " " + result[3]); } } } br2.close(); </code></pre> <p>Hey guys. Anyone can give me advice why is my FOR loop using only first item in my id_linky_list a then it quits? I think that the problem is on this line </p> <blockquote> <p>while ((sCurrentLine2 = br2.readLine()) != null)</p> </blockquote> <p>. I have over 5 000 items in my list and I need to compare them if they exist in my txt file. If I run my App the for loop only takes first item. How should I modify my code to make it work properly? Thank you for any help.</p>
<p>during the first iteration of for loop, the whole file will be read and <code>br2.readLine()</code> will always return null for next iterations.</p> <p>Instead of that if the file size is small you could build a map and you can use that map to check the content </p> <pre><code> File file = new File("filename"); List&lt;String&gt; lines = Files.linesOf(file, Charset.defaultCharset()); Map&lt;String, List&lt;String&gt;&gt; map = lines.stream().collect(Collectors.groupingBy(line -&gt; line.split("\\|")[1])); List&lt;String&gt; id_linky_list = null; for (int i = 0; i &lt; id_linky_list.size(); i++) { if (map.get(id_linky_list.get(i)) != null) { //sysout } } </code></pre> <p><strong>Update</strong></p> <pre><code>Map&lt;String, List&lt;String&gt;&gt; text = Files.lines(file.toPath(), Charset.forName("windows-1250")).collect(Collectors.groupingBy(line -&gt; line.split("\\|")[1])); </code></pre>
getting null value while parsing json data in android <p>i am trying to parse json data in android app i am able to get title of the book and author but i am not able to parse publisher i am getting null value at publisher </p> <pre><code> "kind":"books#volumes", "totalItems":997, "items":[ { "kind":"books#volume", "id":"g3hAdK1IBkYC", "etag":"o+CdTUx3mkQ", "selfLink":"https://www.googleapis.com/books/v1/volumes/g3hAdK1IBkYC", "volumeInfo":{ "title":"Professional Android 4 Application Development", "authors":[ "Reto Meier" ], "publisher":"John Wiley &amp; Sons", "publishedDate":"2012-04-05", } </code></pre> <p>here is the java code written for Json</p> <pre><code> JSONObject root = new JSONObject(jsonResponse); JSONArray itemsArray = root.optJSONArray("items"); for (int i=0;i&lt;itemsArray.length();i++){ JSONObject singleItem = itemsArray.getJSONObject(i); JSONObject volumeInfo = singleItem.getJSONObject("volumeInfo"); String title = volumeInfo.getString("title"); Log.i("title_book",title); String author = volumeInfo.getString("authors"); Log.i("author_book",author); String publisher = singleItem.getString("publisher"); Log.i("publisher_book",publisher); </code></pre>
<p>It seems that the <code>publisher</code> is contained by <code>volumeInfo</code>. Try:</p> <pre><code>String publisher = volumeInfo.getString("publisher"); </code></pre>
Can i program games with unity by python ?? I don't know c# <p>I want to start 3d games programming , should I start 2d first ? please give me useful course . Does unity accept python ? If not , what do you prefer( directpython, openlg,panda3d ) Please give me useful course . I'm beginner Sorry about my bad English And what is game engine</p> <p>If you know only one answer please answer :) </p>
<p>If you need pure Python then you have 2D or 3D modules PyGame, Pyglet, PySDL2, Panda3D, etc.</p> <p>But there is also <a href="https://godotengine.org/" rel="nofollow">Godot Engine</a> which has many tools (like Unity) but it doesn't use Python - it use own language similar to Python.</p>
Asterisk AMI tracking the inbound call <p>I have an assignment, and need help in these two points.</p> <p>There is ubuntu 16.04 server, the following task needs to be in PHP</p> <ol> <li><p>tracking the inbound call using Asterisk AMI, when the incoming calls is in place, you need to track how long the conversation took place in realtime.</p></li> <li><p>create a mini dashboard to display the ongoing call and display the data on point 2. </p></li> </ol> <p>Any help would be appreciated </p>
<p>Simplest way is issue in dialplan UserEvent with all params you want submit to AMI and track ami event UserEvent.</p>
stacking divs -- mix of vertical and horizontal layout <p>I would like to accomplish a mix of horizontal and vertical layouts.</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;span&gt;A&lt;/span&gt; &lt;span&gt;B&lt;/span&gt; &lt;span&gt;C&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;span&gt;D&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>#1</strong> It should look like this</p> <pre><code>A B C &lt;- D -&gt; </code></pre> <p><strong>#2</strong> Instead I have the two div elements next to one another</p> <pre><code>A B C &lt;- D -&gt; </code></pre> <hr> <p>The real example has some very bad CSS that I recommend you not look at. I wanted to set the top three items to the same width of <strong>25px</strong> and to be arranged next to one another. And a picture beneath the two control buttons.</p> <p>For some reason, the <code>div</code> elements are not stacking on top of one another and instead sitting next to each other all in one row. Please help!</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;button style="width: 25px; float: left;"&gt;-&lt;/button&gt; &lt;span style="width: 25px; float: left; text-align: center;"&gt;0&lt;/span&gt; &lt;button style="width: 25px; float: left;"&gt;+&lt;/button&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="starry-night.jpg" width="500"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
<p>Give a width of 75 px to the parent div so that after placing 3, 25px elements the next element will be forced to be on the new line. <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div style="width: 75px;"&gt; &lt;div&gt; &lt;button style="width: 25px; float: left;"&gt;-&lt;/button&gt; &lt;span style="width: 25px; float: left; text-align: center;"&gt;0&lt;/span&gt; &lt;button style="width: 25px; float: left;"&gt;+&lt;/button&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="starry-night.jpg" width="500"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
rle command counting changes in vector <pre><code>n &lt;- length(rle(sign(z))) </code></pre> <p>z contains 1 and -1. n should indicate the number of how many times the sign of z changes. </p> <p>The code above does not lead to the desired outcome. If I expand the command to</p> <pre><code>length(rle(sign(z))[[1]]) </code></pre> <p>it works. I don't understand the underlying mechanism of how [[1]] solves the problem?</p>
<p><code>rle</code> returns a list consisting of two components: <code>lengths</code>, and <code>values</code>. As such, its own <code>length</code> is always 2. By contrast, you want to know the length of either of those components (they obviously have the same length). So either <code>length(rle(…)[[1]])</code> or <code>length(rle(…)[[2]])</code> would work. Better to use the names instead of an index though, e.g.</p> <pre><code>length(rle(z)$lengths) </code></pre> <p>However, this won’t be the number of times the sign changes; rather, it will be the number of times the changes plus 1.</p>
geckodriver executable needs to be in path <p>I have read previous questions asked on this topic and tried to follow the suggestions but I continue to get errors. On terminal, I ran </p> <pre><code>export PATH=$PATH:/Users/Conger/Documents/geckodriver-0.8.0-OSX </code></pre> <p>I also tried</p> <pre><code> export PATH=$PATH:/Users/Conger/Documents/geckodriver </code></pre> <p>When I run the following Python code</p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = True firefox_capabilities['binary'] = '/Users/Conger/Documents/Firefox.app' driver = webdriver.Firefox(capabilities=firefox_capabilities) </code></pre> <p>I still get the following error</p> <pre><code>Python - testwebscrap.py:8 Traceback (most recent call last): File "/Users/Conger/Documents/Python/Crash_Course/testwebscrap.py", line 11, in &lt;module&gt; driver = webdriver.Firefox(capabilities=firefox_capabilities) File "/Users/Conger/miniconda2/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __init__ self.service.start() File "/Users/Conger/miniconda2/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Exception AttributeError: "'Service' object has no attribute 'process'" in &lt;bound method Service.__del__ of &lt;selenium.webdriver.firefox.service.Service object at 0x1006df6d0&gt;&gt; ignored [Finished in 0.194s] </code></pre>
<p>First we know that gekodriver is the driver engine of Firefox,and we know that <code>driver.Firefox()</code> is used to open Firefox browser, and it will call the gekodriver engine ,so we need to give the gekodirver a executable permission. so we download the latest gekodriver uncompress the tar packge ,and put gekodriver at the <code>/usr/bin/</code> ok,that's my answer and i have tested.</p>
How can I send requests to JSON? <p>I'm coding a mobile application with ionic. I have to get a data (daily changing data) from a web page with JSON, but I want to get old data too. For example:</p> <pre><code>data.json?date=2016-11-10 data.json?data=2016-12-10 </code></pre> <p>How can I send request to JSON?</p>
<p>To send data from PHP, once you get your data from the database, the array will apply <code>json_encode($array);</code> and to return you put <code>return json_encode ($ array);</code></p> <p>Try this!</p> <pre><code>var date = '2016-11-10'; $http({ method: 'GET', url: data.php, params: {date: date}, dataType: "json", contentType: "application/json" }).then(function(response) { }); </code></pre>
Create anchor tag within unordered list elements with d3js? <p>I wanted to dynamically create anchor tags within an undordered list:</p> <p>Mannually this works:</p> <pre><code>&lt;h2&gt; Without d3 &lt;/h2&gt; &lt;ul id="anotherList"&gt; &lt;li&gt; &lt;a href="http://www.google.com"&gt; &lt;text&gt;hello&lt;/text&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://www.google.com"&gt; &lt;text&gt;hello&lt;/text&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://www.google.com"&gt; &lt;text&gt;hello&lt;/text&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://www.google.com"&gt; &lt;text&gt;hello&lt;/text&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://www.google.com"&gt; &lt;text&gt;hello&lt;/text&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>So, the HTML structure built by d3 should look like the example above. My d3 code looks like this:</p> <pre><code>var data = [1,2,3,4,5]; d3.select("#divListElement") .selectAll("li") .data(data) .enter() .append("li") .append("a") .attr("xlink:href", "http://www.google.de") .append("text") .text("hello"); </code></pre> <p>When I inspect the DOM structure of both, I see that they are indeed the same. However the example without d3 (manually created) works, while the example with d3 does not work, even though it's the same structure? </p> <p><a href="http://jsfiddle.net/thadeuszlay/Qh9X5/9211/" rel="nofollow">http://jsfiddle.net/thadeuszlay/Qh9X5/9211/</a></p>
<p>xlink:href is meant for svg use (though it looks like it might be deprecated), if you are adding an href to an a tag just use <code>href</code> <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href</a></p> <p><code>.attr("href", "http://www.google.de")</code></p>
'helloworld.pyx' doesn't match any files <p>I am a beginner in python and I have just got familiar with cython as well. I am using Anaconda on Windows 64-bit. I am trying to run the "helloworld" example as follows:</p> <p>1- I build a helloworld.pyx file containing:</p> <pre><code> print("Hello World") </code></pre> <p>2- I build a setup.py file containing:</p> <pre><code> from distutils.core import setup from Cython.Build import cythonize setup(name='Hello world app',ext_modules=cythonize("helloworld.pyx"),) </code></pre> <p>But I get the following error:</p> <pre><code> 'helloworld.pyx' doesn't match any files </code></pre> <p>Could you please tell me what should I do now? Where should I save these two files?</p>
<p>From here: <a href="https://github.com/cython/cython/wiki/enhancements-distutils_preprocessing" rel="nofollow">https://github.com/cython/cython/wiki/enhancements-distutils_preprocessing</a></p> <pre><code>from distutils.core import setup from Cython.Build import cythonize setup( name = 'MyProject', ext_modules = cythonize(["*.pyx"]), ) </code></pre> <p>Looks like cythonize accepts a list of strings, but you're providing a string.</p>
Kendo UI Column with Detail Table <p>I am currently displaying a Kendo UI chart with a standard HTML table underneath it. Does anyone know of a way where I can specify each category to be displayed with a specific width? The reason why I would like to do this is because I would like that the category labels match up exactly with the table headers beneath it so that it's easy for the user to see the data in detail.</p> <p>Here is what I currently have. You will notice that as more dates get added the more it gets out of sync. Any help would be greatly appreciated. Thanks!</p> <p><a href="https://i.stack.imgur.com/S3ZoJ.png" rel="nofollow">current sample</a></p>
<p>Set a width on the <code>td</code>'s of your HTML table equal to the column width of your graph. </p> <p>For example if the columns of your graph are 35px wide, then in your css:</p> <pre><code>td.tableDataBelowMyGraph{ width: 35px; } </code></pre> <p>As it stands, your <code>td</code>'s width are being set by their contents. </p>
Multiple PouchDB to single CouchDB <p>I need to submit data from multiple mobile apps. in my mobile app I am planning to use pouchdb to store the document, later I want this document to sync to couchdb one-way only. what will happen if I submit data from multiple devices ? will pouch db create same document ID and overwrite data in couchDB ?</p>
<p>The document ID will not be the same, assuming you're letting PouchDB create them (the likelihood of PouchDB generating the same ID twice is extremely low)</p>
SQL EXISTS returns all rows, more than two tables <p>I know similar questions like this have been asked before, but I have not seen one for more than 2 tables. And there seems to be a difference.</p> <p>I have three tables from which I need fields, <code>customers</code> where I need <code>customerID</code> and <code>orderID</code> from, <code>orders</code> from which I get <code>customerID</code> and <code>orderID</code> and <code>lineitems</code> from which I get <code>orderID</code> and <code>quantity</code> (= quantity ordered).</p> <p>I want to find out how many customers bought more than 2 of the same item, so basically quantity > 2 with: </p> <pre><code>SELECT COUNT(DISTINCT custID) FROM customers WHERE EXISTS( SELECT * FROM customers C, orders O, lineitems L WHERE C.custID = O.custID AND O.orderID = L.orderID AND L.quantity &gt; 2 ); </code></pre> <p>I do not understand why it is returning me the count of all rows. I am correlating the subqueries before checking the >2 condition, am I not?</p> <p>I am a beginner at SQL, so I'd be thankful if you could explain it to me fundamentally, if necessary. Thanks.</p>
<p>You don't have to repeat <code>customers</code> table in the <code>EXISTS</code> subquery. This is the idea of correlation: use the table of the outer query in order to correlate.</p> <pre><code>SELECT COUNT(DISTINCT custID) FROM customers c WHERE EXISTS( SELECT * FROM orders O JOIN lineitems L ON O.orderID = L.orderID WHERE C.custID = O.custID AND L.quantity &gt; 2 ); </code></pre>
(Javascript) Bouncing balls clip into wall <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.addEventListener("DOMContentLoaded", function(event){ var context, width = window.screen.availWidth - 120, height = window.screen.availHeight - 120, xTemp, yTemp, x = [], y = [], dx = [0], dy = [5], gravity = [1], bounceTime = [1], canvas = document.getElementById("bouncingField"), isSpawned = 0, image = new Image(); document.getElementById("bouncingField").width = width; document.getElementById("bouncingField").height = height; //Image to use as ball texture image.src = "http://www.freeiconspng.com/uploads/soccer-ball-icon-14.png"; //Run func init on page load window.onload = init; //Get 2d context and repaint every 10 milliseconds context = bouncingField.getContext('2d'); setInterval(repaint, 10); canvas.onclick = function setSpawnTrue(){ if(!isSpawned){ x[0] = xTemp; y[0] = yTemp; } else{ x.push(xTemp); y.push(yTemp); dx.push(0); dy.push(5); gravity.push(1); bounceTime.push(1); } isSpawned = 1; } //Draws the various entities function draw(){ context = bouncingField.getContext('2d'); for(var i = 0; i &lt; x.length; i++){ //context.beginPath(); //context.fillStyle = "#00ccff"; //Draw circles of r = 25 at coordinates x and y //context.arc(x[i], y[i], 25, 0, Math.PI*2, true); context.drawImage(image, x[i], y[i], 50, 50); //context.closePath(); //context.fill(); } } //Repaints entities, essentially animating them function repaint(){ for(var i = 0; i &lt; x.length; i++){ context.clearRect(0, 0, 2000, 2000); if(x[i] &lt; 20 || x[i] &gt; width) dx[i] *= -1; if(y[i] &lt; 20 || y[i] &gt; height) { dy[i] *= -1; //We add bounceTime to dy so that it gradually loses speed dy[i] += bounceTime[i]; //Inverting graviy to slow down on rise gravity[i] *= -1; } x[i] += dx[i]; //Gravity affects the ball bounce speed, that gradually slows down. y[i] += dy[i] + gravity[i]; //bounceTime gradually reduces the amount of speed the ball has gravity[i] += 0.2 * bounceTime[i]; bounceTime[i] += 0.01; if(isSpawned){ draw(); } } } //Initializes Event.MOUSEMOVE to capture cursor coordinates function init(){ if(window.Event){ document.captureEvents(Event.MOUSEMOVE); } document.onmousemove = getCoordinates; } //Gets mouse coordinates and puts them into xTemp and yTemp function getCoordinates(e){ xTemp = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); yTemp = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollRight ? document.documentElement.scrollRight : document.body.scrollRight); xTemp -= 14; yTemp -= 14; } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ background-color: #555555; } #bouncingField{ border-style: solid; border-width: 10px; border-color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt; Wingin' it &lt;/TITLE&gt; &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt; &lt;link href="style.css" rel="stylesheet" type="text/css"&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;CANVAS id="bouncingField" width="0" height="0"&gt;&lt;/CANVAS&gt; &lt;/BODY&gt; &lt;/HTML&gt;</code></pre> </div> </div> </p> <p>I'm working on a simple JavaScript project to create bouncing balls that simulate gravity and that bounce off of the floor or the walls. The problem is that sometimes they clip into the floor and "spaz out" until they disappear from the screen. Any clue why? I've been trying to figure it out by adding a tiny time-out every time it collides but JS doesn't have sleep so I'm just confused now.</p> <p>Thank you in advance :)</p>
<p>I hope this helps. the tricky part is making a convincing "stop".</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getCoordinates(event) { return { x: event.offsetX, y: event.offsetY }; } function spawnBall(coords, x, y, dx, dy){ x.push(coords.x); y.push(coords.y); dx.push(0); dy.push(2); } // ========================= // Draws the various entities // ========================= function draw(canvas, image, x, y, width, height) { var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); for(var i = 0; i &lt; x.length; i++){ context.drawImage(image, x[i], y[i], width, height); } } // ========================= // ========================= // At the moment all this is concerned with is the "floor" // ========================= function move(x, y, dx, dy, gravity, bounciness, floor){ for(var i = 0; i &lt; x.length; i++){ // ========================= // Ball is close to the floor and not moving very fast, set it to rest // otherwise it bounces forever. // ========================= if (y[i] &gt;= floor - 10 &amp;&amp; Math.abs(dy[i]) &lt;= 2 * gravity) { dy[i] = 0; y[i] = floor; continue; } // ========================= // ========================= // Update the speed and position // ========================= dy[i] += gravity; y[i] += dy[i]; // ========================= // ========================= // Simulate a bounce if we "hit" the floor // ========================= if(y[i] &gt; floor) { y[i] = floor - (y[i] - floor); dy[i] = -1.0 * bounciness * dy[i]; } // ========================= } } // ========================= document.addEventListener("DOMContentLoaded", function(event){ var canvas = document.getElementById("bouncingField"); canvas.width = window.innerWidth - 50; canvas.height = window.innerHeight - 50; //Image to use as ball texture var image = new Image(); image.src = "http://www.freeiconspng.com/uploads/soccer-ball-icon-14.png"; var gravity = 1; var ballSize = 50; var ballBounciness = 0.8; var floor = canvas.height - ballSize; var x = []; var y = []; var dx = []; var dy = []; // ========================= // This can be done via requestAnimationFrame() // https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame // ========================= var isSpawned = false; setInterval(function(){ if(!isSpawned){ return; } move(x, y, dx, dy, gravity, ballBounciness, floor) draw(canvas, image, x, y, ballSize, ballSize); }, 10); // ========================= // ========================= // Add a ball // ========================= canvas.onclick = function(event) { isSpawned = true; var coords = getCoordinates(event); spawnBall(coords, x, y, dx, dy); } // ========================= });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #555555; } #bouncingField { border-style: solid; border-width: 10px; border-color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="bouncingField"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
Hive - insert values in array from file (comma and semicolon separated) <p>I have a file with columns separated by semicolons. I want to add a <code>type</code> column as an <code>Array&lt;String&gt;</code>. What I have now is that I store my values raw, just like this (the <code>type</code> column is text):</p> <pre><code>| age | type | country | 24 a us 29 a,b au &lt;--------- this line is not OK 25 a uk </code></pre> <p>My file is like the following:</p> <pre><code>age;type1,type2;country age;type1;country age;type2;country </code></pre> <p>How do I correctly put the types in my table as an <code>Array&lt;String&gt;</code>?</p>
<p>Same data will work. Create table :</p> <pre><code>CREATE TABLE array_data_type( age int, type array&lt;string&gt;, contry varchar(100)) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\;' COLLECTION ITEMS TERMINATED BY ','; </code></pre> <p>Load same data in this table.</p> <p>If this data is in a local file:</p> <pre><code>LOAD DATA LOCAL INPATH '&lt;file-path&gt;' INTO TABLE array_data_type; </code></pre> <p>or in case of HDFS file:</p> <pre><code>LOAD DATA INPATH '&lt;hdfs-file-path&gt;' INTO TABLE array_data_type; </code></pre>
Clear Div Content Inside Function <p>I have use 2 functions i want when i click on button it should clear the output of first function result but it doesnot work when i use .innerHTML = ""; how to do it?</p> <pre><code>function HalfRightTriangle() { for (var i = 1; i &lt;=7; i++) { for (var j = 1; j &lt;i; j++) { // document.write("*"); document.getElementById("result").innerHTML += "*"; } // end of inner for loop document.getElementById("result").innerHTML += "&lt;br&gt;"; } // end of outer for loop document.getElementById("result").innerHTML += ""; } // function end </code></pre> <blockquote> <p>Blockquote</p> </blockquote>
<p>If you're only using text, it may be better to just work with a variable, and then set it to innerHTML when done.</p> <p>Something like this:</p> <pre><code>function HalfRightTriangle() { var inner = document.getElementById("result").innerHTML; for (var i = 1; i &lt;= 7; i++) { for (var j = 1; j &lt; i; j++) { inner += "*"; } // end of inner for loop inner += "&lt;br&gt;"; } // end of outer for loop document.getElementById("result").innerHTML = inner; } // function end </code></pre>
Excel macro, search by row return next cell's value <p>I have this Macro already working:</p> <pre><code> Sub ListSheetsValuesAreOn() Dim X As Long, Data As Variant, Uniques As String, SH As Worksheet, NewSH As Worksheet With CreateObject("Scripting.Dictionary") For Each SH In Worksheets Data = Application.Transpose(SH.Range("C23", SH.Cells(Rows.Count, "C").End(xlUp))) For X = 1 To UBound(Data) If IsEmpty(.Item(Data(X))) Then .Item(Data(X)) = Data(X) &amp; "|" &amp; SH.Name ElseIf Data(X) = Split(.Item(Data(X)), "|")(0) And _ Not .Item(Data(X)) Like "*|*" &amp; SH.Name &amp; "*" Then .Item(Data(X)) = .Item(Data(X)) &amp; ", " &amp; SH.Name End If Next Next Sheets.Add After:=Sheets(Sheets.Count) Set NewSH = ActiveSheet NewSH.Range("A1").Resize(.Count) = Application.Transpose(.Items) End With NewSH.Name = "Result Sheet" NewSH.Columns("A").TextToColumns , xlDelimited, , , 0, 0, 0, 0, 1, "|" NewSH.Columns("A:B").AutoFit End Sub </code></pre> <p>What this script does is: Read values in C column and search all the workbook to find these values. Returning the values and the sheets where they've been found. But I want to return not each value in C but the next one in column D. Example:</p> <pre><code>Sheets 1...n Expected output (new sheet) C | D A | B item 1|description of item 1 description of item 1|1,4,6 item 2|description of item 2 description of item 2|3,7,11,12 ... | .... .... | ..... item m|description of item m description of item m| 5,9,15,24 </code></pre>
<p>Few caveats of below solution, I'm using columns A and B as sources, my data is not in need of transposition. </p> <pre><code>Sub Answer() Dim dict As Object Dim Data As Variant Dim ws As Worksheet Dim rng As Range Set dict = CreateObject("Scripting.Dictionary") With dict For Each SH In Worksheets Data = Application.Transpose(SH.Range("A1", SH.Cells(Rows.Count, "B").End(xlUp))) For X = LBound(Data, 1) To UBound(Data, 1) If IsEmpty(.Item(Data(X, 1))) Then .Item(Data(X, 1)) = Data(X, 2) &amp; "|" &amp; SH.Name ElseIf Data(X, 1) = Split(.Item(Data(X, 1)), "|")(0) And _ Not .Item(Data(X, 2)) Like "*|*" &amp; SH.Name &amp; "*" Then .Item(Data(X, 1)) = .Item(Data(X, 2)) &amp; ", " &amp; SH.Name End If Next X Next ' For Each ... End With ... End Sub </code></pre>
Any way for tornado handler to detect closure on other end? <p>I have a tornado coroutine hander that looks in part like:</p> <pre><code>class QueryHandler(tornado.web.RequestHandler): queryQueues = defaultdict(tornado.queues.Queue) @tornado.gen.coroutine def get(self, network): qq = self.queryQueues[network] query = yield qq.get() # do some work with with the dequeued query self.write(response) </code></pre> <p>On the client side, I use <code>python-requests</code> to long poll it:</p> <pre><code>fetched = session.get(QueryURL) </code></pre> <p>I can make a query, the server blocks waiting on the queue until cough up a something to process and finally respond.</p> <p>This works pretty slick until... the long poll gets shutdown and restarted while the handler is blocking on the queue. When I stop the query on the client side, the handler stays happily blocked. Worse if I restart the query on the client side, I now have a second handler instance blocking on the queue. So when the queue DOES have data show up, the stale handler processes it and replies to the bitbucket, and the restarted query is now blocked indefinitely.</p> <p>Is there a pattern I can use to avoid this? I had hoped that when the client side closed, the handler would receive some sort of exception indicating that things have gone south. The queue.get() can have a timeout, but what I really want is not a timeout but a sort of "unless I close" exception.</p>
<p>You want a "queue with guaranteed delivery" which is a hard problem in distributed systems. After all, even if "self.write" succeeds, you can't be certain the other end really received the message.</p> <p>A basic approach would look like this:</p> <ul> <li>each entry in the queue gets an id greater than all previous ids</li> <li>when the client connects it asks to subscribe to the queue</li> <li>when a client is disconnected, it reconnects and asks for all entries with ids greater than the last id it saw</li> <li>when your QueryHandler receives a <code>get</code> with a non-<code>None</code> id, it first serves all entries with ids greater than id, then begins waiting on the queue</li> <li>when your QueryHandler raises an exception from <code>self.write</code>, ignore it: the client is responsible for retrieving the lost entry</li> <li>keep all past entries in a list</li> <li>expire the oldest list entries after some time (hours?)</li> </ul>
PySpark: How to group a column as a list when joining two spark dataframes? <p>I want to join the following spark dataframes on Name:</p> <pre><code>df1 = spark.createDataFrame([("Mark", 68), ("John", 59), ("Mary", 49)], ['Name', 'Weight']) df2 = spark.createDataFrame([(31, "Mark"), (32, "Mark"), (41, "John"), (42, "John"), (43, "John")],[ 'Age', 'Name']) </code></pre> <p>but I want the result to be the following dataframe:</p> <pre><code>df3 = spark.createDataFrame([([31, 32], "Mark", 68), ([41, 42, 43], "John", 59), `(None, "Mary", 49)],[ 'Age', 'Name', 'Weight']) </code></pre>
<p>A DataFrame is equivalent to a relational table in Spark SQL. You can groupBy, join, then select.</p> <pre><code>from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.functions import * sc = SparkContext() sql = SQLContext(sc) df1 = sql.createDataFrame([("Mark", 68), ("John", 59), ("Mary", 49)], ['Name', \ 'Weight']) df2 = sql.createDataFrame([(31, "Mark"), (32, "Mark"), (41, "John"), (42, "John\ "), (43, "John")],[ 'Age', 'Name']) grouped = df2.groupBy(['Name']).agg(collect_list("Age").alias('age_list')) joined_df = df1.join(grouped, df1.Name == grouped.Name, 'left_outer') print(joined_df.select(grouped.age_list, df1.Name, df1.Weight).collect()) </code></pre> <p>Result</p> <pre><code>[Row(age_list=None, Name=u'Mary', Weight=49), Row(age_list=[31, 32], Name=u'Mark', Weight=68), Row(age_list=[41, 42, 43], Name=u'John', Weight=59)] </code></pre>
Spring mvc, RedirectAttributes not working <p>I am trying RedirectAttributes in my webapp, But some how its not picking up my error message, here is my code and error messages.</p> <p>its MyUtil class </p> <pre><code> @Component public class MyUtil { @Autowired public MyUtil(MessageSource messageSource) { MyUtil.messageSource = messageSource; } public static void flash(RedirectAttributes redirectAttributes, String kind, String messageKey) { redirectAttributes.addFlashAttribute("flashKind", kind); redirectAttributes.addFlashAttribute("flashMessage", MyUtil.getMessage(messageKey)); } private static MessageSource messageSource; public static String getMessage(String messageKey, Object... args) { return messageSource.getMessage(messageKey, args, Locale.getDefault()); } } </code></pre> <p>and here is my controller's post method</p> <pre><code> @RequestMapping(value="/", method=RequestMethod.POST) public String homePost(@ModelAttribute("signupForm") @Valid SignupForm signupForm, BindingResult result, ModelMap model, RedirectAttributes redirectAttributes) { if(result.hasErrors()) { MyUtil.flash(redirectAttributes, "success","registerError"); return "redirect:/"; } subserv.subscriber(signupForm); model.addAttribute("name", signupForm.getName()); return "subscribers"; </code></pre> <p>its my message.properties</p> <pre><code> registerError=e-mail already Registered. </code></pre> <p>and here is my error message</p> <pre><code> org.springframework.context.NoSuchMessageException: No message found under code 'regsiterError' for locale 'en_IN'. at org.springframework.context.support.DelegatingMessageSource.getMessage(DelegatingMessageSource.java:69) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE] at com.example.util.MyUtil.getMessage(MyUtil.java:30) ~[classes/:na] at com.example.util.MyUtil.flash(MyUtil.java:23) ~[classes/:na] at com.example.controller.RootController.homePost(RootController.java:59) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410) [tomcat-embed-core-8.5.5.jar:8.5.5] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.5.jar:8.5.5] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_101] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_101] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.5.jar:8.5.5] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101] </code></pre>
<p>It looks like the cause is just a typo <code>registerError</code> vs <code>regiterError</code></p> <p><strong>new stacktrace same problem</strong></p> <p>again, you have the same problem: <code>registerError</code> vs <code>regsiterError</code> (wrong order of <code>i</code> and <code>s</code>)</p>
Mongoose & MongoDB: Retrieve results narrowed by multiple parameters <p>I need to get data from MongoDB that is first narrowed by one initial category, say '{clothing : pants}' and then a subsequent search for pants of a specific size, using an array like sizes = ['s','lg','6', '12'].</p> <p>I need to return all of the results where 'pants' matches those 'sizes'.</p> <p>I've started a search with: </p> <pre><code> Product.find({$and:[{categories:req.body.category, size:{$in:req.body.sizes}}]}, function(err, products) { if (err) { console.log(err); } return res.send(products) }); </code></pre> <p>I really don't know where to go from there. I've been all over the Mongoose docs. </p> <p>Some direction would be very helpful.</p>
<p>The mongoose queries can receive object like Mongodb would. So you can pass the search parameters separated by <code>,</code></p> <pre><code>Product.find({categories:req.body.category, size:{$in:['s','lg','6', '12']}}) </code></pre> <p>For more information on $in, check <a href="https://docs.mongodb.com/manual/reference/operator/query/in/" rel="nofollow">here</a></p> <p>For more information on $and operator, check <a href="https://docs.mongodb.com/manual/reference/operator/query/and/" rel="nofollow">here</a> (note we can ommit the $and operator in some cases and that is what I did)</p>
Running a program in linux (debian) on startup <p>I would like to point out that I tried A LOT of different tutorials from the internet but they don't seem to work...</p> <p>Adding stuff to init.d, rc.local etc. for some reason it doesn't work.</p> <p>I'm really desperate to get this done, but I'm a total noob when it comes to linux.</p> <p>when I type in "matchbox-keyboard" it runs just fine and as intended. </p> <p>That's literally all I want, but I'd like to run it every time so when I turn my raspberry pi on, I won't have to connect a keyboard and a mouse to initialize on-screen keyboard.</p> <p>Is there a simple way to get this done, something like dropping the program into autostart folder in windows?</p> <p>I have no experience with linux at all, I don't know how to write scrips and all that stuff and all I want is to run this "matchbox-keyboard" after every reboot...</p> <p>Please help me, I'm really desperate and I can't figure it out. Spent all day doing it and still nothing...</p>
<p>The simplest way is to drop in a new cronjob (a cronjob is a task that is scheduled to run at a particular time):</p> <pre><code>crontab -e </code></pre> <p>This allows you to edit your cron file. Instead of putting in a time, use <code>@reboot</code>. So you should have a new line in your cronjob file that looks like this:</p> <pre><code>@reboot matchbox-keyboard </code></pre> <p>The cronjobs run in a different environment from your login environment, so you may need to use the full path to the program. I'm also not familiar with the <code>matchbox-keyboard</code> program, but it looks like it will run fine since it can run as a background process.</p>
Which fopen() mode should i use when working with a .wav file? <p>I am using <code>fPointInput = fopen(fileName, "r");</code>, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?</p>
<p>This <a href="http://truelogic.org/wordpress/2015/09/04/parsing-a-wav-file-in-c/" rel="nofollow">article</a> indicates that using <code>rb</code> works well. Note that nothing in this answer is <code>Windows</code> specific. Just standard <code>C</code> IO.</p>
Session variable is not sent in Laravel 5 <p>I have a Laravel Application, and something strange is happening related to the session variables. I have a method in a controller that checks some inputs and depending of some conditions it decides if continues or just return back (and right here where is my problem), when I make <code>return redirect()-&gt;back()</code> I want so send a variable that is a Json, so briefly I have this:</p> <pre><code>$msg=json_encode([ 'status' =&gt; 'failed', 'field'=&gt;'mail' ]); return redirect()-&gt;back()-&gt;with('msg',$msg); </code></pre> <p>So, it redirects very well, but then in the view I have:</p> <pre><code>@if ( Session::has('msg') ) //come stuffs @endif </code></pre> <p>But it seems likes the <code>msg</code> variable is not passed. According to the Laravel documentation when one uses <code>redirect back</code> the variables are accesible trough <code>Session</code></p>
<p>Its' working for me when I tested. Maybe your session is not storing data. Please check whether your session is working or not. My tested output</p> <pre><code> @if ( Session::has('msg') ) {{ session('msg') }} @endif </code></pre> <p><a href="https://i.stack.imgur.com/tiLys.png" rel="nofollow"><img src="https://i.stack.imgur.com/tiLys.png" alt="enter image description here"></a></p>
Running ASP.NET app in VS 2015 debugger with firefox throws login failed for user: NT AUTHORITY/ANONYMOUS LOGON <p>The debug session with VS2015 on my developer workstation works with chrome and connects to the external SQL Server 2012 database from my web app. I cannot figure out why firefox causes this error while in the debugger in the attempt to make a db connection. </p> <p>Firefox works otherwise with this web app in IIS from the webserver which by the way also contains the database on the same server when running outside of VS 2015.</p> <p>What am I missing and why would chrome work but not firefox while debugging in VS 2015 in connecting to the database with integrated security turned on</p> <p>Everything I see on the internet has to do with this issue when running the web app in IIS and the database on an external server with double hop issues. My problem is running from the debugger and only firefox not working! We need to have firefox working for reasons beyond the scope of my question in the debugger.</p> <p>Has anyone seen anything like this before? Thanks!</p> <p>Here is my connection string from my web.config (I also tried with Integrated Security=true)</p> <p> </p> <p>Here is a code snippet where the cmd.Connection.Open() throws the exception</p> <p>Dim cmd As SqlCommand = GetSqlCommand(GetSelectForBlackPearlPersonal(whereClause, orderBy))</p> <p>Try Using cmd.Connection cmd.Connection.Open() . . . End Using Catch ex As Exception</p> <pre><code> Throw New Exception("Database issue: " &amp; ex.ToString) </code></pre> <p>End Try</p>
<p>I found in another post that someone set impersonation to false in their web.config.</p> <p>I just changed the impersonate setting from true to false and now its working on firefox in the debugger</p> <p></p> <p>I am baffled....Does anyone know why this would be the case? thanks! Kevin</p>
Reusing cell doesn't work well - TableView <p>I have a problem about my cell's button. In my tableView each row is composed by: an image, some labels and a button. The button has a checkmark image. When it is clicked, the button's image changes. The problem is that also another button's image changes without reason. This mistake happens because my cell is reused. </p> <p>I have tried to use <code>prepareForReuse</code> method in TableViewCell but nothing happens. I've also tried with <code>selectedRowAt</code> but I didn't have any results. Please help me.</p> <p><strong>Image 1:</strong></p> <p><a href="https://i.stack.imgur.com/5ZP45.png" rel="nofollow"><img src="https://i.stack.imgur.com/5ZP45.png" alt="Image 1"></a></p> <p><strong>Image 2:</strong> </p> <p><a href="https://i.stack.imgur.com/D3ilf.png" rel="nofollow"><img src="https://i.stack.imgur.com/D3ilf.png" alt="Image 2"></a></p> <p>This is my func in my <code>custom Cell:</code></p> <pre><code> override func prepareForReuse() { if checkStr == "uncheck"{ self.checkBook.setImage(uncheck, for: .normal) } else if checkStr == "check"{ self.checkBook.setImage(check, for: .normal) } } func isPressed(){ let uncheck = UIImage(named:"uncheck") let check = UIImage(named: "check") if self.checkBook.currentImage == uncheck{ checkStr == "check" } else self.checkBook.currentImage == check{ checkStr == "uncheck" } } </code></pre> <p>In my <code>tableView</code>:</p> <pre><code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell: ListPropertyUserCell = tableView.cellForRow(at: indexPath) as! ListPropertyUserCell let uncheck = UIImage(named:"uncheck") let check = UIImage(named: "check") if selectedCell.checkBook.imageView?.image == uncheck{ selectedCell.checkStr = "check" } else if selectedCell.checkBook.imageView?.image == check{ selectedCell.checkStr = "uncheck" } } </code></pre>
<p>From the information in your post, this looks like a cell reuse issue. The problem is that the <code>tableView</code> reuses the cells rather than creating new ones, to maintain performance. If you haven't reset the cell's state, the reused cell will be remain configured in the old state.</p> <p>For a quick fix, you can implement the <code>prepareForReuse</code> method on <code>UITableViewCell</code>. </p> <p>However, you'll need to store which cell is 'checked' in your view controller if you want the checkbox to be selected after scrolling the tableView. You can store this yourself, or use the tableView's <code>didSelectRowAtIndexPath</code> method. </p>
Can I use native mqtt to connect to my mqtt broker without the use of websockets? <p>I have a mqtt broker which does not support websocket connection. I need to write an HTML webpage that will connect to the broker and publish a message string on it. Is it possible to not use websockets through my web page and still connect and publish data? If so, how can I do that?</p>
<p>No, you can not connect to anything from with in a browser with anything other than HTTP or WebSockets.</p> <p>A possible solution is to set up a separate WebSockets to MQTT bridge between the web page and the broker.</p>
Ionic2 ion-slides change navbar title <p>I'm trying to change the navbar title using the slides. When swiping through a next slide, how can I achieve this? I tried:</p> <pre><code>onSlideChangeStart(slider) { this.app.setTitle('title1'); } </code></pre> <p>But it just sets the title in the browser, not in the ion-title tag. And I want to set the title according to the slide that is displaying.</p> <p>This is my code:</p> <pre><code>&lt;ion-header&gt; &lt;ion-navbar color="navh" no-border-bottom&gt; &lt;ion-title&gt;title&lt;/ion-title&gt; &lt;/ion-navbar&gt; &lt;/ion-header&gt; &lt;ion-content no-bounce &gt; &lt;ion-slides [options]="mySlideOptions (ionWillChange)="onSlideChangeStart($event)"&gt; &lt;ion-slide&gt; &lt;img #title1 src="assets/img/1.png" &gt; &lt;/ion-slide&gt; &lt;ion-slide&gt; &lt;img #title2 src="assets/img/2.png" &gt; &lt;/ion-slide&gt; &lt;ion-slide&gt; &lt;img #title3 src="assets/img/3.png" &gt; &lt;/ion-slide&gt; &lt;/ion-slides&gt; &lt;/ion-content&gt; </code></pre>
<p>What about using a variable to set the title?</p> <pre><code>import { ViewChild } from '@angular/core'; @Component({ templateUrl:"home.html" }) export class YourAwesomePage { @ViewChild('mySlider') slider: Slides; public title: string; // ... constructor() { this.title = 'Initial title'; // ... } onSlideChangeStart(slide) { // You can use the slide parameter to get info from it or just use the slider reference to know the index of the active slide let currentIndex = this.slider.getActiveIndex(); this.title = "Slider " + currentIndex; } } </code></pre> <p>And then in your view:</p> <pre><code>&lt;ion-header&gt; &lt;ion-navbar color="navh" no-border-bottom&gt; &lt;ion-title&gt;{{ title }}&lt;/ion-title&gt; &lt;/ion-navbar&gt; &lt;/ion-header&gt; &lt;ion-content no-bounce &gt; &lt;ion-slides #mySlider [options]="mySlideOptions" (ionWillChange)="onSlideChangeStart($event)"&gt; &lt;ion-slide&gt; &lt;img #title1 src="assets/img/1.png" &gt; &lt;/ion-slide&gt; &lt;ion-slide&gt; &lt;img #title2 src="assets/img/2.png" &gt; &lt;/ion-slide&gt; &lt;ion-slide&gt; &lt;img #title3 src="assets/img/3.png" &gt; &lt;/ion-slide&gt; &lt;/ion-slides&gt; &lt;/ion-content&gt; </code></pre>
Attempt to invoke interface method on a null object reference <p>I have class <strong>LoadJSONTask</strong>. In this class I am getting the error below. My application is running but when I try to add progress bar in the code its not working.</p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: in.kalakaaristudios.json.listviewmenu, PID: 3809 java.lang.NullPointerException: Attempt to invoke interface method 'void in.kalakaaristudios.json.listviewmenu.LoadJSONTask$Listener.onLoaded(java.util.List)' on a null object reference at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.onPostExecute(LoadJSONTask.java:83) at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.access$dispatch(LoadJSONTask.java) at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:0) at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:21) at android.os.AsyncTask.finish(AsyncTask.java:651) at android.os.AsyncTask.access$500(AsyncTask.java:180) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5441) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) </code></pre> <p><strong>LoadJSONTask class</strong></p> <pre><code>package in.kalakaaristudios.json.listviewmenu; import android.os.AsyncTask; import android.view.View; import android.widget.ProgressBar; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class LoadJSONTask extends AsyncTask&lt;String, Void, Response&gt; { private MainActivity activity; private ProgressBar dwBar; public LoadJSONTask(MainActivity activity) { this.activity = activity; dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar); } public LoadJSONTask(Listener listener) { mListener = listener; } public interface Listener { void onLoaded(List&lt;AndroidVersion&gt; androidList); void onError(); } private Listener mListener; @Override protected Response doInBackground(String... strings) { try { String stringResponse = loadJSON(strings[0]); Gson gson = new Gson(); return gson.fromJson(stringResponse, Response.class); } catch (IOException e) { e.printStackTrace(); return null; } catch (JsonSyntaxException e) { e.printStackTrace(); return null; } } @Override protected void onPreExecute() { super.onPreExecute(); MainActivity mn = new MainActivity(); dwBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Response response) { dwBar.setVisibility(View.GONE); if (response != null) { mListener.onLoaded(response.getAndroid());//getting error here } else { mListener.onError(); } } private String loadJSON(String jsonURL) throws IOException { URL url = new URL(jsonURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString(); } } </code></pre> <p><strong>MainActivity.java</strong></p> <pre><code>package in.kalakaaristudios.json.listviewmenu; import android.os.AsyncTask; import android.view.View; import android.widget.ProgressBar; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class LoadJSONTask extends AsyncTask&lt;String, Void, Response&gt; { private MainActivity activity; private ProgressBar dwBar; public LoadJSONTask(MainActivity activity) { this.activity = activity; dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar); } public LoadJSONTask(Listener listener) { mListener = listener; } public interface Listener { void onLoaded(List&lt;AndroidVersion&gt; androidList); void onError(); } private Listener mListener; @Override protected Response doInBackground(String... strings) { try { String stringResponse = loadJSON(strings[0]); Gson gson = new Gson(); return gson.fromJson(stringResponse, Response.class); } catch (IOException e) { e.printStackTrace(); return null; } catch (JsonSyntaxException e) { e.printStackTrace(); return null; } } @Override protected void onPreExecute() { super.onPreExecute(); MainActivity mn = new MainActivity(); dwBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Response response) { dwBar.setVisibility(View.GONE); if (response != null) { mListener.onLoaded(response.getAndroid()); } else { mListener.onError(); } } private String loadJSON(String jsonURL) throws IOException { URL url = new URL(jsonURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString(); } } </code></pre>
<p>I think your issue is on this line</p> <pre><code>dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar); </code></pre> <p>because you are using the activity class instance to obtain a reference to your ProgressBar View widget</p> <p>You should inflate a layout that contains the ProgressBar widget and use the find to get an instance of your ProgressBar</p> <pre><code>View view = inflater.inflate(R.Layout_that_contains_progress_bar, null); dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar); </code></pre> <p>Alternatively, you can create ProgressBar programmatically like below</p> <pre><code>dwBar = new ProgressBar(activity); </code></pre>
Image format dropdown when using <input type=“file”>? <p>I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the element in HTML. I have a feeling it's impossible, but I'd like to know if there is a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.</p> <p>Currently, i have<br> <code>&lt;form:input path="image" type="file" accept="image/*" style="display: none;"/&gt;</code></p> <p>And it display like below,</p> <p><a href="https://i.stack.imgur.com/VLDE6.png" rel="nofollow"><img src="https://i.stack.imgur.com/VLDE6.png" alt="enter image description here"></a></p> <p>But i need to display like what we have in our mspaint.</p> <p><a href="https://i.stack.imgur.com/1JEdr.png" rel="nofollow"><img src="https://i.stack.imgur.com/1JEdr.png" alt="enter image description here"></a></p>
<p>You can only do something like this</p> <pre><code>&lt;form:input path="image" type="file" accept="image/gif, image/jpeg, image/png" style="display: none;"/&gt; </code></pre> <p>But this won't give you the list you're looking for.</p> <p>Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.</p>
Animating UIScrollView rightwards <p>How to create an animation that moves/scrolls a seeable image section at an uniform speed rightwards? OR rather: How to animate UIScrollView rightwards?</p> <p>Example: The image width is 4968 px. The image is used as a fullscreen background image. Only the first 1242px of the 4968px (image width) should be seeable at the beginning. The seeable image section should move at an uniform speed rightwards. At any time, 1242px of the image are visible. When the end of the image is reached this process should be iterated.</p> <p><a href="https://i.stack.imgur.com/sswQe.png" rel="nofollow"><img src="https://i.stack.imgur.com/sswQe.png" alt="Visualisation of my question"></a></p> <p>Here's my code so far. It is not useful to understand what I want to accomplish because it's incomplete, but you see that I used it in the function update and so on.</p> <pre><code>override func update(_ currentTime: TimeInterval) { if gameStarted == true { enumerateChildNodes(withName: "background", using: ({ (node, error) in let bg = node as! SKSpriteNode bg.position = CGPoint(x: bg.position.x - 2, y: bg.position.y) } })) } } </code></pre>
<p>You can animate its <code>contentOffset</code> property</p> <pre><code>@IBOutlet weak var scrollView: UIScrollView! override func viewDidAppear(animated: Bool) { // This code scrolls to the point (x: 4000, y:0) in 5 seconds UIView.animateWithDuration(5) { [unowned self] in self.scrollView.contentOffset = CGPoint(x: 4000, y: 0) } } </code></pre>
Why would a function output different results when executing as a SQL Server CLR UDF? <p>I'm using a .Net DLL to hash strings so later I can compare them.</p> <p>I've wrapped the call to that function inside a SQL Server CLR UDF and published on the server.</p> <p>Now, when I execute the function the output is different than the one I get when running a Console Application.</p> <p>Function signature is as follows:</p> <pre><code>[Microsoft.SqlServer.Server.SqlFunction] public static SqlInt32 CalculateHash(SqlString input) { string unwrappedValue = input.Value.Normalize(); int hash = HashCalculator.Calculate(unwrappedValue); return new SqlInt32(hash); } </code></pre> <p>As you can see, I'm unwrapping and normalizing the string before even calculating the hash. So, I would expect the results to be the same no matter where I'm calling that code from.</p> <p>Given the string <strong>Test 123</strong> i'm getting:</p> <pre><code>-387939562 - When running from a Console Application 137570918 - When calling from SQL Server </code></pre> <p>SQL Server UDF does not allow <strong>Debug.Print</strong> (or similar) calls.</p> <p>And for some reason, Visual Studio won't stop at the *.cs files breakpoints when debugging the UDF (but that's a different problem I'm still trying to igure out).</p> <p>My question is: Why would the same function give two different results? What goes with the UDF that could be causing this? I even tried changing collation from the database but it does not affect the function's result.</p> <p>Edit: I managed the step into the code when running the sql query and found out that the method String.GetHashCode() is returning a different value when running inside SQL Server. In any case, I'd assumed any charset-like problem would go away since I normalize the string before using it.</p> <p>Edit 2: Given that GetHashCode seemed to be the problem, I've checked the code for it here:</p> <p><a href="http://stackoverflow.com/questions/15174477/how-is-gethashcode-of-c-sharp-string-implemented">How is GetHashCode() of C# string implemented?</a></p> <p>And found out that the .net implementation differs from running 32bits x 64bits. When I put my Console to run in 64bit mode, the output result is the same I got in SQL Server.</p>
<p>Once I managed to debug the UDF running on SQL Server I was finally able to figure out that the algorithm I'm using to hash a given string relies on .net's <strong>GetHashCode</strong> method.</p> <p>And at least for the <strong>String</strong> class, as per <a href="http://stackoverflow.com/questions/15174477/how-is-gethashcode-of-c-sharp-string-implemented">this question</a>, the original implementation gives different results for 32 and 64 bit platforms.</p> <p>So, when I was running on the Console application to test the functionality, it ended up running as a 32 bit application. But SQL Server installed is 64 bits, forcing the other implementation for GetHashCode to run.</p> <p>I was able to replicate SQL Server's results by forcing the Console application to run as a 64bit application.</p> <p>Then, it was only a matter of tweaking the parameters so that 32bit and 64bit platforms give a similar (but not equal) result.</p>
change an object variable from other object(delegation) <p>I am using python to implement something like following. </p> <p>sample1.py</p> <pre><code>Class D: def __ini__(self): return def disconnect(self): ## I want to change isConnected in A, but I can not do something like A.isConnected = False here. I want to use delegation. return </code></pre> <p>sample2.py</p> <pre><code>Class B(A): Class C(D): def _init_(self): super(B.C,self)._init_() def foo(): if self.isConnected: print "error" def __init__(self): super(C, self).__init__() </code></pre> <p>sample3.py</p> <pre><code>Class A(Object): def __init__(self): self.isConnected = False </code></pre> <p>Whenever D.disconnect() is executed, I want to change A.isConnected value. If i am not allowed to call A.isConnected = False. How can I use delegation to achieve my goal. </p> <p>It would be great if you can provide some hints or suggestions.</p> <p>Thanks </p>
<p>I'm unclear on your objective. Sounds like you want to edit a variable before it is created. </p> <p>If that is not the case, you should be able to change A.isConnected with the following code: </p> <p><code>A.isConnected = True</code></p>
how can I construct my mongoose query so that at least one of two statements is always taken under consideration? <p>In my application user can add entry that is visible </p> <p>This is my mongoose query:</p> <blockquote> <p>Mongoose: test.find({updated_at: { '$gte': new Date("Fri, 14 Oct 2011 00:00:00 GMT"), '$lte': new Date("Fri, 14 Oct 2016 20:12:14 GMT") }, username: { '$in': [ 'XXXXXXXXX', 'YYYYYYYYYYYYYY' ] }, '$or': [ { myFlag: false } ] }) { fields: undefined }</p> </blockquote> <p>and this is how I construct it:</p> <pre><code> if (friends != undefined) { var friendsSplitted = friends.split(","); query = query.where("username").in(friendsSplitted); } if (publicEntries != undefined &amp;&amp; publicEntries === "true") { query = query.or({myFlag: false}); } </code></pre> <p>This query basically says:</p> <blockquote> <p>look for all content that belongs to your friends OR for any content that has myFlag set up to false.</p> </blockquote> <p>I want to change it so that is says:</p> <blockquote> <p>look for all content that belongs to your friends AND ALSO for any content that has myFlag set up to false (BUT NOT necessarily belongs to your friends). </p> </blockquote> <p>Can you help me with that?</p>
<p>You should try both queries inside $or as below:</p> <pre><code>test.find({'$or': [ { myFlag: false }, {updated_at: { '$gte': new Date("Fri, 14 Oct 2011 00:00:00 GMT"), '$lte': new Date("Fri, 14 Oct 2016 20:12:14 GMT") }, username: { '$in': [ 'XXXXXXXXX', 'YYYYYYYYYYYYYY' ] } ] }) </code></pre> <p>Hope this helps!</p> <p>comment me if i missed something.</p>
Php block access without redirected .htaccess <p>With htaccess im redirecting:</p> <pre><code>RewriteRule ^secure/ login.php [NC,L] </code></pre> <p>I only want people to be allowed to visit: <code>website.com/secure/</code> But not: <code>website.com/login.php</code></p> <p>Anyone got an idea how to do this? Possibly in php?</p>
<p>You can use:</p> <pre><code>RewriteEngine On # block direct access to /login.php # RewriteRule ^ - [F] line sends status 403 when RewriteCond succeeds. RewriteCond %{THE_REQUEST} /login\.php[\s?/] [NC] RewriteRule ^ - [F] # internally rewrite /secure to /login.php RewriteRule ^secure/?$ login.php [NC,L] </code></pre> <p>First rule is using <code>THE_REQUEST</code> variable. <code>THE_REQUEST</code> variable represents original request received by Apache from your browser and it <strong>doesn't get overwritten</strong> after execution of some rewrite rules. Example value of this variable is <code>GET /index.php?id=123 HTTP/1.1</code></p>
Getting an error in a Do Loop <p>This is a small bit of code which has the error I am having. The SQL Statement at the begginning is this</p> <pre><code>sqlStr = "SELECT Computer, Room_Num, Speed, Num_CPUs, OS_Type, HDD_Size FROM Computers WHERE Num_CPUs = 1 OR Speed &lt; 2.1 OR HDD_Size &lt; 300 ORDER BY Room_Num" Do Until objRecordSet.EOF recordsStr = recordsStr &amp; objRecordSet.Fields.Item("Computer").Value &amp; _ vbTab &amp; pad(objRecordSet.Fields.Item("HostName").Value,12) &amp; _ vbTab &amp; pad(objRecordSet.Fields.Item("Room_Num").Value,14) &amp; _ vbTab &amp; objRecordSet.Fields.Item("CPU_Type").Value &amp; _ vbTab &amp; objRecordSet.Fields.Item("Speed").Value &amp; _ vbTab &amp; objRecordSet.Fields.Item("Num_CPUs").Value &amp; _ vbTab &amp; objRecordSet.Fields.Item("Bit_Size").Value &amp; _ vbTab &amp; pad(objRecordSet.Fields.Item("OS_Type").Value,12) &amp; _ vbTab &amp; objRecordSet.Fields.Item("Memory").Value &amp; _ vbTab &amp; objRecordSet.Fields.Item("HDD_Size").Value &amp; vbCrLf objRecordSet.MoveNext </code></pre> <p>Having the error on the second line:</p> <pre><code>recordsStr = recordsStr &amp; objRecordSet.Fields.Item("Computer").Value &amp; _ </code></pre> <p>The error is:</p> <blockquote> <p>Item Cannot be found in the collection corresponding to the requested name or ordinal.</p> </blockquote> <p>Ok somehow i fixed that error, now getting a new one on a line of code that i did not even touch...</p> <pre><code>Set objConnection = CreateObject("ADODB.Connection") objConnection.Open dataSource Set objRecordSet = CreateObject("ADODB.Recordset") objRecordSet.Open sqlStr , objConnection objRecordSet.MoveFirst </code></pre> <p>Getting an error in the line</p> <pre><code>objRecordSet.Open sqlStr , objConnection </code></pre> <p>Data type mismatch in criteria expression</p>
<p>In your query:</p> <pre><code>sqlStr = "SELECT Computer, Room_Num, Speed, Num_CPUs, OS_Type, HDD_Size FROM Computers WHERE Num_CPUs = 1 OR Speed &lt; 2.1 OR HDD_Size &lt; 300 ORDER BY Room_Num" </code></pre> <p>You bring through the following fields, <code>computer, room_num, speed, num_cpus, os_type, and hdd_size</code> But... in your Do loop you try to get <code>Computer, Hostname, Room_Num, Cpu_Type, Speed, Num_CPUs, Bit_Size, OS_Type, Memory, HDD_Size</code></p> <p>Notice here that <code>Hostname, bit_size, and memory</code> are not present in your query. You can't request those from your recordset because they aren't in your recordset because they are not in your query. Try:</p> <pre><code>sqlStr = "SELECT Computer, Room_Num, Speed, Num_CPUs, OS_Type, HDD_Size, Hostname, Bit_size, memory FROM Computers WHERE Num_CPUs = 1 OR Speed &lt; 2.1 OR HDD_Size &lt; 300 ORDER BY Room_Num" </code></pre> <p>And assuming those are available in your <code>computers</code> table, it will start working.</p>
Vue JS use array to filterBy another array? <p>Yep, it's me again. I'm trying to filter an array based on an array of strings. So while a single string filter is easy with Vue...</p> <p><code>&lt;div v-for="item in items | filterBy 'words' in 'property'"&gt;</code></p> <p>...multiple search strings becomes more complex. There's been several questions about how to do this on StackOverflow already, but very few answers. Currently I'm trying to repurpose the custom filter found <a href="http://stackoverflow.com/questions/37431062/vue-js-filterby-array-as-searchtext">here</a> for my needs, but it's not working.</p> <p><strong>My use case:</strong> I have an array of groups (checkboxes) that the user can select to filter an array of people. Each person is assigned to one or more groups so if <em>any</em> one of their groups is selected by the user, that person should show up.</p> <p>So my templates look like this:</p> <pre><code> &lt;template v-for="group in ensemble_groups"&gt; &lt;input name="select_group[]" id="group_@{{ $index }}" :value="group" v-model="selected_groups" type="checkbox"&gt; &lt;label for="group_@{{ $index }}"&gt;@{{ group }}&lt;/label&gt; &lt;/template&gt; &lt;template v-for="person in cast | filterBy selectGroups"&gt; &lt;div&gt;@{{ person.actor_name }}&lt;/div&gt; &lt;/template&gt; </code></pre> <p>You see my custom filter <code>selectGroups</code> there? Here's my Vue arrays:</p> <pre><code> selected_groups: [], ensemble_groups: ["Leads","Understudies","Children","Ensemble"], cast: [ { actor_name: "Dave", groups: ["Leads"], }, { actor_name: "Jill", groups: ["Leads"], }, { actor_name: "Sam", groups: ["Children","Ensemble"], }, { actor_name: "Austin", groups: ["Understudies","Ensemble"], }, ], </code></pre> <p>And finally here's the custom filter. I can't tell if it's even being triggered or not, because when I click on a group checkbox, nothing happens.</p> <pre><code>filters: { selectGroups: function() { if (!selected_groups || selected_groups.length === 0) { return cast; } return this.recursiveFilter(cast, selected_groups, 0); } }, methods: { recursiveFilter: function(cast, selected_groups, currentPosition) { if (currentPosition+1 &gt; selected_groups.length) return cast; var new_cast; new_cast = cast.filter(function(person) { for (group of person.groups) { if (group.value == selected_groups[currentPosition]) return true; } }); return this.recursiveFilter(new_cast, selected_groups, currentPosition+1); } } </code></pre> <p>So if the user selects <code>Leads</code> only Dave and Jill should appear. If the user then checks <code>Children</code>, Dave, Jill, and Sam should appear. I'm so close!</p>
<p>I would use a computed property instead of a filter and a method.</p> <p>I'd go through each cast member and if any of their groups is in <code>selected_groups</code> I'd allow it through the filter. I'd so this using <code>Array.some</code>.</p> <pre><code>results: function() { var self = this return self.cast.filter(function(person) { return person.groups.some(function(group) { return self.selected_groups.indexOf(group) !== 1 }) }) }, </code></pre> <p>Here's a quick demo I set up, might be useful: <a href="http://jsfiddle.net/crswll/df4Lnuw6/8/" rel="nofollow">http://jsfiddle.net/crswll/df4Lnuw6/8/</a></p>
How to display values with decimal places in Grafana with elasticsearch datasource? <p>I am trying to visualize time series data stored in elastic search using grafana. I have the legend setup to show 2 decimal places but it does not reflect in the UI. <p> The decimal places show up for other dashboard panels with a tsdb datasource. So this issue is specific to using grafana with elasticsearch. Is there any other configuration setup I am missing here which will help me achieve this?</p> <p><a href="https://i.stack.imgur.com/Gh4I1.png" rel="nofollow"><img src="https://i.stack.imgur.com/Gh4I1.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/apLAP.png" rel="nofollow"><img src="https://i.stack.imgur.com/apLAP.png" alt="enter image description here"></a></p>
<p>Just found out that elastic search does not allow displaying values without some sort of aggregation and in my case aggregation is resulting in values getting rounded.</p> <p>There was a related request which seemed to not get much traction in kibana. <a href="https://github.com/elastic/kibana/issues/3572" rel="nofollow">https://github.com/elastic/kibana/issues/3572</a></p> <p>In short not feasible as of [2.x] elastic search.</p>
Cannot set bartintcolor on iPhone 6 plus <p>So my problem is that I cannot set the bar tint color on an iPhone 6 plus. I can set the bar tint color for all other devices but for the iPhone 6 plus the bar tint won't change. Here is the code for the view controller. Additionally, this VC is being pushed onto the stack by a navigation controller. Any help is majorly appreciated all.</p> <pre><code>override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = .redColor() navigationController?.navigationBar.translucent = false navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] navigationController?.navigationBar.tintColor = UIColor.whiteColor() } </code></pre> <p>This is the only thing that I am doing in the view controller and it doesn't work at all.</p>
<p>Ok so I solved the issue. For some reason, iPhone 6 plus calls </p> <pre><code>override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() navigationController?.navigationBar.barTintColor = .primaryGrayColor() navigationController?.navigationBar.translucent = false navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor()] } </code></pre> <p>every time a new view controller is pushed onto a navigation stack. This does not happen in the iPhone 5, iPhone 5s, iPhone 6 or the iPhone 7. </p>
Painting on a JPanel from a different class in Swing <p>I am currently working on a test driven interactive 2D fluid dynamics simulation for my Bachelor thesis. The basic idea is that the user can draw shapes on his screen and the program will simulate how a fluid will flow around these shapes. So far I have only started with the painting process and I have already run into a little problem.</p> <p><a href="https://i.stack.imgur.com/I3zwe.png" rel="nofollow">First, here is a little UML diagram that shows my project structure so far</a></p> <p>As you can see, I have created a Painter class that can visit several shapes and will call one of the abstract paint methods depending on the shape type. Then there is the SwingPainter class which inherits from the Painter class and implements the three paint methods as well as the clear method. Here is the code for my SwingPainter:</p> <pre><code>public class SwingPainter extends Painter { private final GraphicPanel graphicPanel; public SwingPainter(GraphicPanel graphicPanel) { this.graphicPanel = graphicPanel; } private Graphics getGraphics() { return graphicPanel.getGraphics(); } @Override protected void paintLine(Point start, Point end) { getGraphics().drawLine(start.getX(), start.getY(), end.getX(), end.getY()); } @Override protected void paintRectangle(Point start, Point end) { int minX = start.getX() &lt; end.getX() ? start.getX() : end.getX(); int minY = start.getY() &lt; end.getY() ? start.getY() : end.getY(); int width = Math.abs(start.getX() - end.getX()); int height = Math.abs(start.getY() - end.getY()); getGraphics().drawRect(minX, minY, width, height); } @Override protected void paintCircle(Point center, double radius) { int minX = center.getX() - (int) radius; int minY = center.getY() - (int) radius; int diameter = (int) radius * 2; getGraphics().drawOval(minX, minY, diameter, diameter); } @Override public void clear() { graphicPanel.paintComponent(getGraphics()); } } </code></pre> <p>So my problem is that the GraphicPanelPresenter(see UML diagram) is responsible for passing the Painter/Visitor to the shapes when the user left clicks or moves the mouse(the second point of a line will follow the cursor for example). That means the actual painting is done outside of Swing's paint method. As a result I have encountered some flickering while painting and I was wondering if anyone knew how to fix that without throwing the whole painter/visitor functionality out the window(since there are other features concerning the shapes that still have to be implemented and could easily be handled by simply passing them another type of visitor).</p> <p>Well, that was a rather lengthy description for a rather small problem, sorry for the wall of text, but I would be glad for any kind of hint!</p>
<p>You need to do all the of painting in the various Swing paint methods that are designed to be overridden for custom painting (such as <code>paintComponent</code>). Only Swing will know when it's done drawing, or when a new frame needs to be drawn to.</p> <p>What it really seems like you need to do, is to have your <code>GraphicsPanel</code> have a reference to the object that holds your shape's states, and then draw the graphics that represent that state in <code>paintComponent</code>.</p> <p>This should also simplify your class relationship diagram as well, since within <code>GraphicsPanel</code> you can call the state object's methods from your listeners to change the state (I would choose different names to make the state object not aware that the changes are based on UI interactions, so if right click rotates, make the method called <code>rotate</code> instead of <code>handleRightClick</code>).</p>
Drupal 8.2.x text editor stripping-removing "div classes" <p>I have a problem with Druapl 8.2.1 text editor and CKeditor, system keeps stripping - removing classes from " <p>And example of this:</p> <pre><code>&lt;div class="social clearfix"&gt;&amp;nbsp;&lt;/div&gt; </code></pre> <p>System renders:</p> <pre><code>&lt;div&gt;&amp;nbsp;&lt;/div&gt; </code></pre> <p>I can't configure the allowed elements, that was only possible in previous versions (config.allowedContent = true;)</p> <p>Any help would be greatly appreciated</p>
<p>Ok, well after breaking my head thinking and re thinking in all I have already done I just did what it was left to do.</p> <p>Since there is no way to modify the allowedContent in Drupal version 8.2.x... what I did before it was to create a "New text format and editor" but I had selected the option "Limit allowed HTML tags and correct faulty HTML" and in the allowed HTML tags field I had all the classes I wanted to be accepted:</p> <pre><code>&lt;div&gt; &lt;div class&gt; &lt;div id&gt;&lt;a href hreflang&gt; &lt;em&gt; &lt;strong&gt; &lt;cite&gt; &lt;blockquote cite&gt; &lt;code&gt; &lt;ul type&gt; &lt;ol start type&gt; &lt;li&gt; &lt;dl&gt; &lt;dt&gt; &lt;dd&gt; &lt;h2 id&gt; &lt;h3 id&gt; &lt;h4 id&gt; &lt;h5 id&gt; &lt;h6 id&gt; &lt;p&gt; &lt;br&gt; &lt;span&gt;... </code></pre> <p>I just unchecked the "Limit allowed HTML tags and correct faulty HTML" and keep the "Correct faulty and chopped off HTML" option checked, saved and voila!!</p> <p>Now Drupal keeps all my div classes.</p> <p>Take into consideration that in the option "Text editor" I had selected "NONE", it do not work if "CKEditor" is selected.</p> <p>:)</p>
Dependency injection inconsistency in differing ViewControllers in Swinject, post Swift 3.0 update: why? <p>I am registering some <code>Swinject</code> singleton-with-a-small-s (.container) services thus:</p> <pre><code>defaultContainer.register( SomeService.self ) { _ in SomeService() }.inObjectScope( .container ) defaultContainer.register( AnotherService.self ) { responder in AnotherService( someService: responder.resolve( SomeService.self )! ) }.inObjectScope( .container ) </code></pre> <p>Injecting them into some view controllers thus:</p> <pre><code>defaultContainer.registerForStoryboard( SomeViewController.self ) { resolvable, viewController in viewController.someService = resolvable.resolve( SomeService.self ) viewController.anotherService = resolvable.resolve( AnotherService.self )! } defaultContainer.registerForStoryboard( AnotherViewController.self ) { resolvable, viewController in viewController.someService = resolvable.resolve( SomeService.self ) viewController.anotherService = resolvable.resolve( AnotherService.self )! } </code></pre> <p>These view controllers are then being displayed in two different ways, <code>SomeViewController</code> like this:</p> <pre><code>DispatchQueue.main.async { self.performSegue( withIdentifier: "somePageSegue", sender: nil ) } </code></pre> <p>And <code>AnotherViewController</code> like this:</p> <pre><code>let anotherViewController = UIStoryboard( name: "Main" , bundle: nil ).instantiateViewController( withIdentifier: "anotherSegue" ) present( anotherViewController, animated: true, completion: nil ) </code></pre> <p><code>SomeViewController</code> gets its services injected, but unfortunately <code>AnotherViewController</code> does not.</p> <p>This used to work prior to <code>Swinject</code>'s upgrade to Swift 3.0, but does not now. Why is this, and what needs to be changed, please? </p> <p>Thank you.</p> <p><strong>UPDATE</strong></p> <p>I have neither the familiarity with <code>Swinject</code>'s underlying code base nor the time to familiarize myself unfortunately, but digging around with what is happening under the surface I have discovered the following, which is hopefully useful to anyone who might know it better than I:</p> <p><strong>SUCCESSFUL VC DI:</strong></p> <pre><code>// once into: private func injectDependency(to viewController: UIViewController) // then: defaultContainer.registerForStoryboard( SomeViewController.self ) // then many times into: public func _resolve&lt;Service, Factory&gt;(name: String?, option: ServiceKeyOptionType? = nil, invoker: (Factory) -&gt; Service) -&gt; Service? </code></pre> <p><strong>FAILED VC DI:</strong></p> <pre><code>// repeatedly going from: private func injectDependency(to viewController: UIViewController) // to: public func _resolve&lt;Service, Factory&gt;(name: String?, option: ServiceKeyOptionType? = nil, invoker: (Factory) -&gt; Service) -&gt; Service? // and back again, // then twice into: public override func instantiateViewController(withIdentifier identifier: String) -&gt; UIViewController </code></pre> <p><strong>ADDITIONAL NOTES:</strong></p> <p>The failing VC is a UIViewController within a TabBarController, both of which are already laid out in a standard XCode storyboard.</p>
<p>In order for <code>registerForStoryboard</code> to be invoked you need to instantiate given controller from <code>SwinjectStoryboard</code>, not just <code>UIStoryboard</code>:</p> <pre><code>let anotherViewController = SwinjectStoryboard.create(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "anotherSegue") present(anotherViewController, animated: true, completion: nil) </code></pre>
How is this C++ code working with an unusual single boolean statement? <p>Why and how does this code work?</p> <pre><code>#include &lt;iostream&gt; using namespace std; void nothing() { false; } int main() { cout &lt;&lt; "Working" &lt;&lt; endl; nothing(); cout &lt;&lt; "It worked!" &lt;&lt; endl; } </code></pre> <p>As you can see, the function definition of the function <code>nothing()</code> has nothing but a statement <code>false;</code> in it, but still it compiles and runs fine, doing nothing. How and why is this possible? Am I missing something here?</p>
<pre><code>false; </code></pre> <p>is a valid statement in C++. It doesn't do anything useful but it is still valid. Most compilers will probably remove that line from the object code they create for the function.</p> <p>Some compilers, with the right compiler flags, will let you know that the statement has no effect. With <code>g++ --Wall</code>, I get:</p> <pre><code>socc.cc: In function ‘void nothing()’: socc.cc:3:9: warning: statement has no effect [-Wunused-value] false; </code></pre>
How to be changed this code <div></div data-isloaded="true"> <p>i'm new in jquery plz help me to change this code</p> <pre><code> &lt;div&gt;&lt;/div data-isloaded="true"&gt; </code></pre> <p>to this code </p> <pre><code> &lt;div&gt;&lt;/div data-isloaded="false"&gt; </code></pre> <p>with jquery</p>
<pre><code>$('div[data-isloaded="true"]').attr('data-isloaded',false) </code></pre>
UISplitViewController should be root, so how to "push" the real starting view on top? <p>My app design is very simple, at least with respect to describing the intended user-facing views:</p> <p>The starting view is initially empty. Pressing a "Select" button in the navigation bar transitions to a split view. On the left (master) are the photo albums on the device. On the right (detail) are the images in a given album. The user can select up to 6 images across all albums. Pressing a "Done" button in the navigation bar transitions back to the starting view, which now displays the selected images in a grid. And that's it.</p> <p>In my head, this should be as simple as embedding the starting view in a navigation controller and adding a segue from the "Select" button to the split view. But of course, it doesn't work that way. According to the Apple docs:</p> <blockquote> <p>Although it is possible to install a split view controller as a child in some other container view controllers, doing is not recommended in most cases. Split view controllers are normally installed at the root of your app’s window.</p> </blockquote> <p>If at all possible, I would like to retain my user-facing design without any shady business. I strongly suspect that there are one or more "sanctioned" ways to accomplish what I want, but I am too inexperienced with iOS development to know what they might be. Any help is appreciated!</p>
<p>If all you want is to pass back to the starting view controller the array of images, than why not just declare a protocol in the Split ViewController that the starting controller can adopt? </p>
asp.net mvc redirecttoaction does not shows another page <p>I am writing a simple MVC application in which I use a form to put some data, and after I submit the form, if a particular condition is <code>false</code> I would like to show the form again, otherwise I would show another page. When the condition is false, I do <code>ReturnToAction("Form");</code> and it works perfectly, but, when the condition is true and I do <code>RedirectToAction("MyPage");</code> I still see the form, even if the action related to the form submission has been executed. What am I missing? Thank you This is my controller</p> <pre><code>public class HomeController : Controller { private static bool condition = false; public ActionResult Form() { return View(); } [HttpPost] public ActionResult CheckCondition(FormCollection form) { string username = form["txtUsername"]; condidion = true; return RedirectToAction("MyPage"); } public ActionResult MyPage() { if (!condition) { return RedirectToAction("Form"); } else { return RedirectToAction("MyPage"); } } </code></pre> <p>Here you are my Form.aspx:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head runat="server"&gt; &lt;title&gt;Form&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form runat="server" method="post"&gt; &lt;ext:ResourceManager runat="server" /&gt; &lt;ext:Viewport runat="server" Layout="CenterLayout"&gt; &lt;Items&gt; &lt;ext:FormPanel runat="server" id="Form" Url="/Home/CheckCondition" Width="500" Height="500" Layout="CenterLayout" &gt; &lt;Items&gt; &lt;ext:Window ID="Window1" runat="server" Closable="false" Resizable="false" Height="200" Icon="Lock" Title="Dashboard Login" Draggable="false" Width="350" Modal="true" BodyPadding="5" Layout="FormLayout" &gt; &lt;Items&gt; &lt;ext:TextField ID="txtUsername" runat="server" FieldLabel="Username" AllowBlank="false" BlankText="Your username is required." Text="Demo" /&gt; &lt;ext:TextField ID="txtPassword" runat="server" InputType="Password" FieldLabel="Password" AllowBlank="false" BlankText="Your password is required." Text="Demo" /&gt; &lt;/Items&gt; &lt;Buttons&gt; &lt;ext:Button ID="btnLogin" runat="server" Text="Login" Icon="Accept"&gt; &lt;Listeners&gt; &lt;Click Handler=" if (!#{txtUsername}.validate() || !#{txtPassword}.validate()) { Ext.Msg.alert('Error','The Username and Password fields are both required'); // return false to prevent the btnLogin_Click Ajax Click event from firing. return false; } else { #{Form}.submit(); }" /&gt; &lt;/Listeners&gt; &lt;/ext:Button&gt; &lt;/Buttons&gt; &lt;/ext:Window&gt; &lt;/Items&gt; &lt;/ext:FormPanel&gt; &lt;/Items&gt; &lt;/ext:Viewport&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>If you want to show the same form, you should not return a <code>RedirectResult</code>. you should call the <code>View</code> method. Also you should do the condition checking inside the http post action method which handles the form submission.</p> <pre><code>[HttpPost] public ActionResult CheckCondition(FormCollection form) { if (someConditionCodeGoesHere==false) // replace this with your condition code { return View(); } else { return RedirectToAction("Success"); } } public ActionResult Success() { return View(); } </code></pre> <p>replace <code>someConditionCodeGoesHere</code> with your C# code for your condition expression. Try to embrace Stateless Http. Static variables to keep state between http call's are not a great idea.</p> <p>Also consider using a view model to transfer data between your view and action method. Take a look at <a href="http://stackoverflow.com/questions/20333021/asp-net-mvc-how-to-pass-data-from-view-to-controller/20333225#20333225">ASP.Net MVC How to pass data from view to controller</a></p>
How do I store the shifted bit in a bitwise operation in C? <p>I was trying to make a simple function to check how many bits set to 1 were in an int.</p> <p>What I achieved at first was </p> <pre><code>#include &lt;stdio.h&gt; int bitsOne (int x){ int r=0; while (x &gt; 0){ if (x % 2 == 1) r++; x = x/2; } return r; } </code></pre> <p>I was trying to use the <code>&gt;&gt;</code> operator for this instead but I don't know how I can store the shifted number.</p> <hr> <p><strong>Update</strong></p> <p>Using Brick's suggestion I achieved what I wanted,</p> <pre><code>#include &lt;stdio.h&gt; int bitsOne (int x){ int r=0; int bit; while (x &gt; 0){ bit = (x &amp; 1); if (bit == 1) r++; x&gt;&gt;=1; } return r; } </code></pre>
<p>Get the bit in the last slot before you do the shift using a mask:</p> <pre><code>int bit = (x &amp; 1); </code></pre> <p>Then do the shift on x.</p>