title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Can't seem to retrieve stripe charge using python
<p>I have the following python code to create a charge in stripe.</p> <pre><code>a_charge = stripe.Charge.create( amount=cents, currency="usd", source=token, description="my_description", application_fee=application_fee, stripe_account=teacher_stripe_id ) </code></pre> <p>This succeeds (I think), because it shows up in my dashboard with a charge_id. But then, immediately after in the code, the following fails:</p> <pre><code>stripe.Charge.retrieve(a_charge.id) </code></pre> <p>With error: No such charge: somelongstringhere</p> <p>However, somelongstringhere is indeed the ID under charge details on my stripe dashboard. So how come Stripe can't retrieve this charge? Is this not the correct id?</p>
2
How to do multiple routing (router-outlet) in angular2 RC4?
<p><strong>I am finding problem while multiple routing, its loading in single router-oulet how to tell the component to load in specific named outlet? I found out that there is a property in RouterConfig from which i can use outlet to name the router-outlet but i don't know to link it with HTML.</strong></p>
2
Remove percentage printf and shell
<p>I'm beginning to learn the shell commands. And I don't know how to remove the percent character in the end.</p> <p>Example: <code>printf poo</code> shows <code>poo%</code></p> <p>I'm on mac and I use oh my zsh!</p>
2
How to get general user information with SteamID64?
<p>I am having problem with doing simple things using Steams 64 bit id. </p> <p>How can i use SteamAPI to get the general information? like displaying name, username, location.</p> <p>I used SteamAuth to make my social authentication on website, which only has the function, that gets the id.</p> <p>Example:</p> <pre><code>steamid = GetSteamID64() username = GetUsername() displayname = GetDisplay() ... </code></pre> <p>Does SteamAPI on have features related to this? is there any library in python that could support such thing?</p>
2
Is it possible to disable "Double-tap for period" in an Android EditText?
<p>It's been messing up my Edit Text filter. When I double-tap space, the previous character is deleted instead. Here is my filter:</p> <pre><code>@Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (!isValid(source)) { // This simple calls Matcher.matches return ""; } return null; } </code></pre> <p>When I double tap the space key, the filter is called three times with the following sources:</p> <ol> <li>Source with a space source (" ")</li> <li>An empty source ("") (similar to a backspace) --> This one deletes the last character</li> <li>A ". " source</li> </ol> <p>I tried just retaining the last character instead:</p> <pre><code>if(source.toString().isEmpty()) { return ((Character) dest.toString().charAt(dest.toString().length()-1)).toString(); } </code></pre> <p>It fixed the issue but I can't do backspace anymore because of that workaround. Is there a way to just disable the "double-tap space for period" functionality just for this single EditText? I noticed the address bar in the Google Chrome app seems to disable this functionality and just treats double-tapped space as two spaces.</p>
2
Poloniex push api
<p>I am interested in writing some basic php to interface with the Poloniex push api.</p> <p>Their website provides the following info: <a href="https://poloniex.com/support/api/" rel="nofollow">https://poloniex.com/support/api/</a></p> <p>A php wrapper can be found here: <a href="http://pastebin.com/iuezwGRZ" rel="nofollow">http://pastebin.com/iuezwGRZ</a></p> <p>From what i can determine there are three APIs being push, public and trading. The public and trading APIs provide functions that can be passed parameters etc. The push api stumps me totally as i cannot determine how it works.</p> <p>The first link above states the API pushes live data and different feeds can be subscribed to.</p> <p>My questions are: A) How can php receive a live stream of data? B) How do i subscribe to a feed?</p> <p>I may have misunderstood the oush api and my apologies in advance if this is the case.</p> <p>Edit1: I believe i need a WAMP client to connect to a WAMP router such as Minion. <a href="https://github.com/Vinelab/minion" rel="nofollow">https://github.com/Vinelab/minion</a></p> <p>Edit2: Node.js example <a href="http://pastebin.com/dMX7mZE0" rel="nofollow">http://pastebin.com/dMX7mZE0</a></p>
2
Get list of tags with Javascript Use API
<p>I am using AEM 6.1 and need to populate a list of filters dynamically based on the list of tags that are available. The tags are nested so that there is a region tag, then country tags nested inside of it, and then city tags nested inside their countries. I need to retrieve the region and all of its children, I've attempted to use an ajax call to return them but it only seems to return me the top level node and none of the children. There doesn't seem to be much information regarding the JS Use API's interaction with the Tag Manager. Really thankful for any information or links that can point me in the right direction.</p>
2
Angular v-accordion disabling collapse when clicked on a button inside v-pane-header
<p>I'm using angular v-accordion in project, there is a requriment to stop collapsing the accordion when only cliked on a button located inside a v-pane header.</p> <p>this is the sample code. And is have incuded a codepen link also.</p> <pre><code>&lt;v-accordion control="accordionA"&gt; &lt;v-pane expanded="pane.isExpanded"&gt; &lt;v-pane-header&gt; &lt;h5&gt;{{ ::pane.header }}&lt;/h5&gt; &lt;button&gt;Button&lt;/button&gt; &lt;/v-pane-header&gt; &lt;v-pane-content&gt; &lt;p&gt;{{ ::pane.content }}&lt;/p&gt; &lt;v-pane-content&gt; &lt;/v-pane&gt; &lt;/v-accordion&gt; </code></pre> <p>Codepen link : <a href="http://codepen.io/anon/pen/qNjRKZ" rel="nofollow">enter link description here</a></p> <p>Highly appreciate if anyone can help on this.. thank you in advance.</p> <p>Cheers!.</p>
2
How to generate random IPv6 in C#?
<p>I'm new to coding. I need to know how to generate random IPv6 in C Sharp. I found this code which generated random IPv4, how can i alter it for IPv6?</p> <pre><code>static string GenerateIP() { // generate an IP in the range [50-220].[10-100].[1-255].[1-255] return RNG.Next(50, 220).ToString() + "." + RNG.Next(10, 100).ToString() + "." + RNG.Next(1, 255).ToString() + "." + RNG.Next(1, 255).ToString(); } } class RNG { private static Random _rng = new Random(); public static int Next(int min, int max) { return _rng.Next(min, max); } </code></pre>
2
When I click on checkbox then my bootstrap modal pop is closing
<p>I having form in modal popup with 5 checkbox with autopostback = true. When I click on one of the checkbox then my modal popup is close automatically. I am used update panel also and ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true); in code behind this code is reopen my modal popup. But I don't want to reopen the popup. <br/>How should I achieve this?</p>
2
React Native - What does pressRetentionOffset do?
<p>This is what the <a href="https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html#pressretentionoffset" rel="nofollow">documentation says</a> : </p> <blockquote> <p><strong>pressRetentionOffset</strong> {top: number, left: number, bottom: number, right: number} </p> <p>When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.</p> </blockquote> <p>But I don't really get it. Could you help me ? </p>
2
How to reload/refresh with infinite-scroll
<p>I want to have a reload function but I found some difficulties. </p> <p>My app should clear all data by using the reload function and grab the feed again. Event that works, but it shows me only the first 5 news (limit of my api/per page) and ignores completely the loadMore function.</p> <p>factory</p> <pre><code>.factory('newsDataService', function($http) { return { GetPosts: function(page) { return $http.get("http://newsapi.domain.tdl/"); }, GetMorePosts: function(page) { return $http.get("http://newsapi.domain.tdl/?page=" + page); } }; }) </code></pre> <p>controller</p> <pre><code>.controller('NewsCtrl', function($scope, newsDataService) { $scope.page = 1; $scope.noMoreItemsAvailable = false; newsDataService.GetPosts().then(function(items){ $scope.items = []; $scope.items = items.data.response; }); $scope.Reload = function() { console.log('reload'); newsDataService.GetPosts().then(function(items){ console.log(items); $scope.items = items.data.response ; $scope.noMoreItemsAvailable = false; $scope.$broadcast('scroll.refreshComplete'); }) }; $scope.loadMore = function(argument) { $scope.page++; newsDataService.GetMorePosts($scope.page).then(function(items){ if (items.data.response) { $scope.items = $scope.items.concat(items.data.response); $scope.noMoreItemsAvailable = false; } else { $scope.noMoreItemsAvailable = true; } }).finally(function() { $scope.$broadcast("scroll.infiniteScrollComplete"); }); }; }) </code></pre> <p>template:</p> <pre><code>&lt;ion-view view-title="News"&gt; &lt;ion-content&gt; &lt;ion-refresher on-refresh="Reload()"&gt;&lt;/ion-refresher&gt; &lt;div class="list"&gt; &lt;a collection-repeat="news in items" href="#/app/newsreader/{{news.id}}" class="item item-thumbnail-left"&gt; &lt;h2&gt;{{news.headline}}&lt;/h2&gt; &lt;div class="item-text-wrap" ng-bind-html="news.teaser"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="1%"&gt;&lt;/ion-infinite-scroll&gt; &lt;/ion-content&gt; &lt;/ion-view&gt; </code></pre> <p>How can I resolve this?</p>
2
How to move files older than 30 days to archive location and archive the files in archive location?
<p>I have to write a Windows batch script for the following scenario:</p> <p>I have log files present in folder <code>D:\Test</code> in .txt format. And I have another folder named <code>D:\Test\archive</code>.</p> <p>I have to move the files older than 30 days to archive folder <code>D:\Test\archive</code> and then I have to archive all the files present in <code>D:\Test\archiv</code> to a single zip file using <em>WinRAR</em>.</p> <p>My zip file should be in the format <code>ARCHIVE_SYSDATE</code>.</p>
2
Ansible: Command works in terminal but not Ansible
<pre><code>awk 'FNR==1{print ""}{print}' *.txt &gt; virtual.txt | mv virtual.txt virtual.csv </code></pre> <p>Works on terminal but not when I add it to an ansible script. </p> <p>I tried originally:</p> <pre><code>shell: cd Users/Virtual |awk 'FNR==1{print ""}{print}' *.txt &gt; virtual.txt | mv virtual.txt virtual.csv </code></pre> <p>It didn't work. Tried the text below and it cannot find the file</p> <pre><code>- command: chdir=/Users/Virtual awk 'FNR==1{print ""}{print}' *.txt &gt; virtual.txt - shell: "awk 'FNR==1{print ''}{print}' *.txt &gt; virtual.txt" - shell: "mv virtual.txt /Users/virtual.csv" </code></pre>
2
How to get the short display name from a language and region code?
<p>When I use <code>displayNameForKey</code>, for some language, the returned string is too long and different from the native language settings in iOS Settings app. For example:</p> <pre><code>let locale = NSLocale(localeIdentifier: "zh-Hant") let key = NSLocaleIdentifier print(locale.displayNameForKey(key, value: "zh-Hans")!, locale.displayNameForKey(key, value: "zh-Hant-HK")!) // return 中文(簡體)and 中文(繁體,中華人民共和國香港特別行政區) // but what I want is like the native language settings: 簡體中文 and 繁體中文(香港) </code></pre> <p>How can I get the short language name? </p>
2
How to set a Django filter to select all
<p>I have a view in Django that will read a get request and its parameters and make a query based on the parameters. Currently my view looks like this:</p> <pre><code>def getInventory(request): c = request.GET.get('category', '') g = request.GET.get('gender', '') s = request.GET.get('size', '') available = Item.objects.filter(gender=g,category=c,size=s) data = serializers.serialize('json',available) return HttpResponse(data,'json') </code></pre> <p>Sometimes, though, one of the parameters is not specified. I would like this to result in a value representing 'all' rather than an individual value. Is this possible in the way I've done it? I've tried <code>gender=None</code> but that just results in an empty list.</p>
2
How to add configuration specific cmake generator expressions to add_custom_target
<p>I'm trying to persuade cmake to add a custom target which builds a precompiled header on Visual Studio (note: please do not suggest I used a custom build step instead, I specifically need a build <strong>target</strong> which builds a precompiled header). Note that you cannot simply add CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE} during the configuration stage as that won't work in generated .vcxproj's where the user can change the build configuration, so I need to somehow tell cmake in its build stage to output the right stuff for each possible configuration i.e. the appropriate configuration's CMAKE_CXX_FLAGS and CMAKE_CXX_FLAGS_$&lt;CMAKE_BUILD_TYPE&gt;</p> <p>I'm very nearly there with this solution, except for one problem I'm asking for help with:</p> <pre><code># Adds a custom target which generates a precompiled header function(add_precompiled_header outvar headerpath) get_filename_component(header "${headerpath}" NAME) set(pchpath ${CMAKE_CURRENT_BINARY_DIR}/${header}.dir/${CMAKE_CFG_INTDIR}/${header}.pch) set(flags ${CMAKE_CXX_FLAGS}) separate_arguments(flags) set(flags ${flags} $&lt;$&lt;CONFIG:Debug&gt;:${CMAKE_CXX_FLAGS_DEBUG}&gt; $&lt;$&lt;CONFIG:Release&gt;:${CMAKE_CXX_FLAGS_RELEASE}&gt; $&lt;$&lt;CONFIG:RelWithDebInfo&gt;:${CMAKE_CXX_FLAGS_RELWITHDEBINFO}&gt; $&lt;$&lt;CONFIG:MinSizeRel&gt;:${CMAKE_CXX_FLAGS_MINSIZEREL}&gt; ) if(MSVC) add_custom_target(${outvar} COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/${header}.dir/${CMAKE_CFG_INTDIR}" COMMAND ${CMAKE_CXX_COMPILER} /c ${flags} /Fp"${pchpath}" /Yc"${header}" /Tp"${CMAKE_CURRENT_SOURCE_DIR}/${headerpath}" COMMENT "Precompiling header ${headerpath} ..." SOURCES "${headerpath}" ) endif() endfunction() </code></pre> <p>This very nearly works where the correct flags for each build configuration have been expanded into their respective command stanzas in the .vcxproj file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"&gt;setlocal "G:\Program Files\CMake\bin\cmake.exe" -E make_directory G:/boost.afio/cmake/afio.hpp.dir/$(Configuration) if %errorlevel% neq 0 goto :cmEnd "G:\Program Files\Microsoft Visual Studio 14.0\VC\bin\cl.exe" /c /DWIN32 /D_WINDOWS /W3 /GR /EHsc "/MD /O2 /Ob2 /D NDEBUG" /Fp"G:/boost.afio/cmake/afio.hpp.dir/$(Configuration)/afio.hpp.pch" /Yc"afio.hpp" /Tp"G:/boost.afio/include/boost/afio/afio.hpp" if %errorlevel% neq 0 goto :cmEnd :cmEnd endlocal &amp;amp; call :cmErrorLevel %errorlevel% &amp;amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd &lt;/Command&gt; </code></pre> <p>The problem is that the generator <code>$&lt;$&lt;CONFIG:Release&gt;:${CMAKE_CXX_FLAGS_RELEASE}&gt;</code> due to containing spaces expands into the quoted string <code>"/MD /O2 /Ob2 /D NDEBUG"</code> and this of course causes the compiler to complain loudly.</p> <p>What I need therefore is either one of:</p> <ol> <li>Some method of telling cmake generator expressions to not expand content containing a space into a quoted string.</li> </ol> <p>OR</p> <ol start="2"> <li>Some other method of expanding CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE} into each of the configuration specific sections for an add_custom_target.</li> </ol> <p>Many thanks in advance.</p> <p><strong>Edit:</strong> Based on Tsyvarev's answer below, I came up with this:</p> <pre><code># Add generator expressions to appendvar expanding at build time any remaining parameters # if the build configuration is config function(expand_at_build_if_config config appendvar) set(ret ${${appendvar}}) set(items ${ARGV}) list(REMOVE_AT items 0 1) separate_arguments(items) foreach(item ${items}) list(APPEND ret $&lt;$&lt;CONFIG:${config}&gt;:${item}&gt;) endforeach() set(${appendvar} ${ret} PARENT_SCOPE) endfunction() </code></pre> <p>This is working well. Many thanks to Tsyvarev!</p> <p><strong>Edit 2</strong>: It turns out cmake has undocumented support for precompiled header generation at least for MSVC. Take a look at the <code>add_precompiled_header()</code> function in <a href="https://github.com/ned14/boost-lite/blob/master/cmake/BoostLitePrecompiledHeader.cmake" rel="nofollow">https://github.com/ned14/boost-lite/blob/master/cmake/BoostLitePrecompiledHeader.cmake</a>, all you need to do is supply the <code>/Yc</code> flag to an OBJECT type library and voila, the Visual Studio generator does the right thing, correct .vcxproj XML stanzas and all.</p>
2
Installing MySQLdb python 2.7 64bit
<p>I cannot find a way to install the correct version of MySQL-python (Windows, 64 bit). Is there a simple installer available anywhere? I have tried from:</p> <p><a href="http://www.codegood.com/archives/129" rel="nofollow noreferrer">http://www.codegood.com/archives/129</a></p> <p>But when I try import MySQLdb in my IDE I get the error:</p> <pre><code>ImportError: this is MySQLdb version (1, 2, 4, 'beta', 4), but _mysql is version (1, 2, 3, 'final', 0) </code></pre> <p>which I do not understand and doesn't really explain what I need to do to resolve the issue</p> <p>I'm hosting the server on Amazon Web Service RDS</p>
2
How to create html file after HTTP GET request in scapy
<p>I need some help with scapy and python. I sending get request to spesific site... and then with sniff and HTTP filter I am filtering the relevant packets and then i want to get only the HTML code but i dont know how to do this...</p> <pre><code>os.system('iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP') os.system('iptables -L') randport = random.randint(1024,65535) syn = IP(dst=ip) / TCP(sport = randport, dport=80, flags='S') syn_ack = sr1(syn) #getting the ack getstr = 'GET / HTTP/1.1\r\nHost:' + url + '\r\n\r\n' ack = IP(dst=ip) / TCP(dport=80, sport=syn_ack[TCP].dport, seq=syn_ack[TCP].ack, ack=syn_ack[TCP].seq + 1, flags='A') / getstr send(ack) packets = sniff(count=0, lfilter=http_filter, timeout=20) http = open(url + ".html", "w") for p in packets: if p[IP].src == ip: #what i need to do here? </code></pre> <p>Help me, what i need to do for saving only the HTML code, the whole code? save the code without the HTTP header, just HTML that i can open and it will load me the site like the online one</p>
2
Edge Browser - iframe.document.open not working
<p>We have some functionality for exporting data to an excel file. When the 'export' button is clicked, some client-side javascript is called, firstly checking the client browser version, and based on this, deciding which way to render the excel document. It is working in Chrome &amp; Firefox &amp; IE11 when tested locally. However, when I remotely test using a windows 10 machine running Edge browser, the excel is not rendered.</p> <p>I might add that my local machine is a Win7 machine and Im running VS2012 and IE11. The remote machine is Win10 with Edge, hence the need to test remotely. I've tried the emulation in IE11 F12 dev tools but cant replicate the Edge error there.</p> <p>An error of 'undefined or null reference' is thrown for 'open' when using the following code:</p> <pre><code>excelIFrame.document.open("txt/html", "replace"); excelIFrame.document.write(sHTML); excelIFrame.document.close(); excelIFrame.focus(); excelIFrame.document.execCommand("SaveAs", true, "Spreadsheet.xls"); </code></pre> <p>The iframe exists in the html and is not added dynamically.</p> <pre><code>&lt;iframe id="excelIFrame" style="display:none"&gt;&lt;/iframe&gt; </code></pre> <p>I have tried the following possible solutions to get this working, to no avail - </p> <p><strong>Possible Solution 1:</strong> Same 'undefined or null reference error when assigning the document to a temp var </p> <pre><code>var doc = excelIFrame.document; doc.open("txt/html", "replace"); doc.write(sHTML); doc.close(); doc.focus(); doc.execCommand("SaveAs", true, "Spreadsheet.xls"); </code></pre> <p><strong>Possible Solution 2:</strong> Using the contentWindow property of the iFrame. No error thrown, it just opens 'about:blank' containing no content.</p> <pre><code>excelIFrame.contentWindow.contents = sHTML; excelIFrame.src = 'javascript:window["contents"]'; </code></pre> <p>Totally at a loss with this at this stage. The page is an angularJS web page. From reading up on it, I'm aware the document.open is problematic in edge when using iframes. But the following link <a href="https://connect.microsoft.com/IE/feedback/details/1822924/in-an-iframe-document-open-fails-whereas-var-doc-document-doc-open-succeeds" rel="nofollow">document.open fails in an iframe</a> I felt would solve the problem. Any thoughts or suggestions greatly appreciated.</p>
2
how to push a message from web server to browser using node js
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;&lt;/title&gt; &lt;link rel="stylesheet" href="css/animate.css"&gt; &lt;link rel="stylesheet" href="css/style.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" &gt; $(document).ready(function() { $("#notificationLink").click(function() { $("#notificationContainer").fadeToggle(300); $("#notification_count").fadeOut("slow"); return false; }); //Document Click $(document).click(function() { $("#notificationContainer").hide(); }); //Popup Click $("#notificationContainer").click(function() { return false }); }); &lt;/script&gt; &lt;style&gt; body{background-color:#dedede;font-family:arial} #nav{list-style:none;margin: 0px; padding: 0px;} #nav li { float: left; margin-right: 20px; font-size: 14px; font-weight:bold; } #nav li a{color:#333333;text-decoration:none} #nav li a:hover{color:#006699;text-decoration:none} #notification_li{position:relative} #notificationContainer { background-color: #fff; border: 1px solid rgba(100, 100, 100, .4); -webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, .25); overflow: visible; position: absolute; top: 30px; margin-left: -170px; width: 400px; z-index: -1; display: none; } #notificationsBody { padding: 33px 0px 0px 0px !important; min-height:300px; } #notification_count { padding: 3px 7px 3px 7px; background: #cc0000; color: #ffffff; font-weight: bold; margin-left: 100px; border-radius: 9px; position: absolute; margin-top: 0px; font-size: 11px; } &lt;/style&gt; &lt;/head&gt; &lt;body &gt; &lt;div style="margin:0 auto;width:900px; margin-top: 30px;"&gt; &lt;ul id="nav"&gt; &lt;li id="notification_li"&gt; &lt;span id="notification_count"&gt;5&lt;/span&gt; &lt;a href="#" id="notificationLink"&gt;Notifications&lt;/a&gt; &lt;div id="notificationContainer"&gt; &lt;div id="notificationTitle"&gt;Notifications&lt;/div&gt; &lt;div id="notificationsBody" class="notifications"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I am working on a page that has getting the notification from the server. I just create a button and a small div for showing notification number. I want to make that div was getting the notification from the server when the server push to that div. How can I get the push notification from the server. I want the client side code for receiving notification from sever. I just using another system and node js is the server. </p> <p>Thank you.</p>
2
Assembly- Calling function inside another i.e nested functions
<p><br> I try to call windows function inside my custom assembly function<br> The pseudocode would be something like:<br></p> <pre><code>MYFUNC PUSH EBP PUSH WINDOWSFUNCTIONPARAMETER CALL [IMPORTEDWINDOWSFUNCTION] POP EBP RET </code></pre> <p>So I know its safe to leave this like this if I call only one function inside,<br> because thie stack will be restored anyway. <br> The problem is- why can't i add esp, 0x04 after this? - The app crashes<br> Im not sure if i even need to do this but imo its safer to do it after function<br> calls, and somehow i cant get this working inside a function<br> I'm gratefull for any help :)<br></p>
2
Android Facebook Login is not working
<p>I am developing an Android app that uses Facebook login. This is my first Facebook login integration in Android. I am having a trouble with integrating facebook login to my app because nothing is shown login is success or not in my callback.</p> <p>I generated Facebook hash key from debug sign key and set the credentials in Facebook developer settings as below.</p> <p><a href="https://i.stack.imgur.com/MOK8J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MOK8J.png" alt="enter image description here"></a></p> <p>In class name I set com.mmfashionnetwork.ptn.www.mmfashion.LoginActivity That is Login Activity where facebook login button and callback functions exist. My default activity is MainActivity. And facebook app is test mode.</p> <p>This is my login activity and call back functions</p> <pre><code>public class LoginActivity extends AppCompatActivity { private EditText tfEmail; private EditText tfPassword; private Button btnLogin; private ProgressDialog loadingDialog; private TextView tvForgetPassword; private TextView tvCreateAccount; private TextView tvTitle; private Config config; private LoginButton btnFbLogin; private CallbackManager callbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); //other steps setUpFbLoginBtn(); } private void setUpFbLoginBtn() { callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback&lt;LoginResult&gt;() { @Override public void onSuccess(LoginResult loginResult) { Toast.makeText(getBaseContext(),"Success",Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(getBaseContext(),"Canceled",Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException error) { Toast.makeText(getBaseContext(),"Error",Toast.LENGTH_SHORT).show(); } }); } } </code></pre> <p>I also set required credentials in Android manifest file. The problem is callback functions are not get called. As you can see I am toasting message in callback according to state. If I try to login clicking Facebook login button. I was redirect to Facebook as in screenshot.</p> <p><a href="https://i.stack.imgur.com/Cp8YD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cp8YD.png" alt="enter image description here"></a></p> <p>When I click ok, no callback function is called. Current screenshot saying already authorized. But when I logged in for the first time, it is not showing any message when I was redirected to my app Login Activity as well. How can I retrieved data after logging in? In developer settings, I must set login activity class or main activity class? I tried setting both alternate. Both gave me the same result.</p>
2
Java HTTP Request on VPN only website
<p>I am trying to build a website parser for one of our internal websites (accessible only from the company network - we get on the network through Cisco AnyConnect VPN). </p> <p>I can access the site fine in any browser, but not using HTTP requests. Windows network and sharing center shows that I have two active networks:</p> <ol> <li>The actual internet connection</li> <li>The company network (without internet access).</li> </ol> <p>Default HTTP client gets time out as I suppose it makes a request using the actual internet connection (and the website is not accessible to public), but using this code:</p> <pre><code>HttpParams params = httpClient.getParams(); params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName("10.x.x.x")); </code></pre> <p>I get the following error: </p> <blockquote> <p>I/O exception caught when connectiong to /10.x.x.x -> {s} -> <a href="https://zzz.com:443" rel="nofollow">https://zzz.com:443</a>: Network is unreachable: connect</p> </blockquote> <p>Also, might be a stupid test but I have done a HTTP request to a "what is my ip" site and the IP is shown as my Wifi IP not the IP through VPN (which I get when I open browser and browse to a "what is my ip" website). Same thing (wrong IP) when I try this using a gui-less browser (Jaunt or HTMLUnit).</p> <p>Please advise if any fixes for this.</p>
2
How to get Match Groups in ruby like Rubular without spliting the string
<p>How does Rubular (<a href="http://rubular.com/r/iJ1eJ1zpHs" rel="nofollow">Example</a>) get the match groups?</p> <pre><code>/regex(?&lt;named&gt; .*)/.match('some long string') </code></pre> <p><a href="http://ruby-doc.org/core-2.2.0/String.html#method-i-match" rel="nofollow">match</a> method (in example) only returns the first match.</p> <p><a href="http://ruby-doc.org/core-2.2.0/String.html#method-i-scan" rel="nofollow">scan</a> method returns an array without named captures. </p> <p>What is the best way to get an array of named captures (no splitting)?</p>
2
onClick in Expandable RecyclerView (using bignerdranch library)
<p>In the project I'm working, I get a bunch of "Projects"(parent) with "Issues" (child). As I have to show it in a list, I used RecyclerView to do it. To achieve it I used BigNerdRanch library (<a href="https://github.com/bignerdranch/expandable-recycler-view" rel="nofollow">https://github.com/bignerdranch/expandable-recycler-view</a>)</p> <p>The problem come's that I need to click on Child to take all the information of the issue and send it to another activity.</p> <p>The library don't have any method to handle the child click, so I tried to implement a work around and worked (I think is ok..), but here I'm blocked. I don't know how to take the clicked child to launch the activity with the necessary info.</p> <p>Here is the ProjectAdapter:</p> <pre><code>public class ProjectAdapter extends ExpandableRecyclerAdapter&lt;ProjectViewHolder, IssueViewHolder&gt; { private LayoutInflater mInflator; private Context appContext ; public ProjectAdapter(Context context, @NonNull List&lt;? extends ParentListItem&gt; parentItemList) { super(parentItemList); this.mInflator = LayoutInflater.from(context); this.appContext = context; } @Override public ProjectViewHolder onCreateParentViewHolder(ViewGroup parentViewGroup) { View projectView = mInflator.inflate(R.layout.jira_project, parentViewGroup, false); return new ProjectViewHolder(projectView); } @Override public IssueViewHolder onCreateChildViewHolder(ViewGroup childViewGroup) { View issueView = mInflator.inflate(R.layout.jira_issue, childViewGroup, false); return new IssueViewHolder(issueView,this.appContext); } @Override public void onBindParentViewHolder(ProjectViewHolder projectViewHolder, int position, ParentListItem parentListItem) { Project project = (Project) parentListItem; projectViewHolder.bind(project); } @Override public void onBindChildViewHolder(IssueViewHolder issueViewHolder, int position, Object childListItem) { Issue issue = (Issue) childListItem; issueViewHolder.bind(issue); } } </code></pre> <p>IssueViewHolder (Child):</p> <pre><code>public class IssueViewHolder extends ChildViewHolder{ private TextView mIssueTextView; // contendra de momento el "summary" del issue private Context appContext; public IssueViewHolder(View itemView, final Context appContext) { super(itemView); this.appContext = appContext; this.mIssueTextView = (TextView) itemView.findViewById(R.id.jir_issue_name); this.mIssueTextView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Log.d("JIRA", "CLICk CHILD"); Toast.makeText(appContext, "CHILD #"+getAdapterPosition() +"\n CHILD##"+getPosition(), Toast.LENGTH_LONG).show(); } }); } public void bind(Issue issue){ mIssueTextView.setText(issue.getKey()); } } </code></pre> <p>As I said,I'm stucked on How to get the child information.</p> <p>How can I solve it?</p>
2
MongoDB References Not Saving (Mongoose)
<p>So I have encountered a strange problem that has been driving me crazy. I have a schema for Stores which represent storefronts that carry the products of certain Manufacturers which I also have a schema for. One of the properties of the Store schema is an array of Manufacturer objects referenced by ObjectId.</p> <p>Basically, what I want to accomplish is that when a new Store document is created, I want to go through all of the existing Manufacturer documents, and add the <code>_id</code> property of each one to the reference array in the Store document.</p> <p>The strangest thing is, that after I call the <code>.save()</code> method on the newly created Store model after pushing all the <code>_id</code>'s onto the array, the debugging print out shows that the result saved exactly how I want it. However, when I go to make a cURL call to pull the record from my database, the manufacturers array is completely empty and none of the ObjectId's become populated with their reference.</p> <p>I have no idea where to go from here, can anybody help?</p> <p>Thanks</p> <p><strong>Schema Definitions:</strong></p> <pre><code>var Schema = mongoose.Schema; //create a schema for database var storeSchema = new Schema({ "number": String, "state": String, "zip": String, "city": String, "street": String, "manufacturers": [{ "type": mongoose.Schema.Types.Mixed, "ref": "Manufacturer" }] }); var manufacturerSchema = new Schema({ "name": String, "country": String, "products": [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Product" }] }); var Product = mongoose.model("Product", productSchema); var Manufac = mongoose.model("Manufacturer", manufacturerSchema); </code></pre> <p><strong>Creating a Store Document:</strong></p> <pre><code>app.put("/api/v1.0/stores", function(req, res){ console.log("PUT request received at /stores."); if(Object.keys(req.body).length &lt; 5){ //not enough parameters console.log("Not enough parameters were supplied."); res.sendStatus(400); } //create a new database product document and save to database var savedID; var params = req.body; var tmpStore = new Store({ "number": params.number, "state": params.state, "zip": params.zip, "city": params.city, "street": params.street }); //find all manufacturers Manufac.find({}, function(err, result){ result.forEach(function(value){ tmpStore.manufacturers.push(value._id); }); }); tmpStore.save(function(err, result){ if(err) { console.log("Error PUTing store!"); return; } console.log("Saved successfully: " + result); }); res.sendStatus(200); }); </code></pre> <p><strong>Output:</strong></p> <pre><code>App listening on port 8080. PUT request received at /stores. Saved successfully: { __v: 0, number: '1', state: 'OR', zip: '97333', city: 'Corvallis', street: '1680 Washington St.', _id: 578df6a679e28aea6b84bec8, manufacturers: [ 578dae80a8f8ec3266a5d956, 578dd1918caa17b467b7caee, 578dd19f8caa17b467b7caef, 578dd1bd8caa17b467b7caf0 ] } </code></pre> <p><strong>JSON from cURL GET</strong></p> <pre><code>{ "_id": "578df6a679e28aea6b84bec8", "number": "1", "state": "OR", "zip": "97333", "city": "Corvallis", "street": "1680 Washington St.", "__v": 0, "manufacturers": [] } </code></pre> <p><strong>Server-Side GET Request Code:</strong></p> <pre><code>app.get("/api/v1.0/stores", function(req, res) { console.log("Get received at /stores"); Store .find({}) .populate("manufacturers") .exec(function(err, result){ if(err){ console.log("Error fetching stores!"); return; } res.json(result); }); }); </code></pre>
2
Jboss - handshake failure - client connection using TLSv1.1 instead of TLSv1.2
<p>I have a jboss version Version 6.3.0.GA , using java version 1.7.0_71 My collegues on remote server changes allowed TLS protocol from 1.1 to 1.2, and now i have to update my client (deployed in jboss). The problem is that after this change i receive:</p> <pre><code>faultString: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure </code></pre> <p>In ssl debug i see:</p> <pre><code>5:22:43,921 INFO [stdout] (http-/0.0.0.0:8080-1) *** ClientHello, TLSv1 15:22:43,923 INFO [stdout] (http-/0.0.0.0:8080-1) RandomCookie: GMT: 1467638563 bytes = { 250, 245, 94, 108, 232, 16, 43, 124, 53, 95, 38, 104, 249, 96, 71, 207, 230, 7, 84, 183, 41, 224, 63, 213, 186, 7, 179, 255 } 15:22:43,923 INFO [stdout] (http-/0.0.0.0:8080-1) Session ID: {} 15:22:43,923 INFO [stdout] (http-/0.0.0.0:8080-1) Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV] 15:22:43,924 INFO [stdout] (http-/0.0.0.0:8080-1) Compression Methods: { 0 } 15:22:43,924 INFO [stdout] (http-/0.0.0.0:8080-1) Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1} 15:22:43,924 INFO [stdout] (http-/0.0.0.0:8080-1) Extension ec_point_formats, formats: [uncompressed] 15:22:43,925 INFO [stdout] (http-/0.0.0.0:8080-1) Extension server_name, server_name: [host_name: cxg7d.test.centurylink.com] 15:22:43,925 INFO [stdout] (http-/0.0.0.0:8080-1) *** 15:22:43,925 INFO [stdout] (http-/0.0.0.0:8080-1) http-/0.0.0.0:8080-1, WRITE: TLSv1 Handshake, length = 184 15:22:43,958 INFO [stdout] (http-/0.0.0.0:8080-1) http-/0.0.0.0:8080-1, READ: TLSv1.2 Alert, length = 2 15:22:43,959 INFO [stdout] (http-/0.0.0.0:8080-1) http-/0.0.0.0:8080-1, RECV TLSv1 ALERT: fatal, handshake_failure 15:22:43,959 INFO [stdout] (http-/0.0.0.0:8080-1) http-/0.0.0.0:8080-1, called closeSocket() 15:22:43,960 INFO [stdout] (http-/0.0.0.0:8080-1) http-/0.0.0.0:8080-1, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure 15:22:43,963 ERROR [stderr] (http-/0.0.0.0:8080-1) AxisFault 15:22:43,964 ERROR [stderr] (http-/0.0.0.0:8080-1) faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException 15:22:43,964 ERROR [stderr] (http-/0.0.0.0:8080-1) faultSubcode: 15:22:43,964 ERROR [stderr] (http-/0.0.0.0:8080-1) faultString: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure </code></pre> <p>Even after below change has been applied</p> <p>1 - updated the "standalone.xml" with below values</p> <pre><code>&lt;system-properties&gt; &lt;property name="https.protocols" value="TLSv1.2"/&gt; &lt;/system-properties&gt; </code></pre> <p>2 - added below JAVA Options to server start:</p> <pre><code>-Djavax.net.debug=all -Ddeployment.security.TLSv1.2=true -Ddeployment.security.TLSv1.2=true -Ddeployment.security.TLSv1=false -Dhttps.protocols=TLSv1.2 </code></pre> <p>3 - Changed graphically the protocols in java console <a href="http://i.stack.imgur.com/moJhq.png" rel="nofollow">JDK control panel</a></p> <p>but nothing handshake still exists. I suppose that the error is on "Client Hello" that still use TLSv1 instead of 1.2 . Do youhave any suggestion to force this value? S.</p>
2
Angular js application shows blank white page on ios browsers, safari and chrome both. Works fine on windows desktop browsers
<p>I have one redhat cloud application which front-end developed in Angular.js 1.5.5, it works perfectly fine on windows desktop and android device browsers where only on ios mobile browsers chrome or safari it shows blank white page. When I put sample loading text under body tag I was able to see that but nothing rendered except loadig text. To serve static content it has Node-Hapi.js server which has just basic stuff and static folder path. Below is application url - </p> <p><a href="http://restperformance-gunjankrs.rhcloud.com/" rel="nofollow">http://restperformance-gunjankrs.rhcloud.com/</a></p>
2
Hibernate: Repeated column in mapping for entity
<p>I've found a lot of questions about this but they did not solve my problem.</p> <p>This is the structure that I'm trying to map:</p> <p><strong>TABLE A</strong></p> <p>col0 (PK) | colA (PK) | colB</p> <p><strong>TABLE B</strong></p> <p>col0 (PK) |colA (PK) | colC (PK) | ColD</p> <p><strong>TABLE C</strong> </p> <p>col0 (PK) | colA (PK) | colC (PK) | ColE (PK) | ColF</p> <p>I have a problem on the third table (Table C). The exception thrown is </p> <blockquote> <p>org.hibernate.MappingException: Repeated column in mapping for entity: TableC column: colA (should be mapped with insert="false" update="false")</p> </blockquote> <p>Table C: </p> <pre><code>@Entity @Table(name="TableC") public class TableC implements Serializable{ @EmbeddedId private TableCId tableCId; @MapsId("tableBId") @ManyToOne @JoinColumns({ @JoinColumn(name="col0", referencedColumnName="col0"), @JoinColumn(name="colC", referencedColumnName="colC"), @JoinColumn(name="colA", referencedColumnName="colA") }) private TableB tableB; // Getters and setters } </code></pre> <p>Here I defined the TableCId </p> <pre><code> @Embeddable public static class TableCId implements Serializable{ private TableBId tableBId; private Integer colE; // Getters and setters // equals and hashcode } </code></pre> <p>And then the TableBId </p> <pre><code>@Embeddable public static class TableBId implements Serializable{ private Integer col0; private Integer colA; private Integer colC; // Getters and setters // equals and hashcode } </code></pre> <p>I already tried to put <code>insertable=false, updatable=false</code> in @JoinColumn but with no result.</p>
2
Progress indicator on RecyclerView
<p>I work with a <code>RecyclerView</code> that looks like this.</p> <p><a href="https://i.stack.imgur.com/YjToom.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YjToom.png" alt="enter image description here"></a></p> <p>I use an <code>AsyncTask</code> for managing the downloads. I use <a href="https://github.com/dmytrodanylyk/circular-progress-button" rel="nofollow noreferrer">this</a> button so that each item in the list of cards can have the progress of the respective download. I am not sure how to report the status of the download to the <code>RecyclerView</code>. How do I get this to post updates to the cards?</p> <p>The async downloader code is this</p> <pre><code>public class DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; { private final String resourceType; public DownloadFileFromURL(String resourceType) { super(); this.resourceType = resourceType; // do stuff } @Override protected void onPreExecute() { super.onPreExecute(); //showDialog(progress_bar_type); } protected void onProgressUpdate(String... progress) { // setting progress percentage // pDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected String doInBackground(String... f_url) { int count; try { URL url = new URL(f_url[0]); String fileName = url.toString().substring(url.toString().lastIndexOf('/') + 1); URLConnection connection = url.openConnection(); connection.connect(); // this will be useful so that you can show a tipical 0-100% // progress bar int lengthOfFile = connection.getContentLength(); Log.d("lengthofFile", String.valueOf(lengthOfFile)); // download the file InputStream input = new BufferedInputStream(url.openStream(), 8192); String destinationDirectory =""; if(resourceType.equals(SyncUtil.IMAGE_ZIP)) { destinationDirectory= SyncUtil.TMP; } if(resourceType.equals(SyncUtil.VIDEOFILE)) { destinationDirectory = SyncUtil.VIDEO; } File mFolder = new File(AppController.root.toString() + File.separator+destinationDirectory); if (!mFolder.exists()) { mFolder.mkdir(); } OutputStream output = new FileOutputStream(AppController.root.toString()+File.separator+destinationDirectory+File.separator + fileName); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called publishProgress("" + (int) ((total * 100) / lengthOfFile)); output.write(data, 0, count); } output.flush(); // closing streams output.close(); input.close(); if(resourceType.equals(SyncUtil.IMAGE_ZIP)) { BusProvider.getInstance().post(new ZipDownloadComplete(fileName,resourceType)); } if(resourceType.equals(SyncUtil.VIDEOFILE)) { // BusProvider.getInstance().post(new VideoDownloadComplete(fileName)); } } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } @Override protected void onPostExecute(String file_url) { } } </code></pre> <p>The <code>RecyclerView</code> adapter is here </p> <pre><code>@Override public void onBindViewHolder(MyViewHolder holder, int position) { final Video video = videosList.get(position); holder.title.setText(video.getTitle()); holder.description.setText(video.getDescription()); holder.downloadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url ="http://"+ AppController.serverAddr +":"+AppController.port +"/video/"+video.getUrl()+video.getExtension(); DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(SyncUtil.VIDEOFILE); downloadFileFromURL.execute(url,video.getTitle(),video.getDescription()); } }); holder.bind(video,listener); } </code></pre>
2
Escaping exclamation marks required in replace string but not in search string (substring replacement with delayed expansion on)?
<p>Supposing one wants to replace certain substrings by exclamation marks using the <a href="http://ss64.com/nt/syntax-replace.html" rel="nofollow noreferrer">substring replacement</a> syntax while <a href="http://ss64.com/nt/delayedexpansion.html" rel="nofollow noreferrer">delayed expansion</a> is enabled, they have to use immediate (normal) expansion, because the parser cannot distinguish between <code>!</code>s for expansion and literal ones.</p> <p>However, why does one have to escape exclamation marks in the replacement string? And why is it not necessary and even disruptive when exclamation marks in the search string are escaped?</p> <p>The following script replaces <code>!</code>s in a string by <code>`</code> and in reverse order afterwards, so I expect the result to be equal to the initial string (which must not contain any back-ticks on its own of course):</p> <pre><code>@echo off setlocal EnableExtensions DisableDelayedExpansion rem This is the test string: set "STRING=string!with!exclamation!marks!" set "DELOFF=%STRING%" set "DELOFF=%DELOFF:!=`%" set "DELOFF=%DELOFF:`=!%" setlocal EnableDelayedExpansion set "DELEXP=!STRING!" set "DELEXP=%DELEXP:!=`%" set "DELEXP=%DELEXP:`=!%" echo(original string: !STRING! echo(normal expansion: !DELOFF! echo(delayed expansion: !DELEXP! endlocal endlocal exit /B </code></pre> <p>This result is definitely not what I want, the last string is different:</p> <blockquote> <pre><code>original string: string!with!exclamation!marks! normal expansion: string!with!exclamation!marks! delayed expansion: stringexclamation </code></pre> </blockquote> <p>As soon as take the line...:</p> <pre><code>set "DELEXP=%DELEXP:`=!%" </code></pre> <p>....and replace the <code>!</code> by <code>^!</code> there, hence escaping the exclamation mark in the replace string, the result is exactly what I expect:</p> <blockquote> <pre><code>original string: string!with!exclamation!marks! normal expansion: string!with!exclamation!marks! delayed expansion: string!with!exclamation!marks! </code></pre> </blockquote> <p>When I try other escaping combinations though (escape the exclamation mark in both the replace and the search string, or in the latter only), the result is again the aforementioned unwanted one.</p> <p>I walked through the post <a href="https://stackoverflow.com/q/4094699">How does the Windows Command Interpreter (CMD.EXE) parse scripts?</a> but I could not find an explanation to that behaviour, because I learned the normal (or immediate, percent) expansion is accomplished long before delayed expansion occurs and any exclamation marks are even recognised. Also caret recognition and escaping seems to happen afterwards. In addition, there are even quotation marks around the strings that usualy hide carets from the parser.</p>
2
Node-Red: Create server and share input
<p>I'm trying to create a new node for Node-Red. Basically it is a udp listening socket that shall be established via a config node and which shall pass all incoming messages to dedicated nodes for processing. This is the basic what I have:</p> <pre><code>function udpServer(n) { RED.nodes.createNode(this, n); this.addr = n.host; this.port = n.port; var node = this; var socket = dgram.createSocket('udp4'); socket.on('listening', function () { var address = socket.address(); logInfo('UDP Server listening on ' + address.address + ":" + address.port); }); socket.on('message', function (message, remote) { var bb = new ByteBuffer.fromBinary(message,1,0); var CoEdata = decodeCoE(bb); if (CoEdata.type == 'digital') { //handle digital output // pass to digital handling node } else if (CoEdata.type == 'analogue'){ //handle analogue output // pass to analogue handling node } }); socket.on("error", function (err) { logError("Socket error: " + err); socket.close(); }); socket.bind({ address: node.addr, port: node.port, exclusive: true }); node.on("close", function(done) { socket.close(); }); } RED.nodes.registerType("myServernode", udpServer); </code></pre> <p>For the processing node:</p> <pre><code>function ProcessAnalog(n) { RED.nodes.createNode(this, n); var node = this; this.serverConfig = RED.nodes.getNode(this.server); this.channel = n.channel; // how do I get the server's message here? } RED.nodes.registerType("process-analogue-in", ProcessAnalog); </code></pre> <p>I can't figure out how to pass the messages that the socket receives to a variable number of processing nodes, i.e. multiple processing nodes shall share on server instance.</p> <p>==== EDIT for more clarity =====</p> <p>I want to develop a new set of nodes:</p> <p><em>One Server Node:</em></p> <ul> <li>Uses a <a href="http://nodered.org/docs/creating-nodes/config-nodes" rel="nofollow">config-node</a> to create an UDP listening socket</li> <li>Managing the socket connection (close events, error etc) </li> <li>Receives data packages with one to many channels of different data</li> </ul> <p><em>One to many processing nodes</em></p> <ul> <li>The processing nodes shall share the same connection that the Server Node has established</li> <li>The processing nodes shall handle the messages that the server is emitting</li> <li>Possibly the Node-Red flow would use as many processing Nodes as there are channels in the server's data package</li> </ul> <p>To quote the Node-Red documentation on config-nodes:</p> <blockquote> <p>A common use of config nodes is to represent a shared connection to a remote system. In that instance, the config node may also be responsible for <strong>creating the connection and making it available</strong> to the nodes that use the config node. In such cases, the config node should also handle the close event to disconnect when the node is stopped.</p> </blockquote> <p>As far as I understood this, I make the connection available via <code>this.serverConfig = RED.nodes.getNode(this.server);</code> but I cannot figure out how to pass data, which is received by this connection, to the node that is using this connection.</p>
2
Keep-Alive http header with timeout not used by google, stackoverflow, etc?
<p>I started reading about Keep-Alive and was thinking about adding it to my webserver but as I traced <a href="http://google.com" rel="nofollow">http://google.com</a> and <a href="http://stackoverflow.com">http://stackoverflow.com</a>, I noticed they are not sending this header at all back to the clients (with a timeout that is).</p> <p>Why is that? I would think normally you want to kill connections that have been idle for more than 20 seconds or so. I was actually curious what other websites were using. Perhaps they do timeout the idle connection eventually but just don't tell the clients they are going to do that(which seems odd).</p> <p>I did a "telnet google.com 80" and waited about 2 minutes and it never timed out and then I issued a "GET / HTTP/1.1" and waited some more than typed in a bunch of random garbage over and over(not sure they limit the header size either so you 'could' OOM their servers I think). I finally hit enter twice and got back a 200 OK....none of my headers were well-formed but google didn't seem to care(odd).</p> <p>thanks, Dean</p>
2
Jmeter : Websocket Sampler showing error
<p>I am trying to connect WebSocket using Jmeter- Websocket sampler. For this, I used <a href="https://github.com/maciejzaleski/JMeter-WebSocketSampler" rel="nofollow">maciejzaleski</a> plugin.</p> <p>Getting below error from the <code>jmeter log</code>.</p> <blockquote> <p>ERROR - jmeter.threads.JMeterThread: Test failed! java.lang.NoClassDefFoundError: org/eclipse/jetty/util/ssl/SslContextFactory</p> </blockquote> <p>If I am missing something, let me know how to correct it.</p>
2
VBA: Only save the last (The most recent) email attachment in a local folder
<p>I need to save the attachment of last email that has a specific subject (the most recent one) to a local folder, to do this I have created a folder in my Outlook and a rule to send every email with that specific subject to this folder. I have found a code that does what I needed except that it saves every single attachment in the email folder rather than saving only the most recent one. This is the code: how could i modify it so that it does what i need?</p> <pre><code> Sub Test() 'Arg 1 = Folder name of folder inside your Inbox 'Arg 2 = File extension, "" is every file 'Arg 3 = Save folder, "C:\Users\Ron\test" or "" ' If you use "" it will create a date/time stamped folder for you in your "Documents" folder ' Note: If you use this "C:\Users\Ron\test" the folder must exist. SaveEmailAttachmentsToFolder "Dependencia Financiera", "xls", "W:\dependencia financiera\test dependencia\" End Sub Sub SaveEmailAttachmentsToFolder(OutlookFolderInInbox As String, _ ExtString As String, DestFolder As String) Dim ns As NameSpace Dim Inbox As MAPIFolder Dim SubFolder As MAPIFolder Dim Item As Object Dim Atmt As Attachment Dim FileName As String Dim MyDocPath As String Dim i As Integer Dim wsh As Object Dim fs As Object On Error GoTo ThisMacro_err Set ns = GetNamespace("MAPI") Set Inbox = ns.GetDefaultFolder(olFolderInbox) Set SubFolder = Inbox.Folders(OutlookFolderInInbox) i = 0 ' Check subfolder for messages and exit of none found If SubFolder.Items.Count = 0 Then MsgBox "There are no messages in this folder : " &amp; OutlookFolderInInbox, _ vbInformation, "Nothing Found" Set SubFolder = Nothing Set Inbox = Nothing Set ns = Nothing Exit Sub End If 'Create DestFolder if DestFolder = "" ' If DestFolder = "" Then ' Set wsh = CreateObject("WScript.Shell") ' Set fs = CreateObject("Scripting.FileSystemObject") ' MyDocPath = wsh.SpecialFolders.Item("mydocuments") ' DestFolder = MyDocPath &amp; "\" &amp; Format(Now, "dd-mmm-yyyy hh-mm-ss") ' If Not fs.FolderExists(DestFolder) Then 'fs.CreateFolder DestFolder ' End If 'End If 'If Right(DestFolder, 1) &lt;&gt; "\" Then 'DestFolder = DestFolder &amp; "\" 'End If ' Check each message for attachments and extensions 'JUST BEED TGE FIRST EMAIL 'Debug.Print Item(1).SentOn For Each Item In SubFolder.Items For Each Atmt In Item.Attachments If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString) Then FileName = DestFolder &amp; Atmt.FileName Atmt.SaveAsFile FileName 'I = I + 1 End If Next Atmt Next Item ' Show this message when Finished ' If I &gt; 0 Then ' MsgBox "You can find the files here : " _ &amp; DestFolder, vbInformation, "Finished!" ' Else ' MsgBox "No attached files in your mail.", vbInformation, "Finished!" ' End If ' Clear memory ThisMacro_exit: Set SubFolder = Nothing Set Inbox = Nothing Set ns = Nothing Set fs = Nothing Set wsh = Nothing Exit Sub ' Error information ThisMacro_err: MsgBox "An unexpected error has occurred." _ &amp; vbCrLf &amp; "Please note and report the following information." _ &amp; vbCrLf &amp; "Macro Name: SaveEmailAttachmentsToFolder" _ &amp; vbCrLf &amp; "Error Number: " &amp; Err.Number _ &amp; vbCrLf &amp; "Error Description: " &amp; Err.Description _ , vbCritical, "Error!" Resume ThisMacro_exit End Sub </code></pre>
2
Spark Streaming: how to get processing time and scheduling delay by StreamingListener?
<p>The offical documentation says we can get the values of processing time by StreamingListener: The progress of a Spark Streaming program can also be monitored using the StreamingListener interface, which allows you to get receiver status and processing times. <a href="http://spark.apache.org/docs/latest/streaming-programming-guide.html#monitoring-applications" rel="nofollow">http://spark.apache.org/docs/latest/streaming-programming-guide.html#monitoring-applications</a></p> <p>I know there is some information about the metrics of Spark, but it does not contains the processing time and scheduling delay. <a href="http://spark.apache.org/docs/latest/monitoring.html#rest-api" rel="nofollow">http://spark.apache.org/docs/latest/monitoring.html#rest-api</a></p> <p>I read the source code of StreamingListener. It contains a method like this: </p> <pre><code>def printStats() { showMillisDistribution("Total delay: ", _.totalDelay) showMillisDistribution("Processing time: ", _.processingDelay) } </code></pre> <p>I think it is possible to get these metrics but I did not realize it. I need these metrics for my research. How can I get them? Thanks very very much.</p>
2
NSIS - Could not write updated PATH to HKLM
<p>Good evening, I have a problem when I try to modify the environment variable's path. I'm using the <code>EnvVarUpdate</code> nsi tand for some reason when I run the the installer I get this warning. <a href="https://i.stack.imgur.com/NRyyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NRyyA.png" alt="enter image description here"></a></p> <p>Any suggestions are highly appreciated !</p>
2
Angular2 Parent Component Not Triggering Event of Child Component
<p>I am attempting to create a component that allows the user to select actions to be performed on "tests" using a table interface. Each row of the table is a separate child component with the parent component comprising of the table headers and the child component rows, which are created using <code>*ngFor</code>.</p> <p>Everything is mostly going well, except I need the checkbox in the header to check all of the child component checkboxes and the select in the header to select all of the child component to equal the chosen option in the header. The checkboxes look like it works (as demoed in the Plunker), but the event handler in the parent component does not get the updated checked value when the header checkbox is checked, but does when the actual row's checkbox is checked. The demo has the checkboxes printing stuff to the console. I would expect the header checkbox to trigger all of the checkbox's 'checked' event and print multiple statements to the console (two lines per table row).</p> <p>I started putting the pieces in place to handle the header's select changing, but am a little stuck as to how to make a select's option selected when the options are being populated using <code>*ngFor</code>.</p> <p>I don't know if it matters, but I am using angular2-beta 15 and am trying to stay on this version if possible.</p> <p>Plunker and code dump are below.</p> <pre><code>import {Component, EventEmitter, Output, Input} from 'angular2/core' // Child Component @Component({ selector: 'tbody', template: ` &lt;td&gt;{{ test }}&lt;/td&gt; &lt;td&gt; &lt;select (change)="selectedActionChange($event)"&gt; &lt;option *ngFor="#opt of optionList"&gt;{{ opt }}&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td class="center"&gt; &lt;input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="checkboxChanged($event)" /&gt; &lt;/td&gt; ` }) export class ChildComponent { @Input() test: string; @Input() checkboxValue: boolean; @Input() selectedAction: string; @Output() action: EventEmitter&lt;any&gt; = new EventEmitter(); @Output() checked: EventEmitter&lt;any&gt; = new EventEmitter(); optionList: Array&lt;string&gt; = ["Add", "Replace", "Skip"]; selectedActionChange(event) { this.action.emit({ value: event.srcElement.value, test: this.test }); } checkboxChanged(event: any) { this.checked.emit({ value: event, test: this.test }); } } // Parent Component @Component({ selector: 'parent', template: ` &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Test Name&lt;/th&gt; &lt;th&gt; &lt;label&gt;Action&lt;/label&gt; &lt;br /&gt; &lt;select (change)="headerSelectChanged($event)"&gt; &lt;option *ngFor="#opt of optionList"&gt;{{ opt }}&lt;/option&gt; &lt;/select&gt; &lt;/th&gt; &lt;th&gt; &lt;label&gt;Import Test&lt;/label&gt; &lt;br /&gt; &lt;input type="checkbox" checked (change)="headerCheckboxChanged($event)"/&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody *ngFor="#test of testList" [test]="test" [checkboxValue]="masterCheckboxValue" [selectedAction]="masterSelectAction" (action)="actionChange($event)" (checked)="checkedChanged($event)"&gt;&lt;/tbody&gt; &lt;/table&gt; `, directives: [ChildComponent] }) export class ParentComponent { testList: Array&lt;string&gt; = ["Test 1", "Test 2", "Test 3"]; optionList: Array&lt;string&gt; = ["Add", "Replace", "Skip"]; masterCheckboxValue: boolean = true; masterSelectAction: string; headerCheckboxChanged(event: any): void { this.masterCheckboxValue = event.srcElement.checked; } headerSelectChanged(event: any): void { this.masterSelectAction = event.srcElement.value; } actionChange(event: any) { console.log(event.test); console.log(event.value); } checkedChanged(event: any) { console.log(event.test); console.log(event.value); } } </code></pre> <p><a href="http://plnkr.co/edit/xRfTi7DkEd08KE6PjYnT?p=preview" rel="nofollow"><strong>Plunker</strong> link</a></p>
2
Using trailing closure in for-in loop
<p>I'm using <code>map()</code> function of array in for-in loop like this:</p> <pre><code>let numbers = [2, 4, 6, 8, 10] for doubled in numbers.map { $0 * 2 } // compile error { print(doubled) } </code></pre> <p>which produces compile error:</p> <blockquote> <p>Use of unresolved identifier 'doubled'</p> </blockquote> <p>However, if I put parenthesis for <code>map()</code> function, it works fine. i.e.</p> <pre><code>for doubled in numbers.map ({ $0 * 2 }) { print(doubled) } </code></pre> <p>My question is, why wouldn't compiler differentiate code block of trailing function and loop, assuming this is causing the problem?</p>
2
Angular 2 - Services consuming others services before call a method
<p>I've this scenario.</p> <p>backend.json</p> <pre><code>{ "devServer": "http://server1/'", "proServer" : "http://server2/'", "use" : "devServer" } </code></pre> <p>global.service.ts</p> <pre><code>import {Injectable} from '@angular/core'; import {Http, HTTP_PROVIDERS, Response, RequestOptions, URLSearchParams} from '@angular/http'; @Injectable() export class GlobalService { constructor(private _http: Http){} getBackendServer(){ return this.server = this._http.get('./backend.json') .map((res:Response) =&gt; res.json()) } } </code></pre> <p>And I've this other service: search.service.ts</p> <pre><code>import {Injectable} from '@angular/core'; import {Http, HTTP_PROVIDERS, Response, RequestOptions, URLSearchParams} from '@angular/http'; import {GlobalService} from '../services/global.service'; import 'rxjs/add/operator/map'; @Injectable() export class SearchService { server; constructor( private _http: Http, private gs: GlobalService ) { this.server = gs.getBackendServer().subscribe( (data) =&gt; { this.server = data[data.use]; }, (err) =&gt; { console.log(err); } ); } DoGeneralSearch(params:Search){ console.log(this.server); let options = this.buildOptions(params); return this._http.get(this.server + 'room/search', options) .map((res:Response) =&gt; res.json()) } } </code></pre> <p>What I want to do: Looks obvious: I want to keep the information regarding the URL of the backend server in a JSON file - And the global service should return the server so this can be used in any method of the search service.</p> <p>The problem is: the DoGeneralSearch() method executes before the global service is capable to resolve the task to read the JSON file and return the result. So, I've a this.server = Subscriber {isUnsubscribed: false, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: false…} instead the result itself.</p> <p>I need to find some how to prevent the method DoGeneralSearch be executed just after resolved the this.server variable.</p> <p>Any suggestions ?</p>
2
SQL Server Agent Job step is not getting executed
<p>I have written sql agent job that has 2 steps. First step is executing another job which deletes text file from some location and second step is copying specific file and pasting it to some location. If I execute these two steps independently they execute properly. However when I run it as a job, only first step gets executed , second does not. Job history is shows as Success. So it seems second step is also getting executed but is is not performing any action. Please suggest. </p>
2
How to force Android Studio to build with updated NDK library, without having to clean and build entire project?
<p>How can I force Android Studio to build my app using the the updated NDK shared library (.so) file, without having to clean the entire project first?</p> <p>There must be some mechanism by which Android Studio can detect that the shared library has been updated and to use the latest one. If I do a Build->Clean Project and then do a Run->Run 'app' it will use the new version of the library, but it will also have to do a lot of work that is unnecessary, since none of the java source has changed. Even a Run->Clean and Rerun'app' won't use the new library.(!!!)</p>
2
Rails: Migration Errors
<p>when I go to my <a href="http://localhost:3000/" rel="nofollow">http://localhost:3000/</a> I am getting the following:</p> <blockquote> <p>ActiveRecord::PendingMigrationError</p> <p>Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development</p> </blockquote> <p>Extracted source:</p> <pre><code># Raises &lt;tt&gt;ActiveRecord::PendingMigrationError&lt;/tt&gt; error if any migrations are pending. def check_pending!(connection = Base.connection) raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection) end def load_schema_if_pending! </code></pre> <p>Also, when I tried to to the <code>heroku run rake db:migrate</code> in the console, it said:</p> <blockquote> <p>StandardError: An error has occurred, this and all later migrations canceled: PG::DuplicateColumn: ERROR: column "email" of relation "users" already exists</p> </blockquote> <p>I am new to ruby and followed the <a href="https://www.youtube.com/watch?v=-WLPL1AvazE&amp;index=22&amp;list=PL23ZvcdS3XPK9Y4DRU-BiJtiY5L_QhUUq" rel="nofollow">devise tutorial</a> by Mackenzie Child. It's my last step to complete my first ruby application. </p> <p>I am excited and looking forward to your help! :)</p>
2
k-means++ vs random for initial centers
<p>I've seen that in many K-means implementations, like <a href="http://www.vlfeat.org/api/kmeans.html" rel="nofollow">VLFeat k-means</a> or <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html" rel="nofollow">OpenCV k-means</a>, there are essentially 2 methods for choosing starting centroids:</p> <ol> <li>Randomly</li> <li>Following the <a href="https://en.wikipedia.org/wiki/K-means%2B%2B" rel="nofollow">K-Means++</a> algorithm</li> </ol> <p>However, I didn't get in which cases one is better of the other, especially because the starting method is considered important. Can you help me understanding this point?</p>
2
How to get Drools (Kie Session) running in a Netbeans Web-Project (No Maven)?
<p>For several days I'm trying to run Drools in Netbeans but it just doesn't work like I want it to. I even tried to get it working as a maven project but that didn't work as well. I describe what I do to create the project, hopefully someone can give me a hint.</p> <p><strong>First of i need it to work without maven because I'm restricted to not use it.</strong> But before I put it in the real project I want to test it.</p> <p>So first I create a new project </p> <ol> <li>File>New Project.. Wizard</li> <li>Chose "Java Web" Categorie and use Projecttype "Webapplication"</li> <li>Selection a tomcat 8 webserver and Java EE 7 Web</li> <li>No Frameworks for now (later hibernate)</li> <li><p>Create lib folder in project and putting following jars in it:</p> <ul> <li>drools-compiler-6.4.0.Final.jar</li> <li>drools-core-6.4.0.Final.jar</li> <li>drools-decisiontables-6.4.0.Final.jar</li> <li>drools-jsr94-6.4.0.Final.jar</li> <li>drools-reteoo-6.4.0.Final.jar</li> <li>knowledge-api-6.4.0.Final.jar</li> <li>kie-api-6.4.0.Final.jar</li> <li>kie-internal-6.4.0.Final.jar</li> <li>kie-ci-6.4.0.Final.jar</li> <li>mvel2-2.2.6.Final.jar</li> <li>antlr-runtime-3.5.Final.jar</li> </ul></li> </ol> <p>With this Setup I create classes (both in package: Drools) <strong>DroolsMain</strong> (test without webserver and gui for faster debugging)</p> <pre><code>public class DroolsMain { private static KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); private static Collection&lt;KnowledgePackage&gt; pkgs; private static KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); private static StatefulKnowledgeSession ksession; public static void main(final String[] args) { init(); initMessageObject(); fireRules(); } private static void init() { String myRule = "import Drools.Message rule \"Hello World 2\" when message:Message (type==\"Test\") then System.out.println(\"Test, Drools!\"); end"; Resource myResource = ResourceFactory.newReaderResource((Reader) new StringReader(myRule)); kbuilder.add(myResource, ResourceType.DRL); if(kbuilder.hasErrors()) { System.out.println(kbuilder.getErrors().toString()); throw new RuntimeException("unable to compile dlr"); } pkgs = kbuilder.getKnowledgePackages(); kbase.addKnowledgePackages(pkgs); ksession = kbase.newStatefulKnowledgeSession(); } private static void fireRules() { ksession.fireAllRules(); } private static void initMessageObject() { Message msg = new Message(); msg.setType("Test"); ksession.insert(msg); } } </code></pre> <p>and the above used <strong>Message</strong> class</p> <pre><code>public class Message { private String type; private String message; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } </code></pre> <p>I now can run that code and have a the message returned.</p> <p>Now i wanted to try it with Kie...</p> <p>i just comment the methods in <strong>DroolsMain</strong> main() method. and put a Kie method in like current Drools documentation p. 172-174 there:</p> <pre><code>private static void kieTest() { KieServices kieServices = KieServices.Factory.get(); KieContainer kContainer = kieServices.getKieClasspathContainer(); StatelessKieSession kSession = kContainer.newStatelessKieSession(); Applicant bob = new Applicant("Mr. Bob", 16); //assertTrue(bob.isValid()); kSession.execute(bob); //assertFalse(bob.isValid()); } </code></pre> <p>I didn't put the Applicant.class in here becaus its just a bean with 3 attributes. Also I create DRL <strong>applicant.drl</strong> file:</p> <pre><code>package Drools "Is of valid age" import Drools.Applicant when $a : Applicant(age &lt; 18) then $a.setValid(false); end; </code></pre> <p>So this obviously does not work because Kie has maven dependencies so i tried this: 1. Add directories: - DroolsTest/resources/ - DroolsTest/resources/META-INF - DroolsTest/resources/META-INF/maven - DroolsTest/resources/Drools 2. Create DroolsTest/resources/META-INFkmodule.xml</p> <p>Content:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;kmodule xmlns="http://www.drools.org/xsd/kmodule"&gt; &lt;kbase name="Drools" packages="Drools"&gt; &lt;ksession name="ksession-drools" /&gt; &lt;/kbase&gt; &lt;/kmodule&gt; </code></pre> <ol start="3"> <li><p>Create DroolsTest/resources/META-INF/maven/pom.properties Content: (groupId my package name), (artifactId my project name)</p> <p>groupId=Drools artifactId=DroolsTest version=1</p></li> <li>put drl file here: DroolsTest/resources/Drools/applicant.drl</li> </ol> <p>Compiling this throws a RuntimeException:</p> <pre><code>Exception in thread "main" java.lang.RuntimeException: Cannot find a default KieSession at org.drools.compiler.kie.builder.impl.KieContainerImpl.findKieSessionModel(KieContainerImpl.java:555) at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:548) at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:531) at Drools.DroolsMain.kieTest(DroolsMain.java:43) at Drools.DroolsMain.main(DroolsMain.java:52) C:\Users\...\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 3 seconds) </code></pre> <p><strong>Is there a solution to get Kiew working without maven or can I read in a file without it?</strong></p> <hr> <p><strong>UPDATE:</strong> </p> <p>I tried launes solution:</p> <pre><code>import java.io.File; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.Results; import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsMain { private void ntry() { KieServices kieServices = KieServices.Factory.get(); KieFileSystem kfs = kieServices.newKieFileSystem(); File rule = new File("src/main/resources/Drools/applicant.drl"); Resource res = kieServices.getResources().newFileSystemResource(rule); kfs.write(res); KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll(); Results results = kieBuilder.getResults(); System.out.println("---Messages---"); System.out.println(results.getMessages()); KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId()); KieBase kieBase = kieContainer.getKieBase(); KieSession kieSession = kieBase.newKieSession(); } public static void main(final String[] args) { DroolsMain dm = new DroolsMain(); dm.ntry(); } } </code></pre> <p>I also added all jars from the drools distribution. Now it compiles and has no errors</p>
2
Android view zip file without extracting
<p>I am trying to get the contents of a zip file without extracting it. I am using ZipFile to get the entries. But what I observed is it is giving all the files in zip folder in file format like system/app.apk instead of giving system as a directory(like how file.listFiles() gives). How do i get the files in a directory structure format? </p> <p><strong>Zip structure:</strong></p> <pre><code> ZipFolder.zip - system (folder) -&gt; app.apk(file) - meta (folder) -&gt; manifest(folder) -&gt; new.apk (file) </code></pre> <p>Code:</p> <pre><code> ZipFile zipFile = new ZipFile(mPath); Enumeration&lt;? extends ZipEntry&gt; entries = zipFile.entries(); while(entries.hasMoreElements()) { // below code returns system/app.apk and meta/manifest/new.apk // instead of system,meta folders ZipEntry entry = entries.nextElement(); String fileName = entry.getName(); boolean isDirectory = entry.isDirectory(); //returns false } </code></pre>
2
how to declare that a given class implements an interface in Facebook Flow?
<p>I have the following code using Flow:</p> <pre><code>// @flow 'use strict'; import assert from 'assert'; declare interface IPoint { x: number; y: number; distanceTo(other: IPoint): number; } class Point { x: number; y: number; distanceTo(a: IPoint): number { return distance(this, a); } constructor(x: number, y: number) { this.x = x; this.y = y; } } function distance(p1: IPoint, p2: IPoint): number { function sq(x: number): number { return x*x; } return Math.sqrt( sq(p2.x-p1.x)+sq(p2.y-p1.y) ); } assert(distance ( new Point(0,0), new Point(3,4))===5); // distance ( new Point(3,3), 3); // Flow complains, as expected assert((new Point(0,1)).distanceTo(new Point(3,5))===5); // (new Point(0,1)).distanceTo(3); // Flow complains as expected </code></pre> <p>Running <code>npm run flow</code> yields no complains as expected, whereas the commented-out lines give rise to warnings (again, as expected).</p> <p>So all's well with the world except that I don't know how to make it explicit at the point where class <code>Point</code> is defined that it is "implementing" interface <code>IPoint</code>. Is there a way to do so or is it not idiomatic?</p>
2
The package [email protected] does not satisfy its siblings' peerDependencies requirements
<p>When trying to <code>npm install</code> I get these errors. Can't get why it's not running if I'm using the latest version of React.</p> <p><code> npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements! npm ERR! peerinvalid Peer [email protected] wants react@^15.2.1 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.5 npm ERR! peerinvalid Peer [email protected] wants react@^15.2.1 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.7 || ^15.0.0-0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0-0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0-0 npm ERR! peerinvalid Peer [email protected] wants react@~15.2.0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0-0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 || ^15.0.0-rc.1 </code></p>
2
how to know the lowest cuda toolkit version that supports for one specific gpu like gtx1080
<p>For a specific gpu like gtx1080, I want to know that which cuda toolkit versions support for it. I have scanned the official website of nvidia, but find no specific result.</p>
2
@Reference Session is showing unsatisfied error
<p>I'm using a sling servlet. In that I'm using <code>javax.jcr.Session</code> as a reference. After taking a build and when I see in system/console/components, I'm seeing the following error</p> <blockquote> <p>Reference session ["Unsatisfied","Service Name: javax.jcr.Session","Cardinality: 1..1","Policy: static","Policy Option: reluctant","No Services bound"]</p> </blockquote> <p>How can I solve this?</p>
2
Why is internet explorer so bad to develop for?
<p>Why do almost all developers hate developing for Internet Explorer? Recently a client asked for IE 11 support on a new project, and one of the developers basically refused. My goal is to understand her point of view better. What additional development challenges does supporting IE create? Are there sacrifices to the user experience if we try to support IE 11? Or are there just a million little unpredictable problems that vary from project to project?</p>
2
Setting "flags" between threads in Java
<p>I have a class which connects to a server as below.</p> <pre><code>@Override public void run() { while (running) { try { msgHandler.log("Connecting to " + host + ":" + port); Socket s = new Socket(host, port); if (s.isConnected() &amp;&amp; !s.isClosed()) { msgHandler.connectionInit(s); } BufferedInputStream input = new BufferedInputStream(s.getInputStream()); } } </code></pre> <p>The consumer which is the msgHandler, frequently polls the socket if a connection ever goes down as below.</p> <pre><code>@Override public void connectionInit(Socket s) throws IOException { logger.info("Connected to AWW Service on " + configuration.getAwwHost() + ":" + configuration.getAwwPort()); output = new BufferedOutputStream(s.getOutputStream()); connector.componentReady(); Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { try { pollServer(); } catch (IOException e) { // SOCKET GETS BROKEN HERE } } }, 0, 25000); } </code></pre> <p>Question is, how can i communicate from the exception i get when the socket connection gets broken back to the run() thread, so it can try to reinitialize the socket and the input stream?</p> <p>I dont think a notify() or wait() mechanism is appropriate here as wait() will just put the run() thread to sleep. I was thinking whats the equivalent of setting a flag when the connection gets broken, and the run() thread constantly checks the flag, and when it is set to true, it reinitialize the socket. But i am sure there would be a more efficient multi threading approach native to java for achieving this.</p>
2
error = ViewRootImpl: sendUserActionEvent() mView == null
<p>I have this error with a spinner inside a fragment = ViewRootImpl: sendUserActionEvent() mView == null , Does anyone know how to fix it ? , thanks in advance!</p>
2
Aurelia router not working when resetting root
<p>I want to use aurelia-auth in my app and also have a login page that is completely separate from the rest of the app. I have been following the tutorial at this link: <a href="https://auth0.com/blog/2015/08/05/creating-your-first-aurelia-app-from-authentication-to-calling-an-api/" rel="nofollow">https://auth0.com/blog/2015/08/05/creating-your-first-aurelia-app-from-authentication-to-calling-an-api/</a></p> <p>The problem I am having is after I successfully login and attempt to route to the app, none of the routes are found. I get route not found regardless of what I put in for the login redirect url.</p> <p>Here is my code:</p> <p>app.js:</p> <pre><code>... import { Router } from 'aurelia-router'; import { AppRouterConfig } from './router-config'; import { FetchConfig } from 'aurelia-auth'; ... @inject(..., Router, AppRouterConfig, FetchConfig) export class App { constructor(router, appRouterConfig, FetchConfig) { this.router = router; this.appRouterConfig = appRouterConfig; this.fetchConfig = fetchConfig; ... } activate() { this.fetchConfig.configure(); this.appRouterConfig.configure(); } ... } </code></pre> <p>login.js:</p> <pre><code>import { AuthService } from 'aurelia-auth'; import { Aurelia } from 'aurelia-framework'; ... @inject(..., Aurelia, AuthService) export class LoginScreen { constructor(..., aurelia, authService) { this.aurelia = aurelia; this.authService = authService; ... } login() { return this.authService.login(this.username, this.password) .then(response =&gt; { console.log("Login response: " + response); this.aurelia.setRoot('app'); }) .catch(error =&gt; { this.loginError = error.response; alert('login error = ' + error.response); }); } ... } </code></pre> <p>main.js: </p> <pre><code>import config from './auth-config'; import { AuthService } from 'aurelia-auth'; import { Aurelia } from 'aurelia-framework'; ... export function configure(aurelia) { aurelia.use .defaultBindingLanguage() .defaultResources() .developmentLogging() .router() .history() .eventAggregator() ... .plugin('aurelia-auth', (baseConfig) =&gt; { baseConfig.configure(config); }); let authService = aurelia.container.get(AuthService); aurelia.start() .then(a =&gt; { if (authService.isAuthenticated()) { a.setRoot('app'); } else { a.setRoot('login'); } }); } </code></pre> <p>auth-config.js:</p> <pre><code>var config = { baseUrl: 'http://localhost:3001', loginUrl: 'sessions/create', tokenName: 'id_token', //loginRedirect: '#/home' //looks like aurelia-auth defaults to #/ which is fine for me } export default config; </code></pre> <p>router-config.js:</p> <pre><code>import { AuthorizeStep } from 'aurelia-auth'; import { inject } from 'aurelia-framework'; import { Router } from 'aurelia-router'; @inject(Router) export class AppRouterConfig { constructor(router) { this.router = router; } configure() { console.log('about to configure router'); var appRouterConfig = function (config) { config.title = 'My App'; config.addPipelineStep('authorize', AuthorizeStep); config.map([ { route: ['', 'home'], name: 'home', moduleId: '.components/home/home', nav: true, title: 'Home', auth: true }, { route: ['employees'], name: 'employees', moduleId: './components/employees/employees', nav: true, title: 'Employees', auth: true } ]); this.router.configure(appRouterConfig); } }; } </code></pre> <p>When loading the app, it successfully goes to login page and I'm able to successfully login and it tries to redirect, but I get this error in the console:</p> <pre><code>ERROR [app-router] Error: Route not found: / at AppRouter._createNavigationInstruction (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-router.js:1039:29) at AppRouter.loadUrl (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-router.js:1634:19) at BrowserHistory._loadUrl (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-history-browser.js:301:55) at BrowserHistory.activate (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-history-browser.js:200:21) at AppRouter.activate (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-router.js:1689:20) at eval (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-router.js:1670:21) at AppRouter.registerViewPort (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-router.js:1672:10) at new RouterView (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/router-view.js:112:19) at Object.invokeWithDynamicDependencies (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-dependency-injection.js:329:20) at InvocationHandler.invoke (http://127.0.0.1:8080/jspm_packages/npm/[email protected]/aurelia-dependency-injection.js:311:168)error @ aurelia-logging-console.js:54log @ aurelia-logging.js:37error @ aurelia-logging.js:70(anonymous function) @ aurelia-router.js:1637 aurelia-logging-console.js:54 ERROR [app-router] Router navigation failed, and no previous location could be restored. </code></pre> <p>I'm googling around quite a bit for answers to this, but having difficulty finding good answers. Anybody have any ideas? Any help is appreciated! </p>
2
pass a method into another method as a parameter but with parameters
<p>I've posted a similar question (and answered) previously but I've realised I still have a missing piece of the puzzle when passing a method into another method. My question is when passing a method as a parameter how can you include parameters? I've included an example below.</p> <p>Any help much appreciated.</p> <p>Many thanks,</p> <p><strong>Service call</strong></p> <pre><code>private readonly MemberRepo _memberRepo; public SomeService() { _memberRepo = new MemberRepo(); } public string GetMembers(int id) { // This works, i.e. the RunMethod internally calls the Get method on the repo class - problem: how can I pass the id into the repo Get method? var result = RunMethod(_memberRepo.Get); ... return stuff; } private string RunMethod(Func&lt;int, string&gt; methodToRun) { var id = 10; // this is a hack - how can I pass this in? var result = methodToRun(id); .. } </code></pre> <p><strong>Repository</strong></p> <pre><code>public class MemberRepo { public string Get(int id) { return "Member from repository"; } } </code></pre> <p><strong>Update</strong></p> <pre><code>private string RunMethod(Func&lt;int, string&gt; methodToRun) { if(id.Equals(1)) { // Do something // var result = methodToRun(id); .. } </code></pre>
2
How to use locks without causing deadlock in concurrent.futures.ThreadPoolExecutor?
<p>I'm processing Jira changelog history data, and due to the large amount of data, and the fact that most of the processing time is I/O based, I figured that an asynchronous approach might work well. </p> <p>I have a list of all <code>issue_id</code>'s, which I'm feeding into a function that makes a request through the <code>jira-python</code> api, extracts the information into a <code>dict</code>, and then writes it out through a passed in <code>DictWriter</code>. To make it threadsafe I imported a <code>Lock()</code> from the <code>threading</code> module, which I am also passing in. On testing, it seems to get deadlocked at a certain point and just hangs. I noticed in the documentation where it said that if tasks are reliant on one another then they can hang, and I suppose they are due to the lock I'm implementing. How can I prevent this from happening? </p> <p>Here is my code for reference:</p> <p>(At this point in the code there is a list called <code>keys</code> with all the issue_id's)</p> <pre><code>def write_issue_history( jira_instance: JIRA, issue_id: str, writer: DictWriter, lock: Lock): logging.debug('Now processing data for issue {}'.format(issue_id)) changelog = jira_instance.issue(issue_id, expand='changelog').changelog for history in changelog.histories: created = history.created for item in history.items: to_write = dict(issue_id=issue_id) to_write['date'] = created to_write['field'] = item.field to_write['changed_from'] = item.fromString to_write['changed_to'] = item.toString clean_data(to_write) add_etl_fields(to_write) print(to_write) with lock: print('Lock obtained') writer.writerow(to_write) if __name__ == '__main__': with open('outfile.txt', 'w') as outf: writer = DictWriter( f=outf, fieldnames=fieldnames, delimiter='|', extrasaction='ignore' ) writer_lock = Lock() with ThreadPoolExecutor(max_workers=5) as exec: for key in keys[:5]: exec.submit( write_issue_history, j, key, writer, writer_lock ) </code></pre> <p>EDIT: It's also very possible I'm being throttled by the Jira API.</p>
2
How do I close a browser window/tab and return control to another tab using Spring MVC?
<p>I am using Spring MVC to call a web service. The intent is to get back a PDF in a separate window/tab in the browser if the call is successful, else if there is an error returned to have the error returned to the original window/tab. In the jsp code for the html view, I am setting document.forms[0].target = '_blank'; in the submitAction function to create the second browser window/tab to contain the PDF returned by the web service. This works fine if the web service runs with no errors. If an error is returned with no PDF, when I return the mav in my controller it creates the action submission page in the second window/tab with the error message showing in that window. That is not what I want. If I get an error returned from the service, how can I return the error message to the original window/tab and close the second window/tab that was created by making the target equal to '_blank' in the submitAction function?</p>
2
How can I create http:inbound-gateway with JAVA DSL config?
<p>I have the following HTTP inbound gateway with XML config. How can I create the same with JAVA 8 DSL config in Spring Integration?</p> <pre><code>&lt;int-http:inbound-gateway id="testGateWay" supported-methods="GET" request-channel="testRequestChannel" reply-channel="testResponseChannel" path="/services/normalization" /&gt; </code></pre>
2
"@angular/router": "3.0.0-beta.2": What does the terminal property of the Route interface do?
<p>Within the Angular2 3.0.0-beta.2 Router there is a property called <code>terminal</code> for which I cannot find documentation. What does this property do?</p> <p>See source file: <code>@angular/router/src/config.d.ts</code></p>
2
RANK records partitioned by a column in series (Vertica SQL)
<p>I'm trying to use the Vertica rank analytic function to create a rank column partitioned by a column, but only include records that are in a series. For example the query below produces the output below the query</p> <pre><code>select when_created, status from tablea when_created Status 1/1/2015 ACTIVE 3/1/2015 ACTIVE 4/1/2015 INACTIVE 4/6/2015 INACTIVE 6/7/2015 ACTIVE 10/9/2015 INACTIVE </code></pre> <p>I could modify my query to include a rank column which would produce the following output</p> <pre><code>select when_created, status, rank() OVER (PARTITION BY status order by when_created) as rnk from tablea when_created Status rnk 1/1/2015 ACTIVE 1 3/1/2015 ACTIVE 2 4/1/2015 INACTIVE 1 4/6/2015 INACTIVE 2 6/7/2015 ACTIVE 3 10/9/2015 INACTIVE 3 </code></pre> <p>However my goal is start over the rank when a series is broken so the desired output is:</p> <pre><code>when_created Status rnk 1/1/2015 ACTIVE 1 3/1/2015 ACTIVE 2 4/1/2015 INACTIVE 1 4/6/2015 INACTIVE 2 6/7/2015 ACTIVE 1 10/9/2015 INACTIVE 1 </code></pre> <p>Is there a way to accomplish this using the RANK function or is there another way to do it in vertica sql?</p> <p>Thanks, Ben</p>
2
Transform Names Matrix into Dataframe rows
<p>Lets say I have a matrix <code>mat</code> which has both column names and row names:</p> <pre><code>mat &lt;- matrix(1:25, ncol = 5) rownames(mat) &lt;- LETTERS[1:5] colnames(mat) &lt;- LETTERS[6:10] </code></pre> <p>^^ Simple and reproducible example to make the following matrix:</p> <pre><code> F G H I J A 1 6 11 16 21 B 2 7 12 17 22 C 3 8 13 18 23 D 4 9 14 19 24 E 5 10 15 20 25 </code></pre> <p>I need to turn this matrix into a data frame that looks like the following:</p> <pre><code>ROWNAME COLNAME VALUE A F 1 B F 2 C F 3 ...... </code></pre> <p>Is there a function built in to do this? How would I tackle such a problem.</p> <p>Also, this matrix would be one of many matrices so there would need to be a <code>Matrix Name</code> column added so that it could parse over multiple matrices and create a data.frame that is actually 4 columns and as many observations as values in all of the matrices combined. If there is a shortcut for any of these steps it would be greatly appreciated.</p>
2
Exchange Web Services (EWS) or JavaMail Api to connect to Outlook Exchange Server - Java
<p>we are switching from Lotus notes to Outlook 2013 and I'm working on a POC to connect to the Microsoft Exchange. I'm confused on which API to use to connect. <em>Requirement</em>:Basically I need to write Java Application to read inbox and get attachments and move the email to a different folder and in that folder I have to delete emails that are n days old.</p> <ol> <li>Is EWS microsoft recommended? do we have support for bugs, updates etc</li> <li>Can JavaMail Api be used to connect to Microsoft Exchange server.?</li> <li>Can this(Requirement) be done thru reading the local .OST file, if yes how to read and can I move emails to different folder in .OST file.</li> </ol> <p>Any help or suggestions on which API or method will be good in long run.</p>
2
Bintray response conflict with error code 409
<p>We've an Android Studio project on which we collaborate together. A colleague has setup a bintray.com to gather there all required libraries within our android Studio project. We both have our accounts there, we've setup our bintray API key and corresponding github username in the <code>gradle.properties</code> file. For him it works fine and he gets the uploaded libraries like <code>test-1.0.0.pom</code>; but I don't.</p> <p>Instead I get </p> <blockquote> <p>Error:Could not GET '<a href="https://oss.jfrog.org/artifactory/oss-snapshot-local/xxx/yyy/zzz/1.0.0/test-1.0.0.pom" rel="nofollow">https://oss.jfrog.org/artifactory/oss-snapshot-local/xxx/yyy/zzz/1.0.0/test-1.0.0.pom</a>'. Received status code 409 from server: Conflict Enable Gradle 'offline mode' and sync project</p> <p>Gradle sync failed: Could not GET '<a href="https://oss">https://oss</a>. ... with very same error message</p> </blockquote> <p><strong>So I am conflicting with the server ? What am I doing wrong?</strong></p>
2
Unmarshalling JSON data with nested arrays and objects into Go struct
<p>I am unmarshalling Youtube json response into Go struct by using the data received from Youtube API as follows:-</p> <pre><code>{ "kind": "youtube#searchListResponse", "etag": "\"5g01s4-wS2b4VpScndqCYc5Y-8k/5xHRkUxevhiDF1huCnKw2ybduyo\"", "nextPageToken": "CBQQAA", "regionCode": "TH", "pageInfo": { "totalResults": 36, "resultsPerPage": 20 }, "items": [ { "kind": "youtube#searchResult", "etag": "\"5g01s4-wS2b4VpScndqCYc5Y-8k/aMbszoNudZchce3BIjZC_YemugE\"", "id": { "kind": "youtube#video", "videoId": "fvh6CQ7FxZE" }, "snippet": { "publishedAt": "2016-07-16T14:42:36.000Z", "channelId": "UCuX4iswo8acMxDNcbrceRYQ", "title": "Japan อร่อยสุดๆ:การประชันของ 2 สาวกับราเมงดังจากโอซาก้า#ramen", "description": "Ramen Kio ราเมนชื่อดังของโอซาก้าอัดแน่นด้วยเนื้อหมูชาชูแบบเต็มๆเส้นเหนีย...", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/hqdefault.jpg", "width": 480, "height": 360 } }, "channelTitle": "Japan aroi sudsud TV", "liveBroadcastContent": "none" } } ] } </code></pre> <p>To do so, I have created a struct for this in Go</p> <pre><code>type YoutubeData struct { Kind string `json:"kind"` Etag string `json:"etag"` NextPageToken string `json:"nextPageToken"` RegionCode string `json:"regionCode"` PageInfo struct { TotalResults string `json:"totalResults"` ResultsPerPage string `json:"resultsPerPage"` } `json:"pageInfo"` Items []struct { Kind string `json:"kind"` Etag string `json:"etag"` Id struct { Kind string `json:"kind"` VideoId string `json:"videoId"` } `json:"id"` Snippet struct { PublishedAt string `json:"publishedAt"` ChannelId string `json:"channelId"` Title string `json:"title"` Description string `json:"description"` Thumbnails struct { Default struct { Url string `json:"url"` Width string `json:"width"` Height string `json:"height"` } `json:"default"` Medium struct { Url string `json:"url"` Width string `json:"width"` Height string `json:"height"` } `json:"medium"` High struct { Url string `json:"url"` Width string `json:"width"` Height string `json:"height"` } `json:"high"` } `json:"thumbnails"` ChannelTitle string `json:"channelTitle"` LiveBroadcastContent string `json:"liveBroadcastContent"` } `json:"snippet"` } `json:"items"` } </code></pre> <p>I unmarshaled it by using this method</p> <pre><code>youtubeData := YoutubeData{} if json.Unmarshal(b, &amp;youtubeData); err != nil { } else { } </code></pre> <p>In which b is the byte data received from Youtube API. I successfully got all data in the byte object as I printed it out to my console, however, once I unmarshaled it and tried to output it on the template by using {{.}}, I received</p> <pre><code>{youtube#searchListResponse "5g01s4-wS2b4VpScndqCYc5Y-8k/JwGY0TWwWswjZ9LOvemaF5yxsMo" CBQQAA TH { } []} </code></pre> <p>All data are unmarshaled except for the data in json object and array which are <em>pageInfo</em> and <em>items</em>. There are simply blank. I believe I exported them all correctly. Are there some additional steps to get the data into slice or struct nested inside another struct in Go when it comes to json unmarshalling?</p>
2
How to insert string into input field using C# in WPF Webbrowser
<p>I have found lots of info on this issue on Stackoverflow, but looks like I'm still missing something. With the Webbrowser I would like to fill in a string into in input field of a certain webpage. By clicking on a button I wish to put some text in the input field.</p> <p>Here is my code:</p> <pre><code>using System.Windows.Forms; </code></pre> <p>and the function:</p> <pre><code> private void button2_Click(object sender, RoutedEventArgs e) { HtmlDocument doc = (HtmlDocument)webBrowser1.Document; doc.GetElementsByTagName("input")["username"].SetAttribute("Value", "someString"); } </code></pre> <p>The second button handles then the webBbrowser1.Navigate method. </p> <p>Then I get this error:</p> <p><em>{"Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to class type 'System.Windows.Forms.HtmlDocument'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."}</em></p> <p>Any ideas? Thanks.</p>
2
Was setTimer deprecated in Swift 3?
<p>I am trying to create a CocoaPod for Swift 3. Because CocoaPods uses <a href="https://github.com/Quick/Nimble" rel="noreferrer">Nimble</a> and <a href="https://github.com/Quick/Quick" rel="noreferrer">Quick</a>, and those libraries haven't been updated yet, I forked the repos and am trying to convert them.</p> <p>In the Nimble project there is a function called with the signature of:</p> <pre><code>setTimer(start: DispatchTime, interval: UInt64, leeway: UInt64) </code></pre> <p>The compiler says <code>Cannot invoke 'setTimer' with an argument list of type '(start: DispatchTime, interval: UInt64, leeway: UInt64)'</code></p> <pre><code>private let pollLeeway: UInt64 = NSEC_PER_MSEC let interval = UInt64(pollInterval * Double(NSEC_PER_SEC)) asyncSource.setTimer(start: DispatchTime.now(), interval: interval, leeway: pollLeeway) </code></pre> <p>The auto-complete shows all the setTimer methods are deprecated, but from what I <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md" rel="noreferrer">found</a> they shouldn't be.</p> <p>Is there a replacement?</p>
2
Canvas Text and image blurry
<p>I don´t know why the text in canvas is blurry and the image drawed is also blurry, this is my example how I create the canvas with the image and text.</p> <p><a href="https://jsfiddle.net/jorge182/5ju5pLqb/2/" rel="nofollow">https://jsfiddle.net/jorge182/5ju5pLqb/2/</a></p> <pre><code>var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function() { context.save(); context.beginPath(); context.arc(25, 25, 25, 0, Math.PI * 2, true); context.closePath(); context.clip(); context.drawImage(imageObj, 0, 0, 50, 50); context.beginPath(); context.arc(0, 0, 25, 0, Math.PI * 2, true); context.clip(); context.closePath(); context.restore(); context.lineWidth = 2; context.textAlign = 'left'; context.font = '8pt Signika Negative'; context.fillStyle = 'black'; context.fillText('Jorge', 60, 15); context.fillText(' have been here!', 60, 30); context.font = '6pt Signika Negative'; context.textAling = 'left'; context.fillStyle = '#555'; context.fillText('Caribe Photo Weading Photograpy', 60, 40); }; imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg' </code></pre>
2
Use parameter "params string[]" in WCF Rest endpoint
<p>I would like to define an OperationContract, which I can pass any number of string parameters. The values should be interpreted as an array of string. Is there any possibility to use this type of parameter in an OperationContract and define this in the UriTemplate?</p> <pre><code>[ServiceContract] public interface IRestService { [OperationContract] [WebGet(UriTemplate = "operations/{values}")] void Operations(params string[] values); } </code></pre>
2
Postgres: Find matching array or array that contains t
<p>I'm using postgres 9.5 and have a table that looks something like this:</p> <pre><code>+----+--------------+-------------------------------+ | id | string_field | array_field | |----+--------------+-------------------------------| | 1 | string a | [apple, orange, banana, pear] | | 2 | string b | [apple, orange, banana] | | 3 | string c | [apple, orange] | | 4 | string d | [apple, pear] | | 5 | string e | [orange, apple] | +----+--------------+-------------------------------+ </code></pre> <p>Is it possible to query the DB for rows where <code>array_field</code> <strong>is, or contains</strong> <code>[apple, orange, banana]</code>? The results should return rows with id 1 and 2.</p>
2
Populate UITableview with Array from Rest API in Swift
<p>In my mainTableView Controller, I can print the API result in the console but I have no idea how I can set these to be visible in the cells of my tableview</p> <pre><code>import UIKit //from: https://github.com/Ramotion/folding-cell class MainTableViewController: UITableViewController { let kCloseCellHeight: CGFloat = 179 let kOpenCellHeight: CGFloat = 488 let kRowsCount = 100 var cellHeights = [CGFloat]() var restApi = RestApiManager() var items: NSDictionary = [:] override func viewDidLoad() { super.viewDidLoad() restApi.makeCall() { responseObject, error in // use responseObject and error here // self.json = JSON(responseObject!) print("print the json data from api ") self.items = NSDictionary(dictionary: responseObject!) self.tableView.reloadData() print(responseObject!.count) // print(self.items) let resultList = self.items["result"] as! [[String: AnyObject]] print(resultList[5]) } createCellHeightsArray() self.tableView.backgroundColor = UIColor(patternImage: UIImage(named: "background")!) } // MARK: configure func createCellHeightsArray() { for _ in 0...kRowsCount { cellHeights.append(kCloseCellHeight) } } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 10 } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { guard case let cell as DemoCell = cell else { return } cell.backgroundColor = UIColor.clearColor() if cellHeights[indexPath.row] == kCloseCellHeight { cell.selectedAnimation(false, animated: false, completion:nil) } else { cell.selectedAnimation(true, animated: false, completion: nil) } cell.number = indexPath.row } // with as! the cell is set to the custom cell class: DemoCell // afterwards all data can be loaded in this method override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FoldingCell", forIndexPath: indexPath) as! DemoCell //TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer // let resultList = self.items["result"] as! [[String: AnyObject]] // let itemForThisRow = resultList[indexPath.row] // cell.schoolIntroText.text = itemForThisRow["name"] as! String cell.schoolIntroText.text = "We from xx University..." return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -&gt; CGFloat { return cellHeights[indexPath.row] } // MARK: Table vie delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! FoldingCell if cell.isAnimating() { return } var duration = 0.0 if cellHeights[indexPath.row] == kCloseCellHeight { // open cell cellHeights[indexPath.row] = kOpenCellHeight cell.selectedAnimation(true, animated: true, completion: nil) duration = 0.5 } else {// close cell cellHeights[indexPath.row] = kCloseCellHeight cell.selectedAnimation(false, animated: true, completion: nil) duration = 0.8 } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { () -&gt; Void in tableView.beginUpdates() tableView.endUpdates() }, completion: nil) } } </code></pre> <p>I get this result in JSON which is correct</p> <pre><code>{ result = ( { city = Perth; "cou_id" = AU; environment = R; image = "-"; name = "Phoenix English"; rating = 0; "sco_id" = 2; "sco_type" = LS; }, { city = "Perth "; "cou_id" = AU; environment = L; image = "-"; name = "Milner college"; rating = 0; "sco_id" = 3; "sco_type" = LS; }, </code></pre> <p>what do I have to do to set these values and set them here?</p> <pre><code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FoldingCell", forIndexPath: indexPath) as! DemoCell //TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer cell.schoolIntroText.text = "We from xx University..." return cell } </code></pre> <p>I somehow dont figure out how to construct an array from this JSON output and how to access these fields which seem to be nested in many dimensions, as a noob, thx for any inputs.</p> <p>Addition from class restApi:</p> <pre><code>// working method for calling api func makeCall(completionHandler: (NSDictionary?, NSError?) -&gt; ()) { Alamofire.request( .GET, baseURL+schools+nonAcademicParameter, headers: accessToken ) .responseJSON { response in switch response.result { case .Success(let value): completionHandler(value as? NSDictionary, nil) case .Failure(let error): completionHandler(nil, error) } } } </code></pre>
2
Spring Integration: the SecurityContext propagation
<p>I have some perplexity about the SecurityContext propagation in Spring Integration.</p> <p>Here is the point of the documentation:</p> <p><a href="http://docs.spring.io/spring-integration/reference/htmlsingle/#security-context-propagation" rel="nofollow">http://docs.spring.io/spring-integration/reference/htmlsingle/#security-context-propagation</a></p> <p>My perplexity are the following:</p> <blockquote> <p><strong>(1)</strong> To be sure that our interaction with the application is secure, according to its security system rules, we should supply some security context with an authentication (principal) object. The Spring Security project provides a flexible, canonical mechanism to authenticate our application clients over HTTP, WebSocket or SOAP protocols (as can be done for any other integration protocol with a simple Spring Security extension) and it provides a SecurityContext for further authorization checks on the application objects, such as message channels. By default, the SecurityContext is tied with the current Thread's execution state using the (ThreadLocalSecurityContextHolderStrategy). It is accessed by an AOP interceptor on secured methods to check if that principal of the invocation has sufficent permissions to call that method, for example. <strong>This works well with the current thread</strong>, <strong>but often</strong>, processing logic <strong>can be performed</strong> on another thread or even on several threads, or on <strong>to some external system(s)</strong>.</p> </blockquote> <p>This means that the SecurityContext (normally) is accessible only for the current Thread. Right?</p> <p>So, how to make it accessible for another thread of another application (integrated with Spring Integration) ?</p> <blockquote> <p><strong>(2)</strong> Standard thread-bound behavior is easy to configure if our application is built on the Spring Integration components and its message channels. <strong>In this case, the secured objects may be any service activator or transformer</strong>, secured with a <code>MethodSecurityInterceptor</code> in their (see Section 8.8, “Adding Behavior to Endpoints”) or even <code>MessageChannel</code> (see Section D.2, “Securing channels” above). When using DirectChannel communication, the SecurityContext is available automatically, because the downstream flow runs on the current thread. But in case of the QueueChannel, ExecutorChannel and PublishSubscribeChannel with an Executor, messages are transferred from one thread to another (or several) by the nature of those channels. In order to support such scenarios, <strong>we can either transfer an Authentication object within the message headers and extract and authenticate it on the other side before secured object access</strong>. <strong>Or, we can propagate the SecurityContext to the thread receiving the transferred message</strong>.</p> </blockquote> <p>This means that we have to extract the Principal manually? If yes, how?</p> <p>Or it's enough to use the propagation aspect, from 4.2 version?</p> <blockquote> <p><strong>(3)</strong> Starting with version 4.2 <strong>SecurityContext propagation</strong> has been introduced. It is implemented as a <code>SecurityContextPropagationChannelInterceptor</code>, <strong>which can simply be added to any <code>MessageChannel</code> or configured as a <code>@GlobalChannelInterceptor</code></strong>. The logic of this interceptor is based on the SecurityContext extraction from the current thread from the <code>preSend()</code> method, and its populating to another thread from the <code>postReceive()</code> (beforeHandle()) method. Actually, this interceptor is an extension of the more generic ThreadStatePropagationChannelInterceptor, which wraps the message-to-send together with the state-to-propagate in an internal Message extension - MessageWithThreadState, - on one side and extracts the original message back and state-to-propagate on another. The ThreadStatePropagationChannelInterceptor can be extended for any context propagation use-case and SecurityContextPropagationChannelInterceptor is a good sample on the matter.</p> </blockquote> <p><em>"Starting with version 4.2 SecurityContext propagation has been introduced."</em> => Ok, very well.</p> <p>But: <em>"It is implemented as a SecurityContextPropagationChannelInterceptor, which can simply be added to any MessageChannel or configured as a @GlobalChannelInterceptor."</em></p> <p>What does it mean? I have to implement an interceptor that extends "SecurityContextPropagationChannelInterceptor" ?</p> <p>What I have to "add" in my <code>&lt;int:channel&gt;</code> configuration?</p> <p>And if I use <code>&lt;int:channel-interceptor&gt;</code> (the same of @GlobalChannelInterceptor), it's different from using <code>&lt;int:interceptors&gt;</code> ?</p> <p>Other perplexity:</p> <p><em>"The logic of this interceptor is based on the SecurityContext extraction from the current thread from the preSend() method, and its populating to another thread from the postReceive() (beforeHandle()) method."</em></p> <p>But why there are a <em><code>"obtainPropagatingContext"</code></em> method and a <em><code>"populatePropagatedContext"</code></em> method in the <code>SecurityContextPropagationChannelInterceptor</code> class? Where is made the propagation? In the preSend() / postReceive() methods, or in those two methods?</p> <p>Furthermore, I tried to propagate the SecurityContext to an external application, without success...</p> <p>Any explanations about this argument would be appreciated.</p>
2
How to print to Jenkins' console report the messages from failed asserts?
<p>My FullStack tests run on Jenkins and output nothing on success, otherwise the test name and the failed line. This tells nothing about what went wrong.</p> <p>Is there a way to print the assertion error message on the Jenkins console?</p> <p>I have a <code>TestWatcher</code> that already takes a screenshot. Should it also do a <code>System.out.println(e.getMessage())</code>?</p> <p>I want it to print something like this:</p> <pre><code>java.lang.AssertionError: Page is listing a different job Expected: &lt;true&gt; but: was &lt;false&gt; </code></pre>
2
links to other AMP pages in an AMP article
<p>I have several non-AMP pages within a topic. My non-AMP pages will have links within the body of the article to other non-AMP pages in the same topic. Should the AMP versions of the pages link to the other AMP pages in the same topic or should all links in the articles point to the non-AMP (canonical) versions of the pages? </p> <pre><code>Using the following link formats for the example: Non-AMP version: /muffins/blueberry/ AMP version: /muffins/blueberry/amp/ </code></pre> <p><strong>/muffins/blueberry/</strong> has a link to <strong>/muffins/strawberry/</strong><br> Should <strong>/muffins/blueberry/amp/</strong> link to <strong>/muffins/strawberry/amp/</strong> or to <strong>/muffins/strawberry/</strong>?</p> <p>Or said another way, if a visitor comes to your site on an AMP page, do you continue to offer them links to other AMP versions of your pages or should you switch them over to the full pages as soon as possible?</p>
2
Creating a template in Tableau to make moving between similar excel files smooth
<p>I am very new to Tableau and just finished my first sheet/dashboard combination for a set of data.</p> <p>I now want to be able to open up various other excel workbooks (similarly named headers/sheets etc) and get the same Tableau dashboard (with calculated fields etc) just with the new data.</p> <p>I can open each workbook one by one and switch data sources between each, but is there a simpler way? Also this doesnt maintain calculated fields which is a necessity!</p> <p>Thanks</p>
2
Spring MVC, HashMap as model - how to get value using javascript variable as key in jsp
<p>I have a model like this:</p> <pre><code> @ModelAttribute("availableFonts") public Map&lt;String, String&gt; getAllAvaliableFonts() { ... } </code></pre> <p>Model is containing font name as a key and css code as a value. Now in jsp I have a javaScript code which should apply css dynamicly to preview font, which looks more/less like this:</p> <pre><code>var css = '${availableFonts.get("Arial Black")}'; jQuery('#preview').removeClass().addClass(css); </code></pre> <p>And it's working good with hardcoded map.get(). Css value is taken from HashMap which is model in my jsp.</p> <p>But I need this map key as a javaScript variable like:</p> <pre><code> var key = 'Arial Black'; var css = '${availableFonts.get("' + key + '")}'; jQuery('#preview' + i).removeClass().addClass(css); </code></pre> <p>And it's not working. Is it possible to do it in javaScript ?</p>
2
are `Matchers.hasItem` and `Matchers.contains` the same?
<p>I saw this <a href="https://stackoverflow.com/a/22720548/1065869">post</a></p> <p>about the difference between:</p> <pre><code>Matchers.hasItem(..) Assert.assertThat(items, Matchers.hasItem(Matchers.hasToString("c"))); which states </code></pre> <p>and </p> <pre><code>Matchers.contains </code></pre> <p>But I still don't get the difference. They both look for one predicate satisfaction. No?</p>
2
Should I always nest selectors in other selectors when using sass?
<p>My question is about nesting in sass or scss. It is a good thing from the readability perspective that we can nest selectors inside another selectors in sass but is it something that we must do? I am a little bit confused because when I run scss-lint, then I'm getting some errors nesting depth. I red a few articles and now I know that we should go deeper than nesting more than 3 rules one inside another. </p> <p>So I have two questions:</p> <ol> <li><p>Is there anything wrong if I will write my rules in sass just like this (without nesting):</p> <p>.my-class ...</p></li> </ol> <p>Instead of writing like that: </p> <pre><code>header nav .myclass </code></pre> <ol start="2"> <li>Can you explain why is it necessary to nest in sass and what are the advantages of nesting? I know that it is good for overriding rules, but if I don't need to nest that deep? I will appreciate any answers or even links to some articles explaining my questions in more detail. </li> </ol>
2
C# enable/disable network tracing at runtime?
<p>In the examples I can find the tracing is enabled via config file, for example </p> <pre><code> &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;startup&gt; &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /&gt; &lt;/startup&gt; &lt;system.diagnostics&gt; &lt;sources&gt; &lt;source name="System.Net" tracemode="includehex" maxdatasize="1024"&gt; &lt;listeners&gt; &lt;add name="System.Net"/&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;/sources&gt; &lt;switches&gt; &lt;add name="System.Net" value="Verbose"/&gt; &lt;/switches&gt; &lt;sharedListeners&gt; &lt;add name="System.Net" type="System.Diagnostics.TextWriterTraceListener" initializeData="network.log" /&gt; &lt;/sharedListeners&gt; &lt;trace autoflush="true" indentsize="4" /&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>But I don't want config file to be shipped with my dll. Moreover I need to be able to enable/disable tracing and change log name "on the fly" in my code. What I came up with:</p> <pre><code>FileStream stream = new FileStream("D:\\network1.log", FileMode.OpenOrCreate); TextWriterTraceListener listener = new TextWriterTraceListener(stream); Trace.Listeners.Add(listener); Trace.AutoFlush = true; TraceSwitch ts = new TraceSwitch("System.Net", ".Net"); ts.Level = TraceLevel.Verbose; </code></pre> <p>and it is not logging anything, and I don't know where to add the switch, and if that is correct at all. The listener works but it don't fetch any data.</p> <p>I've been reading msdn and this blog post <a href="http://www.codeguru.com/csharp/.net/article.php/c19405/Tracing-in-NET-and-Implementing-Your-Own-Trace-Listeners.htm" rel="nofollow">http://www.codeguru.com/csharp/.net/article.php/c19405/Tracing-in-NET-and-Implementing-Your-Own-Trace-Listeners.htm</a> and from the way I understand it, once added to the <code>Trace.Listeners</code> a listener should log all thace info in the current exe, but that's obvioustly not the case.</p> <p>So how to achieve that?</p> <p>Edit: I've managed to hack around this limitation by dissasembling the TextWriterTraceListener and implementing my own TraceListener with the dissasembled code, adding if staatements in Write and WriteLine methods that check some static fields of another class, and adding my type in the config.</p>
2
Getting Azure SQL Server data into BigQuery
<p>Thank you in advance for your patience. I am writing a lengthy question to attempt to provide as much relevant info as possible.</p> <p>My data is stored in Azure SQL Server (not by my choice) and I want to work with the data in Google BigQuery. I would like to update the data in BigQuery from SQL Server periodically (say once an hour or once every few hours for example). </p> <p>I have found many ways to pull data from SQL Server and many ways to load data into BigQuery. What I've landed on as the easiest solution for now is creating a load job in BigQuery that uses the SQL Server URI. The data in SQL Server has auto modified/created tags that will indicate data that has been updated or added since the last load job. </p> <p>But, I needed an IP address for BigQuery that I could add to my SQL Server whitelist to allow access to the SQL Server data. In Google documentation, the only way I could find to get an IP address was to set up a ComputeEngine VM (which I have done - and I obtained an IP address for the VM). </p> <p>My question now is: how do I set up (or is it even possible to set up) the ComputeEngine VM to run the BigQuery load job so that the ComputeEngine IP will be used to request SQL Server? Or, in the alternative, how do I find the IP that will be used by BigQuery to make the request to SQL Server?</p> <p>If you have any ideas - or another setup that I have not considered, please spell it out for me step-by-step. I am rather new to the industry.</p> <p>Thank you again for your time and consideration.</p>
2
Can I cancel the loading of a URL in the InAppBrowser Cordova plugin from my Ionic 2 app?
<p>In my Ionic app, I need to open the login page of a third-party service in a new browser window. When the login succeeds, the third-party login page will fire a redirect request with a parameter I need to capture. Once I have the parameter, I need to effectively cancel the URL load request.</p> <p>I have a native iOS implementation of this that opens the third-party login page in a web view and then uses the web view's shouldStartLoadWithRequest:requestNaviationType: method to capture the request and parse the parameters. Based on the parsed result, it either loads the URL or cancels the request.</p> <p>The Cordova InAppBrowser function will allow me to open a URL in a new window, and it allows me to listen to the loadstart event. But how can I prevent the redirect URL from loading?</p>
2
Mkv, flv and others video files playing without audio
<p>I am new in this word, I am trying to make my own video playing website for my students, some where I found this HTML5 codes,</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;My Video Site&lt;/title&gt; &lt;!-- Styles --&gt; &lt;link rel="stylesheet" href="../dist/plyr.css"&gt; &lt;!-- Docs styles --&gt; &lt;link rel="stylesheet" href="dist/demo.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;/header&gt; &lt;main role="main" id="main"&gt; &lt;section&gt; &lt;video poster="https://cdn.selz.com/plyr/1.5/View_From_A_Blue_Moon_Trailer-HD.jpg" controls crossorigin&gt; &lt;!-- Video files --&gt; &lt;source src="http://localhost/video_project/The%20Angry%20Birds%20Movie%202016.mkv" type="video/mp4"&gt; &lt;!-- Text track file --&gt; &lt;track kind="captions" label="English" srclang="en" src="https://cdn.selz.com/plyr/1.5/View_From_A_Blue_Moon_Trailer-HD.en.vtt" default&gt; &lt;!-- Fallback for browsers that don't support the &lt;video&gt; element --&gt; &lt;a href="http://localhost/video_project/The%20Angry%20Birds%20Movie%202016.mkv" download&gt;Download&lt;/a&gt; &lt;/video&gt; &lt;/section&gt; &lt;/main&gt; &lt;!-- Plyr core script --&gt; &lt;script src="../dist/plyr.js"&gt;&lt;/script&gt; &lt;!-- Docs script --&gt; &lt;script src="dist/demo.js"&gt;&lt;/script&gt; &lt;!-- Rangetouch to fix &lt;input type="range"&gt; on touch devices (see https://rangetouch.com) --&gt; &lt;script src="https://cdn.rangetouch.com/0.0.9/rangetouch.js" async&gt;&lt;/script&gt; &lt;!-- Sharing libary (https://shr.one) --&gt; &lt;script src="https://cdn.shr.one/0.1.9/shr.js"&gt;&lt;/script&gt; &lt;script&gt;if(window.shr) { window.shr.setup({ count: { classname: 'btn__count' } }); }&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>this codes are works very well, It also can run my MKV, Webm and MP4 videos files, MP4 files are working very well, But when I am trying to play MKV, video is play but without audio and also found another problem, FVL video not playing. Please help with solutions, Codes found source: <a href="https://github.com/selz/plyr" rel="nofollow">https://github.com/selz/plyr</a> Please help help as soon as possible. Thank you.</p>
2
JLine 3 - Keep the prompt always at the bottom
<p>I want the prompt to display at the bottom of the page every time.</p> <p>I have a GIF of that: <a href="http://i.stack.imgur.com/ekbAj.gif" rel="nofollow">The prompt not displaying properly</a></p> <p>The code is that for read line:</p> <pre><code>@Override public void run() { while (((ElytraServer) ElytraAPI.getServer()).isRunning()) { String cmd; ((ElytraServer) ElytraAPI.getServer()).getReader().getTerminal().writer().flush(); cmd = ((ElytraServer) ElytraAPI.getServer()).getReader().readLine("&gt; "); if (!cmd.isEmpty()) { String[] aCMD = cmd.split(" "); String[] arguments = Arrays.copyOfRange(aCMD, 1, aCMD.length); ElytraAPI.getCommandRegistry().dispatch(ElytraAPI.getConsole(), aCMD[0], arguments); } } } </code></pre> <p>It's in a Thread.</p> <p>And there is the another Thread: With JLine 2, the code keep the prompt at the bottom (But it was buggued !)</p> <pre><code>public void run() { while (((ElytraServer) ElytraAPI.getServer()).isRunning()) { try { if (useJline) { /* JLine 2 / Old: reader.print(Ansi.ansi().eraseLine(Erase.ALL).toString() + '\n'); reader.flush(); */ reader.getBuffer().down(); reader.getTerminal().flush(); output.write("".getBytes()); output.flush(); /* // For JLine2 try { reader.drawLine(); } catch (Throwable throwable) { reader.getCursorBuffer().clear(); }*/ reader.getTerminal().flush(); } else { output.write("".getBytes()); output.flush(); } } catch (IOException ioexception) { Logger.getLogger(TerminalConsoleWriterThread.class.getName()).log(Level.SEVERE, null, ioexception); } } } </code></pre> <p>For the full source: <a href="https://github.com/w67clement/Elytra/tree/master/server/src/main/java/com/elytra/server" rel="nofollow">Full source of the program</a></p>
2
Is it possible to keep my Nix packages in sync across machines not running NixOS?
<p>I know with NixOS, you can simply copy over the <code>configuration.nix</code> file to sync your OS state including installed packages between machines.</p> <p>Is it possible then, to do the same using Nix the package manager on a non-NixOS OS to sync only the installed packages?</p>
2
Error setting up EGit in Eclipse Juno
<p>I'm trying to install EGit into Eclipse Juno. But, I get the following error:</p> <pre><code>Cannot complete the install because one or more required items could not be found. Software being installed: Command Line Interface for Java implementation of Git 4.4.0.201606070830-r (org.eclipse.jgit.pgm.feature.group 4.4.0.201606070830-r) Missing requirement: JGit Large File Storage Server 4.4.0.201606070830-r (org.eclipse.jgit.lfs.server 4.4.0.201606070830-r) requires 'package javax.servlet [3.1.0,4.0.0)' but it could not be found Cannot satisfy dependency: From: Java implementation of Git - optional LFS support 4.4.0.201606070830-r (org.eclipse.jgit.lfs.feature.group 4.4.0.201606070830-r) To: org.eclipse.jgit.lfs.server [4.4.0.201606070830-r] Cannot satisfy dependency: From: Command Line Interface for Java implementation of Git 4.4.0.201606070830-r (org.eclipse.jgit.pgm.feature.group 4.4.0.201606070830-r) To: org.eclipse.jgit.lfs.feature.group [4.4.0.201606070830-r] </code></pre> <p>I've tried removing a few components after I add the repository but don't seem to find a way around it. Can anyone suggest what I can do? I tried googling for the missing dependency <code>package javax.servlet [3.1.0,4.0.0)</code></p>
2
How to use getDirection() properly with PointerLockControls in Three.js
<p>I'm using <code>PointerLockControls</code> in <code>Three.js</code>.</p> <p>On mouse click, I want to update a sphere position to the position the camera is facing, at the same <code>z-position</code> of a certain object. I've read about <code>getDirection()</code>, but can't seem to implement it the right way. Here's what I tried:</p> <pre><code>var mouse3D = new THREE.Vector3(); mouse3D.normalize(); controls.getDirection( mouse3D ); sphere.position.x = mouse3D.x; sphere.position.y = mouse3D.y; sphere.position.z = object.position.z; </code></pre> <p>The <code>z-position</code> is fine, but x and y are so close to 0 that the sphere stays "on the ground" and doesn't go "left or right".</p> <p>Any help is much appreciated!</p>
2
JavaScript: format and Unformat Number: Library numbro.js
<p>I'm trying to find a way to format and unformat numbers according to the user local using the library <code>numbro.js</code>.</p> <p>Using this library the format of the number should be like that:</p> <pre><code>var number = 1234; numbro(number).format() // =&gt; 1,234 using the defaultLocal which is 'en-US' </code></pre> <p>But when i want to change the local using: <code>numbro.language('fr-FR')</code> or <code>culture()</code> function it doesn't work for me.</p>
2
Portable Eclipse C\C++ Configuration for C++ compiler (without computer installtion (c drive, PATH etc)) on USB
<p>I am trying to program in C++ using Eclipse. However, this requires Eclipse to work on different computers with a MinGW compiler installation everytime. I know that it will work if I install it on a computer and add the location to the PATH variable, but I want to know how to put the compiler onto my USB as well as the Eclipse program and make it work the same way. </p> <p>It should be installed in such a way that Eclipse can find the compiler on my USB (without the PATH stuff and C drive installation) and compile my program successfully without giving a "Binary not found" error because it could not build my source code. </p> <p>I've solved this problem with Eclipse Java and am completely able to write and compile Java code. However, I don't know how to do it for a C\C++ Eclipse. Can someone help me with this problem?</p> <p>Thanks in advance!</p>
2
Running a shell command in a specific directory in java
<p>I'm currently developing a little software in Java and I'm facing a problem I'm not able to solve. In a few words, I am on ArchLinux and I need to run "makepkg" in a specific directory. Of course I tried with </p> <pre><code>Runtime.getRuntime().exec("cd foo &amp;&amp; makepkg"); </code></pre> <p>But I discovered that I cannot cd in directories. Someone has an idea on how to do this? Thanks anyway</p>
2
php dll module not found
<p>My <code>php_stats.dll</code> always gives a </p> <pre><code>"The specified module could not be found.\r\n in Unknown on line 0" </code></pre> <p>in Apache error log.</p> <p>My set up <strong>XAMPP 32 bit</strong> in a Windows 10 64 bit machine. PHP with XAMPP (so 32 bit too, downloaded last week so up to date).</p> <p>Had to install into D drive due to windows security <strong>PHP_stats.dll</strong> - all versions from 1.0.5 to 2.0.3, all 32 bit, non thread safe and thread safe tried again dowloaded last week (yes I've tried the 64 bit version too)</p> <p><strong>php_stats.dll</strong> is in <em>D:/xampp/php/ext/</em> and <em>D:/xampp/apache/bin/</em> (and c:\windows and c:\windows\system32 too out of despiration)</p> <p><strong>php.ini</strong> extensions folder is set to <em>extension_dir="D:/xampp/php/ext/"</em>, and <strong>http.confg</strong> uses </p> <pre><code>D:/xampp/apache/bin extension=php_stats.dll in php.ini </code></pre> <p>Windows path set to include php directory (even the ext folder explicitly) and apache directories</p> <p>I have run <code>regsvr32 php_stats.dll</code> (from system32 and the 64 bit version tried too) to register the dll</p> <p>All with no change to the error message.</p>
2
Dropdownlist selected value is reset to first item
<p>I have tried to look through many questions about the dropdownlist and still yet to resolve my issue. </p> <p>I have a Dropdownlist and a Submit button. When Submit button is clicked after value selected, it should update the Label text with the selected value of the Dropdownlist. However, what happened was each time value is selected from dropdown, it refreshes the page and the value captured was the first item in dropdownlist. How do I capture the selected value correctly before it refreshes? </p> <p>Am at wits end, not sure where went wrong. </p> <p>*All items in dropdownlist are unique. No duplication. </p> <p>My codes:</p> <p>ASP.NET</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;asp:DropDownList ID="ddlCode" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCode_SelectedIndexChanged"/&gt; &lt;br /&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/&gt; &lt;asp:UpdateProgress ID="updProgress" AssociatedUpdatePanelID="UpdatePanel1" runat="server"&gt; &lt;ProgressTemplate&gt; &lt;img alt="progress" src="img/loading.gif"/&gt;&lt;br /&gt;&lt;h2&gt;Loading...&lt;/h2&gt; &lt;/ProgressTemplate&gt; &lt;/asp:UpdateProgress&gt; &lt;br /&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" &gt; &lt;ContentTemplate&gt; &lt;asp:Button ID="submitBtn" runat="server" cssclass="btn btn-success" OnClick="submitBtn_Click" Text="Submit"/&gt; &lt;asp:Label ID="lblCode" runat="server"/&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="ddlCode" EventName="SelectedIndexChanged"/&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/form&gt; </code></pre> <p>Code behind</p> <pre><code>string ddlSelectedIndex = ""; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //This is to load code into dropdownlist which works fine. LoadCode(); } } protected void ddlCode_SelectedIndexChanged(object sender, EventArgs e) { ddlSelectedIndex =(ddlCode.Items[ddlCode.SelectedIndex].Text).Substring(0, 4); } protected void submitBtn_Click(object sender, EventArgs e) { lblCode.Text = ddlSelectedIndex; } </code></pre>
2
Unimplemented SQL generation for predicate
<p>I have a DB with the following one-to-many relation: Device -properties-> Property</p> <p>I want to get a device that has atleast one property with a certain displaytype.</p> <pre><code> NSArray *energyDisplayTypes = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:18],[NSNumber numberWithInt:39],[NSNumber numberWithInt:50],[NSNumber numberWithInt:62],[NSNumber numberWithInt:63], nil]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:context]; NSError *error; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"properties.displayType IN %@", energyDisplayTypes]; [fetchRequest setPredicate:predicate]; [fetchRequest setEntity:entity]; NSArray *products= [context executeFetchRequest:fetchRequest error:&amp;error]; </code></pre> <p>I keep getting this exception:</p> <pre><code>'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : properties.displayType IN {18, 39, 50, 62, 63}' </code></pre> <p>I don't have that much experience with databases so it's propably something simple. If anyone could help me it would be greatly appreciated</p>
2
Sbt native packager not finding SystemdPlugin
<p>I'm trying to get an rpm built that uses the Systemd archetype. However, I'm getting errors on my import in build.sbt. I am using sbt version 0.13.11 Specifically, I am seeing:</p> <pre><code>build.sbt:3: error: object systemloader is not a member of package com.typesafe.sbt.packager.archetypes </code></pre> <p>I'm trying to use version 1.1.4 of sbt-native-packager. Here is my plugins.sbt:</p> <pre><code>// The Typesafe repository resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/" // The Sonatype snapshots repository resolvers += "Sonatype snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/" addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") </code></pre> <p>My build.sbt:</p> <pre><code>import com.typesafe.sbt.packager.linux.LinuxSymlink import com.typesafe.sbt.packager.rpm.RpmPlugin.autoImport._ import com.typesafe.sbt.packager.archetypes.systemloader._ scalaVersion := "2.11.7" name := "systemdtest" organization := "myTestOrg" enablePlugins(JavaServerAppPackaging, RpmPlugin, SystemdPlugin) version := "1.0" // RPM SETTINGS rpmVendor := "me" packageSummary in Linux := "A summary" packageDescription := "Do some stuff" rpmRelease := "1" rpmBrpJavaRepackJars := false rpmLicense := Some("Copyright this project") rpmGroup := Some("mygroup") rpmPrefix := Some("/opt/mypath") </code></pre> <p>I am getting the error when I try to run</p> <pre><code>sbt stage </code></pre> <p>or</p> <pre><code>sbt rpm:packageBin </code></pre>
2
Attaching spring api doc to eclipse
<p>I am working on spring framework.I want to attach spring api doc in eclipse.I have tried many things like going to Properties->Java Build Path->Libraries and putting the location of documentation in each jar file.But nothing works I get the following message whenever I hover cursor over any method/class. "This element neither has attached source nor attached Javadoc and hence no Javadoc could be found". Please suggest a solution.</p>
2
Change file (editor) encoding in jgrasp to UTF-8
<p>So... I was testing jGrasp and when i openned my testing file I saw something like this:</p> <p><a href="http://i.imgur.com/QpdEHJb.png?1" rel="nofollow">¿Khà?</a></p> <p>instead of this:</p> <p><a href="http://i.stack.imgur.com/zzrbZ.png" rel="nofollow">¿Khà?</a></p> <p>but when i compile it, first i got the weird characters (the encoding was wrong). So i changed the encoding on the WorkSpace>Charset (the default, I/O and cygwin) to UTF-8 and got the correct output (like in the second image)... but it still looks the same on jGrasp.</p> <p>If I change it on jGrasp so it looks "good", on other text editors will look diferent (and also in the compiler).</p> <h3>EDIT</h3> <p>I have found a few other encodings that work, but they aren't UTF-8, and also i don 't want to be changing every moment the encoding.</p>
2
PHP FPM Docker ZF1: The session has already been started. The session id must be set first
<p>In my dev environment, I'm trying to replace the old heavy Vagrant VM with Docker, using <code>docker-compose</code>:</p> <pre><code>version: '2' services: nginx: build: ./containers/nginx networks: mm: ipv4_address: 172.25.0.101 environment: APPLICATION_ENV: development extra_hosts: - "mysite.dev:127.0.0.1" ports: - 80:80 links: - php volumes: - ../:/srv php: build: ./containers/php-fpm networks: mm: ipv4_address: 172.25.0.102 volumes: - ../:/srv links: - memcached ports: - 9000:9000 memcached: image: memcached:latest ports: - 1234:11211 networks: mm: ipv4_address: 172.25.0.103 networks: mm: driver: bridge ipam: driver: default config: - subnet: 172.25.0.0/24 </code></pre> <p>But the application is written with ZF1, and whenever I instantiate an <code>Zend_Session_Namespace</code> object just after <code>Zend_Session::start()</code> the following error appears:</p> <pre><code>Zend_Session_Exception: The session has already been started. The session id must be set first. in /srv/mm/vendor/zendframework/zendframework1/library/Zend/Session.php on line 667 </code></pre> <p>I've tried it all, mouting a session path with <code>VOLUME</code>, changing the <code>session.save_path</code>, installing it all again and again, and nothing happens.</p>
2
PHPMailer being rejected with "Host impersonating" when script run from CLI (cron)
<p>I host a site through bluehost.com, which has an email function that I've built around PHPMailer. It has been running fine, but it looks like bluehost have changed some security settings in the last 24 hours. Having debugged through it, I'm at a loss how to resolve this.</p> <p>It looks like bluehost have configured their end to now validate the host that is connecting to the SMTP server. If I trigger an email while browsing the site, the email still sends fine:</p> <pre><code>SERVER -&gt; CLIENT: 220-box304.bluehost.com ESMTP Exim 4.86_2 #1 Wed, 20 Jul 2016 10:16:19 -0600 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail. CLIENT -&gt; SERVER: EHLO www.fydentry.com SERVER -&gt; CLIENT: 250-box304.bluehost.com Hello www.fydentry.com [69.89.31.104]250-SIZE 52428800250-8BITMIME250-AUTH PLAIN LOGIN250 HELP CLIENT -&gt; SERVER: AUTH LOGIN ... SERVER -&gt; CLIENT: 235 Authentication succeeded </code></pre> <p>Some (most) emails aren't sent interactively though, and are queued in a database, which a php script periodically executes in the background via a cron job, to send those emails out. This used to work fine, but as of yesterday, the script now throws errors:</p> <pre><code>SERVER -&gt; CLIENT: 220-box304.bluehost.com ESMTP Exim 4.86_2 #1 Wed, 20 Jul 2016 10:30:08 -0600 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail. CLIENT -&gt; SERVER: EHLO box304.bluehost.com SERVER -&gt; CLIENT: 550 "REJECTED - Bad HELO - Host impersonating [box304.bluehost.com]" SMTP ERROR: EHLO command failed: 550 "REJECTED - Bad HELO - Host impersonating [box304.bluehost.com]" CLIENT -&gt; SERVER: HELO box304.bluehost.com SERVER -&gt; CLIENT: 550 "REJECTED - Bad HELO - Host impersonating [box304.bluehost.com]" SMTP ERROR: HELO command failed: 550 "REJECTED - Bad HELO - Host impersonating [box304.bluehost.com]" CLIENT -&gt; SERVER: QUIT SERVER -&gt; CLIENT: 221 box304.bluehost.com closing connection SMTP connect() failed. </code></pre> <p>I can see that the interactive log identifies the source site www.fydentry.com, but the php script executed via the cli (cron), just sees the box name, and decides that isn't a valid source.</p> <p>Is there a parameter I can add to the command line, so that the script appears to be running from the site address? Or something I can do within the PHP script to emulate this? Or is this a config issue on the bluehost side, that I should be asking them to rectify? Or have I totally missed something here, and there's something else I should have done?</p> <p>At the moment I've hacked around the issue by calling a basic wrapper script in the cron job, which in turn executes this:</p> <pre><code>file_get_contents("http://www.fydentry.com/my-mailer-script.php"); </code></pre> <p>Which seems to sufficiently fool everything that the script is running from the site. But that doesn't seem like a good long term solution.</p>
2
Push paragraphs down to not overlap with page header in MigraDoc 1.5b3
<p>The code below aims to add an image and date stamp to the page header and then populate the page with some text (for example one header and a couple of paragraphs).</p> <p>The problem is that the text overlaps the page header, it starts at the same height as the date stamp paragraph in the page header. What am I doing wrong?</p> <pre><code>Section section = document.AddSection(); section.PageSetup.StartingNumber = 1; Image image = section.Headers.Primary.AddImage(GetImageFromDB("LogoPageHeader")); // creates base64 encoded image string image.LockAspectRatio = true; image.RelativeVertical = RelativeVertical.Line; image.RelativeHorizontal = RelativeHorizontal.Margin; image.Top = ShapePosition.Top; image.Left = ShapePosition.Left; image.WrapFormat.Style = WrapStyle.TopBottom; // to push date stamp to below the bottom of the image HeaderFooter header = section.Headers.Primary; Paragraph paragraph = header.AddParagraph(DateTime.Now.ToString("MM/dd/yyyy")); paragraph.Format.Alignment = ParagraphAlignment.Right; Paragraph paragraph = document.LastSection.AddParagraph("Question Summary:", "Heading3"); paragraph = document.LastSection.AddParagraph(); paragraph.Format.Alignment = ParagraphAlignment.Left; paragraph.AddText("Question: " + q.Text.Trim()); paragraph = document.LastSection.AddParagraph(); paragraph.Format.Alignment = ParagraphAlignment.Left; paragraph.AddText("Answer: " + (String.IsNullOrEmpty(q.ReplyText.Trim()) ? q.ReplyCode.ToString() : q.ReplyText.Trim())); paragraph.Format.SpaceAfter = "8pt"; </code></pre> <p>The image is about 20x20mm.</p>
2
Access Angular2 Material sidenav in component
<p>I want to have access to the sidenav defined in *.component.html so I can dynamically control its mode (over | push | side) based properties such as screen width. </p> <p>How do I access the md-sidenav below</p> <pre><code>&lt;div class='layout-header'&gt; &lt;md-sidenav-layout fullscreen&gt; &lt;md-sidenav mode="side" #sidenav&gt; &lt;md-nav-list&gt; &lt;md-list-item&gt;Blah&lt;/md-list-item&gt; &lt;/md-nav-list&gt; &lt;/md-sidenav&gt; ... &lt;/div&gt; </code></pre> <p>from its component defined in *.component.ts? </p> <pre><code>@Component({ selector: 'layout-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'], directives: [ MD_SIDENAV_DIRECTIVES, MD_LIST_DIRECTIVES, MD_CARD_DIRECTIVES, MdToolbar, MdButton, MdInput, MdCheckbox, MdRadioGroup, MdRadioButton, MdIcon ], providers: [] }) export class HeaderComponent { } </code></pre> <p>I'm currently </p>
2
file download Resource interpreted as Document but transferred with MIME type application/octet-stream
<p>I have an iframe in the page which I use for file download. I set iframe source pointing to this php file with mp3 song path and tile. </p> <pre><code>&lt;?php header("Content-Type: application/octet-stream"); $name = $_GET['name']; header("Content-Disposition: attachment; filename=\"$name\""); $path = str_replace(' ', '%20', $_GET['path']); readfile($path); exit; ?&gt; </code></pre> <p>When I try to download mp3 song from audio player on this site: </p> <p><a href="http://janeingalls.com/" rel="nofollow">http://janeingalls.com/</a></p> <p>I get this message in console and file size is always 0 bytes when downloaded.</p> <pre><code>Resource interpreted as Document but transferred with MIME type application/octet-stream </code></pre>
2