pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
31,804,966
0
Running NodeJs http-server forever with PM2 <p>My question is about running HTTP-server in combination with PM2. </p> <p>The problem i face is that:</p> <ol> <li>HTTP-server requires as input a folder which is the root of the website and a port number to run the website on.</li> <li>PM2 doesn't recognize the HTTP-server command, even when HTTP-server is installed with the -g option.</li> </ol> <p>So i tried the following (note the double dash which should pass the parameters to the HTTP-server script:</p> <pre><code>/node_modules/http-server/lib$ pm2 start http-server.js -- /home/unixuser/websiteroot -p8686 </code></pre> <p>But it doesn't work.</p> <p>I also tried:</p> <pre><code>http-server /home/unixuser/websiteroot -p8686 </code></pre> <p>Which does work, but doesn't have the great support of pm2 ?</p> <p>Any suggestions would be great, thanks!</p>
13,706,289
0
how to set a base url with sammy? <p>i'm looking around for javascript routing libraries and i come to Sammy, so i'm learning it.</p> <p>All examples that i've seen so far show hot to proceed routing based from a domain as a base url, like www.mydomain.com/# and then all routes goes on</p> <p>but i'm doing some trials within a nested dir within my localhost dir, say /wwwroot/play/sammy/ so my base url would be </p> <pre><code>http://localhost/~rockdeveloper/play/sammy/# </code></pre> <p>and then all routes must go on, like:</p> <pre><code>http://localhost/~rockdeveloper/play/sammy/#/products http://localhost/~rockdeveloper/play/sammy/#/clients http://localhost/~rockdeveloper/play/sammy/#/search </code></pre> <p>is there any way to set this base url so i can proceed to config sammy routes like this ?</p> <pre><code>get('#/products') get('#/clients') get('#/search') </code></pre> <p>by now i have to concatenate the main string to the route, and i wish it would be more smart than this...</p> <pre><code>baseurl='/~rockdeveloper/play/sammy/#/search'; get(baseurl + '#/products'); </code></pre> <p>thanks.</p>
38,233,127
0
Angular - Bootstrap: Page navigation (Next and back button) using Angular UI-route not working when changing the state from controller <p>I am trying to achieve page navigation (Next and back button) using Angular UI-route. I am changing the state from controller and it is getting changed on view as well but is not redirecting me to that page. I have achieved it using button click using $state.go('stateName') but I want use Bootstrap page for this . </p> <p><a href="https://plnkr.co/edit/KV9LEC?p=preview" rel="nofollow">plunker</a></p> <p>here is my code </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$stateProvider .state('settings', { url: '/settings', templateUrl: 'templates/settings.html' }) .state('settings.profile', { url: '/profile', templateUrl: 'templates/profile.html', controller: 'ProfileController' }) .state('settings.account', { url: '/account', templateUrl: 'templates/account.html', controller: 'AccountController' }) .state('settings.profile1', { url: '/profile1', template: 'settings.profile1' }) .state('settings.account1', { url: '/account1', template: 'settings.account1' }); $urlRouterProvider.otherwise('/settings/profile'); // controlller $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { $scope.nextState = 'settings.account'; $scope.previousState = $state.current; //alert('$stateChangeStart') });</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;ul class="pager"&gt; {{nextState}} &lt;li&gt;&lt;a ui-sref=".{{previousState}}"&gt;Previous&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a ng-click=".{{nextState}}"&gt;Next&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
27,226,330
0
<pre><code>SELECT CASE WHEN ((SELECT Count(*) FROM table) &gt;= '100') THEN 'ALERT' ELSE null END </code></pre> <p>Create a job that runs every 10 seconds/5 seconds or what ever and put in the above query and get it to email if there are results.</p>
1,308,103
0
<p>There's already a browser-based system that uses keys to secure data transfer. It's called SSL.</p>
16,278,639
0
<p>There is difference between 1 and 0.1: your first case shows whole number while second case shows fractional.</p> <p>So if you test 10-20 range with value of 9.9 you may get error of data type (fractional instead of whole, or float instead of byte). By doing that, instead of testing range you test data type. This test is also important but different from the boundary analysis.</p>
12,287,876
0
<p>No. I looked in the documentation, and it looks like HighCharts.js only supports <code>renderTo</code> to a single HTML element. <a href="http://api.highcharts.com/highcharts#chart.renderTo" rel="nofollow">http://api.highcharts.com/highcharts#chart.renderTo</a></p> <p>I would assume that you have 5 pie charts that have different datasets, so it wouldn't make sense to load the same chart into multiple DIV elements anyway.</p> <p>You could write a loop that loaded the different charts.</p> <p>For example:</p> <pre><code>function loadCharts(chartData){ for(i=0; i&lt;chartData.length; i++){ var container = chartData[i]['container']; var myData = chartData[i]['myData']; var chart = new Highcharts.Chart({ chart: { renderTo: container, height: 400, plotBackgroundColor: null, plotBorderWidth: 2, borderWidth: 0, plotShadow: false }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, series: [{ data: myData }] }); } } var highchartsdata = [{ container: 'container1', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container2', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container3', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container4', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container5', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }]; loadCharts(highchartsdata); </code></pre> <p>This is an example I didn't test, but should help you get on the right path if that's how you want to go.</p>
29,099,545
0
<p>Why not just set the value to <code>true</code> inside the <code>else</code> block?</p> <pre><code>@if (hasMoreThanOnePerson) { &lt;td&gt; @Html.CheckBoxFor(m =&gt; m.People[i].IsSelected) &lt;/td&gt; } else { @{ Model.People[i].IsSelected = true; } @Html.HiddenFor(m =&gt; m.People[i].IsSelected) // Set TRUE always to hidden field within for loop with indexer } </code></pre>
23,949,998
0
What effect does a space have before the class name? <p>My aim is to have this class apply only when set on <code>&lt;img&gt;</code> tags. It only works when there is no space between the tag name and the class name, but doesn't when there is. I have seen style sheets with spaces in the signature, so I'm sure it must be valid in some contexts.</p> <p>What is the difference between:</p> <pre><code>img.approved-photo { // no space } </code></pre> <p>and</p> <pre><code>img .approved-photo { // has a space } </code></pre>
36,369,339
0
Cannot compare elements of type 'System.Linq.IQueryable`1'. Only primitive types, enumeration types and entity types are supported <p>i have this code in my controller</p> <pre><code>[HttpGet] public ActionResult Nabipour() { string name = "Nabipour"; var username = (from T in _db.tbl_teacher where T.Page==name select T.Username); ViewBag.Nabipour = from N in _db.tbl_Tpage where N.Username.Equals(username) select N; ViewBag.papers = from P in _db.tbl_Tpaper where P.Username.Equals(username) select P; return View(); } </code></pre> <p>and this is my view for this action:</p> <pre><code>@{ ViewBag.Title = "Nabipour"; Layout = "~/Views/Shared/_otherpage.cshtml"; } .... &lt;ul&gt; @foreach (var paper in ViewBag.papers) { &lt;li&gt;&lt;a href="~/Content/Paper/@paper.PaperName"&gt;&lt;/a&gt;&lt;/li&gt; } &lt;/ul&gt; .... </code></pre> <p>so as you see i not checking null in my select code and i tried this code with <code>.FirstOrDefault()</code> in the select. the error</p> <blockquote> <p>Cannot compare elements of type 'System.Linq.IQueryable 1 . Only primitive types, enumeration types and entity types are supported</p> </blockquote> <p>is on <code>@foreach (var paper in ViewBag.papers)</code> please help me what should i do? </p>
3,522,842
0
<p>Here's a binary search algorithm I just wrote for you that does the trick:</p> <pre><code>import java.util.Random; public class RangeFinder { private void find(double query, double[] data) { if (data == null || data.length == 0) { throw new IllegalArgumentException("No data"); } System.out.print("query " + query + ", data " + data.length + " : "); Result result = new Result(); int max = data.length; int min = 0; while (result.lo == null &amp;&amp; result.hi == null) { int pos = (max - min) / 2 + min; if (pos == 0 &amp;&amp; query &lt; data[pos]) { result.hi = pos; } else if (pos == (data.length - 1) &amp;&amp; query &gt;= data[pos]) { result.lo = pos; } else if (data[pos] &lt;= query &amp;&amp; query &lt; data[pos + 1]) { result.lo = pos; result.hi = pos + 1; } else if (data[pos] &gt; query) { max = pos; } else { min = pos; } result.iterations++; } result.print(data); } private class Result { Integer lo; Integer hi; int iterations; long start = System.nanoTime(); void print(double[] data) { System.out.println( (lo == null ? "" : data[lo] + " &lt;= ") + "query" + (hi == null ? "" : " &lt; " + data[hi]) + " (" + iterations + " iterations in " + ((System.nanoTime() - start) / 1000000.0) + " ms. )"); } } public static void main(String[] args) { RangeFinder rangeFinder = new RangeFinder(); // test validation try { rangeFinder.find(12.4, new double[] {}); throw new RuntimeException("Validation failed"); } catch (IllegalArgumentException e) { System.out.println("Validation succeeded"); } try { rangeFinder.find(12.4, null); throw new RuntimeException("Validation failed"); } catch (IllegalArgumentException e) { System.out.println("Validation succeeded"); } // test edge cases with small data set double[] smallDataSet = new double[] { 2.0, 7.8, 9.0, 10.5, 12.3 }; rangeFinder.find(0, smallDataSet); rangeFinder.find(2.0, smallDataSet); rangeFinder.find(7.9, smallDataSet); rangeFinder.find(10.5, smallDataSet); rangeFinder.find(12.3, smallDataSet); rangeFinder.find(10000, smallDataSet); // test performance with large data set System.out.print("Preparing large data set..."); Random r = new Random(); double[] largeDataSet = new double[20000000]; largeDataSet[0] = r.nextDouble(); for (int n = 1; n &lt; largeDataSet.length; n++) { largeDataSet[n] = largeDataSet[n - 1] + r.nextDouble(); } System.out.println("done"); rangeFinder.find(0, largeDataSet); rangeFinder.find(5000000.42, largeDataSet); rangeFinder.find(20000000, largeDataSet); } } </code></pre>
9,001,115
0
Save banking account data secure <p>I need to save banking account data in a web project. The project is asp.net mvc 3 and the database is MSSQL 2008 R2.</p> <p>But how should I do that secure?</p> <p>My solutions are:</p> <ol> <li><p>Solution: Encrypt the Data with TripleDESCryptoServiceProvider and save them to the Database.</p></li> <li><p>Solution: Save only maybe the last 3 numbers of the account data (like amazon shows you), so that the user will recognize which account data he has saved to the system. Encrypt the entire account data and save them to a different database (maybe with a stored procedure) where the web project has no rights to.</p></li> </ol> <p>We only need the account data, collect the monthly fees. So we do not need them in the web project. But the user has to recognise which account data he has given to pay the fees.</p> <p>What are the best solutions?</p> <p>EDIT:</p> <p>Thank you all for your replies. I Think we will really use a service provider, that will store the account data and does all the other stuff like Accounts receivable management.</p>
41,023,266
0
Is there an OData dependency graph somewhere? <p>I'm following <a href="http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/3292/A-OData-4-AngularJs-TypeScript-Sample-Application.aspx" rel="nofollow noreferrer">this guide</a> to migrate an app I developed to an open framework. I get to the part where I'm supposed to install all the OData references. Specifically these:</p> <pre><code>Install-Package Angularjs Install-Package Microsoft.OData.Client Install-Package Microsoft.OData.Core Install-Package Microsoft.OData.Edm Install-Package Microsoft.Spatial Install-Package Microsoft.AspNet.OData Install-Package Microsoft.AspNet.WebApi.WebHost </code></pre> <p>And these are the errors I get:</p> <pre><code>Unable to resolve dependencies. 'Microsoft.OData.Core 7.0.0' is not compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Edm' that is compatible with 'Microsoft.OData.Core 6.15.0 constraint: Microsoft.OData.Edm (= 6.15.0)'. </code></pre> <p>I started running my app over and over until it throws an exception and then adding a <code>bingindRedirect</code> to my <code>Web.config</code> to target the currently installed versions. But this doesn't seem right and will add a lot of maintenance later on. I know how to install old versions and nightly versions. But I have no idea which versions to install. Is there some place that tells me which versions work together correctly?</p> <hr> <p>According to NuGet, I have version 6.15.0 of each installed. So why am I getting errors?</p> <p><a href="https://i.stack.imgur.com/6YR5D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6YR5D.png" alt="Edm"></a></p> <p><a href="https://i.stack.imgur.com/oKIzS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oKIzS.png" alt="Core"></a></p> <p><a href="https://i.stack.imgur.com/Mo60i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mo60i.png" alt="Client"></a></p>
3,188,353
0
<p>Every environment is slightly different. In comparison, you have to decide what works for you. Amazon for example makes their developers own their own code, which some developers hate, but it is a feature of that environment that keeps bug counts low (when was the last time you saw a bug on amazon.com?). </p> <p>Others want a tighter QA process so create an operations department to look after deploys, but I've found they tend to create an atmosphere of negativity in the company: they are rewarded by justifying their role, which entails pointing out and supporting the bad things in the World. If the devs are good at their job, resentment can creep in if their pay is in any way performance-related.</p> <p>Personally, I tend to prefer to look after the whole stack, but increasingly am moving to providers that allow me to worry less and less about hardware (EC2, Heroku, etc.), and to focus more on functionality in the apps. I personally like owning the code and the bugs, as it means I am demonstrably motivated to keeping bug tickets down - every open ticket is a delay to the new functionality I want to work on.</p> <p>Each to their own.</p>
16,618,756
0
<p>Since you're using Windows, <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx" rel="nofollow">GetModuleFileName</a> should do the trick. Just pass <code>NULL</code> for the <code>hModule</code> parameter. Be sure to read the documentation carefully if you want to handle long file names (and you typically do). You'll also have to strip the name of the executable to get the directory path. A quick-and-dirty way to do so is to remove everything after the last <code>\</code>.</p>
20,944,063
0
<p>I dont understand you question.</p> <p>You say you want to add a <code>TextureView</code> to your activity_main.xml layout. but it is already there.</p> <p>Obviously if you use <code>setContentView(mTextureView);</code> after <code>setContentView(R.layout.activity_main);</code> the entire layout will be gone. You are setting the activity content to a single view instead of the entire layout.</p> <p>You are also creating a new <code>TextureView</code> and not using the one on the activity_main layout.</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextureView = (TextureView)findViewById(R.id.textureView1); mTextureView.setSurfaceTextureListener(this); } </code></pre> <p>I think you should be doing something like this. I never tested this though.</p> <p>It seems that you are trying to make a camera preview with the TextureView, there is a good example <a href="http://docs.xamarin.com/recipes/android/other_ux/textureview/display_a_stream_from_the_camera/" rel="nofollow">here</a>, and a more advanced version <a href="http://www.tutorialspoint.com/android/android_textureview.htm" rel="nofollow">here</a>.</p>
32,283,313
0
C# Node pointer issue <p>I am having some trouble setting child nodes using C#. I am trying to build a tree of nodes where each node holds an int value and can have up to a number of children equal to it's value.</p> <p>My issue appears when I iterate in a node looking for empty(null) children so that I may add a new node into that spot. I can find and return the null node, but when I set the new node to it, it loses connection to the parent node. </p> <p>So if I add 1 node, then it is linked to my head node, but if I try to add a second it does not become a child of the head node. I am trying to build this with unit tests so here is the test code showing that indeed the head does not show the new node as it's child (also confirmed with visual studios debugger):</p> <pre><code> [TestMethod] public void addSecondNodeAsFirstChildToHead() { //arange Problem3 p3 = new Problem3(); p3.addNode(2, p3._head); Node expected = null; Node expected2 = p3._head.children[0]; int count = 2; //act Node actual = p3.addNode(1, p3._head); Node expected3 = p3._head.children[0]; //assert Assert.AreNotEqual(expected, actual, "Node not added"); //pass Assert.AreNotEqual(expected2, actual, "Node not added as first child"); //pass Assert.AreEqual(expected3, actual, "Node not added as first child"); //FAILS HERE Assert.AreEqual(count, p3.nodeCount, "Not added"); //pass } </code></pre> <p>Here is my code.</p> <pre><code>public class Node { public Node[] children; public int data; public Node(int value) { data = value; children = new Node[value]; for(int i = 0; i &lt; value; i++) { children[i] = null; } } } public class Problem3 { public Node _head; public int nodeCount; public Problem3() { _head = null; nodeCount = 0; } public Node addNode(int value, Node currentNode) { if(value &lt; 1) { return null; } Node temp = new Node(value); //check head if (_head == null) { _head = temp; nodeCount++; return _head; } //start at Current Node if (currentNode == null) { currentNode = temp; nodeCount++; return currentNode; } //find first empty child Node emptyChild = findEmptyChild(currentNode); emptyChild = temp; nodeCount++; return emptyChild; } public Node findEmptyChild(Node currentNode) { Node emptyChild = null; //find first empty child of current node for (int i = 0; i &lt; currentNode.children.Length; i++) { if (currentNode.children[i] == null) { return currentNode.children[i]; } } //move to first child and check it's children for an empty //**this causes values to always accumulate on left side of the tree emptyChild = findEmptyChild(currentNode.children[0]); return emptyChild; } </code></pre> <p>I feel the problem is I am trying to treat the nodes as pointers like I would in C++ but that it is not working as I expect.</p>
3,841,110
0
<p>It's probably worth just testing if the following works:</p> <pre><code>SqlConnection con = new SqlConnection("Data Source=server;Initial Catalog=Invoicing;Persist Security Info=True;ID=id;Password=pw"); </code></pre> <p>To me it looks like your connection string is probably not right - there's no user provided. I use the following connection string: "Data Source=ServerNameHere;Initial Catalog=DBNameHere;User ID=XXXX;Password=XXXX"</p>
11,754,070
0
Editing Dynamically Generated Telerikmvc3 Grid <p>I have a dynamically generated MVC3 grid that is populated from a ViewModel. I need to add editing to the grid and cant get it to even go into edit mode.</p> <p>Also I need to be able to make some of the columns readonly.</p> <p>My code is below:</p> <pre><code>@(Html.Telerik() .Grid&lt;System.Data.DataRow&gt;(Model.Data.Rows.Cast&lt;System.Data.DataRow&gt;()) .HtmlAttributes(new { style = "width: 2500px" }) .Name("Grid") .ToolBar(tb =&gt; tb.Template("Outstanding Orders")) .DataKeys(dataKeys =&gt; dataKeys.Add("DeliveryID")) .Columns(columns =&gt; { columns.Command(commands =&gt; { commands.Edit().ButtonType(GridButtonType.ImageAndText) .HtmlAttributes( new { style = "width: 60px; min-width: 40px; background: #0066FF" }); }).Width(100).Title("Commands"); columns.Command(commandbutton =&gt; { commandbutton.Select().ButtonType(GridButtonType.ImageAndText) .HtmlAttributes( new { style = "width: 60px; min-width: 40px; background: #0066FF" }); columns.LoadSettings(Model.Columns as IEnumerable&lt;GridColumnSettings&gt;); }) .DataBinding(dataBinding =&gt; dataBinding.Server() .Select("_DeliveryGrid", "Deliveries") .Update("Save", "Deliveries")) .Editable(editing =&gt; editing.Mode(GridEditMode.InLine)) .Sortable(settings =&gt; settings.Enabled(true)) .Scrollable(c =&gt; c.Height("9000px")) .EnableCustomBinding(true) .Resizable(resize =&gt; resize.Columns(true)) ) </code></pre> <p>My viewmodel definition</p> <pre><code>public class DeliveriesGridViewModel { public DataTable Data { get; set; } public IEnumerable&lt;GridColumnSettings&gt; Columns { get; set; } } </code></pre> <p>Thanks for the help</p>
14,361,227
0
<p>This will do the trick:</p> <pre><code>if($_SERVER['REMOTE_ADDR'] === '127.0.0.1') { // do something } </code></pre> <p>Be careful you don't rely on X_FORWARDED_FOR as this header can be easily (and accidentally) spoofed.</p> <p>The correct way to do this would be to set an environmental variable in your server configuration and then check that. This will also allow you to toggle states between a local environment, staging and production.</p>
15,601,937
0
Zebra printer serbian latin characters <p>I have a problem with Zebra printer RW220 not printing serbian latin characters, like čćžšđ. I developed an android app which uses the printer. The printing part is based on Zebra SDK. Here's the part of the code:</p> <pre><code>private byte[] getConfigLabel() { PrinterLanguage printerLanguage = printer.getPrinterControlLanguage(); byte[] configLabel = null; if (printerLanguage == PrinterLanguage.ZPL) { try { configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (printerLanguage == PrinterLanguage.CPCL) { String cpclConfigLabel = "! 0 200 200 780 1\r\n" + "T ARIAL9PT.CPF 0 60 10 ABCČĆŽŠĐ\r\n" + "PRINT\r\n"; configLabel = cpclConfigLabel.getBytes(); } return configLabel; } </code></pre> <p>The font used is Arial, which I converted using Zebra Utilities to CPF, for use with printer. I also added the characters to the font, but it doesn't print them. In this example, it just prints the ABC. And with the system fonts, it prints some strange characters. I also tried adding "ENCODING UTF-8" line before "T ARIAL9PT.CPF 0 60 10 ABCČĆŽŠĐ\r\n", but it doesn't do anything, same with the system fonts. How can I make it print serbian latin characters? Thanks.</p> <p>EDIT: ISO-8859-2 prints Č and Ć, but not Ž.</p>
38,632,937
0
<p>You can put these variables in an interface. That way, you will make these "public static final".</p> <p>Ideally you can even put these into properties file. In that case, these should be config properties of your application which may control a feature or anything that could've been changed from outside(e.g. an url).</p>
34,423,220
0
<p>Just to add to the accepted answer (not enough rep to comment), I had this issue arise when blocking using <code>task.Result</code>, event though every <code>await</code> below it had <code>ConfigureAwait(false)</code>, as in this example:</p> <pre><code>public Foo GetFooSynchronous() { var foo = new Foo(); foo.Info = GetInfoAsync.Result; // often deadlocks in ASP.NET return foo; } private async Task&lt;string&gt; GetInfoAsync() { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre> <p>The issue actually lay with the external library code. The async library method tried to continue in the calling sync context, no matter how I configured the await, leading to deadlock.</p> <p>Thus, the answer was to roll my own version of the external library code <code>ExternalLibraryStringAsync</code>, so that it would have the desired continuation properties.</p> <p><hr> <strong>wrong answer for historical purposes</strong></p> <p>After much pain and anguish, I found the solution <a href="http://weblogs.asp.net/pglavich/asp-net-web-api-request-response-usage-logging" rel="nofollow">buried in this blog post</a> (Ctrl-f for 'deadlock'). It revolves around using <code>task.ContinueWith</code>, instead of the bare <code>task.Result</code>.</p> <p>Previously deadlocking example:</p> <pre><code>public Foo GetFooSynchronous() { var foo = new Foo(); foo.Info = GetInfoAsync.Result; // often deadlocks in ASP.NET return foo; } private async Task&lt;string&gt; GetInfoAsync() { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre> <p>Avoid the deadlock like this:</p> <pre><code>public Foo GetFooSynchronous { var foo = new Foo(); GetInfoAsync() // ContinueWith doesn't run until the task is complete .ContinueWith(task =&gt; foo.Info = task.Result); return foo; } private async Task&lt;string&gt; GetInfoAsync { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre>
25,530,556
0
<p>Having the triggers activate when the application is not running at all (not even in background) isn't supported through the Worklight APIs. You could try and use Worklight Android Native SDK together with cmarcelk's suggestions. Or you could use the Worklight Android triggers within a native service, together with the Broadcast Receivers mechanism so that it will run automatically on boot. You could then use an Intent to open the application from the trigger callback.</p>
4,157,941
0
<p>I think the loop is just fine, but if you want to keep track,</p> <pre><code>var winList = new Array(); var count = 10; for(var i=0; i &lt; count; i++){ winList[i] = window.open("http://www.test.com"); } </code></pre> <p>This way, you can keep references to your windows.</p> <p>hth</p>
34,894,906
0
<p>I don't have enough rep to post this as a comment to the question.</p> <p>Maybe your PowerBuilder source control methodology is holding you back. Do you control the PB objects inside of the PBLs? Or do you control *.sr? (PB Export) files, maybe using PowerGen to synchronize them into the PBLs?</p> <p>At work, a set of PBLs is published to programmers by the Build Manager at every build. This avoids having to pay one PowerGen license per programmer for them to sync up (which can take 5-40 minutes depending on the number of changes and the app size). You need just one license for the build server.</p> <p>One caveat is that programmers need to understand the flow correctly so not to lose code or cause regressions, but a good inspection of the TortoiseHg diff window should allow to catch most problems before committing. </p>
20,698,101
0
After manually rebalancing hadoop hdfs disks DataNode won't restart <p>I use Hadoop hadoop-2.0.0-mr1-cdh4.1.2 in a cluster of 40 machines. Each machine has 12 disks used by hadoop. Some disks in one machine were unbalanced, and I decided to re-balance manually as mentioned in this post: <a href="http://stackoverflow.com/questions/13153790/rebalance-individual-datanode-in-hadoop">rebalance individual datanode in hadoop</a> I stopped the DataNode on that server, moved block file pairs, moved whole sub-directories between some of the disks.</p> <p>As soon as I stopped the DataNode, the NameNode complained about missing blocks by displaying the following message in the UI: WARNING : There are 2002 missing blocks. Please check the logs or run fsck in order to identify the missing blocks.</p> <p>Then, I tried to restart the DataNode. It refuses to successfully start and it keeps logging errors and warnings such as follows:</p> <p>java.io.IOException: Invalid directory or I/O error occurred for dir: /data/disk3/dfs/data/current/BP-208475052-10.165.18.36-1351280731538/current/finalized/subdir61/subdir28</p> <p>2013-12-20 01:40:29,046 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: IOException in offerService java.io.IOException: block pool BP-208475052-10.165.18.36-1351280731538 is not found</p> <p>2013-12-20 01:40:29,088 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: Exception in BPOfferService for Block pool BP-208475052-10.165.18.36-1351280731538 (storage id DS-737580588-10.165.18.36-50010-1351280778276) service to aspen8hdp19.turner.com/10.165.18.56:54310 java.lang.NullPointerException</p> <p>2013-12-20 01:40:34,088 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: IOException in offerService java.io.IOException: block pool BP-208475052-10.165.18.36-1351280731538 is not found</p> <p>So, I have some questions:</p> <ul> <li>Isn't it enough to follow the approach I mentioned? I.e. stop DataNode, move block file pairs and/or subdirectories, restart DataNode.</li> <li>Do I need to restart NameNode or other services?</li> <li>Why does it complain about missing blocks or corrupt files?</li> <li>How can I restart the DataNode and get rid of those exceptions therefore having the DN communicate successfully with the NN?</li> </ul> <p>I appreciate your help. Eduardo.</p>
14,026,722
0
<p>The background is relative to your div, not to margins, use paddings instead.</p>
4,995,708
0
<p>It's like "normal" fields. So before the static constructor. You can check with a very simple program.</p> <p>The order is:</p> <ul> <li>static fields</li> <li>static constructor</li> <li>"normal" fields</li> <li>"normal" constructor</li> </ul> <p>A sample program:</p> <pre><code>class Program { static void Main(string[] args) { Console.WriteLine("Start"); int b = A.B; Console.WriteLine("Read A.B"); new A(); Console.WriteLine("Built A"); } } class A { public static int B = mystaticfunc(); static int mystaticfunc() { Console.WriteLine("Static field"); return 1; } static A() { Console.WriteLine("Static constructor"); } int C = myfunc(); static int myfunc() { Console.WriteLine("Field"); return 1; } public A() { Console.WriteLine("Constructor"); } } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Start Static field Static constructor Read A.B Field Constructor Built A </code></pre>
38,536,136
0
Unique methods for use through the class rather than an object <p>So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the <code>static</code> keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. <code>MyClass.main()</code>) rather than solely through the object (<code>MyObject.main()</code>). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that <code>MyClass.main()</code> would work, however <code>MyObject.main()</code> would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.</p> <p>In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!</p> <p>Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.</p> <p>Thanks!</p>
2,811,457
0
<p>Safe from what? If an attacker has root, they can subvert system calls and spy on memory buffers before encryption and after decryption, and nothing you can do is safe.</p> <p>If an attacker does not have root, they can't see this information even if you don't encrypt it.</p> <p>So I don't see a point to this.</p>
23,189,974
0
<p>Your production environment has the <code>short_open_tag</code> setting disabled. For full compatibility its recommended that you do not turn it on and instance use the full php tag <code>&lt;?php</code> instead of <code>&lt;?</code></p>
40,185,920
0
custom vertex color with threejs LineSegments() <p>I am struggling with threejs to use a shaderMaterial on a THREE.LineSegments my goal is to have per vertex color, on a bunch of line segments:</p> <p>I have a vertex and a fragment shader :</p> <pre><code> &lt;script type="x-shader/x-vertex" id="vertexshader"&gt; varying vec3 vColor; attribute vec3 customColor; void main() { vColor = customColor; } &lt;/script&gt; &lt;script type="x-shader/x-fragment" id="fragmentshader"&gt; varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0 ); } &lt;/script&gt; </code></pre> <p>then in the threejs scene , I create all the relevant stuff for the shader, and apply it to the object:</p> <pre><code> var customColors = new Float32Array(_count*2*3); // 2 vertex by segment *length(RGB) for (var i = 0; i &lt; customColors.length/3; i++) { var ratio = i / (customColors.length/3.0); customColors[(i*3)] = ratio; customColors[(i*3)+1] = ratio; customColors[(i*3)+2] = ratio; }; geo.addAttribute('customColor' , new THREE.BufferAttribute(customColors,3)); var drawCount = _count * 2; geo.setDrawRange( 0, drawCount ); var uniforms = { opacity : 0.5 }; var customMaterial = new THREE.ShaderMaterial( { uniforms : uniforms, vertexShader : document.getElementById( 'vertexshader' ).textContent, fragmentShader : document.getElementById( 'fragmentshader' ).textContent, } ); var lines = new THREE.LineSegments(geo, customMaterial); </code></pre> <p>I can't find where the problem is. The line segments don't appear at all,not even in black. All I have managed to do is to 'hard code' the color in the fragment shader ( which defeats the purpose evidently).</p> <p>No error message whatsoever in the console.</p> <p>please help, what am i doing wrong here ?</p>
28,625,148
0
Adding icons to tabs using Easy Responsive Tabs from WP <p>I cant find anything to answer me this. How can I add icons to the title of my ERT tabs? ERT generates a shortcode which I have added to home php file and it works beautifully but how can I edit the shortcode so that the title tab includes an icon? code looks like this in the PHP:</p> <pre><code>'&lt;?php echo do_shortcode('[restabs alignment="osc-tabs-center" pills="nav-pills" responsive="true" icon="true" text="Next" tabcolor="#ffffff" tabheadcolor="#2C3E51" seltabcolor="#2C3E51" seltabheadcolor="#ffffff" tabhovercolor="#f7933b"] [restab title="(NEED ICON HERE)OUR WORK" active="active"] &lt;table style="width: 100%; border: none; margin-top: 0px; font-size: 10px"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;/tr&gt; [/restab] [/restabs]'); ?&gt;' </code></pre>
14,450,658
0
<p>Does this work?</p> <pre><code>def json = request.JSON try { def context = json.optJSONObject("context") userService.updateContext(context) }catch(e) { log.error json.toString() } </code></pre>
22,184,715
0
<p>There are two (or more) problems. The first: you are using <code>typedef</code> when you are trying to declare an array of structs. Don't. Instead of</p> <pre><code>typedef struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; </code></pre> <p>use</p> <pre><code>struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; </code></pre> <p>Notice that you now have the structure (not a pointer to the structure) - so when you want to access an element you need <code>.</code> not <code>-&gt;</code> Thus:</p> <pre><code> symbles_arr[symbol_counter]-&gt;symbolName=*toCheck; </code></pre> <p>needs to become</p> <pre><code> strcpy(symbles_arr[symbol_counter].symbolName, *toCheck); </code></pre> <p>because you allocated space for the symbol name in the structure, and you can't just take that pointer and point it somewhere else.</p> <p>Finally - you don't need to <code>malloc</code> space for <code>toCheck</code> since <code>strtok</code> actually returns a pointer to the original string (it doesn't make a copy). The side effect of this is that your input string (the one passed to <code>strtok</code>) becomes mangled in the process - after you're done using it, it has a lot of <code>'\0'</code> added.</p> <p>There may be other problems, but this should get you on your way...</p>
19,801,904
0
I have a website and when I put one page in the root it works fine but within a folder I get an error? <p>I have uploaded the same file on to the website. The php code in it looks like this <code> <pre>$f = fopen("http://thefreetechhelp.com/testsrc/top.txt", "r"); while(!feof($f)) { echo fgets($f); } fclose($f); ?&gt; &lt;/code&gt; </code></pre> <p>And there is two of these in the document. Below are the links, notice how in the second one you get the error</p> <p><a href="http://thefreetechhelp.com/index.html" rel="nofollow">http://thefreetechhelp.com/index.html</a></p> <p><a href="http://thefreetechhelp.com/articles/index.html" rel="nofollow">http://thefreetechhelp.com/articles/index.html</a></p> <p>the server is Debian GNU/Linux if that helps</p>
28,257,088
0
<p>One way to go about it is to create a view with your basic logic:</p> <pre><code>CREATE VIEW myview AS SELECT * FROM mytable WHERE column_b = 'X' AND column_c = 'Y' </code></pre> <p>Now, this logic can be reused:</p> <pre><code>SELECT * FROM myview WHERE column_a NOT IN (SELECT column_k FROM myview) </code></pre>
19,320,850
1
Error with my Python File Search Algorithm <p>I have a problem with my python code.When my search code encounters an error it terminates the search it is conducting even when it has not yet finish searching a specific location. This mostly happens when it encounters a write protected folder or file.I am using <code>os.walk()</code> for transversing the file system tree and <code>glob.glob()</code> module to perform the searches How do i deal with this issue?</p> <p>Here is part of my code:</p> <pre><code>def searchEntity(drive,search_term): f_files={} print 'Searching in %s ........' %drive try: for dirpath,dirname,filename in os.walk(drive): os.chdir(dirpath) l=glob.glob('*'+search_term+'*') for e in l: self.f_files[e]=dirpath print e except Exception,e: print e finally: print'&lt;&lt;Search Completed&gt;&gt;' </code></pre> <p>How can i skip this write protected locations and continue with the search or should i use a better searching method. Here is an example of the error i am receiving:<br /></p> <p>Searching in <code>C:/ ........</code><br /> <code>[Error 5] Access is denied: 'C:/Program Files\\Microsoft SQL Server\\110\\Shared\\ErrorDumps'</code></p>
30,943,140
0
<p>By using <code>add</code>, you are effectively getting a calendar instance that is 2015 years, 6 months, 20 days, and 19 hours <em>later</em> than now. Instead use the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#GregorianCalendar-int-int-int-int-int-" rel="nofollow">constructor</a>:</p> <pre><code>Calendar cal = new GregorianCalendar(2015, 5, 20, 19, 0); </code></pre> <p>and do not call <code>add</code>.</p> <p>Alternatively, you can use <code>set</code> instead of add:</p> <pre><code>cal.set(Calendar.YEAR, 2015); cal.set(Calendar.MONTH, 5); // 0-based cal.set(Calendar.DAY_OF_MONTH, 20); cal.set(Calendar.HOUR, 19); cal.set(Calendar.MINUTE, 0); </code></pre>
21,524,234
0
<p>I think that the only way is to grab widget with QPixmap::grabWidget(). And to use this image in delegate. Seems, that it is not possible to do because of <a href="http://stackoverflow.com/questions/19138100/how-to-draw-control-with-qstyle-and-with-specified-qss">QSS limitation</a></p>
33,167,029
0
<p>Going along with Charles Ward's answer, the following worked for me: <code>com.leapmotion.leap.LeapJNI.Controller_setPolicy(Controller.getCPtr(controller), controller, 1 &lt;&lt; 15);</code></p>
2,154,512
0
<p>Java uses <a href="http://en.wikipedia.org/wiki/IEEE_754" rel="nofollow noreferrer">IEEE 754</a> for its floating point numbers and therefore follows their rules.</p> <p>According to the <a href="http://en.wikipedia.org/wiki/NaN" rel="nofollow noreferrer">Wikipedia page on NaN</a> it is defined like this:</p> <blockquote> <p>A bit-wise example of a IEEE floating-point standard single precision NaN: <code>x111 1111 1axx xxxx xxxx xxxx xxxx xxxx</code> where <code>x</code> means <i>don't care</i>. </p> </blockquote> <p>So there are quite a few bit-patterns all of which are <code>NaN</code> values.</p>
17,083,428
0
MSSQL merge with distributed transaction alternative <p>I have a distributed transaction where I need to merge into the target remote table. Now MERGE INTO isn't allowed according to MSDN: “target_table cannot be a remote table”.</p> <p>So my workaround goes as follows: 0. begin distributed transaction 1. define a cursor 2. open it 3. if cursor has at least one record (CURSOR_STATUS()=1) fetch next 4. if exists (select top 1 * from target_remote_table where id = @myCurrentCursorId) -> when true update target_remote_table when false insert into target_remote_table 5. commit/rollback distributed transaction depending on trancount and xact_state</p> <p>It works but I know that cursors are evil and you shouldn't use them. So I want to ask if there is any other way I could solve this by not using cursors?</p> <pre><code>USE [My_DB] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[my_proc_merge_into_remote_table] @ID_A INT, @ID_B INT AS BEGIN SET NOCOUNT ON; -- CURSOR VALUES DECLARE @field_A INT DECLARE @field_B INT DECLARE @field_C INT DECLARE @field_D BIT DECLARE @field_E INT DECLARE @field_F DATETIME DECLARE @field_G VARCHAR(20) DECLARE @field_H DATETIME DECLARE @field_I VARCHAR(20) BEGIN TRY BEGIN DISTRIBUTED TRANSACTION -- CURSOR !! DECLARE my_cursor CURSOR FOR SELECT b.field_A , b.field_B, c.field_C, a.field_D, a.field_E, GETDATE() AS field_F, a.field_G, GETDATE() AS field_H, a.field_I FROM dbo.source_tbl a LEFT JOIN dbo.base_element_tbl l ON a.obj_id = l.obj_id AND a.element_id = l.element_id INNER JOIN dbo.base_obj_tbl b ON a.obj_id = b.obj_id INNER JOIN dbo.element_tbl c ON a.element_id = c.element_id WHERE a.ID_B = @ID_B AND a.ID_A = @ID_A; OPEN my_cursor; -- check if cursor result set has at least one row IF CURSOR_STATUS('global', 'my_cursor') = 1 BEGIN FETCH NEXT FROM my_cursor INTO @field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I; WHILE @@FETCH_STATUS = 0 BEGIN -- HINT: MY_REMOTE_TARGET_TABLE is a Synonym which already points to the correct database and table IF EXISTS(SELECT TOP 1 * FROM MY_REMOTE_TARGET_TABLE WHERE field_A = @field_A AND field_B = @field_B AND field_C = @field_C AND field_E = @field_E) UPDATE MY_REMOTE_TARGET_TABLE SET field_D = @field_D, field_H = @field_H, field_I = @field_I; ELSE INSERT INTO MY_REMOTE_TARGET_TABLE (field_A, field_B, field_C, field_D, field_E, field_F, field_G, field_H, field_I) VALUES (@field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I); FETCH NEXT FROM my_cursor INTO @field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I; END; END; CLOSE my_cursor; DEALLOCATE my_cursor; IF (@@TRANCOUNT &gt; 0 AND XACT_STATE() = 1) BEGIN COMMIT TRANSACTION END END TRY BEGIN CATCH IF (@@TRANCOUNT &gt; 0 AND XACT_STATE() = -1) ROLLBACK TRANSACTION END CATCH; END </code></pre>
33,234,754
0
<p>Like adeneo said: dataType: 'array' is invalid and probably jquery will trigger the .fail() instead of .done(). </p> <p><a href="https://api.jquery.com/deferred.fail/" rel="nofollow">https://api.jquery.com/deferred.fail/</a></p>
9,089,647
0
css to format line 1 and 2 of my h1 differently? & change position of line break <p>Hi I am using a featured post widget in wordpress and its is displaying my h1 heading over 2 lines. However I want to change the margin or line breaks so that instead of saying "Workplace Injury" on the first line and "Prevention" on the second line, It would say "Workplace" on the first line and "Injury Prevention" on the second</p> <p>Any ideas. I've tried using a psuedo first line command but no luck ie.</p> <pre><code>#home-header-right .featuredpage .post-7 h2:first-line, #home-header-right .featuredpage .post-20 h2:first-line, #home-header-right .featuredpage .post-7 a:first-line, #home-header-right .featuredpage .post-20 a:first-line { padding: 0 50px 0 0; } </code></pre>
20,930,988
0
<p>It is because the callback is being run on a thread.</p> <p>Why?</p> <p>The Console application.</p> <p>According to the <code>Progress</code> class MSDN documentation:</p> <blockquote> <p>Any handler provided to the constructor or event handlers registered with the ProgressChanged event are invoked through a SynchronizationContext instance captured when the instance is constructed. If there is no current SynchronizationContext at the time of construction, the callbacks will be invoked on the ThreadPool.</p> </blockquote> <p>Essentially, your callbacks are out of whack because there is no <code>SynchronizationContext</code> in a Console application.. so they are being fired on ThreadPool threads.</p> <p>Try it in a Windows application.. here's a screenshot of the output for the exact same code:</p> <p><img src="https://i.stack.imgur.com/fjRrA.png" alt="Sync example"></p>
7,044,505
0
<p>If both scripts have been included in the same HTML file, sure, it will work out of the box. Best way to know is to try it.</p>
2,588,472
0
32 bit operation vs 64 bit operation on a 64bit machine/OS <p>Which operation i.e a 32 bit operation or a 64 bit operation (like masking a 32 bit flag or a 64 bit flag), would be cheaper on a 64 bit machine?</p>
28,912,282
0
Trying to write "<<<" in ksh <p>I am having trouble with the code below:</p> <pre><code>IFS=: read c1 c2 c3 c4 rest &lt;&lt;&lt; "$line" </code></pre> <p>Don't get me wrong this code works good but it doesn't seem to be used for ksh. I basically need to write the same code without the "&lt;&lt;&lt;". There is not much info on the "&lt;&lt;&lt;" online. If anybody has any ideas it would be much appreciated.</p> <p><strong>EDIT:</strong></p> <p>Ok code is as follows for the entire portion of programming:</p> <pre><code>m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then oldIFS=$IFS IFS=: set -- $line IFS=$oldIFS c1=$1 c2=$2 c3=$3 c4=$4 shift; shift; shift; shift rest="$*" echo -e "Last Name: $1\nFirst Name: $2\nState: $4" while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;; </code></pre> <p>Ok so everything works except for the </p> <pre><code>echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" </code></pre> <p>It will just show:</p> <p>Last Name:</p> <p>First Name:</p> <p>State:</p> <p>So I can see it is not adding it to my echo correctly.</p> <p><strong>FINAL EDIT</strong></p> <p><strong><em>CODE:</em></strong></p> <pre><code>#Case statement for modifying an entry m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then echo "$line" | while IFS=: read c1 c2 c3 c4 rest; do echo -e "Last Name: $c1\nFirst Name: $c2\nState: $c4" last=$c1 first=$c2 done while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $last\nFirst Name: $first\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;; </code></pre>
2,355,399
0
Creating a "skeleton" of an existing database <p>I have a huge database in production environment which I need to take a copy off, but the problem is that the data is over 100Gb's and downloading a backup off it is out of the question. I need to get a "skeleton" image of the database. What I mean by "skeleton" is, I need to get the database outline so that I can recreate the database locally by running SQL scripts.</p> <p>Is there a quick and easy way to retrieve the SQL for recreating the database structure and tables?</p> <p>Or will I have to write something in order to do this programmatically?</p>
11,653,985
0
<p>An IMHO improved way based upon ZZ Coder's solution is to use a ResponseInterceptor to simply track the last redirect location. That way you don't lose information e.g. after an hashtag. Without the response interceptor you lose the hashtag. Example: <a href="http://j.mp/OxbI23" rel="nofollow">http://j.mp/OxbI23</a></p> <pre><code>private static HttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllTrustManager() }; sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory())); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new org.apache.http.impl.conn.SingleClientConnManager(schemeRegistry); // some pages require a user agent AbstractHttpClient httpClient = new DefaultHttpClient(cm, params); HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1"); httpClient.setRedirectStrategy(new RedirectStrategy()); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { if (response.containsHeader("Location")) { Header[] locations = response.getHeaders("Location"); if (locations.length &gt; 0) context.setAttribute(LAST_REDIRECT_URL, locations[0].getValue()); } } }); return httpClient; } private String getUrlAfterRedirects(HttpContext context) { String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL); if (lastRedirectUrl != null) return lastRedirectUrl; else { HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); return currentUrl; } } public static final String LAST_REDIRECT_URL = "last_redirect_url"; </code></pre> <p>use it just like ZZ Coder's solution: </p> <pre><code>HttpResponse response = httpClient.execute(httpGet, context); String url = getUrlAfterRedirects(context); </code></pre>
21,815,567
0
Button is not moving when I change its coordinates <p>Given this code : </p> <pre><code>&lt;style type="text/css"&gt; #button{ width: 5em; height: 2em; background-color:#62B1F6; font-size:20px; position:static; left: 400px; top:485px; z-index: 1;} &lt;/style&gt; </code></pre> <p>When I change the parameters of <code>left,top</code> , the button doesn't move . </p> <p>What am I doing wrong ? </p>
9,175,243
0
<p>Force, I must tell you that an <strong>Android Service do not require root access</strong> instead some actions(i.e. Access, Read, Write system resources) requires Root Permissions. Every Android Service provided in Android SDK can be run without ROOT ACCESS. </p> <p>You can make the actions to execute with root permissions with the help of shell commands.</p> <p>I have created an abstract class to help you with that</p> <pre><code>import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import android.util.Log; public abstract class RootAccess { private static final String TAG = "RootAccess"; protected abstract ArrayList&lt;String&gt; runCommandsWithRootAccess(); //Check for Root Access public static boolean hasRootAccess() { boolean rootBoolean = false; Process suProcess; try { suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); DataInputStream is = new DataInputStream(suProcess.getInputStream()); if (os != null &amp;&amp; is != null) { // Getting current user's UID to check for Root Access os.writeBytes("id\n"); os.flush(); String outputSTR = is.readLine(); boolean exitSu = false; if (outputSTR == null) { rootBoolean = false; exitSu = false; Log.d(TAG, "Can't get Root Access or Root Access deneid by user"); } else if (outputSTR.contains("uid=0")) { //If is contains uid=0, It means Root Access is granted rootBoolean = true; exitSu = true; Log.d(TAG, "Root Access Granted"); } else { rootBoolean = false; exitSu = true; Log.d(TAG, "Root Access Rejected: " + is.readLine()); } if (exitSu) { os.writeBytes("exit\n"); os.flush(); } } } catch (Exception e) { rootBoolean = false; Log.d(TAG, "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage()); } return rootBoolean; } //Execute commands with ROOT Permission public final boolean execute() { boolean rootBoolean = false; try { ArrayList&lt;String&gt; commands = runCommandsWithRootAccess(); if ( commands != null &amp;&amp; commands.size() &gt; 0) { Process suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); // Execute commands with ROOT Permission for (String currentCommand : commands) { os.writeBytes(currentCommand + "\n"); os.flush(); } os.writeBytes("exit\n"); os.flush(); try { int suProcessRetval = suProcess.waitFor(); if ( suProcessRetval != 255) { // Root Access granted rootBoolean = true; } else { // Root Access denied rootBoolean = false; } } catch (Exception ex) { Log.e(TAG, "Error executing Root Action", ex); } } } catch (IOException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (SecurityException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (Exception ex) { Log.w(TAG, "Error executing operation", ex); } return rootBoolean; } } </code></pre> <p>Extend your class with RootAccess or create an instance of RootAccess class and Override runCommandsWithRootAccess() method.</p>
14,663,745
0
<p>Sadly a bit redundant due to MySQL's lack of a <code>WITH</code> statement, but this should do what you want. In case of a tie, it will return the higher answer.</p> <pre><code>SELECT s1.question_id, MAX(s1.answer) answer, MAX(s1.c) occurrences FROM (SELECT question_id, answer, COUNT(*) c FROM survey_result GROUP BY question_id,answer) s1 LEFT JOIN (SELECT question_id, answer, COUNT(*) c FROM survey_result GROUP BY question_id,answer) s2 ON s1.question_id=s2.question_id AND s1.c &lt; s2.c WHERE s2.c IS NULL GROUP BY question_id </code></pre> <p><a href="http://sqlfiddle.com/#!2/ddb55/2" rel="nofollow">An SQLfiddle to play with</a>.</p>
40,110,658
0
<p>One reason why your application might be getting slower is the way you treat the onBackPressed() event. Every time you hit the back press button anywhere in the app you are creating a new MainActivity, but you never finish the previous one and since that's your MainActivity you are pretty much recreating your whole application on every back press.</p>
6,185,321
0
<p>Two possible answers:</p> <p>1) The traditional way to check for a file on an FTP server is the SIZE command - if you get a size, the file exists, otherwise you get an error and you know it doesn't exist.</p> <p>2) Found some code that demonstrates a possible way to do this:</p> <p><a href="http://stackoverflow.com/questions/5823475/get-file-size-on-ftp-download">Get file size on FTP download</a></p> <p>Hope this helps.</p>
10,562,314
0
google checkout call back function doesn't work <p>I have problem in google checkout. I have set my googleCallBack url "https://www.mysite.com/orders/googleCallBack" but it gives error </p> <pre><code>We encountered an error trying to access your server at https://www.mysite.com/orders/googleCallBack -- the error we got is java.io.IOException: Error 'SSL_CERTIFICATE_ERROR' connecting to url 'https://https://www.mysite.com/orders/googleCallBack'. More documentation for this error. </code></pre> <p>I check my goDaddy SSL certificate and validate it. But its working fine but googleCheckout give me an error. Actually order place successfully on Google Checkout but after callback on our site doesn't place order.</p> <p>Can anyone help me?</p>
3,370,656
0
C++ Boost multi-index type identification <p>In boost multi-index, can I verify whether a particular index type is ordered/not through meta programming? There are the ordered indexes, hash indexes, sequence indexes etc. Can I find them out through meta programming?</p> <p>Suppose there is a index like:</p> <pre><code> int main() { typedef multi_index_container&lt;double&gt; double_set; return 0; } </code></pre> <p>I want to know whether the double_set index is ordered or hashed or sequenced. Of course in this case, it is ordered.</p>
1,425,784
0
<p>One thing I always do (if possible) I run the DB Tuning Advisor.</p> <p>Don't get me wrong - I don't follow all his rules and suggestions, but it is an easy way to see what's going on, how often what occures and so on. Some hours of (typical!!!) workload are good to get some basic "feeling" what's going on.</p> <p>And after it you can decide to implement some of the suggestions or not. And even if you did your best in design - such a check looks what's really going on (not always predictable) and maybe you forget some statistics or a different index could help...</p>
1,815,095
0
<blockquote> <p>do all JVMs optimize the usage of Strings in a way such that when the same string is used several times, it will always be the same physical instance?</p> </blockquote> <p>I doubt that very much. In the same class file, when definined like:</p> <pre><code>String s1 = "Yes"; String s2 = "Yes"; </code></pre> <p>you'll probably have s1 == s1.</p> <p>But if you have like:</p> <pre><code>String x = loadTextFromFile(); // file contains es StringBuilder b = new StringBuilder(); s2 = b.append("Y").append(x).toString(); // s2 = "Yes" </code></pre> <p>I don't think the runtime is going to check and compare all the loaded strings to the return value of them builder. </p> <p>So, always compare objects with equals(). That's good advice anyway since every good equals starts with:</p> <pre><code>if (this == o) { return true; } </code></pre>
25,747,172
0
JSON Request displaying console issue <p>I am trying to get the console.log to work with the 'interests' information using the following JSON request but I get the following error message in the console.</p> <blockquote> <p>XMLHttpRequest cannot load <a href="https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all" rel="nofollow">https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. </p> </blockquote> <pre><code>&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $.getJSON ('https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all'), function(data) { consol.log(data.interests) } &lt;/script&gt; </code></pre> <p>Can anyone help with this?</p>
10,854,304
0
<pre><code>select * from log_metrics a inner join (select session_id from log_metrics group by session_id having count(*) &gt; 10) b on a.session_id = b.session_id </code></pre> <p>Here's a SQL fiddle: <a href="http://sqlfiddle.com/#!2/7bed6/3" rel="nofollow">http://sqlfiddle.com/#!2/7bed6/3</a></p>
33,642,859
0
<p>-eq is similar to == operator which will compare the address for Objects not values. You must use Array or other collection utilities to compare two Objects.</p>
10,081,699
0
<p>It great that you have started learning Ruby! But Ruby in it self is simply a programming language. I think you wan't to check out Rails!</p> <p><a href="http://guides.rubyonrails.org/getting_started.html" rel="nofollow">http://guides.rubyonrails.org/getting_started.html</a></p> <p>Rails is written in Ruby and a lot of what you will write will be Ruby so you will probably get started quickly.</p>
17,656,342
0
<p>Would something like this work?</p> <pre><code>SELECT max(a.field_date_and_time_value2) as last_time , b.uid FROM field_data_field_date_and_time a INNER JOIN node b ON /* this piece might be wrong. what is the relationship between the first table and the second one? */ b.nid = '".$node-&gt;nid."' where a.field_date_and_time_value2 &gt; '".$today."' AND b.uid = $node-&gt;nid </code></pre>
20,382,511
0
<p>This one works fine:</p> <pre><code>; 0_9.asm ; assemble with "nasm -f bin -o 0_9.com 0_9.asm" org 0x100 ; .com files always start 256 bytes into the segment mov cx, 9 ; counter mov dl, "0" ; 0 top: push dx push cx mov ah, 2 int 21h mov dl, "_" ; display underscore mov ah, 2 int 21h pop cx pop dx inc dl loop top mov dl, "9" ; display 9 mov ah, 2 int 21h mov ah, 4ch ; "terminate program" sub-function mov al,00h int 21h </code></pre>
35,565,770
0
Difference between service and container in docker compose <p>I was going through <code>volumes_from</code> option in docker compose. Apparently you can import a volumes from either a container or a service. From the docker compose documentation it is:</p> <blockquote> <p><strong>volumes_from</strong></p> <p>Mount all of the volumes from another service or container, optionally specifying read-only access(ro) or read-write(rw).</p> <pre><code>volumes_from: - service_name - service_name:ro - container:container_name - container:container_name:rw </code></pre> <p>Note: The container:... formats are only supported in the version 2 file format. In version 1, you can use container names without marking them as such:</p> <pre><code>- service_name - service_name:ro - container_name - container_name:rw </code></pre> </blockquote> <p>I am confused here what is the difference between containers and services here?</p>
1,552,913
0
<p>You say it works if you use the full path to <code>tclsh84.exe</code>. So, a solution might be to find out that full path and use it in your call to <a href="http://php.net/proc_open" rel="nofollow noreferrer">proc_open</a>.</p> <p><br> If you know your <code>tclsh84.exe</code> is in the directory in which your PHP script is, you could use something based on <a href="http://php.net/dirname" rel="nofollow noreferrer"><code>dirname</code></a> and <a href="http://php.net/manual/en/language.constants.predefined.php" rel="nofollow noreferrer"><code>__FILE__</code></a> ; a bit like this, I suppose :</p> <pre><code>$dir = dirname(__FILE__); var_dump($dir); // directory in which the current PHP script is in $path = $dir . DIRECTORY_SEPARATOR . 'tclsh84.exe'; var_dump($path); </code></pre> <p>Considering the PHP script I am using is <code>/home/squale/developpement/tests/temp/temp.php</code>, I would get :</p> <pre><code>string '/home/squale/developpement/tests/temp' (length=37) string '/home/squale/developpement/tests/temp/tclsh84.exe' (length=49) </code></pre> <p>And, if needed, you can use '<code>..</code>' to go up in the directories tree, and, then use directories names to go down.</p> <p><br> Another solution might be to make sure that the program you are trying to execute is in your PATH environment variables -- but if it's a program that's used only by your application, it doesn't make much sense to modify your PATH, I guess...</p>
21,768,982
0
<p>You can use get_permalink the way you use get_post: <a href="http://codex.wordpress.org/Function_Reference/get_permalink" rel="nofollow">http://codex.wordpress.org/Function_Reference/get_permalink</a></p> <pre><code>$post_id = 105; $queried_post = get_post($post_id); $title = $queried_post-&gt;post_title; $permalink = get_permalink($post_id); echo '&lt;a href="' . $permalink . '"&gt;' . get_the_post_thumbnail($post_id) . '&lt;/a&gt;'; </code></pre> <p>However, the permalink is likely in the $queried_post object. You can <code>print_r($queried_post)</code> to inspect it.</p>
6,204,109
0
Regex get content between two pipes AND return a space where two pipes are next to each other with no spaces <p>How can I get all content between pipes and return a space where it comes across two pipes next to each other? </p> <p>An example string and desired output is:</p> <pre><code>|test1| test2|test3 || test 4 | Result1: "test1" Result2: "test2" Result3: "test3" Result4: " " Result5: "test4" </code></pre> <p>The closest I've got so far is: </p> <ul> <li><code>/[^\|]+)/</code> which will get all data between pipes but does not detect <code>||</code>.</li> <li><code>/\|([^\|]*)/</code> which will get all data between pipes and detect <code>||</code> but have an extra whitespace result at the end.</li> </ul>
33,445,762
0
Increment %z hex numbers with VIM? <p>Is there a way to increment <code>%z</code> hex numbers with VIM? Typically I can do this by just doing <code>ctrl + a</code> for normal numbers. But unfortunately I am using a old school system that uses <code>%z</code> rather than <code>0x</code> to denote hexadecimal numbers. I've tried </p> <pre><code>Set nf=hex </code></pre> <p>But that sadly only works for <code>0x</code> hex numbers. Anyone come across this before? I haven't found much on the google machine.</p>
3,310,015
0
<p>How about changing that <code>Action</code> delegate to <code>Action&lt;T&gt;</code>.</p> <pre><code>public static class Tools { public static void RunAsync&lt;T&gt;(Action&lt;T&gt; function, Action callback, T parameter) { BackgroundWorker worker = new BackgroundWorker(); worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { callback(); }; worker.DoWork += delegate(object sender, DoWorkEventArgs e) { function(parameter); }; worker.RunWorkerAsync(); } } </code></pre>
40,404,458
0
<p>Unless <code>startActivityForResult(audioIntent,1)</code> has options to disable the popup, no. It's an activity that someone else has written. The way you want it, you will need to write your own activity with (probably) google's speech recognition plugged into that. Good luck &amp; have fun!</p>
18,403,604
0
Boot AngularJS + Cloud Endpoints <p>Is there a way to initialize angular and endpoints without manual boot of angular?</p> <p>I thought I'd found an elegant solution <a href="https://cloud.google.com/resources/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications" rel="nofollow">here</a>.</p> <p>Unfortunately for me window.init isn't always declared before it's called by the callback despite the sequence order of scripts. It works fine on refresh but not always on first page load. The console outputs "Uncaught TypeError: Object [object global] has no method 'init' ".</p> <p>Finally I've tried to manually bootstrap angular from the endpoints callback (eg <a href="http://stackoverflow.com/questions/15905755/angularjs-and-google-cloud-endpoint-walk-through-needed">here</a>, but on trying this it caused lag where angular should replace the handlebar placeholders, so the html was full of handlebars for a few seconds. I appreciate this may be the only way to do this however the first link above from google suggests otherwise.</p> <p><strong>UPDATE:</strong></p> <pre><code>function customerInit(){ angular.element(document).ready(function() { window.init(); }); } </code></pre> <p>This seems to solve my problem, it enforces that angular controller is initialized before endpoints. This isn't mentioned on googles page here, but it seems necessary to enforce the order of initialization.</p> <p>hmtl:</p> <pre><code>&lt;html ng-app lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"&gt;&lt;/script&gt; &lt;script src="js/customer.js"&gt;&lt;/script&gt; &lt;script src="https://apis.google.com/js/client.js?onload=customerInit"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container" ng-controller="customerCtrl"&gt; &lt;div class="page-header"&gt; &lt;h1&gt;Customers&lt;/h1&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-lg-10"&gt; &lt;table id="customerTable" class="table table-striped table-bordered table-hover"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Surname&lt;/th&gt; &lt;th&gt;Email Address&lt;/th&gt; &lt;th&gt;Home Phone&lt;/th&gt; &lt;th&gt;Mobile Phone&lt;/th&gt; &lt;th&gt;Work Phone&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr ng-repeat="customer in allCustomers"&gt; &lt;td&gt;{{customer.firstName}}&lt;/td&gt; &lt;td&gt;{{customer.surName}}&lt;/td&gt; &lt;td&gt;{{customer.emailAddress}}&lt;/td&gt; &lt;td&gt;{{customer.homePhone}}&lt;/td&gt; &lt;td&gt;{{customer.mobilePhone}}&lt;/td&gt; &lt;td&gt;{{customer.workPhone}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>customer.js:</p> <pre><code>function customerInit(){ window.init(); } function customerCtrl ($scope) { window.init= function() { $scope.$apply($scope.load_customer_lib); }; $scope.is_backend_ready = false; $scope.allCustomers = []; $scope.load_customer_lib = function() { gapi.client.load('customer', 'v1', function() { $scope.is_backend_ready = true; $scope.getAllCustomers(); }, '/_ah/api'); }; $scope.getAllCustomers = function(){ gapi.client.customer.customer.getCentreCustomers() .execute(function(resp) { $scope.$apply(function () { $scope.allCustomers = resp.items; }); }); }; }; </code></pre>
32,769,097
0
<p>When you do <code>String y = in.nextLine()</code>, the next token is the leftover newline from the previous <code>nextInt()</code> call, so <code>y</code> ends up being equal to <code>\n</code>.</p> <p>Place a call to <code>nextLine()</code> after you use <code>nextInt()</code>:</p> <pre><code>int x = in.nextInt(); in.nextLine(); </code></pre> <p>Afterwards you should be able to call <code>nextLine</code> only once when getting the user input:</p> <pre><code>String y = in.nextLine(); if(y.equals("Washington")){ </code></pre>
7,474,364
0
Ambiguity with inheriting an optional-parameter base method <p>I have a base class with one optional default parameter, which a child class automatically provides a value for:</p> <pre><code>public class Merchant { public string WriteResults(List&lt;string&gt; moreFields = null) { List&lt;string&gt; ListOfObjects = new List&lt;string&gt;() {Name, Address}; if (moreFields != null) { ListOfObjects.AddRange(moreFields); } return ListOfObjects.ToString() //not real output } public class SpecificMerchant : Merchant { new public string WriteResults() { return ((Merchant)this).WriteResults(new List&lt;string&gt;() { Address, Phone //class-specific parameters }); } } </code></pre> <p>I used the <code>new</code> keyword when calling <code>SpecificMerchant.WriteResults</code> because both the parent and the base can take no parameters, but the compiler says this is unnecessary:</p> <blockquote> <p>The member 'SpecificMerchant.WriteResults()' does not hide an inherited member. The new keyword is not required.</p> </blockquote> <p>Why? Aren't I, in practice, overriding the parent method?</p>
6,660,701
0
<p>There are too many ways that you can do it. Please check <a href="http://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net">this</a> topic. If you want to use free library or tool you can use <a href="http://itextsharp.com/" rel="nofollow">iTextSharp</a>, but free version doesn't cover all requirement. So you can use some other tools such as <a href="http://www.websupergoo.com/abcpdf-9.htm" rel="nofollow">ABCPdf</a></p>
19,290,759
0
MVVM Light - Changing the startup URI <p>Having created a new WPF 4.5 MVVM Light Application, I wanted to change the startup URI so that I could do some checks before the app starts. I made the following change to App.xaml:</p> <pre><code>&lt;Application x:Class="MvvmLight1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:MvvmLight1.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" StartupUri="MainWindow.xaml" mc:Ignorable="d"&gt; </code></pre> <p>To:</p> <pre><code>&lt;Application x:Class="MvvmLight1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:MvvmLight1.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"&gt; </code></pre> <p>And added an <code>OnStartup</code> method to the <code>App.xaml.cs</code>:</p> <pre><code>public partial class App : Application { static App() { DispatcherHelper.Initialize(); } protected override void OnStartup(StartupEventArgs e) { //base.OnStartup(e); MainWindow win = new MainWindow(); win.Show(); } } </code></pre> <p>Doing this seems to change the context that the window runs in. I did try setting the data context to the MainViewModel, but this didn't seem to help.</p>
26,882,164
0
<p>For MySQL and SQLite,ejabberd provides a way to store messages in a very simple way.</p>
2,631,205
0
<p>Well, certainly leave off the '/src/' portion of the package listing for that invocation. Either way, the easiest and most flexible way to run your tests this is to make sure all your tests are in a subpackage of where AllTests is (e.g. com.app.myapp.test.tests) and use this for the suite:</p> <pre><code>public static Test suite() { return new TestSuiteBuilder(AllTests.class) .includeAllPackagesUnderHere().build(); } </code></pre> <p>Make sure your tests run individually, too, without the suite runner -- the suite won't pick up your tests if they're set up wrong to begin with.</p> <p>(This is better than explicitly listing the package name since it's more portable -- you can rename your test package without breaking it, for example.)</p>
13,455,460
0
<p>I guess eval will work:</p> <pre><code>var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]"); console.log(str); </code></pre> <p>​</p>
388,175
0
<p>I like to cache in the model or data layer as well. This isolates everything to do with retrieving data from the controller/presentation. You can access the ASP.NET cache from <code>System.Web.HttpContext.Current.Cache</code> or use the Caching Application Block from the Enterprise Library. Create your key for the cached data from the parameters for the query. Be sure to invalidate the cache when you update the data.</p>
29,927,728
0
<p>Reversibly encoding the hash doesn't impact collision rate... Unless your encoding causes some loss of data (then it isn't reversible any more).</p> <p>Base64 and other <a href="http://en.wikipedia.org/wiki/Binary-to-text_encoding" rel="nofollow">binary-to-text encoding schemes</a> are all reversible. Your first output is the hexadecimal (or base16) representation, which is 50% efficient. Base64 achieves 75% efficiency, meaning it cuts the 40-character hex representation to 28 characters.</p> <p>The most efficient binary encoding scheme is <a href="http://en.wikipedia.org/wiki/YEnc" rel="nofollow">yEnc</a>, which achieves 98% efficiency, meaning a 100 byte long input will be roughly 102 bytes when encoded with yEnc. This is where the real problem arises for you: SHA-1 outputs are 160 bits (20 bytes) long. If you achieve 200% character-byte efficiency by using every 2-byte UTF16 character, you're still looking at <strong>10 characters</strong>. You can't achieve this, because 2-byte values from U+D7FF to U+E000 are not valid UTF16 characters. Those byte values are reserved as prefixes for higher-plane characters.</p> <p>Even if you find such a hyper-efficient<sup>1</sup> encoding scheme using unicode, you can't really use those as URLs. <a href="http://www.faqs.org/rfcs/rfc1738.html" rel="nofollow">Unicode characters are forbidden from URLs</a> and to be standards compliant, you should use % encodings for your URLs. Many browsers will automatically convert them, so you may find this acceptable, but many of the characters you would regularly use would not be human readable and many more would appear to be in different languages.</p> <p>At this point, if you really need <em>short</em> URLs, you should reconsider using a hash value and instead implement your own identity service (e.g. assign every page or resource an incremental ID, which is admittedly hard to scale) or utilizing another <a href="http://en.wikipedia.org/wiki/URL_shortening" rel="nofollow">link-shortening service</a>.</p> <p><sup>1</sup>: This not possible from a bit standpoint. Unicode could achieve a higher character-to-bit ratio, but the unicode characters themselves are represented by multiple bytes. The % encodings for UTF8, which most browsers use as the default for unrecognized encodings, get messy quickly.</p>
7,679,474
0
<p>If I may suggest an alternative approach - which is to use an array. You shouldn't try to dynamically create variable names. For that purpose, good engineers from a long, long time ago in a year far far away invented an array.</p> <p>So, to solve your problems from now and the whole eternity - rewrite your code to use:</p> <pre><code>$newNode-&gt;field[$key]['und'][0]['value'] = $value; </code></pre>
11,941,693
0
running a job in unix <p>I have the following small script - myjob.qsub: </p> <pre><code>#!/bin/sh -login #PBS -l walltime=00:15:00 #PBS -l nodes=1:ppn=1 #PBS -l mem=2gb #PBS -N myrun05168 /myexecutable &gt;mylog.log </code></pre> <p>I did make it executable by:</p> <pre><code>chmod u+x myexecutable </code></pre> <p>When I try to run by changing directory to the folder of executible and then sumbit the job:</p> <pre><code>qsub myjob.qsub </code></pre> <p>gives me error of no /myexecutable file or directory.</p> <p>I tried to use "./": </p> <pre><code> #!/bin/sh -login #PBS -l walltime=00:15:00 #PBS -l nodes=1:ppn=1 #PBS -l mem=2gb #PBS -N myrun05168 ./myexecutable &gt;mylog.log </code></pre> <p>but doesnot help. </p> <p>when I just tried to run my executable in command line as, it works: </p> <pre><code>./myexecutable </code></pre> <p>As I can not run this as this job need to be submitted as job in cluster computer. </p> <p>Any suggestions ? </p>
24,409,698
1
Django view function not being called <p>Ths is the function in question. The problem is that it does not seem to do be called. User can download any files on the server, regardless of whether <code>pk</code> matches <code>request.user.id</code> or not.</p> <pre><code>def permit(request, pk): # First I sanitize system_path from request, then... if int(request.user.id) == int(pk) and int(request.user.id) &gt;= 1: sendfile(request, system_path) else: return render_to_response('forbidden.html') return HttpResponseRedirect('/notendur/list') </code></pre> <p>As you can see, it takes <code>pk</code> and compares it to <code>request.user.id</code>, and serves the file if that is the case.</p> <p>Then the relevant bits of <code>urls.py</code></p> <pre><code>urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), #upload urls (r'^notendur/', include('notendur.urls')), #This needs to be changed to welcome.html (r'^$', RedirectView.as_view(url='/notendur/list/')), # Just for ease of use. #security url(r'^media/uploads/(?P&lt;pk&gt;[^/]+)', 'notendur.views.permit'), url(r'^media', 'notendur.views.permit'), ) </code></pre> <p>This error sort of came out of the blue. I hadn't edited anything pertaining to this as far as I am aware.</p> <p>I know the function is not being called because I commented out the <code>sendfile()</code> and put <code>render_to_response('forbidden.html')</code> instead. Did not have any effect; user could still download file unexamined.</p>
15,707,497
0
HttpOnly settings can be done in application having servlet api-2.5 and web.xml 2.5 version? <p>wanna enable httpOnly attribute to session cookie for our application. we are using servlet-api 2.5 version and web.xml as 2.5 .. now i have tried adding below code in web.xml </p> <pre><code>&lt;cookie-config&gt; &lt;http-only&gt;true&lt;/http-only&gt; &lt;/cookie-config&gt; </code></pre> <p>i got error parsing error in <code>web.xml</code> at <code>&lt;cookie-config&gt;</code></p> <p>can any please help on this.. do i need to update servlet version to 3 and web.xml to 3 as well ...</p> <p>or any other ways to do it writing in java code itself.. we are using jboss 5 version..</p>
35,057,284
0
simple "Up a directory" button in htaccess? <p>a while ago i was using htaccess to display some files, and recently i started that project again and found i had somehow deleted the "go up a level" button back then. </p> <p>Can anyone tell me what the code line in htaccess looks like to get this button back? Should be relatively simple but i just cant find it... heres what i got.</p> <pre><code>Options +Indexes # DIRECTORY CUSTOMIZATION &lt;IfModule mod_autoindex.c&gt; IndexOptions IgnoreCase FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* SuppressHTMLPreamble # SET DISPLAY ORDER IndexOrderDefault Descending Name # SPECIFY HEADER FILE HeaderName /partials/header.html # SPECIFY FOOTER FILE ReadmeName /partials/footer.html # IGNORE THESE FILES, hide them in directory IndexIgnore .. IndexIgnore header.html footer.html icons # IGNORE THESE FILES IndexIgnore header.html footer.html favicon.ico .htaccess .ftpquota .DS_Store icons *.log *,v *,t .??* *~ *# # DEFAULT ICON DefaultIcon /icons/generic.gif AddIcon /icons/dir.gif ^^DIRECTORY^^ AddIcon /icons/pdf.gif .txt .pdf AddIcon /icons/back.png .. &lt;/IfModule&gt; Options -Indexes </code></pre>
2,986,167
0
Best way to store configuration settings outside of web.config <p>I'm starting to consider creating a class library that I want to make generic so others can use it. While planning it out, I came to thinking about the various configuration settings that I would need. Since the idea is to make it open/shared, I wanted to make things as easy on the end user as possible. What's the best way to setup configuration settings without making use of web.config/app.config?</p>
6,835,427
0
<p>If you do not mind additional statements (while loop) the following will work in c99</p> <pre><code>#define NBITS_32(n,out_len) 0; while (n &amp;&amp; !(0x80000000 &gt;&gt; out_len &amp; n)) out_len++; out_len = n ? abs(out_len - 32) : n uint8_t len1 = NBITS_32(0x0F000000, len1); uint8_t len2 = NBITS_32(0x00008000, len2); uint8_t len3 = NBITS_32(0xFFFFFFFF, len3); uint8_t len4 = NBITS_32(0x00000001, len4); printf("%u\n%u\n%u\n%u\n", len1, len2, len3, len4); </code></pre> <p>Output:</p> <blockquote> <p><strong>28<br/> 16<br/> 32<br/> 1</strong></p> </blockquote>
16,705,516
0
<p>It seems like <code>buffer</code> is probably set to <code>NULL</code> or some other invalid pointer and probably segfaults when you dereference it. It could also be your first call to <code>free</code> if the pointer is invalid. Ideally you need to show us the code that calls this function.</p> <p>Also keep in mind it's bad form to call a matching <code>malloc</code> and <code>free</code> in different functions. Unless that function has only one purpose, to allocate a new structure or to free an existing one (In other words allocation of any resource should be done in the same function as deallocation of that same resource. The only exception is a function that composes more complex allocations and deallocations).</p> <pre><code>int load_filenew(char *filename, char **buffer) { int size = 0; FILE *fp = 0; if(buffer == NULL) { return 1; } fp = fopen(filename, "rb"); if (!fp) { printf(" fopen failed.\n"); return 2; } fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); if (size) { *buffer = (char *)malloc(size + 1); if (!*buffer) { printf(" malloc failed.\n"); fclose(fp); return 3; } memset(*buffer, 0, size + 1); fread(*buffer, size, 1, fp); (*buffer)[size] = '\0'; } else { fclose(fp); return 3; } fclose(fp); return 0; } </code></pre>
28,157,759
0
<p>In order to Updateupdate the data on the database your SqlDataAdapter need to have its InsertCommand, UpdateCommand, DeleteCommand properties set.</p> <p>So, try the below code:</p> <pre><code> ds.Tables[0].Rows.Add(newRow); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp); adp.DeleteCommand = commandBuilder.GetDeleteCommand(true); adp.UpdateCommand = commandBuilder.GetUpdateCommand(true); adp.InsertCommand = commandBuilder.GetInsertCommand(true); adp.Update(ds.Tables[0]); //connection.UpdateDatabase(ds); connection.Close(); </code></pre> <p>Edit: The Update method takes the name of a DataSet and a table. The DataSet for us is ds, which is the one we passed in to our UpdateDatabase method when we set it up. After a dot, you type the name of a table in your dataset.</p>
1,287,691
0
<p>Futures are also used in certain design patterns, particularly for real time patterns, for example, the ActiveObject pattern, which seperates method invocation from method execution. The future is setup to wait for the completed execution. I tend to see it when you need to move from a multithreaded enviroment to communicate with a single threaded environment. There may be instances where a piece of hardware doesn't have kernel support for threading, and futures are used in this instance. At first glance it not obvious how you would communicate, and surprisingly futures make it fairly simple. I've got a bit of c# code. I'll dig it out and post it. </p>
25,316,922
0
How do I find f3dynamics library? <p>I have a workbook in a machine that contains a macro that works with the f3dynamics library, it is not listed in the references box. I have looked up everywhere and I cannot find the F3dynamics library.</p> <p>I need to move it to another machine so the macro runs in the new machine, I have installed office 2003, 2007, 2010 in the new machine and it is not working for those versions,</p> <p>is there any macro that lists all references, including this "hidden" reference?</p>
32,013,312
0
<p><strong>You can't resize an array.</strong></p> <p><a href="https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx" rel="nofollow">To quote MSDN:</a></p> <blockquote> <p>The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.</p> </blockquote> <p>What methods like Array.Resize actually do is allocate a new array and copy the elements over. It's important to understand that. You're not resizing the array, but reallocating it.</p> <p>So long as you're using arrays, in the end the answer is going to boil down to "allocate a new array, then copy what you want to keep over to it".</p>
13,145,156
0
<p><a href="http://deftjs.org/" rel="nofollow">http://deftjs.org/</a></p> <p>Essential extensions for enterprise web and mobile application development with Ext JS and Sencha Touch</p> <p>DeftJS enhances Ext JS and Sencha Touch’s APIs with additional building blocks that enable large development teams to rapidly build enterprise scale applications, leveraging best practices and proven patterns discovered by top RIA developers at some of the best consulting firms in the industry.</p> <p><strong>FEATURES</strong></p> <p><strong>IoC Container</strong></p> <ul> <li>Provides class annotation driven dependency injection.</li> <li>Maps dependencies by user-defined identifiers.</li> <li>Resolves dependencies by class instance, factory function or value.</li> <li>Supports singleton and prototype resolution of class instance and factory function dependencies.</li> <li>Offers eager and lazy instantiation of dependencies.</li> <li>Injects dependencies into Ext JS class configs and properties before the class constructor is executed.</li> </ul> <p><strong>MVC with View Controllers</strong></p> <ul> <li>Provides class annotation driven association between a given view and its view controller.</li> <li>Clarifies the role of the controller - i.e. controlling a view and delegating work to injected business services (ex. Stores).</li> <li>Supports multiple independent instances of a given view, each with their own view controller instance.</li> <li>Reduces memory usage by automatically creating and destroying view controllers in tandem with their associated views.</li> <li>Supports concise configuration for referencing view components and registering event listeners with view controller methods.</li> <li>Integrates with the view destruction lifecycle to allow the view controller to potentially cancel removal and destruction.</li> <li>Simplifies clean-up by automatically removing view and view component references and event listeners.</li> </ul> <p><strong>Promises and Deferreds</strong></p> <ul> <li>Provides an elegant way to represent a ‘future value’ resulting from an asynchronous operation.</li> <li>Offers a consistent, readable API for registering success, failure, cancellation or progress callbacks.</li> <li>Allows chaining of transformation and processing of future values.</li> <li>Simplifies processing of a set of future values via utility functions including all(), any(), map() and reduce().</li> <li>Implements the CommonJS Promises/A specification.</li> </ul>
24,130,603
0
<p>I think the method should look like this </p> <pre><code>- (IBAction)ChangeSeg:(UISegmentedControl *)sender { if(sender.selectedSegmentIndex == 0){ UpperLower=0; } else if(sender.selectedSegmentIndex == 1){ UpperLower=1; } } </code></pre> <p>The sender will have the selectedSegmentIndex that was chosen.</p>
9,170,096
0
<p>This works for me. </p> <p><strong>ASPX :</strong> </p> <pre><code>&lt;iframe id="ContentIframe" runat="server"&gt;&lt;/iframe&gt; </code></pre> <p>I can access the iframe directly via id.</p> <p><strong>Code Behind :</strong> </p> <pre><code>ContentIframe.Attributes["src"] = "stackoverflow.com"; </code></pre>
6,720,268
0
<p>I wrote a server side script that shows the output of headers from both examples and APIKEY was set identically in both cases. There were some differences in HTTP_ACCEPT / HTTP_ACCEPT_ENCODING and WWW::Mechanize adds some additional headers:</p> <pre><code>'downgrade-1.0' =&gt; '1' 'force-response-1.0' =&gt; '1' 'nokeepalive' =&gt; '1' </code></pre> <p>So I would suggest the problem is somewhere else. </p>