title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Bug: my UILabel displays on a single cell, how to fix?
<p>My UILabel appears on some cell and times when I scroll my UICollectionView others appear on the cell but not all, how to fix? Thank you</p> <p>This label mixes with the same label other cell</p> <blockquote> <p>// cellForItemAtIndexPath</p> </blockquote> <pre><code>self.date = [NSDate dateWithTimeIntervalSince1970:[[searchResult objectForKey:@"drawDate"] intValue]]; self.dateFormatter = [[NSDateFormatter alloc] init]; [self.dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]]]; [self.dateFormatter setDateStyle:NSDateFormatterShortStyle]; cell3.titleContest.hidden = YES; cell3.titleContest.alpha = 0; //self.dateContest.text = @""; NSTimer *timer = [[NSTimer alloc] init]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES]; </code></pre> <blockquote> <p>// countDownTimer</p> </blockquote> <pre><code>- (void)updateCounter:(NSTimer *)tmr { NSTimeInterval iv = [self.date timeIntervalSinceNow]; int d = iv / 86400; int h = (iv / 3600) - (d * 24); int m = (iv - (h + d * 24) * 3600) / 60; int s = lroundf(iv) % 60; cell3.titleContest.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", d, h, m, s]; if (d + h + m + s &lt;= 0 ) { [tmr invalidate]; } [UIView animateWithDuration:0.5 animations:^{ cell3.titleContest.hidden = NO; cell3.titleContest.alpha = 1; } completion:^(BOOL finished) { }]; } </code></pre>
3
Spock Mock method matching objects with placeholders
<p>I need to test a few interactions with an eventbus. I have wrapped all the arguments in Event classes. The issue is that when I want to verify the events I have to create the event objects in my test and provide all the arguments. I would prefer to only specify the arguments that are important to make clear which arguments are important.</p> <pre><code>def "initial layout should call page events"() { given: "register for event" def listener = Mock(Closure) eventBus.registerForEvent(PageVisibilityChangedEvent, listener) when: "viewport twice the size of our pages and can fit 2 pages" worldport.updateScreenSize(new IntSizeImpl(200, 400)) then: "after the initial layout pages 0 and 1 should have become visible" 1 * listener.call(new PageVisibilityChangedEvent(_, 0, _, Visibility.VISIBLE, _)) 1 * listener.call(new PageVisibilityChangedEvent(_, 1, _, Visibility.VISIBLE, _)) 0 * _ } </code></pre>
3
Mongoose unable to find index for $geoNear query
<p>I got this error when trying to query a model based on location. <br></p>
3
Spring websocket listen to external queue on client side using SockJs
<p>I have an application that is using spring-websockets and here is the use case</p> <p>1) User sends a normal HTTP request to the controller(server)</p> <p>2) The server takes the request and converts it into a message and puts it onto a queue(which has replyTo) and it comes back with request validation successful and I show it on the UI</p> <p>3) The application that listens to the messages on the queue is a separate application and while it processes the message, it puts the output on another queue in ActiveMQ</p> <p>4) I am trying to listen to this queue using SockJS on the client side and I do not get any messages.</p> <p>This is because I am subscribing to the queue in SockJS but I am not actually subscribing as when I look at Active MQ it shows the number of subscribers for that queue is 0.</p> <p>Can you point me in the right direction as to how to approach this scenario? </p>
3
Polymer: Data binding breaking with on-tap handler on a button within a dom-repeat
<p>Ran into an issue here with Polymer's data binding functionality when used in conjunction with dom-repeat. I'm wondering what I'm missing in order to make this work.</p> <p>Data binding seems to work fine in some cases with the repeat element, e.g. with input boxes. However, using an on-tap event on a button and editing a field on the associated item object doesn't seem to work for some reason.</p> <p>Here is my SSCCE (Plunker: <a href="http://plnkr.co/edit/Vof1nYdDFR4Jg4ZXL9DI?p=preview" rel="nofollow">http://plnkr.co/edit/Vof1nYdDFR4Jg4ZXL9DI?p=preview</a>):</p> <pre><code>index.html ========== &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"&gt;&lt;/script&gt; &lt;link rel="import" href="dummy_element.html"&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;Click the "Toggle" button to toggle between Edit and View modes.&lt;/p&gt; &lt;dummy-element&gt;&lt;/dummy-element&gt; &lt;/body&gt; &lt;/html&gt; dummy_element.html ================== &lt;link rel="import" href="https://polygit.org/components/polymer/polymer.html"&gt; &lt;dom-module id="dummy-element"&gt; &lt;template&gt; &lt;template is="dom-repeat" items="{{records}}"&gt; &lt;p&gt; &lt;span hidden="{{item.editing}}"&gt;View mode: {{item.value}}&lt;/span&gt; &lt;span hidden="{{!item.editing}}"&gt;Edit mode: &lt;input value="{{item.value}}" /&gt;&lt;/span&gt; &lt;button on-tap="onTap"&gt;Toggle&lt;/button&gt; &lt;/p&gt; &lt;/template&gt; &lt;/template&gt; &lt;script&gt; Polymer({ is: 'dummy-element', properties: { records: { type: Array, value: function () { return [ {value: '#1', editing: false}, {value: '#2', editing: true}, ]; }, }, }, onTap: function (e) { e.model.item.editing = !e.model.item.editing; console.log('Editing:', e.model.item.editing); }, }); &lt;/script&gt; &lt;/dom-module&gt; </code></pre> <p>My intent: my click handler on the Toggle buttons should toggling the "editing" flag between true and false for the row in question, and the UI should automatically update to reflect the change.</p> <p>What happens: while the underlying model seems to change, the UI does not get redrawn.</p> <p>Any advice?</p>
3
google play games service same e-mail account returns difference id
<p>i'm using google-play-games-service plug-in for unity 0.9.26.</p> <pre><code>namespace GooglePlayGames { public class PluginVersion { // older versions, used when upgrading to other versions public const string VersionKeyCPP = "00911"; public const string VersionKeyU5 = "00915"; public const int VersionInt = 0x0926; public const string VersionString = "0.9.27"; public const string VersionKey = "00927"; // used to check for the correct min version or play services. public const int MinGmsCoreVersionCode = 8115000; // used to get the right version of dependencies. public const string PlayServicesVersionConstraint = "8.1+"; } </code></pre> <p>my server identify user with this id</p> <pre><code>Social.localUser.id //(like 123456789012345678901) 21character </code></pre> <p>i saw this id is unique, but after release my app sometimes user send difference id(not null or empty, like g1234568901234567890 start 'g' same 21character) so server can't find user data.</p> <p>is this my fault or kind of bug?</p>
3
Mobile Navigation Bar is only expanding on the home page
<p>I have basically the same navigation bar code on every page, but when its accessed on mobile i'm only able to expand the navigation bar on home.html , when i navigate to another page via the navigation bar i can no longer expand it.</p> <p>Website: <a href="http://www.richardsongirlssoccer.com" rel="nofollow">http://www.richardsongirlssoccer.com</a></p> <p>JSFiddle: <a href="https://jsfiddle.net/sjvroufr/1/" rel="nofollow">https://jsfiddle.net/sjvroufr/1/</a></p> <pre><code>$(document).ready(function() { $("#navToggle a").click(function(e){ e.preventDefault(); $("header &gt; nav").slideToggle(); $("#logo").toggleClass("menuUp menuDown"); }); $(window).resize(function() { if($( window ).width() &gt;= "600") { $("header &gt; nav").css("display", "block"); if($("#logo").attr('class') == "menuDown") { $("#logo").toggleClass("menuUp menuDown"); } } else { $("header &gt; nav").css("display", "none"); } }); $("header &gt; nav &gt; ul &gt; li &gt; a").click(function(e) { if($( window ).width() &lt;= "600") { if($(this).siblings().size() &gt; 0 ) { e.preventDefault(); $(this).siblings().slideToggle("fast") $(this).children(".toggle").html($(this).children(".toggle").html() == 'close' ? 'expand' : 'close'); } } }); }); </code></pre>
3
the_permalink in loop gives the same results
<p>I need to show an archive list post by post. I created plugin with this code:</p> <pre><code>function posts_by_year() { // array to use for results $years = array(); // get posts from WP $posts = get_posts(array( 'numberposts' =&gt; -1, 'orderby' =&gt; 'post_date', 'order' =&gt; 'ASC', 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish' )); // loop through posts, populating $years arrays foreach($posts as $post) { $years[date('Y', strtotime($post-&gt;post_date))][] = $post; } // reverse sort by year krsort($years); return $years; } ?&gt; &lt;?php function wyswietl_archiwum (){ ob_start(); ?&gt; &lt;?php foreach(posts_by_year() as $year =&gt; $posts) : ?&gt; &lt;h2&gt;&lt;?php echo $year; ?&gt;&lt;/h2&gt; &lt;ul&gt; &lt;?php foreach($posts as $post) : setup_postdata($post); ?&gt; &lt;li&gt; &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endforeach; ?&gt; &lt;?php return ob_get_clean(); } ?&gt; &lt;?php add_shortcode( 'archiwum', 'wyswietl_archiwum' ); </code></pre> <p>When I put shortcode <code>[archiwum]</code> on any page, I get the list but every one item displays current page title and links to itself.</p> <p>screenshot: <a href="https://i.stack.imgur.com/qEw9h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEw9h.png" alt="screenshot" /></a></p> <p>Any idea how to make it proper?</p>
3
Run function base on conditional statement
<p>In my WordPress functions file I have used the code </p> <pre><code>function banners() { if ( $GLOBALS['theme_settings']['banners'] == false ) { wp_enqueue_style('banner', get_template_directory_uri().'/css/banners.css', array(), '1.0.0', 'all'); } } add_action('admin_enqueue_scripts', 'banners'); </code></pre> <p>and this works fine, however, I can't help but think there must be a better way because the add_action will sometimes be running with no file to enqueue. I have tried to put the conditional statement outside of the function but that doesn't seem to work.</p>
3
How can I use a for loop in PHP to return mysql data
<p>I am making an app that will list employees by a certain store in a listview. My current function in my DB_Functions.php file is:</p> <pre><code>public function getEmployeeList($name) { $stmt = $this-&gt;con-&gt;prepare("SELECT employee_name FROM employees WHERE name = ?"); $stmt-&gt;bind_param('s', $name); if ($stmt-&gt;execute()) { $employee_list = $stmt-&gt;get_result()-&gt;fetch_assoc(); $stmt-&gt;close(); if (empty($employee_list)) { return NULL; } else { return $employee_list; } } } </code></pre> <p>and in my employees.php file I have the following code:</p> <pre><code>&lt;?php require_once 'include/DB_Functions.php'; $db = new DB_Functions(); $response = array('error' =&gt; FALSE); if (isset($_POST['name'])) { $name = $_POST['name']; $employee_list = $db-&gt;getEmployeeList($name); if ($employee_list != false) { $response['error'] = FALSE; //EMPLOYEE LIST OBJECT HERE } else { $response['error'] = TRUE; $response['error_msg'] = 'No employees have been added to this profile.'; echo json_encode($response); } } else { $response['error'] = TRUE; $response['error_msg'] = 'You have not logged in to your store\'s account, please log in first.'; echo json_encode($response); } ?&gt; </code></pre> <p>I would like to have an employee_list object in the commented space above. Something like:</p> <pre><code>$response['employee_list']['0'] = $employee_list['0']; $response['employee_list']['1'] = $employee_list['1']; $response['employee_list']['2'] = $employee_list['2']; </code></pre> <p>etc... etc...</p> <p>After that JSONObject is returned to the android app, the contents will be listed in a listview. I would need a for loop (<em>I think</em>) because the employee number will never be known since each store will be able to add and remove employees as they wish. Can someone point me in the right direction and also advise if I am using the correct approach as far as the rest of the code. Thanks.</p>
3
response json to javascript
<p>I have the following json_response:</p> <pre><code>"list" : { "meta": { "type": "resource-list", "start": 0, "count": 1 }, "resources": [ { "resource": { "classname": "Quote", "fields": { "change": "-0.091499", "chg_percent": "-0.790833", "day_high": "11.730000", "day_low": "11.430000", "issuer_name": "J. C. Penney Company, Inc.", "issuer_name_lang": "J. C. Penney Company, Inc.", "name": "J.C. Penney Company, Inc. Holdi", "price": "11.478500", "symbol": "JCP", "ts": "1458576181", "type": "equity", "utctime": "2016-03-21T16:03:01+0000", "volume": "3269312", "year_high": "11.990000", "year_low": "6.000000" } } } ] } </code></pre> <p>and I extract ids with following java script</p> <pre><code>var name = ''; var jsonstr = json_response var obj = $.parseJSON(jsonstr); $.each(obj, function () { name += name += this['list']['meta']['type']+ "&lt;br/&gt;"; }); $('#divjson').html(name); </code></pre> <p>QUESTION: how can I get the value of day_low or day_high using above java script?</p> <p>Thanks,</p>
3
parse and construct a complicated json
<p>i have an array like below,</p> <pre><code>array=[ { 'mm': '1', exp: 'exp1' }, { 'mm': '2', exp: 'exp2' }, { 'mm': [ '1', '3', '7' ], exp: 'exp3' }, { 'mm': [ '1', '2', '4', '6' ], exp: 'exp4' }, { 'mm': [ '1', '3', '2' ], exp: 'exp5' }, { 'mm': [ '8', '2', '9' ], exp: 'exp6' }, { 'mm': [ '4', '7', '1', '2' ], exp: 'exp7' }, { 'mm': [ '5', '6', '2', '4', '3', '8', '1' ], exp: 'exp8' } ] </code></pre> <p>i need to restructure this array (turn keys to values and values to keys) like below(cannot hardcode any values in 'mm' or 'exp' keys as they always keep changing,</p> <pre><code> [ { 'mm': '1', exp: ['exp1','exp3','exp4',','exp5','exp7','exp8'] }, { 'mm': '2', exp: ['exp2','exp4','exp5','exp6','exp7','exp8'] }, { 'mm': '3', exp: ['exp3','exp5','exp8'] }, { 'mm':'4', exp:['exp4','exp7','exp8'] }, { 'mm':'5', exp:['exp8'] }, { 'mm':'6', exp:['exp4','exp8'] }, { 'mm':'7', exp: ['exp3','exp7'] }, { 'mm':'8', exp: ['exp6','exp8] }, { 'mm':'9', exp: ['exp6'] } ] </code></pre> <p>you get the idea, hopefully, lemme know if you find an efficient solution while i try to get this done myself.</p>
3
Exclude given objects from array
<p>I have the below array. I am attempting to exclude certain objects from this array in processing.</p> <p>For example. I would like to exclude the type 'dog' and only use any object that is of type duck.</p> <p>I'd like to do this using underscore/lodash but will use plain JS if need be.</p> <pre><code>animals: [ { type: 'duck', name: 'quack', }, { type: 'duck', name: 'quieck', }, { type: 'dog', name: 'bark', }, ] </code></pre>
3
how use one scope between two based on a condition?
<p>I have a model <code>POSTS</code>. in that i have two scopes in this model <code>active</code>, <code>inactive</code>. i want use one of it <code>PostsController</code> based on <code>params[:active]</code> value. like following</p> <pre><code>if params[:active] == "true" @posts = POSTS.where some_condition .include some_thing .active .page .per else @posts = POSTS.where some_condition .include .inactive .page .per end </code></pre> <p>is there any better way to do the same thing? i tried many ways to do it. but i couldn't. help me. thanks </p>
3
CSS Nesting Not Getting Expected
<p>I'm new to HTML/CSS so this may be a stupid/basic question, but I legitimately cannot find the answer to why this is happening:</p> <p>I am making a super-basic webpage where there are buttons in the navigation bar that change the image that is displayed in the content section. I just want to change the appearance of the buttons but seem to be unable to do so:</p> <p>HTML doc:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;homepage&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="homestyle.css"&gt; &lt;script src='navfunc.js'&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- WRAPPER DIV --&gt; &lt;div id='wrapper'&gt; &lt;!-- HEADER DIV --&gt; &lt;div class = 'header'&gt; &lt;h1&gt; Price History and Stock Data &lt;/h1&gt; &lt;/div&gt; &lt;!-- SIDEBAR/NAV DIV --&gt; &lt;div class = 'sidebar'&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('AMBA')"&gt; AMBA &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('APH')"&gt; APH &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('ASX')"&gt; ASX &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('B')"&gt; B &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('BDS')"&gt; BDSI &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('CNC')"&gt; CNC &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('CNK')"&gt; CNK &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('COLB')"&gt; COLB &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('EWBC')"&gt; EWBC &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('FB')"&gt; FB &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('GPRO')"&gt; GPRO &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('HAIN')"&gt; HAIN &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('HEI')"&gt; HEI &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('LCI')"&gt; LCI &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('MANU')"&gt; MANU &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('NCLH')"&gt; NCLH &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('RCL')"&gt; RCL &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('TSN')"&gt; TSN &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('TSO')"&gt; TSO &lt;/button&gt; &lt;/li&gt; &lt;li&gt; &lt;button type="button" onclick="navfunc('WWD')"&gt; WWD &lt;/button&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;!-- CONTENT DIV --&gt; &lt;div class = 'content'&gt; &lt;img id='hmap' src = 'AMBA_heatmap.png' alt='AMBA', style="width: 880px; height: 660px;"&gt; &lt;/div&gt; &lt;!-- FOOTER DIV --&gt; &lt;div class = 'footer'&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS Doc:</p> <pre><code>/* WRAPPER ------------------------------------------------------------------ */ #wrapper{ margin-left:auto; margin-right:auto; width:1280px; } /* HEADER ------------------------------------------------------------------ */ div.header{ background-color: #87CEFA; font-family: 'Trebuchet MS', Verdana, Sans-Serif ; text-decoration: underline; text-align: center; font-size: 150%; color: #286F02; padding: 25px; margin: 0px; border-bottom: 2px solid black; } /* SIDEBAR ------------------------------------------------------------------ */ div.sidebar{ float: left; height: 1024px; width: 225px; border-right: 2px solid black; border-bottom: 2px solid black; border-top: 2px solid black; padding: 5px; margin:2px; background-color: #0F4FAF; /* Blue*/ } div.sidebar ul { list-style-type: none; margin-top: 10px } div.sidebar ul li{ margin: 10px; font-size: 22px; } nav.sidebar button { background-color: '#4CAF50'; /* Green */ border: none; color: white; width: 95px; padding: 10px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } /* CONTENT ------------------------------------------------------------------ */ div.content { width: 910px; height: 1024px; background-color:#C0C0C0; border: 2px solid #0F0F0F; border-collapse: collapse; float: left; margin:1px; padding:5px; } /* FOOTER ------------------------------------------------------------------ */ div.footer { width: 100%; } </code></pre> <p>The center of attention in these docs is just the nav bar section where i write:</p> <pre><code>div.sidebar button { background-color: '#4CAF50'; /* Green */ border: none; color: white; width: 95px; padding: 10px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } </code></pre> <p>But the buttons still take on default button values. I messed around with it a little and got some styles to change in the browser but then if i changed them again or changed them back, they stopped working... </p> <p>Sorry if this is kinda vague, but I'm under the impression that there is something fundamental that I'm missing and can't seem to figure out what it is.</p> <p>Thanks for any help/advice!</p>
3
ES6 play nice.. How to use this.someFunction() inside angular directive without controllerAs?
<p>Take for example this Angular directive that works fine in Chrome &amp; Firefox:</p> <pre><code>// using Angular v1.4.8 myApp.directive('myDir', function(){ return { restrict: 'E', templateUrl: 'directive/myDir/myDir.html', bindToController: true, controllerAs: 'mydir', controller: function($scope){ var thisdir = this; // Using ES6 arrow functions thisdir.shoutOut = () =&gt; { console.log("Shouting out!"); } } } }); </code></pre> <p>Now on IE11 it throws a syntax arrow because the browser does not recognize arrow functions. However, I can still use:</p> <pre><code>function shoutOut(){ console.log("Shouting out!"); } </code></pre> <p>But I want to be able to use <code>var thisdir = this</code> throughout my directives. For cleaniness of code, I also want to avoid using <code>$scope</code> in my directives. Ultimately my directives will depend on eachother in order to create a larger directive/component, which is why i would like to use <code>var thisdir = this</code>.</p> <p>So how can I achieve this while maintaining syntax compatibility with older browsers? If you see a cleaner way to go about this, please let me know!</p>
3
GUI for plotting data from 3D cell matricies in Matlab
<p>I have a matlab cell matrix in which each cell contains a vector of numbers. I am trying to visualize the cell matrix data and plot various rows with various columns. However, I am still not sure which rows/columns should I pick and whether I should take the average, max or first/second/third.. value from each cell to get the desired output I am looking for. As I continuously change my plotting parameters, it gets really annoying to change multiple loops and their limits every time I want to try another plot. Trying to extract the correct information you want from a such a jungle becomes really frustrating.</p> <p><img src="https://i.stack.imgur.com/uWSKU.png" alt="Screenshot of the cell matrix"></p> <p>I am looking for a software/toolbox/GUI to help me play around and visualize this 3D cell matrix so I can plot whatever I need by some simple clicks and avoid the confusion of several loops inside each other.</p> <p>Would there be any idea to help me through that?</p>
3
How does LayoutInflater deals with IDs when there are multiple copies of an .xml file?
<p>To make my point easier to explain, I will use an example:</p> <pre><code>&lt;EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/thisIdIsVeryCool"/&gt; </code></pre> <p>this is the .xml that I want to inflate and I will call it sublayout.xml</p> <p>Now imagine that I inflate sublayout.xml in the main_layout.xml three times.</p> <p>It does not give any error so I run the app on my device. Now, right in front of my eyes, there are 3 EditText, all of wich with <code>thisIdIsVeryCool</code> as id. this makes no sense to me...</p> <p>What if i want to check if <code>thisIdIsVeryCool</code> is empty or not, and 2 of these EditText are indeed empty, but one of them is not?</p> <p>Ok, it seems like i haven't ever tried to actually write a code like that and i'm lazy, but trust me, i've tried. Actually, i've tryed a slightly different thing, and it seems that, when in the .java I refer to <code>thisIdIsVeryCool</code>, it affects only the inflated sublayout.xml that was created first.</p> <p>so... how are called the others EditText?</p> <p>And in general:</p> <p>How does LayoutInflater deals with IDs?</p>
3
retrieve data without UI thread
<p>I want to retrieve data from php file to my new android app. I tried to do it as background process there for I want to use it without UI thread. I couldn't remove UI thread from this code any one hep me to remove UI thread in this code do it?</p> <p>I try it but there is lot of red underlines. Actually I try to get data from host using a AlarmManager in every 5 seconds</p> <p>my AlarmDemo class</p> <pre><code> public class AlarmDemo extends Activity { Toast mToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm_demo); // repeated alerm Intent intent = new Intent(AlarmDemo.this, RepeatingAlarm.class); PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this, 0, intent, 0); // We want the alarm to go off 5 seconds from now. long firstTime = SystemClock.elapsedRealtime(); firstTime += 5 * 1000; // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5 * 1000, sender); // Tell the user about what we did. if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(AlarmDemo.this, "Rescheduled", Toast.LENGTH_LONG); mToast.show(); // end repeatdalarm } } </code></pre> <p>my RepeatingAlarm class</p> <pre><code> public class RepeatingAlarm extends BroadcastReceiver { Context context; Button b; EditText et,pass; TextView tv; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List&lt;NameValuePair&gt; nameValuePairs; ProgressDialog dialog = null; private AutoCompleteTextView autoComplete; private MultiAutoCompleteTextView multiAutoComplete; private ArrayAdapter&lt;String&gt; adapter; @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show(); dialog = ProgressDialog.show(RepeatingAlarm.this, "", "Validating user...", true); new Thread(new Runnable() { public void run() { login(); } }).start(); } void login(){ try{ httpclient=new DefaultHttpClient(); httppost= new HttpPost("http://androidexample.com/media/webservice/getPage.php"); //add your data nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2); // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { String text = response; tv.setText("Response from PHP : " + text); dialog.dismiss(); } }); }catch(Exception e){ dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } } </code></pre> <p>please help me I'm new in android</p>
3
Cards are in 2 rows?
<p>i tried to make something new in materializecss and I created one div with class row in which I have put 2 cards.one cards is in div with class col s4 and other one is in div with class col s8. Those cards are in 2 separate rows. Cannot figure out why. Why are they not in same row?</p> <p>here is example of code, first div with class row does not work fine, second one works fine, what is the difference?</p> <pre><code>&lt;div class="row"&gt;&lt;!-- start top vijesti --&gt; &lt;div class="col s1"&gt;1&lt;/div&gt; &lt;div class="col s7"&gt;ff&lt;/div&gt; &lt;div class="col s4"&gt;ff&lt;/div&gt; &lt;/div&gt;&lt;!-- end top vijesti --&gt; &lt;div class="row"&gt; &lt;div class="col s1"&gt;1&lt;/div&gt; &lt;div class="col s1"&gt;2&lt;/div&gt; &lt;div class="col s1"&gt;3&lt;/div&gt; &lt;div class="col s1"&gt;4&lt;/div&gt; &lt;div class="col s1"&gt;5&lt;/div&gt; &lt;div class="col s1"&gt;6&lt;/div&gt; &lt;div class="col s1"&gt;7&lt;/div&gt; &lt;div class="col s1"&gt;8&lt;/div&gt; &lt;div class="col s1"&gt;9&lt;/div&gt; &lt;div class="col s1"&gt;10&lt;/div&gt; &lt;div class="col s1"&gt;11&lt;/div&gt; &lt;div class="col s1"&gt;12&lt;/div&gt; &lt;/div&gt; </code></pre>
3
ControlTemplate working correctly in Blend but not in actual application
<p>I created a custom button, nothing too fancy, just an extension of the mahApps SquareButton with a little colored marker at the left side.</p> <p><a href="https://i.stack.imgur.com/4oa3d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4oa3d.png" alt="enter image description here"></a></p> <p>I designed it in Blend, and copied the code into my real application in Visual Studio. When starting in Blend it's working just fine, when starting in Visual Studio the marker is not visible and also the Text gets left aligned, the button is looking nearly like a normal SquareButton. What am I doing wrong?</p> <p><a href="https://i.stack.imgur.com/KxlA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KxlA4.png" alt="enter image description here"></a></p> <hr> <p>The XAML I put copied from Blend:<br /></p> <pre><code>&lt;Style x:Key="MarkerButtonStyle" TargetType="{x:Type Button}"&gt; &lt;Setter Property="MinHeight" Value="25"/&gt; &lt;Setter Property="FontFamily" Value="{DynamicResource DefaultFont}"/&gt; &lt;Setter Property="FontWeight" Value="SemiBold"/&gt; &lt;Setter Property="Background" Value="{DynamicResource WhiteBrush}"/&gt; &lt;Setter Property="BorderBrush" Value="{DynamicResource BlackBrush}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource TextBrush}"/&gt; &lt;Setter Property="Padding" Value="5,6"/&gt; &lt;Setter Property="BorderThickness" Value="2"/&gt; &lt;Setter Property="SnapsToDevicePixels" Value="True"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;Grid Background="{TemplateBinding Background}"&gt; &lt;VisualStateManager.VisualStateGroups&gt; &lt;VisualStateGroup x:Name="CommonStates"&gt; &lt;VisualState x:Name="Normal"/&gt; &lt;VisualState x:Name="Disabled"&gt; &lt;Storyboard&gt; &lt;DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"&gt; &lt;SplineDoubleKeyFrame KeyTime="0" Value="0.7"/&gt; &lt;/DoubleAnimationUsingKeyFrames&gt; &lt;DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="PART_ContentPresenter"&gt; &lt;EasingDoubleKeyFrame KeyTime="0" Value="0.3"/&gt; &lt;/DoubleAnimationUsingKeyFrames&gt; &lt;/Storyboard&gt; &lt;/VisualState&gt; &lt;/VisualStateGroup&gt; &lt;VisualStateGroup x:Name="FocusStates"&gt; &lt;VisualState x:Name="Focused"/&gt; &lt;VisualState x:Name="Unfocused"/&gt; &lt;/VisualStateGroup&gt; &lt;VisualStateGroup x:Name="ValidationStates"&gt; &lt;VisualState x:Name="Valid"/&gt; &lt;VisualState x:Name="InvalidFocused"/&gt; &lt;VisualState x:Name="InvalidUnfocused"/&gt; &lt;/VisualStateGroup&gt; &lt;/VisualStateManager.VisualStateGroups&gt; &lt;Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{x:Null}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/&gt; &lt;Rectangle Fill="#FFAA2222" HorizontalAlignment="Left" Width="15" Margin="{Binding BorderThickness, ElementName=Background}" StrokeThickness="0" IsHitTestVisible="False"/&gt; &lt;Rectangle x:Name="DisabledVisualElement" Fill="{DynamicResource ControlsDisabledBrush}" IsHitTestVisible="False" Opacity="0"/&gt; &lt;Custom:ContentControlEx x:Name="PART_ContentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsMouseOver" Value="True"&gt; &lt;Setter Property="Background" Value="{DynamicResource GrayBrush8}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource BlackBrush}"/&gt; &lt;/Trigger&gt; &lt;Trigger Property="IsPressed" Value="True"&gt; &lt;Setter Property="Background" Value="{DynamicResource BlackBrush}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource WhiteBrush}"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>Just the custom part of the button:</p> <pre><code>&lt;Rectangle Fill="#FFAA2222" HorizontalAlignment="Left" Width="15" Margin="{Binding BorderThickness, ElementName=Background}" StrokeThickness="0" IsHitTestVisible="False"/&gt; </code></pre> <p>And the code i put around to get it into VS:</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls" xmlns:view="clr-namespace:MyApplication.View"&gt; &lt;Style x:Key="MarkerButtonStyle" TargetType="{x:Type view:MarkerButton}"&gt; ... &lt;/Style&gt; &lt;Style TargetType="{x:Type view:MarkerButton}" BasedOn="{StaticResource MarkerButtonStyle}"/&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>Then I used the button like this:</p> <pre><code>&lt;view:MarkerButton MarkerColor="{Binding Color}" Content="{Binding Name}" MarkerWidth="15" .... /&gt; </code></pre> <hr> <p>With Punker76's solution of extending the button I get this:</p> <p><a href="https://i.stack.imgur.com/QEAI5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QEAI5.png" alt="enter image description here"></a></p> <p>The positioning is broken, but the xaml seems to be right....</p> <hr> <p>Fixed my old solution, the problem was my width: I declared it as uint instead of double. Still, the button appears different to the normal square style (different border, focus rect, text alignment) and I don't know why.</p> <p><a href="https://i.stack.imgur.com/asFgj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/asFgj.png" alt="enter image description here"></a></p>
3
jQuery animate and size settings works only in Chrome
<p>I am trying to get a slider to work on all browsers, but it only works on Chrome. I wrote it once, then I rewrote it thinking I did some mistake. But it seems that I fail find what causes my code not to work in any browser except Chrome. Also the responsiveness of how many thumbnails it should show is only working on Chrome. My best guess is that it's because I am not using selectors right.</p> <p>I only wrote the code for the right arrow, and stopped at that because I was trying to find out what causes the animation not to work and also the calculations which determine margins and maximum slides.</p> <p><a href="https://jsfiddle.net/b050k4re/" rel="nofollow">https://jsfiddle.net/b050k4re/</a></p> <p><strong>HTML:</strong></p> <pre><code>&lt;div id="slider-wrapper"&gt; &lt;h2&gt;Check out our Shows!&lt;/h2&gt; &lt;p&gt;You can check out each of the hosts bios and podcast list by clicking on their image below!&lt;/p&gt; &lt;div class="slider-container"&gt; &lt;img src="https://cdn0.iconfinder.com/data/icons/basic-ui-elements-round/700/01_arrow_left-128.png" class="arrow" id="go-left"&gt; &lt;div id="slider"&gt; &lt;ul class="slides"&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="slide"&gt; &lt;a href="http://google.com" target="_blank"&gt; &lt;img src="http://www.online-image-editor.com//styles/2014/images/example_image.png"&gt; &lt;div class="show-title"&gt;Cat&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;img src="https://cdn0.iconfinder.com/data/icons/basic-ui-elements-round/700/01_arrow_left-128.png" class="arrow" id="go-right"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong> </p> <pre><code>body { margin: 0 0; } #slider { width: 100%; height: 130px; overflow: hidden; margin: 0px 10px; float: left; } #slider .slides { display: block; width: 6000px; height: 130px; margin: 0; padding: 0; left: 0; position: relative; } #slider .slide { float: left; list-style-type: none; width: 121px; height: 120px; border: 1px solid #fff; margin: 5px 10px; position: relative; box-shadow: 2px 1px 2px #888888; } #go-left { float: left; } #go-right { float: right; } .arrow { width: 40px; height: 40px; margin-top: 50px; cursor: pointer; } .arrow#go-right { -moz-transform: scaleX(-1); -o-transform: scaleX(-1); -webkit-transform: scaleX(-1); transform: scaleX(-1); filter: FlipH; -ms-filter: "FlipH"; } .slider-container { max-width: 960px; width: 100%; margin: 0px auto; height: 100px; margin-top: 50px; } #slider &gt; ul &gt; li &gt; a &gt; img { height: 100%; width: 100%; } .show-title { position: absolute; bottom: 0; width: 100%; text-align: center; background-color: rgba(0, 8, 21, 0.7); line-height: 121px; vertical-align: middle; color: #fff; font-family: 'Ubuntu', sans-serif; font-weight: 650; border-top: 2px #eee solid; display: none; height: 100%; } .slide a { width: inherit; height: inherit; display: block; } #slider-wrapper { background-color: #eee; height: 220px; padding-top: 40px; /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#00112c+0,000000+100 */ background: rgb(0,17,44); /* Old browsers */ background: -moz-radial-gradient(center, ellipse cover, rgba(0,17,44,1) 0%, rgba(0,0,0,1) 100%); /* FF3.6-15 */ background: -webkit-radial-gradient(center, ellipse cover, rgba(0,17,44,1) 0%,rgba(0,0,0,1) 100%); /* Chrome10-25,Safari5.1-6 */ background: radial-gradient(ellipse at center, rgba(0,17,44,1) 0%,rgba(0,0,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00112c', endColorstr='#000000',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */ } #slider-wrapper h2 { color: #fff; font-family: 'Ubuntu', sans-serif; padding: 0px; margin-top: -20px; text-align: center; text-transform: uppercase; } #slider-wrapper p { color: #fff; text-align: center; font-family: 'Ubuntu', sans-serif; padding: 0; margin-bottom: -30px; margin-top: -10px; } .slide &gt; a &gt; div &gt; p { display: none; } </code></pre> <p><strong>jQuery:</strong></p> <pre><code>jQuery(document).ready(function($) { // The total number of thumbnails var thumbnailCount = $("#slider .slides .slide").length; // Thumbnail size var thumbWidth = 120; var thumbHeight = 120; // Minimum margin between thumbnails var minMargin = 5; // Variables through which we determine how many thumbnails // we can show. We decide this by calculating how many // fit, taking in consideration margins, thumbnail sizes // and borders. var arrowWidth = parseInt($("img#go-left").css("width").replace("px", ""), 10); var thumbMargin = parseInt($(".slides .slide").css("margin-right").replace("px", ""), 10); var sliderMargin = parseInt($("#slider").css("margin-right").replace("px", ""), 10); var slideBorder = parseInt($(".slides .slide").css("border-width").replace("px", ""), 10); // Slider container holds the arrows and the slides together. // We want the slider container to have a maximum width // Default is 960px // Get the size of the slider-container var sliderContainer = parseInt($(".slider-container").css("width").replace("px", ""), 10); // The slides container width must be the slider container width // minus the arrow widths and the margins of the slides container // itself. var slidesContainer = sliderContainer - (2 * arrowWidth + 2 * sliderMargin); $("#slider").css("width", slidesContainer); // The displayed slides limit is decided by the slides container // width and the width of the thumbnails var slideLimit = slidesContainer / thumbWidth; var maxSlides = Math.floor(slideLimit); // We know the number of maximum slides for the current screen size // We have to calculate the margins from the remaining size // depending on the thumbnail border sizes var remainingSpace = (slideLimit - maxSlides) * thumbWidth; var newMarginSizes = (remainingSpace - 2 * maxSlides * slideBorder) / (2 * maxSlides); // If the new Margin Sizes are smaller than the minimum margin sizes that we want // We are going to lower the the slide limit by 1 until the new margins are // bigger or equal to the wanted minimum margin sizes while (newMarginSizes &lt;= minMargin &amp;&amp; maxSlides &gt;= 1) { maxSlides--; remainingSpace = (slideLimit - maxSlides) * thumbWidth; newMarginSizes = (remainingSpace - 2 * maxSlides * slideBorder) / (2 * maxSlides); } // We need to know how much we have to slide the // slides container in order to show it perfectly. var slideSize = thumbWidth + newMarginSizes * 2 + slideBorder * 2; // We assign the new margin sizes for the slides $(".slides .slide").css({"margin-left": newMarginSizes, "margin-right": newMarginSizes}); // Functionality for left and right arrows var leftArrow = $(".slider-container #go-left"); var rightArrow = $(".slider-container #go-right"); var slides = $("#slider .slides"); // We need to know how many slides are left to show on either // sides. var remainingSlidesRight = thumbnailCount - maxSlides; var remainingSlidesLeft = 0; leftArrow.click(function() { }); rightArrow.click(function() { console.log("remaining left: " + remainingSlidesLeft + "\n" + "remaining right: " + remainingSlidesRight); if (remainingSlidesRight &gt; 0) { slides.animate({'left': "-=" + slideSize}, 1000); remainingSlidesRight--; remainingSlidesLeft++; } else { slides.animate({'left': "0"}, 1000); remainingSlidesRight = thumbnailCount - maxSlides; remainingSlidesLeft = 0; } }); }); </code></pre>
3
Java EE Clarification on Workflow for JSP and Servlets
<p>I am attempting to learn Java EE. After struggling through trying to understand the Java stack, it appears that that a basic dynamic web application can be accomplished by focusing on JSP and Servlets so I want to start there.</p> <p>In Net Beans I have a basic project set up with a tomcat server and when I hit run I can get the web page to generate and display the default index.jsp page. I have added a css file to the project and this jsp page looks like any standard html page now. I then create a new servlet. I was also able to create a link in the index.jsp page so when I click on it, it calls the servlet.</p> <p>What I don't understand is why when I create the servlet in Net Beans, the processRequest method comes pre-populated with several html print statements. I could easily make this page look like the jsp page I started with, making me wonder why I even need a JSP page. It appears the entire application could be comprised of servlets.</p> <p>Could someone please explain the proper interaction between the two? It appears the index page can contain links that call various servlets, perhaps to access a database of comments, then do I create the response table in the servlet, or would I pass that information to another JSP page?</p> <p>Understanding these basic workflows would really help. Thanks</p>
3
Swashbuckle Complex Objects
<p>Given an object parameter such as:</p> <pre><code>public class XYZ { public List&lt;ABC&gt; listABC { get; set; } } public class ABC { public string A { get; set; } public string B { get; set; } public string C { get; set; } } </code></pre> <p>I know it is possible to get Swashbuckle to show XYZ.listABC in the UI and then to enter the list in the text box if you use [FromUri(Name="XYZ")] before the parameter. </p> <p>Is there a way to expose the list object ABC in the UI instead of having a generic text box for XYZ.listABC?</p>
3
React.js bundle size too big when using router and browserify
<p>This is my Routes.jsx file</p> <pre><code>var React = require('react'); var Router = require('react-router/lib/router') var useRouterHistory = require('react-router/lib/useRouterHistory'); var hashHistory = require('history/lib/createHashHistory'); var IndexRoute = require('react-router/lib/IndexRoute'); var Route = require('react-router/lib/Route'); var History = useRouterHistory(hashHistory)({ queryKey: false }); var Base = require('./components/Pages/Base.jsx'); var HomePage = require('./components/Pages/HomePage.jsx'); var Historial = require('./components/Pages/Historial.jsx'); var NuevoPedido = require('./components/Pages/NuevoPedido.jsx'); var Routes = ( &lt;Router history={History}&gt; &lt;Route path="/" component={Base}&gt; &lt;IndexRoute component={HomePage} /&gt; &lt;Route path="/historial" component={Historial} /&gt; &lt;Route path="/pedido/nuevo" component={NuevoPedido} /&gt; &lt;/Route&gt; &lt;/Router&gt; ); module.exports = Routes; </code></pre> <p>My compile script looks like this</p> <pre><code>watchify src/main.jsx -v -t [ babelify --presets [ react es2015 ] ] -o public/js/main.js </code></pre> <p>This outputs a file that's 1532 KB</p> <p>And my production script looks like this</p> <pre><code>SET NODE_ENV=production &amp; browserify src/main.jsx -v -t [ babelify --presets [ react es2015 ] ] -g [uglifyify] -o public/js/bundle.js </code></pre> <p>This outputs a file that's 730 KB</p> <p>I have the following dependencies</p> <pre><code> "dependencies": { "desandro-classie": "^1.0.1", "node-uuid": "^1.4.7", "react": "^0.14.7", "react-dom": "^0.14.7", "react-router": "^2.0.0", "reflux": "^0.3.0", "validator": "^5.0.0", "whatwg-fetch": "^0.11.0" }, </code></pre> <p>Even uglified and compressed the file size is 730 kb which is huge for the little code i have written.</p> <p>I noticed that if a take out EG:</p> <pre><code>var NuevoPedido = require('./components/Pages/NuevoPedido.jsx'); Which is a "page wrapper" </code></pre> <p>and it's corresponding route</p> <pre><code>&lt;Route path="/pedido/nuevo" component={NuevoPedido} /&gt; </code></pre> <p>Removing any route and it's component cut's down like 500 kb from the 1.5 mb file, but that's crazy because those components are not any near to be 500kb, so i suspect that there has to be some kind of dependencies duplication, i tried npm dedupe with no luck.</p> <p>You can check my github rep <a href="https://github.com/Mercality/dilugaReact" rel="nofollow">https://github.com/Mercality/dilugaReact</a> to verify this.</p>
3
How to animate multiple points (planets) using gnuplot, from a single data file.
<p>I'm trying to make an animation of Jupiter, the sun and an asteroid at the stable Lagrange point L5 as they orbit around their center of mass. I want to do this animation using gnuplot.</p> <p>I have written a programme which finds their positions at time t/AU. The data I get is below, has columns, time, x position, y position, and has rows, planet, sun, asteroid. I have looked at other solutions to animating in gnuplot but they do not seem to work for me. Please help me understand what I need to type into the gnuplot command line to get an animation of this data please.</p> <p>Thank you.</p> <pre><code>0 0 5.19481 0 0 -0.00519481 0 4.50634 2.6 0.01 0.0275397 5.19473 0.01 -2.75397e-05 -0.00519473 0.01 4.52006 2.57607 0.02 0.0550786 5.19451 0.02 -5.50786e-05 -0.00519451 0.02 4.53365 2.55208 0.03 0.082616 5.19415 0.03 -8.2616e-05 -0.00519415 0.03 4.54712 2.52801 0.04 0.110151 5.19364 0.04 -0.000110151 -0.00519364 0.04 4.56046 2.50386 0.05 0.137683 5.19298 0.05 -0.000137683 -0.00519298 0.05 4.57367 2.47965 0.06 0.165211 5.19218 0.06 -0.000165211 -0.00519218 0.06 4.58675 2.45537 etc... </code></pre>
3
How would I make this test pass?
<p>How would i make the constructor store its parameter into the instance variable sentence? do i need to use the new operator?</p> <pre><code>public class SentenceCounter { public String sentence; public SentenceCounter(String sentence) { } public Object getSentence() { return sentence; } } </code></pre> <hr> <pre><code>public class TestSentenceCounter { private static final String SENTENCE1 = "This is my sentence."; private static final String SENTENCE2 = "These words make another sentence that is longer"; private SentenceCounter sc1; private SentenceCounter sc2; /** * Create two instance variable is correct */ @Before public void setup() { sc1 = new SentenceCounter(SENTENCE1); sc2 = new SentenceCounter(SENTENCE2); } /** * Make sure the instance variable is correct */ @Test public void testConstructor() { assertEquals(SENTENCE1, sc1.getSentence()); assertEquals(SENTENCE2, sc2.getSentence()); } } </code></pre>
3
Calling external script from Flink
<p>This might seem like a very complex problem to some of you. I want to use Apache Flink to apply some algorithms on data from a SocketStream. However, these algorithms are external executables that I am running using Scala's <code>sys.process</code> package. Here is what I want Flink to do:</p> <ol> <li><p>Get individual lines from SocketStream:</p> <p><code>val text = env.socketTextStream(hostName, port) val lines = text.flatMap { _.toLowerCase.split("\\n") filter { _.nonEmpty } }</code></p></li> <li><p>Call my executable algorithm with these lines as command line parameters. Somewhat like this:</p> <p><code>var op = "./Somefile.py "+lines!</code></p></li> <li><p>Print the output I get from the executable.</p> <p><code>op.print()</code></p></li> </ol> <p>Obviously this is not the correct way to do what I am trying to do as <code>op</code> unlike <code>lines</code> is not a data sink and thus nothing is getting printed. Is there some way I can achieve this?</p>
3
"Re-opening" DocuSign "Delivered" envelope in embedded view
<p>My question in a nutshell: Using the SOAP API, is there a way to allow the signer to "Re-open" an envelope that is in Delivered Status (Not expired or completed) in an embedded application?</p> <p>The details: Using the SalesForce SOAP API examples given here <a href="https://github.com/docusign/docusign-soap-sdk" rel="nofollow">https://github.com/docusign/docusign-soap-sdk</a> (thank you to whoever provided these!), I am having great success creating NEW envelopes. However, using the methods provided in the samples, a brand new envelope is created without regard for existing envelopes. I would like to see if there are any unexpired, delivered envelopes and present that before creating a new one. Unfortunately, I'm not seeing any way to fetch an envelope using an Envelope ID (eg: C87908AD-908E-45F6-B4F9-8B6A514XXXXX) and present that to the signer.</p>
3
Creating Android Menu
<p>I want to create a menu in my android app but it doesn't appear after running. this is my code Setting.xml</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="fr.learning_adventure.android.itac.android_app_activity.EspacePersonnelActivity"&gt; &lt;item android:id="@+id/action_settings" android:orderInCategory="100" android:title="connexion" /&gt; &lt;/menu&gt; </code></pre> <p>EspacePersonnelActivity:</p> <pre><code>public class EspacePersonnelActivity extends ActionBarActivity { private WifiManager wifiManager; private Learner learner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_espacepersonnel); @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.settings, menu); return true; } </code></pre>
3
Google Analytics API calculate internal referrals.
<p>I can find out the traffic sources for a page with a given permalink from the Google Analytics API that return a result like this:</p> <pre><code>Array( [direct] =&gt; 1 [social] =&gt; 0 [3rdparty] =&gt; 0 [search] =&gt; 0 ) </code></pre> <p>using a query call like this:</p> <pre><code>public static function get_traffic_sources( $args ) { global $post; $default = array( 'per_days' =&gt; 30 , 'skip' =&gt; 0, 'query' =&gt; 'traffic_sources', 'path' =&gt; Inbound_Google_Connect::get_relative_permalink( $post-&gt;ID ) ); $request = array_replace( $default , $args ); return Inbound_Google_Connect::load_data( $request ); } </code></pre> <p>But I would like to find out the number of internal referrals. Google does not seem to include this in their traffic_sources query. Any leads on how I could get this extra bit of information?</p>
3
Array data split
<p>I don't know if i am doing the array add by a correct method.</p> <pre><code>for (var i=0; i &lt; result.length; i++){ var a = Array();// loop against the Data array on each object in result var b = Array(); a.push(result[i].data.mentionTotal); b.push(result[i].profileName); mentionArr.push(b+a); } </code></pre> <p>The for loop above gave a result like this :</p> <pre><code>[["orange1494"],["ansontest231403"],["happyboy0"],["babygirl0"]] </code></pre> <p>But i want to split the data so i tried to do:</p> <pre><code>mentionArr.push(b+'","'+a); </code></pre> <p>In order to split it but the outcome is like :</p> <pre><code>["orange\",\"1494","ansontest23\",\"1403","happyboy\",\"0","babygirl\",\"0"] </code></pre> <p>Which i am not able to use this array to do my task.</p> <p>How may i solve it to:</p> <pre><code>[["orange","1494"],["ansontest23","1403"],["happyboy","0"],["babygirl","0"]] </code></pre>
3
Why not correctly displayed button?
<p>Here is an example with a standard theme.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hotpink { width: 100%; height: 100vh; border: 1px solid #999; } .pink { width: 100%; height: 100vh; border: 1px solid #999; } .deeppink { width: 100%; height: 100vh; border: 1px solid #999; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap-theme.css"&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-2"&gt;&lt;/div&gt; &lt;div class="col-md-8 hotpink"&gt; &lt;div class="row"&gt; &lt;div class="left-side pink col-md-10"&gt;&lt;/div&gt; &lt;div class="right-side deeppink col-md-2"&gt; &lt;a href="" class="btn btn-default"&gt;отправить&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>duplicate on <a href="http://codepen.io/anon/pen/BKLwmo" rel="nofollow">codepen</a> where the result is displayed on the entire width of the display.</p> <p>And here is an example with the subject material-design.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hotpink { width: 100%; height: 100vh; border: 1px solid #999; } .pink { width: 100%; height: 100vh; border: 1px solid #999; } .deeppink { width: 100%; height: 100vh; border: 1px solid #999; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/css/bootstrap-material-design.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/css/ripples.css"&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/js/material.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/js/ripples.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-2"&gt;&lt;/div&gt; &lt;div class="col-md-8 hotpink"&gt; &lt;div class="row"&gt; &lt;div class="left-side pink col-md-10"&gt;&lt;/div&gt; &lt;div class="right-side deeppink col-md-2"&gt; &lt;a href="" class="btn btn-default"&gt;отправить&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>duplicate on <a href="http://codepen.io/anon/pen/reMGpJ" rel="nofollow">codepen</a>. Why and how to fix it?</p>
3
how is the subclass property "quantity" initialised
<p>I'm trying to learn the concept of inheritance and initialisation in swift and have came up with the following code. "the swift programming language 2.1" states that if a subclass provides implementation of all of its superclass's designated initialiser, the subclass also automatically inherits all of its superclass convenience initialisers too. </p> <p>Therefore the subclass "<code>RecipeIngredient</code>" should have inherited superclass "<code>Food</code>"'s <code>convenience init(){ self.init(name: "[unnamed]")</code>. But this particular convenience init only initialise the var <code>name</code>, how can it initialise the subclass property <code>quantity</code>? Could someone please explain it to me, how is the subclass property <code>quantity</code> initialised when I create an instance of subclass using the superclass <code>convenience init(){ self.init(name: "[unnamed]")</code>? Thanks in advance for any help!</p> <pre><code>class Food { var name: String init(name: String){ self.name = name } convenience init() { self.init(name: "[unnamed]") } } class RecipeIngredient: Food{ var quantity: Int init(name: String, quantity: Int){ self.quantity = quantity super.init(name: name) } override convenience init(name: String){ self.init(name: name, quantity: 1) } } let ingredientOne = RecipeIngredient() ingredientOne.name ingredientOne.quantity </code></pre>
3
Read a file and apply the operation and store it
<p>Say I have a file called param.txt. It contains,</p> <pre><code>param1 = 5; param2 = 10; param3 = 12; param4 = 5; param5 = param1 + param2; param6 = param2 * param1; param7 = param5 - param2; param8 = param1 * param2 - param4; </code></pre> <p>I am reading this file in a perl script and storing all the parameter values till param4 in a hash. </p> <p>How will I store param5,param6,param7,param8 by applying the intended operation of just by reading file and build the hash?</p>
3
Distances in google sheets
<p>I have a set of 20,000 addresses and I need to find the distance between those and a set address. The program works but I keep encountering the "service invoked too many times in one day" error message. Does anyone know if there is a way to buy more "queries" from google? </p> <p>Thanks!</p> <p>Code I am using: </p> <pre><code>function DrivingMeters(origin, destination) { var randnumber = Math.random()*10000; Utilities.sleep(randnumber); var directions = Maps.newDirectionFinder() .setOrigin(origin) .setDestination(destination) .getDirections(); return directions.routes[0].legs[0].distance.value; } function DrivingMiles(origin, destination) { return DrivingMeters(origin, destination)/1609.34; } function DrivingSeconds(origin, destination) { var directions = Maps.newDirectionFinder() .setOrigin(origin) .setDestination(destination) .getDirections(); return directions.routes[0].legs[0].duration.value; } function DrivingHours(origin, destination) { return DrivingSeconds(origin, destination)/(60*60); } </code></pre>
3
slider menu bugs and active button
<p>I am trying to create a slider menu which opens from left to right. I have created an arrow button separate from the menu and the menu itself which is a white rectangle which appear from left to right.</p> <p>I have a couple of problems:</p> <ol> <li>first the arrow don't look like part of the slider menu which is separate from all the other components.</li> <li>I have a strange bug that when I open the menu, it first can appear in different sizes according to content height, then the height changes in the same manner.</li> <li>When I open the slider menu, the upper menu's height get extended with no reason.</li> </ol> <p>Any clue how to fix this bugs or make this menu look prettier? </p> <p>The code to the menu is the following:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> $(function () { $("#arrow_btn").click(function () { $("#navbar").toggleClass('active'); $("#upper_left_menu").toggleClass('open_left_menu'); console.log("look for arrow btn element"); console.log("upper_left_menu", $("#upper_left_menu")); console.log('$("#navbar")', $("#navbar")); }); $(".project_item").click(function (event) { var list = $(this).siblings(); var i = $(this).find('i'); $(list).toggleClass('closed_nested_list'); if ($(i).hasClass('fa-plus')) { $(i).removeClass('fa-plus'); $(i).addClass('fa-minus'); } else { $(i).addClass('fa-plus'); $(i).removeClass('fa-minus'); } console.log('traverse over all project items'); console.log('i', i); console.log('list', list); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code> .arrow { color: gray; font: bold 11px "Helvetica"; padding: 2px; text-decoration: none; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; } .arrow:after { background: gray; color: #FFF; content: "&gt;"; display: inline-block; font: bold 11px "Georgia"; height: 25px; line-height: 25px; margin-left: 2px; text-align: center; width: 25px; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; } .arrow:hover:after{ background: #1679C6; } .upper_menu{ position:relative; display:block; background-color: #F2F6F7; width: 100%; height: 20%; } .open_left_menu{ background-color:white; width:30px; height:30px; box-shadow: 4px 0 5px rgba(0,0,0,0.2); z-index: 1; -webkit-transition: all 600ms ease; -moz-transition: all 600ms ease; -ms-transition: all 600ms ease; -o-transition: all 600ms ease; transition: all 600ms ease; } #upper_left_menu{ } #upper_right_menu{ position: absolute; top: 0px; right: 0px; } #exclamation-triangle, #envelope{ font-size: 24px; } .warning, .email{ margin: 10px; } #exclamation_notifications_count, #email_notifications_count{ padding-left: 5px; } #navbar { position: absolute; left: -16em; top: 0; bottom: 0; height: 100%; background-color: white; box-shadow: 4px 0 5px rgba(0,0,0,0.2); z-index: 1; cursor: pointer; margin-top: 26px; animation: 10s; } #navbar ul { width: 224px; list-style-type: none; margin: 0; padding: 1em; } /* hovering */ #navbar, #navbar * { -webkit-transition: all 600ms ease; -moz-transition: all 600ms ease; -ms-transition: all 600ms ease; -o-transition: all 600ms ease; transition: all 600ms ease; } #navbar.active { left: 0px; } .nested_list{ display:inline-block; visibility:visible; } .closed_nested_list{ display:none; } .project_item{ font-family:'Segue UI', Calibri, arial, verdana, sans-serif; font-size: 18px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;nav class="upper_menu"&gt; &lt;div id="upper_left_menu"&gt; &lt;span id="arrow_btn" class="arrow"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="upper_right_menu"&gt; &lt;a href="#" class="warning"&gt;&lt;i id="exclamation-triangle" class=" fa fa-exclamation-triangle"&gt;&lt;/i&gt;&lt;span id="exclamation_notifications_count"&gt;2&lt;/span&gt;&lt;/a&gt; &lt;a href="#" class="email"&gt;&lt;i id="envelope" class=" fa fa-envelope-o"&gt;&lt;/i&gt;&lt;span id="email_notifications_count"&gt;5&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; &lt;nav id="navbar"&gt; &lt;ul&gt; &lt;li class="project_container"&gt; &lt;span class="project_item" &gt; &lt;i class="fa fa-plus"&gt;&lt;/i&gt; FDR Project &lt;/span&gt; &lt;ul id="listOne" class="nested_list closed_nested_list"&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit01&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit02&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit03&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="project_container"&gt; &lt;span class="project_item" href="#"&gt;&lt;i class="fa fa-plus"&gt;&lt;/i&gt; Niagara Project&lt;/span&gt; &lt;ul id="listTwo" class="nested_list closed_nested_list"&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit01&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit02&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit03&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="project_container"&gt; &lt;span class="project_item" href="#"&gt;&lt;i class="fa fa-plus"&gt;&lt;/i&gt; Jarvis Plant&lt;/span&gt; &lt;ul id="listThree" class="nested_list closed_nested_list"&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit01&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit02&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit03&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="project_container"&gt; &lt;span class="project_item" href="#"&gt;&lt;i class="fa fa-plus"&gt;&lt;/i&gt; Jarvis Plant&lt;/span&gt; &lt;ul id="listFour" class="nested_list closed_nested_list"&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit01&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit02&lt;/li&gt; &lt;li class="list_item"&gt;&lt;img height="24" width="24" src="../images/engine-lighting-bolt.png" /&gt; Unit03&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
3
Jax ws web service
<p>This is my server side code:</p> <pre><code>package com.son; import javax.jws.WebService; @WebService public class Calculator1 { public int add(int a, int b) { return (a + b); } public int sub(int a, int b) { return (a - b); } } </code></pre> <p>This is my publisher code.</p> <pre><code>package com.son.endpoint; import javax.xml.ws.Endpoint; import com.son.Calculator; import com.son.Calculator1; public class CalcEndpointPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8089/CalcWS/Calculator1", new Calculator1()); } } </code></pre> <p>After this I have used wsgen command.</p> <p>This is, my client code</p> <pre><code>package com.son.client; import com.son.Calculator1; import com.son.Calculator1Service; public class CalcClient { public static void main(String[] args) { int a = 67; int b = 898; Calculator1Service calcService = new Calculator1Service(); Calculator1 calc = calcService.getCalculator1Port(); System.out.println(a + " + " + b + " = " + calc.add(a, b)); System.out.println(a + " - " + b + " = " + calc.sub(a, b)); } } </code></pre> <p>I am getting the answer. My senior is asking how to pass an object, or how we can pass n number of values, please tell me how to code, as I am new in this, and also tell the code please.</p> <p>Thanks in advance</p>
3
R maps package displaying county as wildcard pattern
<p>R maps package displaying county as wildcard pattern. Ex. While trying to draw - <code>map("county", region=c("texas,gray"))</code> the map fetches counties - "grey" and "greyson", whereas the expectation is to draw only gray county. Any fixes/workarounds?</p>
3
Update application layout icon
<p>In my application controller I have a method which I use to set notifications and the notifications icon on the application layout menu. I run this method with before_action:</p> <pre><code>def set_notifications if user_signed_in? @notifications = Notification.where(user_id: current_user.id) @notifications.each do |n| if n.read == false return @icon_path = 'notification-alert-icon' end end @icon_path = 'notification-icon' end end </code></pre> <p>This works fine as I get the correct notification icon when I have unread notifications:</p> <pre><code>&lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;&lt;%= image_tag(@icon_path) %&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;% if @notifications == 0 %&gt; &lt;li class="text-center" style="color:white;"&gt;Você ainda não tem notificações&lt;/li&gt; &lt;% else %&gt; &lt;% @notifications.each do |n| %&gt; &lt;li&gt;&lt;%= link_to n.question.title, question_path(n.question), class: 'text-center' %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to 'Ver todas as notificações', "#" %&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>When the user clicks the notification icon, then clicks the question he was notified on, the questions_controller marks that notification as read (inside the show action):</p> <pre><code>notifications = Notification.where(question_id: question.id) if Notification.exists?(question_id: question.id) if notifications notifications.each do |notification| if notification.user_id == current_user.id notification.read = true notification.save end end end </code></pre> <p>What I haven't been able to do is: how do I update the @notifications object and the notification icon on the application layout after marking the notification as read? I know I can call the method set_notifications but that alone won't reload application layout and change the icon right?</p>
3
Update Google Play services for an old app
<p>I have an old app which uses Google play services 5.08. Since the app uses kiosk mode, we never updated google play services on the device. Now I have to update the google play services to 8.4. I also want the already existing users to use the app without getting crashes. So how do I support both of 5.08 and 8.4 APIs to support in the app? I see Google doesn't expose the APIs of 5.08 when I use 8.4 in Gradle file. </p>
3
Retrieving data from Azure
<p>I created an azure account connected it with a current android application, created a table and added data to this table from within my application. The text is added into a textbox and one the button is clicked the data is sent to Azure. I want to be able to retrieve this data in the "Text" field in a list. Could anyone show me how I would do this. </p> <p>My Code is as fallows</p> <p>MainActivity</p> <pre><code>public class MainActivity extends AppCompatActivity { private MobileServiceClient mClient; private EditText title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { mClient = new MobileServiceClient( "https://craigsapp.azure-mobile.net/", "BTkcgnFQvevAdmmRteHCmhHPzdGydq84", this ); } catch (MalformedURLException e) { e.printStackTrace(); } } public void onClickB(View view) { title= (EditText) findViewById(R.id.editText); Item item = new Item(); item.Text = title.getText().toString(); mClient.getTable(Item.class).insert(item, new TableOperationCallback&lt;Item&gt;() { public void onCompleted(Item entity, Exception exception, ServiceFilterResponse response) { if (exception == null) { // Insert succeeded } else { // Insert failed } } }); } } </code></pre> <p>Item Activity </p> <pre><code>public class Item { public String Id; public String Text; } </code></pre>
3
Bash history command, store whole term ignoring any options
<p>I have a script which repeatedly waits for user entered text and then calls another script with the entered text. <a href="https://stackoverflow.com/a/6794304/2102457">SO code credit, 'version 1'.</a></p> <pre class="lang-bash prettyprint-override"><code>while IFS="" read -r -e -p 'Enter search term: ' -a search_term; do if [ "$search_term" != "" ]; then /path/to/script ${search_term[@]} else echo "Bye." exit 0 fi history -s ${search_term[@]} done </code></pre> <p>It calls the Bash builtin <code>history</code> command to allow scrolling up to previous entries.</p> <p>The problem is when <code>search_term</code> begins with an option, e.g. <code>-x exclude_this search term</code>. This results in the following error: <code>history: -x: invalid option</code>. How do I force the <code>history</code> command to add the whole of <code>search_term</code> as a history entry and not to process any options that <code>search_term</code> may begin with? i.e. The whole of <code>-x exclude_this search term</code> should be added as a history entry.</p> <p>Note: This can actually be solved by adding an initial empty string like this <code>history -s "" ${search_term[@]}</code> but each history entry is then prefixed by a space and repeated use adds a space each time pushing the entries further and further right. So this is a rather inelegant solution.</p> <p>Thanks.</p>
3
Node , SSh2 Server waiting for input
<p>I am currently building a Web based SSH client. I am using node and SSH2 module to connect to Linux machine . The issue is trying to identify when the server is waiting for a response from the client say "sudo" .</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> this.onWsMessage = function(packet) { log('Message Received from '); if (cmd != '') { log('-----------------------------------------&gt;' + cmd); source[this.getId()].sshStream.write(cmd + '\n'); } }; var client = clients[cid]; sshClient .on('ready', function() { console.log('CONNECTED'); sshClient.shell({pty: true}, function(err, stream) { _shellHandler(err, stream, client); }); }) .on('error', function(err) { console.log('ERROR', err); }) .connect(serverInfo); } function _shellHandler(err, stream, client) { source[client.getId()].sshStream = stream; stream .on('close', function() { log('ssh connection close'); //sshClient.end(); this._client.end(); }) .on('data', function(data) { console.log(stream); var msg = data.toString().replace(msgPattern, ''); this.sendUTF(msg, 'ssh'); }.bind(client)); }</code></pre> </div> </div> </p> <p>I have been going through the documentation and i was unable to identify any event that trigger as a result.</p>
3
PowerShell Set-AuthenticodeSignature - IncludeChain Options Advantages/Disadvantages?
<p>When using <code>Set-AuthenticodeSignature</code>, there is an option called <code>IncludeChain</code>. While there is documentation about what each of the options are, I haven't been able to uncover much guidance surrounding the advantages/disadvantages of each setting (when you would pick one setting over another). </p> <p>Everywhere I see <code>IncludeChain</code> in examples, it is always set to <code>All</code>. I think <code>All</code> is likely the best answer, but I'd like to understand the benefits and disadvantages of each of the settings. </p> <ul> <li><code>Signer</code> </li> <li><code>NotRoot</code> (default) </li> <li><code>All</code></li> </ul> <p>Other than <code>All</code> making the file quite a bit bigger, what are the specific advantages and disadvantages of each of the settings?</p> <h3>References</h3> <ul> <li><a href="https://technet.microsoft.com/en-us/library/hh847874.aspx" rel="nofollow noreferrer">https://technet.microsoft.com/en-us/library/hh847874.aspx</a></li> <li><a href="http://go.microsoft.com/fwlink/?LinkID=113391" rel="nofollow noreferrer">http://go.microsoft.com/fwlink/?LinkID=113391</a></li> <li><a href="https://stackoverflow.com/q/912955/18475">How Can I Prevent Needing to Re-sign My Code Every 1 or 2 Years?</a></li> </ul> <h3>Example</h3> <pre><code>$certPfx = "super secret location" $certPassword = "super secret password" $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPfx, $certPassword) Set-AuthenticodeSignature -Filepath "ps1 file location" ` -Cert $cert ` -TimeStampServer "url to timestamp server" ` -IncludeChain All ` -HashAlgorithm SHA256 </code></pre>
3
javascript adds body_0$ to ID selector
<p>I am doing a form validation using and the javascript works with just input fields but not Textboxes. I use:</p> <pre><code> var _firstname; var box; try { box = $("#firstname"); alert("You must enter a first name"); box.focus(); return false; }catch{ } </code></pre> <p>with a front end of :</p> <pre><code> &lt;div&gt;First Name &lt;span class="required"&gt;*&lt;/span&gt;&lt;/div&gt; &lt;asp:TextBox ID="firstname" name="firstname" runat="server" /&gt; </code></pre> <p>When I debug the code, it adds a body_0$ to the front of the ID (ie: body_0$firstname), so I'm guessing that's why its always popping up with the "You must enter a first name" alert. Is there a work around?</p>
3
How to modify a two dimensional array passed to a function?
<p>My function is as following</p> <pre><code>func helper(root: TreeNode?, _ result: [[Int]], _ list: [Int], _ sum: Int, _ total: Int) { list.append(root!.val) if(total + root!.val == sum &amp;&amp; root?.left == nil &amp;&amp; root?.right == nil) { result.append(list) } if(root?.left != nil &amp;&amp; sum &lt; total + root!.val) { helper(root!.left, result, list, sum, total + root!.val) } if (root?.right != nil &amp;&amp; sum &lt; total + root!.val) { helper(root!.right, result, list, sum, total + root!.val) } } </code></pre> <p>When I tried to modify <code>list</code> and <code>result</code> it gave me errors . I've searched that <code>input</code> keyword can be used to pass parameters by reference, then it can be modified locally as well as externally, but I couldn't make the syntax correct. How can I make it work? Or there is any better way I can modify them?</p>
3
Drag and drop players in a results table inside form to send to PHP (using DragulaJS)
<p>I'm developing the front-end of an app to track tournaments. In one page, the user needs to update the tournament result by dragging a player from a list on the left inside the final results table on the right, that I'll send to a PHP backend for processing (I'm not developing the backend, just need to send the correct data via POST). My requirements are:</p> <ol> <li>Have a list of players</li> <li>Have a results table with fixed positions in each row (one row for 1st, one row for 2nd).</li> <li>Each position will have 4 related inputs, all named <code>position-1-NAME</code>, in the same row, but different columns</li> <li>The user should be able to drag players into each position</li> <li>One player can only be in one position, and each position can only have one player</li> <li>When a player is placed in the table, he should be removed from the list</li> </ol> <p>I've tried several approaches but the one that came close is using the <a href="https://github.com/bevacqua/dragula" rel="nofollow">Dragula JS</a> plugin.</p> <p>Then, I create the list of players with an <code>ul</code> with the <code>id</code> to make it a container in Dragula:</p> <pre><code> &lt;ul id="players-container"&gt; &lt;li&gt; Player 1 &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Then, I have a <code>table</code> inside a <code>form</code> tag, and the name of the fields are all named according to the position, like <code>position-1-name-of-the-input</code>:</p> <pre><code>&lt;form method="POST" action="file_to_process_form.php"&gt; &lt;thead&gt; &lt;th&gt;Position&lt;/th&gt; &lt;th&gt;Player&lt;/th&gt; ... &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; 1st Position &lt;/td&gt; &lt;td class="target"&gt; &lt;input type="text" name="position-1-player-name" value="" hidden&gt; &lt;/td&gt; &lt;td&gt; ...other inputs &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>Then, in JavaScript, I made a hack to grab the <code>text()</code> from the <code>li</code> being dragged and put it inside the <code>value</code> attribute of the <code>input</code> of the <code>table</code>, so that I can send the name of the player in the first position to the backend. The code:</p> <pre><code>dragula([document.querySelector('#players-container'), document.querySelector('.target')], { isContainer: function(el){ return el.classList.contains('target'); }, revertOnSpill: true }).on('drop', function(el, target, source, sibling){ elValue = $(el).text(); $(target).find('input').attr('value', elValue); }); </code></pre> <p>So far, this is working with some bugs:</p> <ol> <li><p>I can drop two players in the same <code>td</code>, and they will show both dragged <code>li</code> in the UI, but the form will only have the value of the last dropped player.</p></li> <li><p>If I drag the player into all positions, one after another, all inputs will have the value of his name until I drag another player into that position.</p></li> </ol> <p>So, I want to accomplish a couple of things:</p> <ol> <li><p>Allow only one player inside each <code>td class="target"</code>. I've tried to disable the <code>td</code> by removing the <code>.target</code> class but then I can't move the player again after being dropped.</p></li> <li><p>Remove the value of the input when I drag the player out.</p></li> </ol> <p>I know this is a bit of a hack but I don't have a lot of experience with JS/jQuery and this is the only solution that remotely works so far.</p> <p>My questions:</p> <ol> <li><p>How can I prevent multiple players form being dragged to the same <code>td</code> with Dragula or JS / jQuery code?</p></li> <li><p>[SOLVED -- see edit] How can I remove the <code>value</code> of the <code>input</code> when I drag a player OUT of the <code>td</code>?</p></li> <li><p>Do you know a better way to implement these requirements to recommend?</p></li> </ol> <p><strong>EDIT</strong></p> <p>I've managed to solve the question 2 by adding the following code:</p> <pre><code>dragulaObject.on('drag', function(el, source) { $(source).find('input').attr('value', ''); }); </code></pre>
3
Positioning the content of a navbar to the center
<p>I am trying to center the content inside my navigation bar to the center. Used the class navbar-center but it does not work as you can see on the code above.</p> <pre><code> &lt;div class="container"&gt; &lt;nav class="navbar navbar-default"&gt; &lt;div class="container-fluid"&gt; &lt;ul class="nav navbar-nav navbar-center"&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Public&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Comercial&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Residential&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--end of div--&gt; &lt;/nav&gt;&lt;!--end of navbar--&gt; &lt;/div&gt;&lt;!-- end of div container--&gt; </code></pre> <p>I also tried the following code on my css but it didn't work either:</p> <pre><code> .nav{ text-align: center; } </code></pre> <p>A help on it will be appreciated.</p>
3
issue with a variable in javascript
<p>I'm stuck on this little metronome project. It's supposed to flash back and forth between two background colors. It works fine as long as both colors are defined (switch "col" in JS line 12 to any color and it works). However, I'm also trying to make it so I can randomize one of the colors onclick. I can tell (console.log) that my number randomizer is producing a correct hex color value for my variable "col" but I can't get that variable to work. I have tried "col" without quotes.</p> <p>Here is a link to the codepen: <a href="http://codepen.io/Fedreg/pen/xVqwjQ/" rel="nofollow noreferrer">http://codepen.io/Fedreg/pen/xVqwjQ/</a></p> <pre><code> &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;div id="title"&gt; flashnome &lt;/div&gt; &lt;div id="desc"&gt; the silent metronome &lt;p&gt; &lt;button onclick="slower();" id="button1"&gt; slower &lt;/button&gt; &lt;button onclick="faster();" id="button1"&gt; faster &lt;/button&gt; &lt;/p&gt; &lt;p&gt; &lt;button onclick="change();" id="button1"&gt;Change Color&lt;/button&gt; &lt;/p&gt; &lt;/div&gt; &lt;/body&gt; @import url(https://fonts.googleapis.com/css?family=Josefin+Sans:400,700); html, body { height: 100%; width:100%; } #title { text-align: center; color: white; font-size: 5em; font-family: 'Josefin Sans', sans-serif; margin: auto; text-transform: uppercase; padding: 2em 0 .2em; } #desc { text-align: center; color: white; font-size: 2em; font-family: 'Josefin Sans', sans-serif; margin: auto; text-transform: uppercase; padding: 0; } #button1 { text-align: center; font-size: .7em; font-family: 'Josefin Sans', sans-serif; margin: 0 auto; text-transform: uppercase; padding: 8px; } var x = 500; var flashStep = 1; var myInterval; function change() { var col = '#' + (Math.random().toString(16) + '000000').slice(2, 8); console.log(col); } function flash() { if (flashStep == 1) { document.bgColor = "col"; flashStep = 2; } else { document.bgColor = "#333"; flashStep = 1; } } function faster() { window.clearInterval(myInterval); myInterval = window.setInterval(flash, x -= 25); } function slower() { window.clearInterval(myInterval); myInterval = window.setInterval(flash, x += 25); } myInterval = window.setInterval(flash, x); function change() { var col = '#' + (Math.random().toString(16) + '000000').slice(2, 8); console.log(col); } </code></pre>
3
Can't get spaces in paths correct in a Bat file
<p>I'm stuck and could use some help with this batch script.<br> <code>%output%</code>gives the correct path even with spaces.<br> <code>%input%</code> gives me <code>Error: The file 'C:\Input' could not be opened for reading: open file error.</code><br> The code is so similair, I don't understand why it reads one but not the other.<br> I've tryed with <code>"input=C:\Input folder\"</code> and <code>input="C:\Input folder\"</code> but still nothing.</p> <p>I'm getting the folder paths thru jscript in a HTA file.</p> <p>The code works great if I change the input to a folder without any space like <code>C:\Input\</code></p> <p>Thanks in advance.</p> <pre><code>@echo off &amp; setlocal set input=C:\Input folder\ set output=C:\Output folder\ set PATH=%PATH%;C:/Program Files/MKVToolNix/ for %%a in (%input%*.mkv) do ( mkvmerge -q -o "%output%%%~na%%~xa" -s eng --title %%a "%%a" if errorlevel 1 ( echo Warnings generated! ) else ( for %%b in (%output%*.mkv) do ( mkvpropedit -q "%output%%%~na%%~xa" --edit track:s1 --set flag-default=1 if errorlevel 1 ( echo %%~na%%~xa - Error! ) else ( echo %%~na%%~xa - Complete. ) ) ) ) endlocal pause </code></pre>
3
Insert class in PHP code for Woocommerce
<p>I am a bit of a beginner in php and I am trying to target 3 text outputs in a php file and give them a unique class so I can style them via css. </p> <pre><code>if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } $customer_id = get_current_user_id(); if ( ! wc_ship_to_billing_address_only() &amp;&amp; get_option( 'woocommerce_calc_shipping' ) !== 'no' ) { $page_title = apply_filters( 'woocommerce_my_account_my_address_title', __('My Addresses:', 'woocommerce') ); $get_addresses = apply_filters( 'woocommerce_my_account_get_addresses', array( 'billing' =&gt; __( 'Billing Address:', 'woocommerce' ), 'shipping' =&gt; __( 'Shipping Address:', 'woocommerce' ) ), $customer_id ); } else { $page_title = apply_filters( 'woocommerce_my_account_my_address_title', __( 'My Address:', 'woocommerce' ) ); $get_addresses = apply_filters( 'woocommerce_my_account_get_addresses', array( 'billing' =&gt; __( 'Billing Address:', 'woocommerce' ) ), $customer_id ); } $col = 1; ?&gt; </code></pre> <p>I am trying to target 'My Addresses:' as well as 'Billing Address:' and 'Shipping Address:'.</p> <p>I have worked with this just a bit before and I never had to add a class inside php code, but surely it must be possible, but I can't seem to find any info on where exactly to add my div class, p class etc..</p> <p>Any help would be greatly appreciated!</p> <p>Thanks a lot,</p> <p>Vaya</p>
3
SCNAction of scenekit only executing action once
<p>I want objects that I created to "fall" down the view of the controller. I also want an infinite amount of objects to fall, so continuing the animation until the the user goes to another view controller. I used a for-loop to make up to 100 objects. Here is the code...</p> <pre><code> SCNMaterial *blackMaterial = [SCNMaterial material]; blackMaterial.diffuse.contents = [UIColor blackColor]; int xcoordinate = arc4random_uniform(20); int xcoordinateTwo = arc4random_uniform(20); for (int i = 0; i &lt; 100; i++){ SCNText *x = [SCNText textWithString:@"X" extrusionDepth: 2.75]; SCNNode *xNode = [SCNNode nodeWithGeometry:x]; xNode.position = SCNVector3Make(xcoordinate, 15.0, -60.0); xNode.scale = SCNVector3Make(2.0, 2.0, 0.45); x.materials = @[blackMaterial]; x.chamferRadius = 5.0; SCNAction *moveTo = [SCNAction moveTo:SCNVector3Make(xcoordinate, -100.0, -60.0)duration:10.0]; [xNode runAction:moveTo]; SCNTorus * torus = [SCNTorus torusWithRingRadius:6.30 pipeRadius:2.30]; SCNNode *torusNode = [SCNNode nodeWithGeometry:torus]; torusNode.position = SCNVector3Make(xcoordinateTwo, 15.0, -60.0); torus.materials = @[blackMaterial]; torusNode.eulerAngles = SCNVector3Make(-1.5708, 0, 0); [torusNode runAction:moveTo]; [scene.rootNode addChildNode:torusNode]; [scene.rootNode addChildNode:xNode]; } </code></pre> <p>The problem for me is that only one of each object is being created instead of a 100. Can I anyone help me with what the issue is.</p>
3
javax.mail.AuthenticationFailedException when sending from AWS Linux AMI
<blockquote> <p>I have made the gmail settings to have less secure app. My application is hosted on AWS Linux AMI. The same application works fine on localhost in windows </p> </blockquote> <pre><code>public MailServiceImpl() { java.util.Properties properties=new java.util.Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "465"); session = Session.getInstance(properties, new GmailAuthenticator( "[email protected]", "password"){ public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication("[email protected]", "password"); } }); } private void send(InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc, String subject, String text, InternetAddress from, InternetAddress[] replyTo,String[] attachFiles) throws NoValidRecipientsException { try { // make sure that there are recipients if ((to == null) &amp;&amp; (cc == null) &amp; (bcc == null)) { log.warn("no valid recipient email address(es) specified"); throw new NoValidRecipientsException(); } // create message MimeMessage message = new MimeMessage(session); // set recipients message.setRecipients(Message.RecipientType.TO, to); message.setRecipients(Message.RecipientType.CC, cc); message.setRecipients(Message.RecipientType.BCC, bcc); // set replyto if (replyTo != null) { message.setReplyTo(replyTo); } // set from if (from != null) { message.setFrom(from); } else { log.warn("no valid 'from' email address specified"); } // set subject message.setSubject(subject); // set content type as text for now. // message.setText(text); /** Attachment Starts **/ if(attachFiles !=null){ // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(text, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments if (attachFiles != null &amp;&amp; attachFiles.length &gt; 0) { for (String filePath : attachFiles) { MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(filePath); } catch (IOException ex) { ex.printStackTrace(); } multipart.addBodyPart(attachPart); } } // sets the multi-part as e-mail's content message.setContent(multipart); }else{ message.setContent(text, "text/html"); } /*** Attachment ends **/ // send the message log.info("before Transport send"); Transport.send(message); } catch (MessagingException e) { log.error("error sending email", e); throw new MailServiceException(e); } } </code></pre> <p>public class GmailAuthenticator extends Authenticator {</p> <pre><code> String user; String pw; public GmailAuthenticator (String username, String password) { super(); this.user = username; this.pw = password; } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pw); } } </code></pre> <p>I get the below Error </p> <pre><code> 08:07:52,876 ERROR MailServiceImpl:280 - error sending email javax.mail.AuthenticationFailedException at javax.mail.Service.connect(Service.java:306) at javax.mail.Service.connect(Service.java:156) at javax.mail.Service.connect(Service.java:105) at javax.mail.Transport.send0(Transport.java:168) at javax.mail.Transport.send(Transport.java:98) at increed.service.mail.MailServiceImpl.send(MailServiceImpl.java:278) at increed.service.mail.MailServiceImpl.send(MailServiceImpl.java:134) at increed.service.mail.Messenger.sendCustomerEmail(Messenger.java:113) at increed.com.user.action.CollectionNavigation.fetchCustomerMailDetails(CollectionNavigation.java:429) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionI: at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(Cha: at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) increed.service.mail.MailServiceException: increed.service.mail.MailServiceException: javax.mail.AuthenticationFailedException at increed.service.mail.MailServiceImpl.send(MailServiceImpl.java:136) at increed.service.mail.Messenger.sendCustomerEmail(Messenger.java:113) at increed.com.user.action.CollectionNavigation.fetchCustomerMailDetails(CollectionNavigation.java:429) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) </code></pre>
3
Remove pattern in first occurence from right to left in file name in bash
<p>Say I have a string file name <code>aa.bb.cc.xx.txt</code> I would like to remove the first content between . and . (remove .xx) before the .txt to have <code>aa.bb.cc.txt</code>. </p> <p>I don't want to use rev, cut and rev because this uses 3 commands</p> <pre><code>echo 'aa.bb.cc.xx.rpm' |rev | cut -d '.' --complement -s -f 2 |rev </code></pre> <p>Is there any better solution by using bash? Thanks</p>
3
Listen for new urls of ads posted to site
<pre><code>for (var i = 3848450; i &gt; 3848400; i--) { var query = { url: 'http://classifieds.rennug.com/classifieds/viewad.cgi?adindex=' + i, type: 'html', selector: 'tr', extract: 'text' } , uriQuery = encodeURIComponent(JSON.stringify(query)), request = 'http://127.0.0.1:8888//?q=' + uriQuery + '&amp;callback=?'; jQuery.getJSON(request, function (data) { var datastring = data[0].results; var datasplit = datastring.toString().split('Sign'); $('#inner-content').append(datasplit[0]); }); } </code></pre> <p>I want to listen for new URLs of ads that are posted without writing some kind of arbitrary code that takes up a lot of memory looping through new URLs, etc. I can do that but it seems redundant and such as my code listed above. Im using noodle.js to get the info from the pages. Now I would like a way to listen for new urls instead of looping through every possible url from a to z. Since I don't know z it's a safe bet I'll be using an if statement but how would one go about incorporating this nth URL without ending up with undefined iterations. Im still learning and find this place has many helpful people. This is simply a fun project I'm doing to learn something new.</p>
3
Android Keyboard - not reachable in cordova app
<p>I am writing a kiosk application for a rooted Android 4.4 tablet. For this I am using <strong>cordova</strong>. This application can only be controlled with a bluetooth remote control. Unfortunetely there is no Touch, Mouse or Keyboard available.</p> <p>Using the app with the remote control basically is no problem, but unfortunately it is impossible for the user to fill out <code>&lt;input&gt;</code> -fields!</p> <p>If the user navigates to an input field, the android-software-keyboard successfully shows up, but it never gets the focus of the remote control. No matter what you press or what you try - you cannot reach it with the remote control. (See attached screenshot)</p> <p>I have found a <a href="https://github.com/driftyco/ionic-plugin-keyboard" rel="nofollow noreferrer">cordova plugin</a>, but this is mainly for issues when the software-keyboard doesn't show up at all. It doesn't help in my case.</p> <p><strong>How can I fix this? How can I focus the keyboard in Java or JavaScript?</strong></p> <p><a href="https://i.stack.imgur.com/duplM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/duplM.png" alt="enter image description here"></a></p>
3
How to keep my unity3d program (c# v3.5) even if there is an exit(1) in a c++ dll / native plugin?
<p>I use a c++ dll in my unity3d project and if any input is incorrect, the library use exit(1), which makes unity3d crashes/closes. Is there any way to avoid this behavior without modifying the original c++ code ?</p>
3
SQL simplify table of many columns into less column
<p>I have a table shown like this :</p> <pre><code>PO_ID | PO_TYPE | PO_STAT | MR_ID | MR_TYPE | MR_STAT | IN_ID | IN_TYPE | IN_STAT 1 | A1 | CO | 1 | B1 | DR | 1 | C1 | CO 2 | A1 | CO | 2 | B2 | CO | 2 | C1 | CO </code></pre> <p>I'd like to simplify this table to become like this : </p> <pre><code>ID | TYPE | STAT 1 | A1 | CO 2 | A1 | CO 1 | B1 | DR 2 | B2 | CO 1 | C1 | CO 1 | C1 | CO </code></pre> <p>How is it possible ? </p>
3
Multi-provision, multi-vm Vagrantfile vm filtering
<p>When provisioning for EC2, I only want the 'app' vm. When provisioning locally, I want 'app' and 'pg'. I'm having trouble writing a single Vagrantfile that can cater to both scenarios.</p> <p>I'd like to invoke this by just using a provider as a way to make it work:</p> <pre><code>vagrant up --provider=aws </code></pre> <p>vs</p> <pre><code>vagrant up --provider=virtualbox </code></pre> <p>AWS would spawn just app. Virtualbox would spawn app and pg.</p> <p>I'm using vagrant 1.7.2</p> <p>I have something like the following Vagrantfile:</p> <pre><code>... Vagrant.configure(2) do |config| ... config.vm.define "app" do |app| # setup app here ... config.vm.provider :virtualbox do |vbox, override| # setup virtualbox for app vm here ... end ... config.vm.provider :aws do |aws, override| # setup aws for app vm here ... end end ... config.vm.define "pg" do |pg| # setup postgres here ... end ... end </code></pre> <p>Edit: clarified invocation.</p>
3
JavaFX DataBinding behaves strange
<p>I have a Worker that fills a result list. A ListView is bound to this result list and gets filled with partial results as soon as they are available. Works great!</p> <p>Then there is a button that works with items in the list. So it should be disabled as long the list is empty. This works for every other list. But not for this one.</p> <p>I have reduced the sample by stripping the UI components and just using properties. The result is the same. Either there is some kind of bug or I do not understand how the binding works.</p> <p>I hope for any helping comments on this.</p> <p>Just put this code into a main() method and you should see the problem. I am using Java 1.8 Update 74.</p> <pre><code>// a list of items, e.g. in a list view ReadOnlyObjectWrapper&lt;ObservableList&lt;String&gt;&gt; items = new ReadOnlyObjectWrapper&lt;&gt;( FXCollections.observableArrayList(new ArrayList&lt;&gt;())); // a button that is disabled if there are no items BooleanProperty disabled = new SimpleBooleanProperty(); disabled.bind(Bindings.createBooleanBinding(() -&gt; Boolean.valueOf(items.get().isEmpty()), items)); // a list with results, e.g. from a worker ReadOnlyObjectWrapper&lt;ObservableList&lt;String&gt;&gt; results = new ReadOnlyObjectWrapper&lt;&gt;( FXCollections.observableArrayList(new ArrayList&lt;&gt;())); // the items are bound to the results (the list is showing partial result then) items.bind(results); // the button is still disabled System.out.println(disabled.get()); // expected true !WORKS! // add a result (should inform the items and the button) results.get().add("Hello"); // both list should be identical now System.out.println(results.get()); // expected [Hello] !WORKS! System.out.println(items.get()); // expected [Hello] !WORKS! // the button should not be disabled anymore System.out.println(disabled.get()); // expected false !FALIED! // try to re-bind the button disabled.unbind(); disabled.bind(Bindings.createBooleanBinding(() -&gt; Boolean.valueOf(items.get().isEmpty()), items)); System.out.println(disabled.get()); // expected false !WORKS! </code></pre>
3
r pre-specify parts of file path
<p>I currently have individual scripts for each species in my analysis, I'd like to try and get it into one script where I can specify at the beginning which species/year of data etc. I am analysing. I'd like to know if it is possible to instead set at the beginning of the script certain objects and then have more generic code to read in the files. for example;</p> <p>existing code</p> <pre><code>ABR &lt;- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Abroad.csv",sep=",",skip = 2,header=T) SCO &lt;- read.csv("Y:/Pelagic Work/FIN Data/2015/HOM/Scotland.csv",sep=",",skip = 2,header=T) </code></pre> <p>I'd like something like;</p> <pre><code>Year &lt;- 2015 Species &lt;- HOM ABR &lt;- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Abroad.csv",sep=",",skip = 2,header=T) SCO &lt;- read.csv("Y:/Pelagic Work/FIN Data/Year/Species/Scotland.csv",sep=",",skip = 2,header=T) </code></pre>
3
Javascript onchange only with specific option class
<p>I have a dropdown box, when onchange redirects to a url - works fine. However I only want it to trigger the onchange when the option has a class of ".level-0" - how do I do that?</p> <pre><code>&lt;script type="text/javascript"&gt; &lt;!-- var dropdown = document.getElementById("cat"); function onCatChange() { if ( dropdown.options[dropdown.selectedIndex].value != -1 ) { location.href = "&lt;?php echo home_url();?&gt;/?sfid=770&amp;_sft_city-type="+dropdown.options[dropdown.selectedIndex].value; } } dropdown.onchange = onCatChange; --&gt; &lt;/script&gt; </code></pre>
3
No animations/selections in Tabhost
<p>I am trying to implement a tabview with the nice gradual change from one view to another animation and have the current tab highlighted. At current all I can get is the basic tabview that functions, but does instant switching of tabs and no highlighting of selections. Here is my current code:</p> <pre><code>package com.example.ex.test; public class MainActivity extends navBar { private FragmentTabHost mTabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"), smithingTable.class, null); mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"), smithingTable2.class, null); mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"), Map.class, null); } } </code></pre> <p>meanwhile in my activity main I have: </p> <pre><code>&lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0"/&gt; &lt;FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0"/&gt; &lt;FrameLayout android:id="@+id/realtabcontent" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>and in tab1 for example (tab2 is the same but with slight variation)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".DeviceFragment" &gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test1" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView3" android:layout_gravity="center_horizontal" android:src="@drawable/newcomer_map" /&gt; </code></pre> <p></p>
3
Summing in R on time criteria
<p>I have a dataset (called stamp data) that looks like this: </p> <pre><code>Date_Time Cost --------- ----- 01/02/2015 01:52 PM 6 01/02/2015 02:22 PM 2 01/03/2015 02:42 PM 50 01/04/2015 03:01 PM 25 </code></pre> <p>And a different data set (customer data) that looks like this:</p> <pre><code>Purchase_time Amount ------------- --------- 01/02/2015 01:57 PM 5 01/02/2015 02:46 PM 12 01/02/2015 03:13 PM 2 01/02/2015 03:30 PM 8 </code></pre> <p>I would like to sum the "Amount" column from customer data over the Date_Time column from stamp data for different time windows, with the end result looking like this:</p> <pre><code>Date_Time Cost Amount_15min Amount_30min --------- ----- -------------- ------------- 01/02/2015 01:52 PM 6 5 5 01/02/2015 02:22 PM 2 0 12 01/03/2015 02:42 PM 50 12 12 01/04/2015 03:01 PM 25 8 8 </code></pre> <p>Ideally, I would like to create columns for 15 minute intervals, going through to 360 minutes (or more) </p> <p>How can I do this in R? </p> <p>Thanks!</p>
3
Linux: AWK in line
<p>Hopefully anyone can help me changing the code below, my tempfile consists of the code: </p> <pre><code>Temp=8.4* Humidity=70.4% </code></pre> <p>instead of the code </p> <pre><code>Temp = 24 *C, Hum = 40 % </code></pre> <p>which works for below script.</p> <p>I need 8.4 as Temp=# and 70.4 as HUM=#</p> <pre><code>TEMP=$(cat $TMPFILE|grep Temp |awk '{print $3}') if [ $TEMP ] then TEMP=$(cat $TMPFILE|grep Temp |awk '{print $3}') HUM=$(cat $ $TMPFILE |grep Temp |awk '{print $7}') </code></pre> <p>Thank you very much in advance!</p>
3
Bootstrap push/pull questions
<p>I am kind of new to the responsive design and i have some issues working with push pull in bootstrap.</p> <p>First question is it correct to write rows like that?</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;h1&gt;Projects:&lt;/h1&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;textarea class="form-control preventEdit" rows="5" style="min-width: 100%" disabled&gt;PRO&lt;/textarea&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;h1&gt;Description:&lt;/h1&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;textarea class="form-control preventEdit" rows="5" style="min-width: 100%" disabled&gt;DES&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>so at this moment I have something that looks like this at extra small and small devices:</p> <p>|TEXT1|</p> <p>|BOX1|</p> <p>|TEXT2|</p> <p>|BOX2|</p> <p>But I need to make the layout look like this at medium and bigger</p> <p>|TEXT1||TEXT2|</p> <p>|BOX1 ||BOX2 |</p> <p>Tried doing it with push and pull but the result is nothing like I wanted. The boxes just flies away.</p> <p>the code I tried:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;h1&gt;Projects:&lt;/h1&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6 col-md-push-6 "&gt; &lt;textarea class="form-control preventEdit" rows="5" style="min-width: 100%" disabled&gt;PRO&lt;/textarea&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6 col-md-pull-6"&gt; &lt;h1&gt;Description:&lt;/h1&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;textarea class="form-control preventEdit" rows="5" style="min-width: 100%" disabled&gt;DES&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any ideas how to get the result I need?</p> <p>Thank you for you help in advance.</p>
3
Cloning existing sheet and adding information inside it
<p>I have 2 sheets in my <code>.xlsx</code> file. i need to open sheet number <code>1</code> and clone it with data as i do <code>foreach</code> loop.</p> <pre><code>Message: Workbook already contains a worksheet named 'otchet-shablon'. Rename this worksheet first. </code></pre>
3
How to exclude something from the keyboard?
<p>Is it possible on a windows phone to exclude something from the keyboard? I want to exclude the "," and keep only the "." character on the keyboard with <code>InputScope="Number"</code>.</p>
3
Firebug: How do I get only the list console.log() items in the console tab?
<p>During debugging, I feel sometime to see only the console.log() stuffs in the <strong>Console</strong> tab of the developer tools. How do I achieve this? What settings or configuration will help me to achieve this if it all this is a possible way in Firebug?</p>
3
How to get the timer scheduled tasks done in EJB
<h3>Features I am trying to achieve:</h3> <ol> <li>Schedule newsletters to send to customers</li> <li>I have a JSF page that allows user to trigger the schedule. Once a new schedule is triggered, this schedule information will be added to the progress section in the same page. The progress section is a table, of which each row represents a schedule. Each schedule shows how many emails have already been sent. Upon clicking "refresh" button, the progress table is refreshed to show the current status.</li> </ol> <h3>Relavent technologies used</h3> <ul> <li>JSF</li> <li>EJB</li> </ul> <h3>Question</h3> <p>I have already scheduled the emails but <strong>I do not know how to retrieve the status on the JSF page</strong>.</p> <p>My session bean looks something like this:</p> <pre><code>@Stateless public class DefaultEmailScheduleService implements EmailScheduleService { Queue&lt;String&gt; emailAddresses; @Resource TimerService timerService; @EJB EmailService emailService; @PostConstruct private void postConst() { } @Override public void scheduleEmails(ScheduleExpression se, Collection&lt;String&gt; emailAddresses) { //set timer this.emailAddresses = new ConcurrentLinkedQueue&lt;&gt;(emailAddresses); TimerConfig timerConfig = new TimerConfig(); timerConfig.setPersistent(false); Timer timer = timerService.createCalendarTimer(se, timerConfig); //TODO update newsletter/email history } @Timeout public void send(Timer timer) { if(!emailAddresses.isEmpty()){ Newsletter newsletter = new Newsletter(); newsletter.setTo(emailAddresses.poll()); newsletter.setSubject("Testing"); newsletter.setContent("This is testing newsletter"); emailService.send(newsletter); System.out.println(newsletter.getFrom() + " --- sent"); } else { System.out.println("no more emails"); timer.cancel(); } } } </code></pre> <h3>My solution</h3> <p>The somewhat hacking solution I've found so far, which I think would work is that, every time an <code>Newsletter</code> object polled from the queue is sent, I save this <code>Newsletter</code> object to an application scoped bean(like a singleton) so that the newsletters sent can be retrieved by JSF page. When the queue is empty, I clean up the Application bean and update the database. However, I felt like this approach is a smell for some reason.</p> <p>Any help is greatly appreciated.</p>
3
Connect Python3.5 (Mac OS X El Capitan) to Oracle cluster (remote)
<p>I am trying to connect Python3.5 (Mac OS X El Capitan) to Oracle cluster (remote).</p> <p>At first I install Instant Client for x64 (<a href="http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html" rel="nofollow">http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html</a>) Then I install cx_Oracle (<a href="https://pypi.python.org/pypi/cx_Oracle/5.2.1" rel="nofollow">https://pypi.python.org/pypi/cx_Oracle/5.2.1</a>)</p> <p>For installation cx_Oracle I set:</p> <pre><code>export ORACLE_HOME=/Applications/oracle/instantclient_11_2 export LD_LIBRARY_PATH=$ORACLE_HOME export DYLD_LIBRARY_PATH=$ORACLE_HOME export PATH=$ORACLE_HOME:$PATH </code></pre> <p>Now I get error: </p> <pre><code>**Unable to acquire Oracle environment handle** </code></pre> <p>I don't know why it's happen. Any ideas?</p> <p>I even create file <strong>tnsnames.ora</strong> and put it to <code>/Applications/oracle/instantclient_11_2/network/admin/tnsnames.ora</code></p> <pre><code>orcl= (description= (address_list= (address = (protocol = TCP)(host = xxx.xxx.xxx.xxx)(port = 1521)) ) (connect_data = (service_name=oratst) ) ) </code></pre> <p>My python code:</p> <pre><code>import traceback import os os.environ["ORACLE_HOME"] = "/Applications/oracle/instantclient_11_2" os.environ["LD_LIBRARY_PATH"] = "/Applications/oracle/instantclient_11_2" os.environ["DYLD_LIBRARY_PATH"] = "/Applications/oracle/instantclient_11_2" os.environ["LD_LIBRARY_PATH"] = "/Applications/oracle/instantclient_11_2" import cx_Oracle try: connection = cx_Oracle.Connection('user', 'password', cx_Oracle.makedsn('remote_ip', 1521, 'sid')) except Exception as e: print(type(e)) print(e) traceback.print_tb(e.__traceback__) </code></pre> <p>P.S. cx_Oracle - is very strange module. It's try to get access to libs in:</p> <pre><code>/ade/b/3071542110/oracle/rdbms/lib/libclntsh.dylib.11.1 /ade/dosulliv_ldapmac/oracle/ldap/lib/libnnz11.dylib </code></pre> <p>I never have this paths but I created symlinks.</p>
3
Cannot save the data to the url using json
<p>My json code { "Status": "NO UPDATES" } Iam getting the output as couldn't save the data. JSONResult iam getting as "FAILED"-- when i check the log.v(jsonresult,"jsonResult") iam unable to solve the issue please help me out.</p> <pre><code>btn_Save.setOnClickListener(new OnClickListener() { public void onClick(View v) {try {StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); String postReceiverUrl = "http://"; Log.v(TAG, "postURL: " + postReceiverUrl); // HttpClient @SuppressWarnings("resource") HttpClient httpClient = new DefaultHttpClient(); // post header HttpPost httpPost = new HttpPost(postReceiverUrl); List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2); Log.v(TAG, jsonobject.toString()); nameValuePairs.add(new BasicNameValuePair("EmployeeId", wepemployeeDeptId.getText().toString())); nameValuePairs.add(new BasicNameValuePair("visitorname", wepName.getText().toString())); Log.v(TAG, "Visitor Name: " + wepName.getText().toString()); nameValuePairs.add(new BasicNameValuePair("PhoneNo", wepMobile.getText().toString())); // nameValuePairs.add(new BasicNameValuePair("WhomToMeet", wepWhomToMeet.getSelectedItem().toString())); nameValuePairs.add(new BasicNameValuePair("Address", wepAddress.getText().toString())); nameValuePairs.add(new BasicNameValuePair("EmailID", wepEmail.getText().toString())); // nameValuePairs.add(new BasicNameValuePair("visitType", wepVisitType.getSelectedItem().toString())); nameValuePairs.add(new BasicNameValuePair("PurposeOfMeet", wepPurpose.getText().toString())); nameValuePairs.add(new BasicNameValuePair("DateofVisit", wepVisitDate.getText().toString())); nameValuePairs.add(new BasicNameValuePair("Intime", wepInTime.getText().toString())); nameValuePairs.add(new BasicNameValuePair("Outtime", wepOutTime.getText().toString())); nameValuePairs.add(new BasicNameValuePair("BadgeNo", wepBadgeNumber.getText().toString())); // nameValuePairs.add(new BasicNameValuePair("CreatedBy", wepcreatedby.getText().toString())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // execute HTTP post request HttpResponse response = httpClient.execute(httpPost); String jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); Log.i("jsonResult",jsonResult); JSONObject object = new JSONObject(jsonResult); String status = object.getString("Status").trim(); Toast.makeText(getBaseContext(), "Please wait...",100).show(); if(status.toString().equals("SUCCESS")) { Intent i = new Intent(Entry.this,MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); Toast.makeText(getBaseContext(), "Details Inserted",1000000).show(); } if(status.toString().equals("FAILED")) { Toast.makeText(getBaseContext(), "Couldn't save the data...",1000000).show(); } } catch (JSONException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); </code></pre>
3
How can i save this into a variable so that i can save it to a file
<p>I have a bit of code which prints what I want to save but I cant save it as a variable because of the format. Please can you show me how to save this as a variable so that I can save it into a file </p> <p>It wont let me add a picture but this is what I want to add to a variable (What its printing)</p> <pre><code>print(text[i],end="") </code></pre>
3
C++ Compile code for all variants of finite number of settings
<p>For example, there is hard logic inside function <code>void Func(long param1, long param2, long param3, long param4, long param5)</code>.</p> <p>It has a lot of statements inside depends on parameters, different checks, calculations depends on combinations and etc.</p> <p>And that function is called many million times and takes serious amount of execution time. And I'd like to reduce that time.</p> <p>All parameters are taken from <code>config.ini</code> file, so, they are unknown at compile time.</p> <p>But I know, that param1 may be in diapason [1..3], param2 in diapason [0..1] and etc.</p> <p>So, finally, there is maybe 200 combinations of those parameters.</p> <p>And I'd like my compiler compile separated 200 combination, and at the beginning of run-time, when <code>config.ini</code> loaded, just choose one of them, and avoid run-time calculation of parameter's dependencies.</p> <p>Is that possible to achieve in C++98? Or in C++11/14?</p>
3
Tensorflow: Setting an array element with a sequence
<p>I'm trying to train a CNN using my own image dataset, but when passing the batch data and label to the <code>feed_dict</code> I get the error <code>ValueError: setting an array element with a sequence</code> from what I read <a href="https://stackoverflow.com/questions/34156639/tensorflow-python-valueerror-setting-an-array-element-with-a-sequence-in-t">here</a>, this is a dimension issue, and probably coming from my <code>batch_label</code> Tensor, but I couldn't figure out how to make it a one-hot Tensor (what my graph expects).</p> <p>I uploaded the full code as a gist here: <a href="https://gist.github.com/guivn/f7f753547f77a3b12992" rel="nofollow noreferrer">https://gist.github.com/guivn/f7f753547f77a3b12992</a></p>
3
Java DocumentDB connectivity without registering for Azure
<p>Is there a way to check java to documentDB connectivity without having to register on Azure? It will be great help even in case I can connect and select some data. </p>
3
Creating an android project does not create the R.java file for me and there appears to be gradle errors as well
<p>I had a problem with my android studio not creating the R.java file ( which its still not doing ) but ontop of that, im getting this error which I dont understand at all. </p> <p><a href="https://i.stack.imgur.com/Sc98u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sc98u.png" alt="Error 1"></a></p> <p>as well as this error</p> <p><a href="https://i.stack.imgur.com/d4oxJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d4oxJ.png" alt="Error 2"></a> </p> <p>Please help.</p>
3
Google Compute Startup Script PHP Files From Bucket
<p>I'd like to automatically load a folder full of php files from a bucket when an instance starts up. My php files are normally located at <code>/var/www/html</code></p> <p>How do I write a startup script for this?</p> <p>I think this would be enormously useful for people such as myself who are trying to deploy autoscaling, but don't want to have to create a new image with their php files every time they want to deploy changes. It would also be useful as a way of keeping a live backup on cloud storage.</p>
3
Scroll to new tab when drawer item selected
<p>So I have created custom ViewPager, PagerAdapter and drawer. Now I want to call Tab which is in position of clicked drawer item. As it is all custom cannot Use transaction. I'm not new to java so no need to rewrite program just write what to do.</p> <pre><code>@Override public void onItemClick(AdapterView&lt;?&gt; parent,View view,int position,long id){ selectDrawerItem(position); /* scroll code here*/ } private void selectDrawerItem(int position) { // Highlight the selected item, update the title, and close the drawer drawerListView.setItemChecked(position, true); drawerLayout.closeDrawer(drawerListView); } </code></pre>
3
Oxmetrics, Matrices as input in loglikelihood function (GARCH)
<p>I'm trying to write a program in Oxmetrics that estimates a multivariate GARCH model. My multivariate GARCH model has the unconditional covariance matrix (should be the X variable) as input, but i'm unsure about how to correctly specify the correct matrix at each iteration.</p> <p>My program looks as follows for now:</p> <pre><code>//Global variable; visible also in the likelihood function decl X; //Likelihood contributions garch_likelihood_contributions(likval_t, par) { //Local variables decl covar, lik, H,C,A, i; //Parameters C = par[0]; A = par[1]; //conditional covariance sequence H = constant(.NaN,2,2); H = C*C'+ exp(-A)*H[0][]+A*exp(-A)*X[0][]; H[][0] = 0; //Initial value X[][0] = sumc(covar[m])/2071; // Not correct specified yet, should be the sample average of the covariance matrices // for(decl i=1; i&lt;columns(X); ++i) { H[0][i] = C*C'+ exp(-A)*H[i-1][]+A*exp(-A)*X[i-1][]; } //likelihood contributions lik = constant(.NaN,columns(X),1); lik[0] = 0.5*log(determinant(H[][i-1]))+ 0.5*X[1][]*invert(H[][i-1])*X[1][]'; for(decl i=1;i&lt;2071;++i) { lik[i] = 0.5*log(determinant(H[][i-1])) + 0.5*X[i-1][]*invert(H[][i-1])*X[i-1][]'; // her stod X[i+1] } // adFunc[0] = lik; // return !ismissing(adFunc[0]); } decl likval_t; //Return vector of likelihood-contributions likval_t[0] = lik; //Return success return 1; } //Likelihood function garch_likelihood(par, likval, avScore, amHessian) { //Local variables decl likval_t; //Likelihood contributions garch_likelihood_contributions(&amp;likval_t, par); //Return likelihood-value likval[0] = double(sumc(likval_t)); //Return success return 1; } main() { //Declare variables decl data; decl loglik, par; decl C, A, covar; decl vol, r, S_t, K, P; //Load data: data = loadmat("covariances.in7")'; P = data[0][0:]; covar = data[0:1][0:]; X = constant(.NaN,2,2); for (decl i = 0, i &lt; columns(P), i+2 ) { j[i] = &lt;0,2;0,2&gt; X[i]= vech(j[i]); } //Initial values for parameters par = 0.1|0.5; //i.e. (omega, alpha, beta). Try out different starting values! //Settings for likelihood estimation MaxControlEps(1e-6,1e-4); MaxControl(20000, 1, 1); //Maximize likelihood function print("\n\n","Maximizing likelihood: \n"); MaxBFGS(garch_likelihood, &amp;par, &amp;loglik, 0, 1); print("%r",{"C","A"} ,"%c",{"MLE"}, par); println("\nMaximized likelihood: ", loglik); } </code></pre> <p>Inside the main, you should noticed that I have tried to specify the variable X as a 2x2 matrix for each iteration. The idea is that for each i, the loop should allocate the 2 first cloumns and rows from the datasheet "covariances.in7" into X. The step for the loop should be 2, such that i = 1,3,5,7 ect.</p> <p>Please post your thoughts, it's really appreciated.</p> <p>Best regards,</p> <p>Kristian</p>
3
SQL Server : Datetime conversion
<pre><code>select CONVERT(date,d) as dateX from dates where d &gt;= '2008-01-01' and d&lt; '2079-12-31' </code></pre> <p><code>CAST(d as DATE)</code> caused the same error.</p> <p>Where d is smalldatetime type in a one column dates dimension.</p> <blockquote> <p>The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.</p> </blockquote>
3
Integrating AWS device farm with Jenkins
<p>I want to integrate my Jenkins build with AWS device farm. So, while creating a project on AWS device farm, it asks to upload the apk to test. I want that the apk should be picked from Jenkins server location and I don't have to manually upload apk to AWS device farm.</p> <p>Is this possible?</p>
3
Load an exe file and set a variable from web page
<p>I have recently been making a game in Unity (C#) and at the start a variable is set to a number. The number is a seed which is used to generate a 2d world out of blocks. This means that if the number is 5 then it will generate the same world for everyone using the seed 5.</p> <p>I would like to upload seeds to my webpage so when a user clicks a button, the compiled unity application (.EXE) opens and the "seed" variable is set to a certain number depending on which button is pressed. For instance I could make a button which loads the program with the seed variable set to '5', or I could load it with the seed variable set to number '8'. </p> <p>I am wondering if this is possible due to the file being complied and if so how would I do it? I have the code to load a .EXE file here:</p> <pre><code>&lt;a href="file:///C:\\Windows\\notepad.exe"&gt;Click me&lt;/a&gt; </code></pre> <p>Sorry if I am a bit too specific or confusing, this is my first post.</p>
3
HTTP 500 error when generating Java Client Library using endpointscfg from a GAE API
<p>I tried to generate java client library using a discovery doc retrieved from my API endpoints (which is running on golang) but failed wit the following message.</p> <pre><code>endpointscfg.py gen_client_lib java happylaundry.rest.discovery Traceback (most recent call last): File "//Users/lorenz/go/go_appengine/endpointscfg.py", line 133, in &lt;module&gt; run_file(__file__, globals()) File "//Users/lorenz/go/go_appengine/endpointscfg.py", line 129, in run_file execfile(_PATHS.script_file(script_name), globals_) File "/Users/lorenz/go/go_appengine/google/appengine/tools/endpointscfg.py", line 561, in &lt;module&gt; main(sys.argv) File "/Users/lorenz/go/go_appengine/google/appengine/tools/endpointscfg.py", line 557, in main args.callback(args) File "/Users/lorenz/go/go_appengine/google/appengine/tools/endpointscfg.py", line 458, in _GenClientLibCallback args.build_system) File "/Users/lorenz/go/go_appengine/google/appengine/tools/endpointscfg.py", line 335, in _GenClientLib build_system, client_name) File "/Users/lorenz/go/go_appengine/google/appengine/tools/endpointscfg.py", line 366, in _GenClientLibFromContents raise ServerRequestException(error) __main__.ServerRequestException: HTTP 500 (Internal Server Error) error when communicating with URL: https://google-api-client-libraries.appspot.com/generate. Response: </code></pre> <p>I tried to use the same command and generated for a very simple program, and it runs without errro. From the syntax or structure of the discovery doc, i can't see anything ran wrong. Do you guys have any idea?</p>
3
Fill Excel + populate active x comobo box from Microsoft Sql Management Studio database table
<p>I have an excel file I am trying to pull values in from a Microsoft SQL Database. I am trying to add values from a table using the table's ID and string value associated with that ID. I have run into an invalid argument error. I was able to add the xlVal if i declared the integer value and set the first item = 0, then i could add 1 to the xlVal to make each integer value unique but these values won't allow me to reference the specific row in the database if i want to pull the values back to update the database. Basically i am wondering if there is a way to set the pvargindex value = to my database ID value since i don't have an integer in my database starting with 0. I also tried adding a row (select type..., 0) before the loop ran but i was unable to get this to work either.</p> <pre><code>Private Sub populateType() Dim dbName As Object Dim dbResults As Object Set dbName = CreateObject("ADODB.Connection") Set dbName = openDBConn("./System", "System") Set dbResults = dbName.Execute("SELECT ID_Type, Type FROM Const_Type WHERE Active = 1 AND Type &lt;&gt; 'N/A' ORDER BY Type") Sheet1.ComboBox1.Clear Do While Not dbResults.EOF Dim xlStr As String xlStr = dbResults("Type").Value Dim xlVal as integer xlVal = dbResults("ID_Type").Value Sheet1.ComboBox1.AddItem xlStr, xlVal dbResults.MoveNext Loop </code></pre> <p>End Sub</p>
3
jQuery get class value from parent div
<p>I am trying to get the value in the class from 'quickCost' while I click on the 'icon-remove-sign'. I can get all of the html using the jQuery below but I don't know how to get to the class 'quickCost' from there to abstract the value. </p> <p>In this case I am looking to get the $33.33 dollar amount. My jQuery code outputs only the html. I am sure I am close. Thanks for any tips. </p> <pre><code>&lt;div class="quickItem"&gt; &lt;i class="icon-remove-sign" id="1457494010"&gt;&lt;/i&gt;1 CD&lt;div class="quickCost"&gt;$33.33&lt;/div&gt; &lt;/div&gt; </code></pre> <p>jQuery</p> <pre><code>$( '.icon-remove-sign' ).click(function() { var theCost = $( $(this).parent() ).html(); console.log(theCost); // Outputs all html in parent div }); </code></pre>
3
Why I can't connect from another client to the server?
<p>Hi everybody I'm building a simple webapp using NodeJS+express4+socket.io at the last version available, basically the problem that I can't solve is that until I'm browsing to my webapp from a browser in the server it works perfectly, but when I'm trying to acces it from the same network but on another pc the index.html is served good but the client can't connect tonthe socket, here a piece of code:</p> <p><strong>SERVER:</strong></p> <pre><code>var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var exec = require('child_process').exec, child; var uptime; var temp; var sysOS; var ramU; var ramT; var cpuUsage; app.use(express.static(__dirname + '/bower_components')); app.get('/', function(req, res, next) { res.sendFile(__dirname + '/index.html'); console.log('Ok, Up and running on 8080'); }); io.on('connection', function(socket) { var infos; var interval =setInterval(function(){ //Get Uptime child = exec("uptime -p | grep 'up ' | cut -d ' ' -f2-", function(error, stdout, stderr){ uptime = stdout; }); //Get Temperature child = exec("/opt/vc/bin/vcgencmd measure_temp | grep 'temp=' | cut -d '=' -f3,2-", function(error, stdout, stderr){ temp = stdout; }); //Get OS child = exec("cat /etc/os-release | grep 'PRETTY_NAME' | cut -d '=' -f2", function(error, stdout, stderr){ sysOS = stdout; }); //Get RAM USED child = exec("free -m | grep 'cache: ' | cut -d ' ' -f10", function(error, stdout, stderr){ ramU = stdout; }); //Get RAM TOTAL AVAILABLE child = exec("free -m | grep 'Mem: ' | cut -d ' ' -f12", function(error, stdout, stderr){ ramT = stdout; }); child = exec("top -bn 1 | awk 'NR&gt;7{s+=$9} END {print s/4}' | tr -d ' '", function(error, stdout, stderr){ cpuUsage = stdout; }); infos = [{Uptime: uptime}, {Temperature: temp}, {OS: sysOS}, {ramUsed: ramU}, {ratTot: ramT}, {CPU: cpuUsage}]; socket.emit("infos", infos); }, 2000); }); console.log('Ok, Up and running on 8080'); server.listen(8080); </code></pre> <p><strong>CLIENT:</strong></p> <pre><code>$(document).ready(function(){ var progressBar; var ramPerc; var cpu; var socket = io.connect("http://localhost:8080"); socket.on("infos", function(infos) { cpu = infos[5].CPU.trim(); cpuPB = '&lt;div class="progress"&gt; &lt;div class="progress-bar progress-bar-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width:'+cpu+'%"&gt; '+cpu+'% CPU USATA &lt;/div&gt; &lt;/div&gt;'; $("#uptempo").html(infos[0].Uptime); $("#divTemp").html(infos[1].Temperature); $("#divOS").html(infos[2].OS); ramPerc = (((infos[3].ramUsed*100))/(infos[4].ratTot)).toFixed(2); progressBar = "&lt;div class='progress'&gt; &lt;div class='progress-bar progress-bar-success' role='progressbar' aria-valuemin='0' aria-valuemax='100' style='width:"+ ramPerc + "%'&gt;"+ ramPerc + " % RAM usata &lt;/div&gt; &lt;/div&gt;"; $("#divRam").html(progressBar); $("#divCpu").html(cpuPB); }); }); </code></pre> <p>In the client script of course I have to connect to <a href="http://localhost:8080/" rel="nofollow">http://localhost:8080/</a> so why from another client on the same network can't connect to it? I'm I doing something wrong? Do I need to implement a proxy, if yes, how?</p>
3
how to move from gcmIntentService to fragment
<p>I want to open Notifications fragment on receiving a notification. Once i click on receiving notification i want to move to Notification fragment.</p> <p>Here is my code :</p> <pre><code>if(chatType.equals("7")){ notification.contentView = contentView; /* PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotificationsActivity.class).putExtra("json_msg",msg). setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT); notification.contentIntent = contentIntent; */ Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent.putExtra("json_msg",msg),0); notification.contentIntent = contentIntent; /* FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.containerView,new NotificationsFragment()).commit(); */ // notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification notification.defaults |= Notification.DEFAULT_LIGHTS; // LED notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration notification.defaults |= Notification.DEFAULT_SOUND; // Sound notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, notification); } else { notification.contentView = contentView; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ChatActivity.class).putExtra("json_msg",msg). setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT); notification.contentIntent = contentIntent; // notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification notification.defaults |= Notification.DEFAULT_LIGHTS; // LED notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration notification.defaults |= Notification.DEFAULT_SOUND; // Sound notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, notification); } </code></pre>
3
Finding and Deleting a Node from this linked list in java
<p>I have to write a program that implements a linked list of Students, in this case Student is a separate class that will be called. My linked List is supposed to be able to find a Student using the Name of that student and this is the area where my program fails it doesn't seem to find that Node for that Student, hence it also wont delete. I am writing this for a class and the professor does not allow the use of the built in Linked List class.</p> <p>This is My Code </p> <pre><code>public class StudentList { StudentNode head; public StudentList() { shead = null; } public void setShead(StudentNode data) { shead = data; } public StudentNode getShead() { return shead; } public void insert(StudentNode data) { StudentNode iterator = head; if (iterator == null) { head = data; } else { while (iterator.getnext() != null) { iterator = iterator.getnext(); } iterator.setnext(data); } } public void delete(StudentNode data) { StudentNode iterator = head; StudentNode current; if (iterator == data) { head = iterator.getnext(); } else { while (iterator.getnext() != null) { if (iterator.getnext().equals(data)) { // current iterator.setnext(iterator.getnext().getnext()); // current.setSptr(iterator.getnext()); break; } else { iterator = iterator.getSptr(); } } } } public StudentNode find(String n) { StudentNode iterator = head; StudentNode result = null; while (iterator.getnext() != null) { if (iterator.getStudent().getName().equals(n)) { result = iterator; System.out.println("" + iterator.getStudent().getName()); } else { result = null; } iterator = iterator.getnext(); } return result; } public void print(){ StudentNode iterator = head; while(iterator != null){ JOptionPane.showMessageDialog(null,""+ iterator.getStudent().getName()); iterator = iterator.getnext(); } } } </code></pre> <p>This is the Node</p> <pre><code>public class StudentNode{ private Student data; private StudentNode next; public StudentNode(){ data = null; next = null; } public StudentNode(Student data){ this.data = data; next = null; } public Student getStudent(){ return data; } public void setStudent(Student data){ this.data = data; } public StudentNode getnext(){ return next; } public void setnext(StudentNode next){ this.next = next; } } </code></pre>
3
What is this `@sp` syntax in this quick sort code for scala?
<p>I am trying to understand this quick sort code from the following <a href="https://github.com/non/spire/blob/master/core/shared/src/main/scala/spire/math/Sorting.scala" rel="nofollow">repo</a></p> <pre><code> object QuickSort { @inline final def limit: Int = 16 final def sort[@sp A:Order:ClassTag](data:Array[A]): Unit = qsort(data, 0, data.length - 1) final def qsort[@sp A](data:Array[A], left: Int, right: Int)(implicit o:Order[A], ct:ClassTag[A]): Unit = { if (right - left &lt; limit) return InsertionSort.sort(data, left, right + 1) val pivot = left + (right - left) / 2 val next = partition(data, left, right, pivot) qsort(data, left, next - 1) qsort(data, next + 1, right) } final def partition[@sp A](data:Array[A], left:Int, right:Int, pivot:Int)(implicit o:Order[A], ct:ClassTag[A]): Int = { val value = data(pivot) //swap(pivot, right) var tmp = data(pivot); data(pivot) = data(right); data(right) = tmp var store = left var i = left while (i &lt; right) { if (o.lt(data(i), value)) { //swap(i, store) tmp = data(i); data(i) = data(store); data(store) = tmp store += 1 } i += 1 } //swap(store, right) tmp = data(store); data(store) = data(right); data(right) = tmp store } } </code></pre> <p>What is the purpose of <code>[@sp A]</code> ? I know <code>[A]</code> syntax is for generics, but what does adding <code>@sp</code> do? Can someone shed some insight on this?</p> <p>Thanks</p>
3
Increase duration time of dismissViewControllerAnimated()
<p>I've been trying to figure out how increase the duration time of <code>dismissViewControllerAnimated(true, completion: nil)</code> but can't seem to find an answer in Apples <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/dismissViewControllerAnimated:completion:" rel="nofollow">documentation</a>. My view controller appears with an animation from bottom to top and behaves in the reverse order when dismissed. I want the animation to be slower, say 0.5 sec, any suggestions? </p>
3
Why this simple linked list program does not function properly?
<p>This is a simple singly linked list program which I'm trying to make using class in C++. Below is the program:</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstdlib&gt; #include&lt;cstring&gt; #include&lt;algorithm&gt; class Node { int data; Node *next;// to store the address of next node public: void Insert(Node*, int); void Print(Node*); bool isPalindrome(Node*); }; void Node:: Insert(Node *head, int info) { Node *temp; temp = new Node; temp-&gt;data = info; temp-&gt;next = NULL; // check if the head node is empty // if yes then copy address of new node(temp) into head; if(head == NULL) { head = temp; } Node *temp2;// for traversing upto the last node temp2 = head; while(temp2-&gt;next != NULL) temp2 = temp2-&gt;next; temp2-&gt;next = temp;// assigned the address of new node at the end of the list } void Node:: Print(Node *head) { if(head == NULL) { std::cout&lt;&lt;"\n The Linked list is empty "&lt;&lt;std::endl; return ; } else { while(head != NULL) { std::cout&lt;&lt;" "&lt;&lt;head-&gt;data; head = head-&gt;next; } } } int main() { Node obj; Node * head; head = NULL; int choice, info; while(1) { std::cout&lt;&lt;"\n Enter your choice : \n"; std::cout&lt;&lt;"\n 1. Insert Element \n 2. Print Element \n 3. EXIT \n: "; std::cin&gt;&gt;choice; switch(choice) { case 1: std::cout&lt;&lt;"\n Enter a element : "; std::cin&gt;&gt;info; obj.Insert(head, info); break; case 2: obj.Print(head); break; case 3: exit(0); } } return 0; } </code></pre> <p>Problem with this program:</p> <p>output instance:</p> <pre><code> Enter your choice : 1. Insert Element 2. Print Element 3. EXIT : 1 Enter a element : 1 Enter your choice : 1. Insert Element 2. Print Element 3. EXIT : 1 Enter a element : 2 Enter your choice : 1. Insert Element 2. Print Element 3. EXIT : 2 The Linked list is empty Enter your choice : 1. Insert Element 2. Print Element 3. EXIT </code></pre> <p>While printing the linked list it shows: The Linked list is empty. Why?</p> <p>Here in main():</p> <pre><code>Node obj;// this I have create to call member functions of the class. Node * head; head = NULL; </code></pre> <p>And what happens when <code>Node *head;</code> is executed? does the implicit constructor of class gets called?</p>
3
Python - Function is not being executed
<p>I have this program that defines a function and then calls it, but no matter what I do, the program doesn't execute the function's call. Am I missing something? I already checked with the other questions but I couldn't find anything similar to what I am facing.</p> <pre><code>baudrate = 115200 port = '/dev/ttyUSB2' def serial_data(ser): print ser.name # it doesn't print here at all! sys.stdout.flush() while True: yield ser.readline() ser.close() for line in serial_data('/dev/ttyUSB2', 115200): print "data : " print line data = [] ser = serial.Serial(port, baudrate) serial_data(ser) </code></pre> <p>The output for this program is </p> <pre><code>#nothing, it just hangs. </code></pre> <p>If I remove the infinite loop, the program terminates immediately.</p>
3
vb.net code to dock the custom tab below the formula bar in excel 2013
<p>I'm trying to dock the custom task pane below the formula bar in excel 2013, but some how it's place above the formula bar.</p> <pre><code> If CustomTaskPanes.Count &lt; 1 Then myUserControl1 = New MyUserControl myCustomTaskPane = Me.CustomTaskPanes.Add(myUserControl1, "My Task Pane") myCustomTaskPane.Visible = True With myCustomTaskPane .DockPosition = pos.up .DockPosition = pos.Medium End With End If </code></pre>
3
text which loaded from mysql server doesn't appears at list view
<p>I'm trying to build an android app which receive data from MySQL database into android app. I followed this tutorial : <a href="http://www.geeks.gallery/simple-json-parsing-example-in-android-part-iii/" rel="nofollow">http://www.geeks.gallery/simple-json-parsing-example-in-android-part-iii/</a></p> <p>the problem appears as I'm clicking on button which load the data into listview, for some reason the text doesn't appear in that list. as I followed the code, I acutely saw that the correct data is inserted to the corresponded relevant hash map "oslist".</p> <p>any suggestions? thanks, hanan</p> <p>activity_main.xml</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:weightSum="1" android:orientation="vertical"&gt; &lt;ListView android:id="@+id/list" android:layout_width="wrap_content" android:layout_height="335dp" android:layout_above="@+id/getdata" android:choiceMode="singleChoice" /&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="load data" android:id="@+id/getdata" android:layout_gravity="center_horizontal" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>main_activity.java </p> <pre><code>package com.example.aradline; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ ListView list; TextView ver; TextView name; TextView api; ArrayList&lt;HashMap&lt;String, String&gt;&gt; oslist = new ArrayList&lt;&gt;(); private static String url = "http://www.geeks.gallery/android/android_version_json_data.php"; private static final String TAG_OS = "Android Version List"; private static final String TAG_VER = "Version No"; private static final String TAG_NAME = "Version Name"; private static final String TAG_API = "API Level"; JSONArray android = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button getdata = (Button) findViewById(R.id.getdata); getdata.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new JSONParse().execute(); } }); list = (ListView) findViewById(R.id.list); ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist, R.layout.list_child, new String[] { TAG_VER, TAG_NAME, TAG_API }, new int[] { R.id.vers, R.id.name, R.id.api }); list.setAdapter(adapter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show(); } }); } private class JSONParse extends AsyncTask&lt;String, String, JSONObject&gt; { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); ver = (TextView) findViewById(R.id.vers); name = (TextView) findViewById(R.id.name); api = (TextView) findViewById(R.id.api); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Getting Data ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected JSONObject doInBackground(String... args) { JsonParser jParser = new JsonParser(); // Getting JSON from URL JSONObject json = jParser.getJSONFromUrl(url); return json; } @Override protected void onPostExecute(JSONObject json) { pDialog.dismiss(); try { // Getting JSON Array from URL android = json.getJSONArray(TAG_OS); for (int i = 0; i &lt; android.length(); i++) { JSONObject c = android.getJSONObject(i); // Storing JSON item in a Variable String name = c.getString(TAG_NAME); String ver = c.getString(TAG_VER); String api = c.getString(TAG_API); // Adding value HashMap key =&gt; value HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;(); map.put(TAG_VER, ver); map.put(TAG_NAME, name); map.put(TAG_API, api); oslist.add(map); } } catch (JSONException e) { e.printStackTrace(); } } } } </code></pre> <p>list_child.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/vers" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/api" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre>
3
Rails - Modular many-to-many relations
<p><strong>Context</strong></p> <p>In the context of a Ruby on Rails application, in a school's project.</p> <p>Let's consider the context of a team-based game, with many characters to choose from. I want to represent affinities between two characters in different context, which means whether two characters are being teamed-up or are facing each other or even when one is present in the game while the other is missing.</p> <p>I would then have tables that looks something like this in my database</p> <ul> <li>Characters</li> <li>Ally-Relation</li> <li>Enemy-Relation</li> <li>PlayingSingle-Relation</li> </ul> <p>Each of these <code>&lt;name&gt;-Relation</code> tables represents a many-to-many relation between Characters, with an additional score that represents the strongness of the relation</p> <p>Of course, relations between character are subject to changes. We might decide for any reason that a relation has become irrelevant, or another relation that we didn't thought of before just appeared.</p> <p>In terms of display, we want to look for both the best and worst other characters in a specific relation.</p> <p><strong>Question</strong></p> <p>I came up with something like this.</p> <pre><code>class Relation &lt; ActiveRecord::Base scope :best, -&gt;(character_id) { Character.find(where(character_left: character_id).order("score desc").limit(5).pluck(:character_right)) } end </code></pre> <p>Where <code>character_left</code> and <code>character_right</code> are the two characters to be considered for in the relation and the score is the strenght of the bond.</p> <p>However, when fetching data, my teacher thinks it would be best to have scopes in the Characters model to find both the best and worst other character in a specific relation. This, because the teammate that is doing, say, the HTML code don't give a damn about the structure of the Relations when he wants to display characters. He told me about using <code>has_and_belongs_to_many</code> and he sketched me some code he would expects that looks something like <code>Character.best(:relation)</code> to fetch the data.</p> <p>While I think what I did is better (obviously :) ). Having the scopes that will fetch Characters from within the Relation models, as they subject to appear and disappear keeps the request relation specifics. This prevents us from modifying the Characters model every time we fumble with the Relations. Having somethings that looks like <code>Relation.best(:hero)</code> seems cleaner to me.</p> <p>What do you think about it ? What are good practices around this very specific situation. Are there any right way to apply and use modular many-to-many relation s in a Ruby on Rails application ?</p>
3
Header set Content-Security-Policy not handling multiple domains correctly
<p>I'm trying to protect from XSS attacks under Apache setting the following directive:</p> <pre><code>Header set Content-Security-Policy "default-src 'self' code.jquery.com;" </code></pre> <p>to only allow the jquery.com CDN which is quite handy. However the directive keeps giving me in Firefox the following:</p> <blockquote> <p>The page's settings blocked the loading of a resource at self ("script-src <a href="http://www.website.com" rel="nofollow">http://www.website.com</a> <a href="http://code.jquery.com" rel="nofollow">http://code.jquery.com</a>").</p> </blockquote>
3
Inconsistent behaviour of conf.setLocale()
<p>As per the given <a href="https://stackoverflow.com/a/2900144/5754623">solution</a>, I'm using the following code to change the language programmatically:</p> <pre><code> DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); if (Build.VERSION.SDK_INT &gt;= 17) { conf.setLocale(newLocale); } else { conf.locale = newLocale; } res.updateConfiguration(conf, dm); </code></pre> <p>I'm calling this in <code>onCreate()</code> in each activity before <code>setContentView()</code> and after <code>super.Oncreate()</code>.</p> <p><code>conf.setLocale()</code> internally calls <code>setLayoutDirection()</code> and is supposed to change the layout direction according to the specified <code>locale</code>. But it's behaviour is not consistent. The layout direction gets overridden by the system frequently. What should be the workaround for this? </p> <p>Any help would be greatly appreciated.</p>
3
Inheritance with two abstract classes
<p>Im trying to create an arraylist that contains at least two instances of each class, I need to achieve this using a single arraylist. The problem is the class HourlyWorker and ContractWorker both implement the abstract class Smarty where the Class Hobbit implements the abstract class Simpleton and i cant figure out how to use both in one arraylist.</p> <pre><code>public class MainClass { private ArrayList&lt;Smarty&gt; list; public MainClass() { list = new ArrayList&lt;Smarty&gt;(); list.add(new HourlyWorker("Bob", 50, 40, 8.0)); list.add(new HourlyWorker("Bill", 70, 50, 12.0)); list.add(new ContractWorker("Jill", 80, 8, 100.0)); list.add(new ContractWorker("Amy", 125, 12, 85.0)); list.add(new Hobbit("Frodo", 12)); list.add(new Hobbit("Merry", 8)); } </code></pre> <p>The part that doesnt work is</p> <pre><code>list.add(new Hobbit("Frodo", 12)); list.add(new Hobbit("Merry", 8)); </code></pre> <p>Also the abstract class Smarty implements Simpleton</p> <p>all my classes</p> <p>abstract class Smarty</p> <pre><code>public abstract class Smarty extends Simpleton { private int IQ; public Smarty(){ } public Smarty(String name, int IQ) { setFirstName(name); this.IQ = IQ; } public Smarty(int IQ){ this(); this.IQ = IQ; } public int getIQ(){ return IQ; } public void setIQ(int IQ){ this.IQ = IQ; } public abstract double getIncome(); } </code></pre> <p>abstract class Simpleton</p> <pre><code>public abstract class Simpleton { private String name; public Simpleton(){ } public Simpleton(String name){ this.name = name; } public String getFirstName(){ return name; } public void setFirstName(String name){ this.name = name; } public abstract String getName(); public abstract String doMath(); public abstract String saySomethingSmart(); } </code></pre> <p>class HourlyWorker</p> <pre><code>public class HourlyWorker extends Smarty{ private int hoursWorked; private double hourlyPay; public HourlyWorker(String name,int IQ, int hoursWorked, double hourlyPay){ super(IQ); setFirstName(name); setHoursWorked(hoursWorked); this.hourlyPay = hourlyPay; } public int getHoursWorked(){ return hoursWorked; } public void setHoursWorked(int hoursWorked){ this.hoursWorked = hoursWorked; } public double getHourlyPay(){ return hourlyPay; } public void setHourlyPay(double hourlyPay){ this.hourlyPay = hourlyPay; } public String multiply(int x, int y){ return x + " x " + y + " = " + x * y; } @Override public String getName() { // TODO Auto-generated method stub return getFirstName(); } @Override public String doMath() { // TODO Auto-generated method stub return "I can Multiply! " + multiply(2, 3); } @Override public String saySomethingSmart() { // TODO Auto-generated method stub return "Hippos are dangerous!"; } @Override public double getIncome() { // TODO Auto-generated method stub double x = getHoursWorked(); double y = getHourlyPay(); double income = x * y; return income; } } </code></pre> <p>class ContractWorker</p> <pre><code>public class ContractWorker extends Smarty{ private int contractsCompleted; private double payPerContract; public ContractWorker(String name,int IQ, int contractsCompleted, double payPerContract) { // TODO Auto-generated constructor stub super(IQ); setFirstName(name); this.contractsCompleted = contractsCompleted; this.payPerContract = payPerContract; } public int getContractsCompleted(){ return contractsCompleted; } public void setContractsCompleted(int contractsCompleted){ this.contractsCompleted = contractsCompleted; } public double getPayPerContract(){ return payPerContract; } public void setPayPerContract(double payPerContract){ this.payPerContract = payPerContract; } public String division(int x, int y){ return x + " / " + y + " = " + x/y; } public double getIncome() { // TODO Auto-generated method stub double x = getContractsCompleted(); double y = getPayPerContract(); double income = x*y; return income; } @Override public String doMath() { // TODO Auto-generated method stub return ": I can do division! " + division(10,2); } @Override public String saySomethingSmart() { // TODO Auto-generated method stub return ": The stars are aligned tonight."; } @Override public String getName() { // TODO Auto-generated method stub return getFirstName(); } } </code></pre> <p>class Hobbit</p> <pre><code>public class Hobbit extends Simpleton{ private int carrots; public Hobbit(String name, int carrots){ super(name); this.carrots = carrots; } public int getCarrotsPicked(){ return carrots; } public void setCarrotsPicked(int carrots){ this.carrots = carrots; } public String add(int x, int y){ return x + " + " + y + " = " + x+y; } @Override public String getName() { // TODO Auto-generated method stub return getFirstName(); } @Override public String doMath() { // TODO Auto-generated method stub return "I can add! " + add(2,2); } @Override public String saySomethingSmart() { // TODO Auto-generated method stub return "Leave me alone Sam!"; } } </code></pre>
3